gonmr

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2026 License: GPL-3.0, GPL-3.0 Imports: 21 Imported by: 0

README

GoNMR

GoNMR is an importable Go package and a concurrent Windows/Linux/macOS CLI for 1D NMR processing. It provides 55 typed operations plus 17 fixture-tested R2Go compatibility functions, without requiring an R installation.

Install

go get github.com/tarekwasfy01/GONMR
go install github.com/tarekwasfy01/GONMR/cmd/gonmr@latest

Use as a package

package main

import (
    "fmt"
    gonmr "github.com/tarekwasfy01/GONMR"
)

func main() {
    corrected, err := gonmr.RemoveDCOffset([]float64{5, 3, 3}, 2)
    fmt.Println(corrected, err)
}

The public API includes FFT/IFFT, apodization, zero filling, phase and baseline correction, interpolation, calibration, peak detection, integration, binning, normalization, matrix operations, QC, noise estimation and seeded simulation. ParallelMap and ParallelMapComplex provide ordered worker-pool processing.

Build and test the CLI

.\scripts\build.ps1
.\scripts\smoke-test.ps1 -Exe dist\gonmr.exe

Every built CLI contains the complete corresponding source archive required for GPL redistribution. It can be inspected or extracted without Internet:

.\dist\gonmr.exe source-info
.\dist\gonmr.exe extract-source gonmr-corresponding-source.zip

Examples:

'[3,4]' | .\dist\gonmr.exe normalize
'[[1,2,3],[4,5,6]]' | .\dist\gonmr.exe batch -op zero-fill-power2 -factor 2 -workers 4
'[{"real":[1,0,0,0],"imag":[0,0,0,0]}]' | .\dist\gonmr.exe batch-complex -op fft -workers 4

License

The combined work is distributed under GPL-3.0-or-later because it contains adapted GPL-3 code. Corresponding source, build scripts, exact provenance and all applicable third-party license texts are included. See THIRD_PARTY_NOTICES.md and licenses/.

Documentation

Overview

Package gonmr provides dependency-free 1D NMR signal processing, including apodization, zero filling, FFT/IFFT, phase and baseline correction, peak detection, integration, normalization, statistics and ordered worker pools.

GoNMR consolidated processor.

This single-file program consolidates the useful algorithms found in the successful R2Many raw output. Provenance and license details remain in TRANSPILED_SOURCES.md and THIRD_PARTY_NOTICES.md.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlphaToLineWidth

func AlphaToLineWidth(alpha float64) float64

func ApplyCols

func ApplyCols(matrix DenseMatrix, operation func([]float64) (float64, error)) ([]float64, error)

func ApplyRows

func ApplyRows(matrix DenseMatrix, operation func([]float64) (float64, error)) ([]float64, error)

func ApplyWindow

func ApplyWindow(values []float64, kind string, dwellTime, parameter float64) ([]float64, error)

ApplyWindow applies common NMR apodization windows. DwellTime is seconds per point. Parameter is line width in Hz for exponential, Gaussian sigma in seconds for gaussian, and exponent for sinebell.

func AsymmetricBaseline

func AsymmetricBaseline(y []float64, lambda, p, epsilon float64, maxIterations int) ([]float64, error)

AsymmetricBaseline is the complete, runnable form of ptw's generated asysm. It uses the second-difference Whittaker system required by the R algorithm.

func BaselineCorrect

func BaselineCorrect(y []float64, lambda, p, epsilon float64, maxIterations int) ([]float64, error)

func BinMean

func BinMean(values []float64, width int) ([]float64, error)

func CalibrateAxis

func CalibrateAxis(ppm []float64, observed, target float64) ([]float64, error)

CalibrateAxis moves an entire ppm axis so that an observed reference lands on its known target position.

func DecodeBinary

func DecodeBinary(data []byte, kind, endian string) (any, error)

DecodeBinary implements the typed core shared by the vendor-reader helpers.

func FilePath

func FilePath(parts ...string) string

func Gauss

func Gauss(x, center, width, asymmetry float64) float64

func GrepIndices

func GrepIndices(values []string, pattern string, ignoreCase bool) ([]int, error)

func Grepl

func Grepl(values []string, pattern string, ignoreCase bool) ([]bool, error)

func IntegrateTrapezoid

func IntegrateTrapezoid(x, y []float64) (float64, error)

func IsWholeNumber

func IsWholeNumber(value, tolerance float64) bool

func LineWidthToAlpha

func LineWidthToAlpha(lineWidthHz float64) float64

func LinearInterpolate

func LinearInterpolate(x, y, newX []float64) ([]float64, error)

LinearInterpolate changes a monotonic spectral grid. Values outside the old grid use the nearest endpoint, matching the boundary behaviour of the R grid-changing helpers selected for this processor.

func Lorentz

func Lorentz(x, center, width, asymmetry float64) float64

Lorentz, Gauss, and PseudoVoigt directly translate the formulas in Rnmr1D/src/libCdeconv.cpp.

func MapValues

func MapValues[T, U any](values []T, operation func(T) (U, error)) ([]U, error)

func NearestIndex

func NearestIndex(ppm []float64, target float64) (int, error)

NearestIndex returns the zero-based position closest to the requested ppm.

func OrderFloat

func OrderFloat(values []float64, decreasing bool) []int

func PPMResolution

func PPMResolution(ppm []float64) (float64, error)

func PadZeros

func PadZeros(values []float64, count int, side string) ([]float64, error)

func PasteColumns

func PasteColumns(columns [][]string, separator, collapse string) ([]string, error)

PasteColumns implements vector recycling for the useful base-R paste core.

func PseudoVoigt

func PseudoVoigt(x, center, width, asymmetry, eta float64) float64

func RMSError

func RMSError(reference, sample []float64) (float64, error)

func RandomNormal

func RandomNormal(count int, mean, standardDeviation float64, seed int64) ([]float64, error)

func RandomSample

func RandomSample(values []float64, count int, replacement bool, seed int64) ([]float64, error)

func RandomUniform

func RandomUniform(count int, minimum, maximum float64, seed int64) ([]float64, error)

func RawToHex

func RawToHex(values []byte) string

func ReadBinaryFile

func ReadBinaryFile(path, kind, endian string, offset int64, count int) (any, error)

func ReadChar

func ReadChar(data []byte) string

Explicit typed entry points for every helper-complete reader identified by the multiplied function/helper matrix.

func ReadFloat32

func ReadFloat32(data []byte, endian string) ([]float32, error)

func ReadInt16

func ReadInt16(data []byte, endian string) ([]int16, error)

func ReadInt32

func ReadInt32(data []byte, endian string) ([]int32, error)

func ReadUint16

func ReadUint16(data []byte, endian string) ([]uint16, error)

func RegexReplace

func RegexReplace(values []string, pattern, replacement string, all bool) ([]string, error)

func RemoveDCOffset

func RemoveDCOffset(values []float64, tailPoints int) ([]float64, error)

func RepVector

func RepVector(values []float64, times, each int) ([]float64, error)

func ReplicateValues

func ReplicateValues[T any](count int, operation func(int) (T, error)) ([]T, error)

func Run

func Run(args []string, input io.Reader, output io.Writer) error

Run executes the JSON command-line interface against the supplied streams. It is exported so applications can embed the CLI without spawning a process.

func SegmentPeakList

func SegmentPeakList(peakList []int, start, end int) []int

SegmentPeakList translates speaq's findSegPeakList to zero-based indices relative to start. Bounds are exclusive, matching the R comparisons.

func SeqInclusive

func SeqInclusive(start, end, step int) ([]int, error)

func SeqLen

func SeqLen(length int) ([]int, error)

func SeqRows

func SeqRows(matrix DenseMatrix) [][]float64

func SetDiffFloat

func SetDiffFloat(left, right []float64) []float64

func ShiftAxis

func ShiftAxis(ppm []float64, offset float64) []float64

func ShiftPolynomialZero

func ShiftPolynomialZero(coefficients []float64, zero float64) ([]float64, error)

ShiftPolynomialZero ports ptw's calc.zerocoef coefficient transform.

func ShiftSeries

func ShiftSeries(values []float64, points int, padding string) ([]float64, error)

ShiftSeries moves intensity samples without wrapping. Positive point counts move the signal right; negative counts move it left.

func SplitVector

func SplitVector(values []string, separator string, fixed bool) ([][]string, error)

func StandardError

func StandardError(values []float64) (float64, error)

func StartsWithVector

func StartsWithVector(values []string, prefix string) []bool

func UniqueFloat

func UniqueFloat(values []float64) []float64

func UnitVector

func UnitVector(values []float64) ([]float64, error)

UnitVector is the typed equivalent of ChemoSpec's .normVec.

func UpperVector

func UpperVector(values []string) []string

func WhichIndices

func WhichIndices(mask []bool) []int

WhichIndices returns R-compatible one-based indices.

func ZeroFillPowerOfTwo

func ZeroFillPowerOfTwo(values []float64, factor int) ([]float64, error)

func ZeroFillTo

func ZeroFillTo(values []float64, target int) ([]float64, error)

Types

type BatchResult

type BatchResult struct {
	Index  int    `json:"index"`
	Result any    `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

func ParallelMap

func ParallelMap(ctx context.Context, spectra [][]float64, workers int, operation func([]float64) (any, error)) ([]BatchResult, error)

ParallelMap uses a fixed worker count, preserves input order, and records per-spectrum errors instead of losing the rest of a batch.

func ParallelMapComplex

func ParallelMapComplex(ctx context.Context, spectra []PhaseSpectrum, workers int, operation func(PhaseSpectrum) (any, error)) ([]BatchResult, error)

type BinnedXY

type BinnedXY struct {
	MeanX []float64 `json:"mean_x,omitempty"`
	SumY  []float64 `json:"sum_y,omitempty"`
}

func BinData

func BinData(x, y []float64, width int) (BinnedXY, error)

BinData ports ChemoSpec's .binData core: incomplete leading points are discarded, x bins are averaged, and intensity bins are summed.

type CenterSpread

type CenterSpread struct {
	Y    float64 `json:"y"`
	YMin float64 `json:"ymin"`
	YMax float64 `json:"ymax"`
}

func CenterSpreadInterval

func CenterSpreadInterval(values []float64, method string) (CenterSpread, error)

CenterSpreadInterval ports ChemoSpec's .seXy interval helpers. Supported methods are se, ci95, iqr (Tukey hinges), and mad (R's default 1.4826 scale).

type DenseMatrix

type DenseMatrix struct {
	Rows        int       `json:"rows"`
	Cols        int       `json:"cols"`
	Data        []float64 `json:"data"`
	ColumnNames []string  `json:"column_names,omitempty"`
}

func CBind

func CBind(matrices ...DenseMatrix) (DenseMatrix, error)

func CrossProduct

func CrossProduct(left, right DenseMatrix) (DenseMatrix, error)

func EmbedVector

func EmbedVector(values []float64, dimension int) (DenseMatrix, error)

func ExpandGrid

func ExpandGrid(columns [][]float64) (DenseMatrix, error)

func MatMul

func MatMul(left, right DenseMatrix) (DenseMatrix, error)

func NewDenseMatrix

func NewDenseMatrix(rows, cols int, data []float64) (DenseMatrix, error)

func ScaleColumns

func ScaleColumns(matrix DenseMatrix, center, scale bool) (DenseMatrix, error)

func SweepMatrix

func SweepMatrix(matrix DenseMatrix, margin int, statistics []float64, operation string) (DenseMatrix, error)

func TransposeMatrix

func TransposeMatrix(matrix DenseMatrix) (DenseMatrix, error)

type InterpolationRequest

type InterpolationRequest struct {
	X    []float64 `json:"x"`
	Y    []float64 `json:"y"`
	NewX []float64 `json:"new_x"`
}

type MatrixSummary

type MatrixSummary struct {
	RowSums  []float64 `json:"row_sums"`
	RowMeans []float64 `json:"row_means"`
	ColSums  []float64 `json:"column_sums"`
	ColMeans []float64 `json:"column_means"`
}

func MatrixSummaries

func MatrixSummaries(matrix DenseMatrix) (MatrixSummary, error)

type NoiseEstimate

type NoiseEstimate struct {
	Method string  `json:"method"`
	Value  float64 `json:"value"`
}

func EstimateNoise

func EstimateNoise(values []float64, method string) (NoiseEstimate, error)

type NumericQC

type NumericQC struct {
	Count             int     `json:"count"`
	Minimum           float64 `json:"minimum"`
	Maximum           float64 `json:"maximum"`
	Mean              float64 `json:"mean"`
	SampleVariance    float64 `json:"sample_variance"`
	StandardDeviation float64 `json:"standard_deviation"`
	RMS               float64 `json:"rms"`
}

func SummarizeNumeric

func SummarizeNumeric(values []float64) (NumericQC, error)

SummarizeNumeric computes stable one-pass quality-control statistics.

type Peak

type Peak struct {
	Index     int     `json:"index"`
	Intensity float64 `json:"intensity"`
}

func LocalMaxima

func LocalMaxima(spectrum []float64) []Peak

LocalMaxima follows the plateau-aware rule generated from speaq's returnLocalMaxima. Indices are zero-based in the Go API.

type PhaseSpectrum

type PhaseSpectrum struct {
	Real []float64 `json:"real"`
	Imag []float64 `json:"imag"`
}

func ApodizeComplex

func ApodizeComplex(input PhaseSpectrum, kind string, dwellTime, parameter float64) (PhaseSpectrum, error)

func FFTShift

func FFTShift(input PhaseSpectrum) (PhaseSpectrum, error)

func FourierTransform

func FourierTransform(input PhaseSpectrum, inverse bool) (PhaseSpectrum, error)

FourierTransform computes a complex discrete Fourier transform. Inverse transforms are normalized, so inverse(forward(x)) returns x.

func PhaseCorrect

func PhaseCorrect(real, imag []float64, phi0, phi1 float64, reverse bool) (PhaseSpectrum, error)

PhaseCorrect applies zero- and first-order phase correction in degrees.

func SimulateComplexNoise

func SimulateComplexNoise(count int, standardDeviation float64, seed int64) (PhaseSpectrum, error)

type RawFunctionInfo

type RawFunctionInfo struct {
	Name    string `json:"name"`
	Topic   string `json:"topic"`
	Package string `json:"package"`
	Source  string `json:"source"`
}

type RegionRequest

type RegionRequest struct {
	PPM       []float64    `json:"ppm"`
	Intensity []float64    `json:"intensity"`
	Regions   [][2]float64 `json:"regions,omitempty"`
}

type RunLength

type RunLength struct {
	Value  float64 `json:"value"`
	Length int     `json:"length"`
}

func RunLengths

func RunLengths(values []float64) []RunLength

type SNRResult

type SNRResult struct {
	Ratio float64 `json:"ratio"`
	DB    float64 `json:"db"`
}

func SignalNoiseRMS

func SignalNoiseRMS(signal, noise []float64) (SNRResult, error)

SignalNoiseRMS reports RMS(signal)/RMS(noise), plus the equivalent decibels.

type SpectrumXY

type SpectrumXY struct {
	X []float64 `json:"x"`
	Y []float64 `json:"y"`
}

func CropSpectrum

func CropSpectrum(ppm, intensity []float64, minimum, maximum float64) (SpectrumXY, error)

func ExcludeRegions

func ExcludeRegions(ppm, intensity []float64, regions [][2]float64) (SpectrumXY, error)

Directories

Path Synopsis
cmd
gonmr command
transpiled
raw-all-r2go-v2.1/17_misc_review_required/ChemoSpec/R/r2go_runtime/cir
Package cir provides the C intermediate representation used to lower GNU R entry points into data-driven Pure-Go programs.
Package cir provides the C intermediate representation used to lower GNU R entry points into data-driven Pure-Go programs.
raw-all-r2go-v2.1/17_misc_review_required/ChemoSpec/R/r2go_runtime/converted/rgo
Code generated by r2go-importconverted; DO NOT EDIT.
Code generated by r2go-importconverted; DO NOT EDIT.
raw-all-r2go-v2.1/17_misc_review_required/ChemoSpec/R/r2go_runtime/runtime
Code generated by r2go-sourcegraph; DO NOT EDIT.
Code generated by r2go-sourcegraph; DO NOT EDIT.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL