Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions app/scripts/nmr-cli/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions app/scripts/nmr-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"lodash.merge": "^4.6.2",
"mf-parser": "^3.9.2",
"ml-spectra-processing": "^14.34.0",
"nmr-correlation": "^3.0.2",
"nmr-processing": "^22.23.6",
"openchemlib": "^9.25.0",
"playwright": "1.62.1",
Expand Down
76 changes: 76 additions & 0 deletions app/scripts/nmr-cli/src/correlation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { buildCorrelationData } from 'nmr-correlation'
import type { Options as CorrelationOptions, Spectra } from 'nmr-correlation'
import { FifoLogger } from 'fifo-logger'
import {
buildWebSource,
core,
parsingOptions,
processSpectra,
} from './parse/prase-spectra'

// Default tolerances
const DEFAULT_TOLERANCE_H = 0.02
const DEFAULT_TOLERANCE_C = 0.25

export interface CorrelationInput {
url: string
mf: string
toleranceH?: number
toleranceC?: number
}

function resolveTolerance(value: number | undefined, fallback: number): number {
return value === undefined || Number.isNaN(value) ? fallback : value
}

export async function generateCorrelationData(input: CorrelationInput) {
const { url, mf, toleranceH, toleranceC } = input
const logger = new FifoLogger()

const source = buildWebSource(url)

const { state } = await core.readFromWebSource(source, {
...parsingOptions,
logger,
})

const spectraBeforeProcessing = state.data ? [...state.data.spectra] : []

if (state.data) {
processSpectra(
state.data,
{ autoProcessing: true, autoDetection: true },
logger
)
}

// processSpectra replaces a spectrum's array slot with a new object only
// when it successfully parses it; on failure it leaves the original raw
// object in place (see its catch block) instead of removing it. Compare
// by reference against the pre-processing snapshot to filter those out,
// so buildCorrelationData never sees a spectrum it can't actually read.
// Note: a pre-existing bug (see https://github.com/NFDI4Chem/nmrkit/issues/139)
// currently makes every spectrum fail this step, so real cross-spectrum correlation links are untested here.
const spectra = (state.data?.spectra ?? []).filter(
(spectrum, index) => spectrum !== spectraBeforeProcessing[index]
)

const options: CorrelationOptions = {
mf,
tolerance: {
H: resolveTolerance(toleranceH, DEFAULT_TOLERANCE_H),
C: resolveTolerance(toleranceC, DEFAULT_TOLERANCE_C),
},
}

let correlationData
try {
correlationData = buildCorrelationData(spectra as Spectra, options)
} catch (error) {
throw new Error(
`Failed to build correlation data: ${error instanceof Error ? error.message : String(error)}`
)
}

return { ...correlationData, logs: logger.getLogs() }
}
59 changes: 58 additions & 1 deletion app/scripts/nmr-cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { parseSpectra } from './parse/prase-spectra'
import { generateSpectrumFromPublicationString } from './publication-string'
import { generateNMRiumFromPeaks } from './peaks-to-nmrium'
import type { PeaksToNMRiumInput } from './peaks-to-nmrium'
import { generateCorrelationData } from './correlation'
import { hideBin } from 'yargs/helpers'
import { parsePredictionCommand } from './prediction'
import { readFileSync } from 'fs'
Expand All @@ -15,8 +16,15 @@ Usage: nmr-cli <command> [options]
Commands:
parse-spectra Parse a spectra file to NMRium file
parse-publication-string resurrect spectrum from the publication string
predict Predict spectrum from Mol
predict Predict spectrum from Mol
peaks-to-nmrium Convert a peak list to NMRium object
correlation Build correlation data from NMR spectra fetched from a URL

Options for 'correlation' command:
-u, --url Spectra ZIP file URL
--mf Molecular formula
--tolerance-h H tolerance override (default: 0.02)
--tolerance-c C tolerance override (default: 0.25)

Options for 'parse-spectra' command:
-u, --url File URL
Expand Down Expand Up @@ -250,12 +258,61 @@ const peaksToNMRiumCommand: CommandModule = {
},
}

// Define the correlation command
const correlationCommand: CommandModule = {
command: ['correlation', 'corr'],
describe: 'Build correlation data from NMR spectra fetched from a URL',
builder: yargs => {
return yargs.options({
u: {
alias: 'url',
describe: 'Spectra ZIP file URL',
type: 'string',
demandOption: true,
nargs: 1,
},
mf: {
describe: 'Molecular formula',
type: 'string',
demandOption: true,
nargs: 1,
},
'tolerance-h': {
describe: 'H tolerance override (default: 0.02)',
type: 'number',
},
'tolerance-c': {
describe: 'C tolerance override (default: 0.25)',
type: 'number',
},
})
},
handler: async argv => {
try {
const result = await generateCorrelationData({
url: argv.u as string,
mf: argv.mf as string,
toleranceH: argv['tolerance-h'] as number | undefined,
toleranceC: argv['tolerance-c'] as number | undefined,
})
console.log(JSON.stringify(result))
} catch (error) {
console.error(
'Error:',
error instanceof Error ? error.message : String(error),
)
process.exit(1)
}
},
}

yargs(hideBin(process.argv))
.usage(usageMessage)
.command(parseFileCommand)
.command(parsePublicationCommand)
.command(parsePredictionCommand)
.command(peaksToNMRiumCommand)
.command(correlationCommand)
.showHelpOnFail(true)
.help()
.parse()
13 changes: 8 additions & 5 deletions app/scripts/nmr-cli/src/parse/prase-spectra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,19 +196,22 @@ async function processAndSerialize(
outputResult({ nmriumState: { data, version }, images, logs }, o);
}

async function loadSpectrumFromURL(options: RequiredKey<FileOptionsArgs, 'u'>, logger: FifoLogger) {
const { u: url, include, exclude } = options;

function buildWebSource(url: string) {
const { pathname: relativePath, origin: baseURL } = new URL(url)
const source = {
return {
entries: [
{
relativePath,
},
],
baseURL,
}
}

async function loadSpectrumFromURL(options: RequiredKey<FileOptionsArgs, 'u'>, logger: FifoLogger) {
const { u: url, include, exclude } = options;

const source = buildWebSource(url)

const { state } = await core.readFromWebSource(source, { ...parsingOptions, fileFilter: { include, exclude }, logger });

Expand Down Expand Up @@ -257,4 +260,4 @@ function parseSpectra(argv: yargs.ArgumentsCamelCase<FileOptionsArgs>



export { loadSpectrumFromFilePath, loadSpectrumFromURL, parseSpectra }
export { loadSpectrumFromFilePath, loadSpectrumFromURL, parseSpectra, processSpectra, parsingOptions, core, buildWebSource }
Loading