Package 'nirs4all'

Title: Composable Near-Infrared Spectroscopy Pipelines for R
Description: Provides an R-facing pipeline API for near-infrared spectroscopy. Composes portable preprocessing (including local and robust normalization, area normalization, detrending, train-fitted MSC and Savitzky-Golay filtering) and partial least squares operations from 'n4m' with explicit R learner controllers, including native sparse PLS-DA and post-SIMPLS group-sparse PLS, optional 'parsnip' and 'mlr3' regression and classification adapters, 'ranger' probability-forest and optional 'xgboost' regression and classification controllers, and optional CPU 'torch' regression and classification controllers. Offers local fit, predict, portable 'n4m' model and bounded trained-pipeline serialization, and a native 'dagml' cross-validation, fixed-candidate selection, refit and replay path for single-node pipelines and optional sequential n4m transform nodes, including fixed-candidate selection and parallel preprocessing branches joined and composed with sequential preprocessing before a model. Native-only n4m refit artifacts are detached into portable N4MM bytes in the DAG bundle; other persisted refit models and transform states remain R sidecars. Both can predict new R samples. Optional 'nirs4allformats' datasets feed local and native paths with numeric or categorical targets while preserving sample and spectral-axis identities. Shared native dense-regression workflows provide out-of-fold selection, resumable hyperparameter search, experiment result views, held-out split conformal calibration and frozen robustness audits. Complete native multimodal predictors preserve aligned raw source schemas and portable fitted state.
Authors: Gregory Beurier [aut, cre], nirs4all contributors [ctb]
Maintainer: Gregory Beurier <[email protected]>
License: CeCILL-2.1 | AGPL (>= 3)
Version: 0.8.0
Built: 2026-11-20 12:42:23 UTC
Source: https://github.com/GBeurier/nirs4all-r

Help Index


Define an area-normalization preprocessing step

Description

Use libn4m's native spectrum-area normalization.

Usage

nirs4all_area_normalization(method = "sum")

Arguments

method

One of "sum", "abs_sum", or "trapz".

Value

A preprocessing step for nirs4all_pipeline().


Calibrate and audit frozen native regression predictions

Description

Attach native split conformal calibration from a held-out labelled cohort to a frozen archive, replay prediction intervals, evaluate keyed truth, and audit observed or seeded spectral-noise scenarios. Native validation rejects training/calibration identity overlap and incompatible schemas. Positional prediction requires explicit sample IDs; structured datasets retain their own IDs. Metrics require untouched native JSON attached to calibration and prediction results. Robustness audits do not retrain the model.

Usage

nirs4all_calibrate(model, data, coverages = c(0.9), small_sample_policy = "error", source_id = "spectra",
    archive = tempfile(fileext = ".n4a"), methods_library = Sys.getenv("N4M_LIBRARY_PATH",
        Sys.getenv("N4M_LIB_PATH")), cli = Sys.getenv("NIRS4ALL_CORE_CLI"))

nirs4all_predict_calibrated(model, X, sample_ids = NULL, methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
    cli = Sys.getenv("NIRS4ALL_CORE_CLI"), source_id = NULL)

nirs4all_conformal_metrics(model, prediction, y, sample_ids, cli = Sys.getenv("NIRS4ALL_CORE_CLI"))

nirs4all_export_calibrated(model, path)

nirs4all_load_calibrated(path, cli = Sys.getenv("NIRS4ALL_CORE_CLI"))

nirs4all_robustness(model, X, y, sample_ids = NULL, scenarios = NULL, methods_library = Sys.getenv("N4M_LIBRARY_PATH",
    Sys.getenv("N4M_LIB_PATH")), cli = Sys.getenv("NIRS4ALL_CORE_CLI"), source_id = NULL)

Arguments

model

Native workflow, calibrated object, or native archive path as supported by the operation.

data

IO dataset record, dataset object, or native JSON dataset file.

coverages

Requested split conformal coverage probabilities.

small_sample_policy

Native small-sample policy, error or unbounded.

source_id

Selected dense source identifier; for structured uncertainty, optional source selection.

archive

New output native archive path.

methods_library

Path to the installed native libn4m shared library.

cli

Core archive executable, or DAG-ML executable for the local workflow. Native objects retain the supplied runtime path.

X

Finite samples-by-features matrix, or a structured dataset on uncertainty routes.

sample_ids

Ordered unique sample IDs. Structured uncertainty inputs use their own IDs instead.

prediction

Untouched result from native calibrated prediction.

y

Numeric target values aligned to the feature rows or explicit sample IDs.

path

New output file, or an existing native archive when loading or replaying.

scenarios

Native frozen-audit scenario records; defaults to observed and seeded Gaussian spectral noise.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Concatenate parallel preprocessing branches

Description

Each branch starts from the same input matrix. Train-fitted states, such as MSC references, are learned independently on the training rows of their branch. Output columns are prefixed by the branch name.

Usage

nirs4all_concat(branches)

Arguments

branches

Named list of at least two non-empty lists of nirs4all steps.

Value

A composable nirs4all preprocessing step.


Define learner controllers

Description

Provides an n4m PLS controller, base-R linear-model controller, optional ranger classification and regression controllers, a glmnet regression controller, and a custom-controller constructor. Only the n4m fitted model has a cross-language N4MM representation.

Usage

nirs4all_controller(fit, predict, name, task = "regression", predict_proba = NULL)
nirs4all_pls(n_components = 2L, algo = "pls_simpls",
             center_x = TRUE, scale_x = TRUE,
             center_y = TRUE, scale_y = TRUE)
nirs4all_lm()
nirs4all_ranger(num.trees = 500L, seed = 1L, ...)
nirs4all_ranger_classifier(num.trees = 500L, seed = 1L, ...)
nirs4all_glmnet(lambda, alpha = 1, standardize = TRUE)

Arguments

fit

Function of transformed X and y returning fitted state.

predict

Function of fitted state and transformed X returning numeric predictions.

name

Non-empty controller label.

task

Regression or classification task kind.

predict_proba

Optional function of fitted state and transformed X returning a class probability matrix.

n_components

Positive PLS component count.

algo

n4m PLS solver name.

center_x, scale_x, center_y, scale_y

Native n4m centering and scaling flags.

num.trees

Positive forest size.

seed

Non-negative ranger seed.

...

Additional ranger arguments, excluding reserved fit arguments.

lambda

Positive glmnet regularization strength.

alpha

Elastic-net mixing value from zero (ridge) to one (lasso).

standardize

Whether glmnet standardizes features internally.

Value

A learner controller accepted by nirs4all_pipeline.


Replay a native Core N4a package through native DAG and Methods processes

Description

Core owns the physical N4a V1 container (schema 1), inventory closure, entrypoint resolution and hashes; the native Package schema (2 predictor, 3 refit) is reported separately as package_schema_version. DAG-ML owns package validation, signed replay scheduling and portable-artifact hydration/release. The R adapter passes current buffers to installed Methods numerical operations. No Python interpreter, R ZIP parser or R machine-learning coordinator is used.

Usage

nirs4all_core_archive(path, core_cli = Sys.which("nirs4all-core-archive"),
  entrypoint = NULL)

nirs4all_core_archive_predict(archive, request, data_envelopes, adapter,
  trusted_controllers, dag_cli = Sys.which("dag-ml-cli"),
  workdir = tempfile("nirs4all-core-replay-"),
  outcome_id = "outcome:nirs4all-r.core.replay",
  run_id = "run:nirs4all-r.core.replay", process_timeout_ms = 0)

nirs4all_core_archive_predict_methods(archive, request, data_envelopes,
  methods_inputs, methods_library, methods_library_sha256,
  workdir = tempfile("nirs4all-core-methods-"),
  outcome_id = "outcome:nirs4all-r.core.methods",
  run_id = "run:nirs4all-r.core.methods")

nirs4all_core_multimodal_adapter(sources, operators, node_params, source_ids,
  controller_manifest, trusted_manifest, target_names = "y",
  workdir = tempfile("nirs4all-core-r-adapter-"))

Arguments

path

A Core N4a V1 .n4a container with a native Package schema 2 or 3 root.

core_cli

Installed native Core archive executable.

entrypoint

Optional declared entrypoint ID forwarded to Core; when NULL Core resolves the unique matching entrypoint or refuses.

archive

Validated reference returned by nirs4all_core_archive.

request

Signed native TrainingReplayRequest list or exact JSON file.

data_envelopes

Native map of target-free prediction envelopes, as a list or exact JSON file.

adapter

Executable persistent R process adapter, or an adapter preparation result.

trusted_controllers

Independently installed controller manifests, as a list or exact JSON file.

dag_cli

Installed native DAG-ML executable.

workdir

New or empty directory for contracts and lifecycle/output logs.

outcome_id, run_id

Explicit native replay identifiers.

process_timeout_ms

Native worker timeout; zero is unbounded.

methods_inputs

Native map of explicit ordered sample IDs, numerical matrix x and target names. Target values y are refused.

methods_library

Exact native libn4m file for callback-free replay.

methods_library_sha256

Independently attested lowercase SHA-256 of the Methods library.

sources

Four named raw source declarations: nir, image, series, metadata.

operators, node_params

Current native operator and effective parameter maps.

source_ids

Explicit ordered native source identifiers.

controller_manifest

Expected signed producer manifest.

trusted_manifest

Independently installed current manifest for that producer.

target_names

One ordered target name for the closed raw native profile.

Details

The raw multimodal adapter reuses the closed U07 scaler, tensor-PCA, mixed-column and Ridge profile with fixed declared shapes. It preserves the original native Python/R/WASM/Octave producer owner. Fitting, REFIT, HPO and target access are refused. Other independently trusted, installed native process adapters can be supplied when they implement the archive's profile.

Requests and current data envelopes are native contracts supplied explicitly; they are not constructed by reading or trusting the archive. An archive object retains its raw SHA and prediction revalidates the original file. This POSIX process surface requires the Core and DAG native executables and installed n4m. It does not accept historical Python joblib bundle archives, nor pre-V1 ZIP archives (Core refuses them; there is no fallback).

nirs4all_core_archive_predict_methods is the direct callback-free route for supported N4MM, N4ME and RolePipeline packages produced by native Methods controllers. It calls Core's existing Package 2/3 replay, which delegates package validation and scheduling to DAG-ML and numerical state import/prediction to Methods. The explicit library hash pins an exact private loaded snapshot and checks the Methods ABI. The raw U07 controller has a distinct identity and uses the process route; it is not substituted for a native Methods controller.

Value

Archive opening returns a validated reference holding Core's native view (archive_id, full-file archive_sha256, package_schema_version, entrypoint, operation, package_member) and the neutral V1 manifest. Prediction returns the native replay outcome and workdir. Adapter preparation returns its executable, independent manifests, workdir and lifecycle log path.


Run a native DAG-ML CV, refit and predict campaign from R matrices

Description

Builds an explicit fold campaign. DAG-ML owns phase scheduling, out-of-fold evidence, variant selection, refit and replay. Eligible native-only n4m refits carry N4MM bytes in the DAG bundle; other fitted states remain RDS sidecars. A named list of pipelines compares fixed candidates by OOF RMSE for regression or accuracy for classification, then refits the winner. With split_steps = TRUE, each preprocessing step is a separate DAG node; n4m feature branches and joins may be composed with sequential steps. The replay cohort is the training cohort, not an independent test set. Arbitrary model branching and adaptive HPO are not yet exposed.

Usage

nirs4all_dag_cv_refit_predict(pipeline, X, y = NULL, folds = 5L,
  sample_ids = NULL, root_seed = 1L, cli = Sys.which("dag-ml-cli"),
  workdir = tempfile("nirs4all-dag-"), process_workers = 1L,
  group_ids = NULL, split_steps = FALSE, splitter = NULL)

Arguments

pipeline

Pipeline definition with a built-in learner, or a named list of at least two such pipelines to compare by native OOF score. Seeded native augmentations, when present, apply only to each training fold and refit X.

X

Finite numeric samples-by-features matrix or a nirs4all_dataset from nirs4all_from_formats().

y

Finite numeric regression target or factor/character class labels; omit for a dataset.

folds

Integer number of non-shuffled folds.

sample_ids

Optional unique sample IDs aligned to X and y.

root_seed

Non-negative DAG-ML root seed.

cli

Path to the dag-ml-cli executable.

workdir

New or empty output directory.

process_workers

Positive process-adapter worker count.

group_ids

Optional group ID per sample. Named vectors must match sample_ids exactly. Validation folds preserve whole groups.

split_steps

If TRUE, run each n4m preprocessing step as a separate DAG transform node. Named variants must have the same number of steps; their methods and parameters may differ. Each nirs4all_concat() step is lowered to parallel branch transforms and a feature-join node; concat steps may be composed with other preprocessing steps but cannot yet be combined with variants. Train-only augmentations are refused with split_steps because that would change their position relative to preprocessing.

splitter

Optional nirs4all_native_splitter() specification for SPXY fold, grouped SPXY fold or binned stratified group fold. Its n_splits must equal folds; one-shot splits are refused.

Value

Native DAG-ML outcome list with the persisted workdir path.


Predict new samples from a native DAG-ML refit artifact

Description

Checks the SHA-256 fingerprints of the winning native N4MM payload or R model and any preceding transform artifacts, then predicts new samples locally. A native-only raw bundle does not need its original workdir; RDS sidecars still do. This does not run a new DAG-ML PREDICT phase or score the new cohort. Load only trusted RDS artifacts.

Usage

nirs4all_dag_predict(outcome, X)

Arguments

outcome

Result of nirs4all_dag_cv_refit_predict(). RDS-backed results need their persistent workdir; native-only raw bundles do not.

X

Finite numeric samples-by-features matrix or a nirs4all_dataset from nirs4all_from_formats().

Value

Numeric regression predictions or factor class predictions in input row order.


Prepare a native Methods multimodal DAG process adapter

Description

Prepares a persistent JSONL Methods regression controller for an existing native DAG-ML plan with named numeric sources and native upstream OOF inputs. Native Methods owns fitting, prediction and opaque N4ME state. DAG-ML owns signing, folds, OOF construction, selection, refit and replay.

Usage

nirs4all_dag_role_adapter(sources, operators, controller_manifest,
  trusted_manifest, targets = NULL, target_names = "y", allow_fit = FALSE,
  workdir = tempfile("nirs4all-role-adapter-"))

Arguments

sources

Named list of numeric source tables, each with a finite matrix X, explicit unique sample_ids, and optional ordered feature_names. Column names are used when present; otherwise names are zero-based positional strings. Each source may have an independent row order.

operators

Named map of model node IDs to their current compiled native operators: n4m:<method-id> or N4mRolePipeline recipes.

controller_manifest

Native DAG-ML model manifest for controller:methods.r.regression, version 1.0.0.

trusted_manifest

Independently trusted current installed manifest. Must equal controller_manifest; a package cannot supply its own trust.

targets

Optional table with numeric values and explicit unique sample_ids. Values is a vector or samples-by-targets matrix.

target_names

Unique ordered response names.

allow_fit

Explicitly allow FIT_CV/REFIT; defaults to FALSE. A replay adapter must receive no target values.

workdir

New or empty local directory for the adapter config and launcher.

Details

Use the executable with native DAG-ML process wrappers. Validate training/replay signatures, plans, complete artifact coverage and signed controller manifests against independently trusted current manifests in native DAG-ML before invoking callbacks. This adapter does not implement canonical fingerprints, search spaces or a scheduler.

The RAW codec is dagml.methods.regression.v1, with plugin dagml.methods.r.regression, version 1.0.0. It preserves the ordered native recipe and requires one N4ME state per declared step. Export refuses retained training rows. Hydration verifies artifact identity, hashes, size and relative URI; prediction verifies the full effective current recipe and independently resolved ordered feature names. Native pointers are released on success, worker close and failure, using the upstream n4m R finalizer. Only locally trusted RDS configs are read.

The numeric regression profile excludes raw N-D encoders, classification, generated-view consumption attestations, custom losses, residual targets, additional FIT_CV test streams and nonuniform fit influence. It currently requires a POSIX shell. Existing matrix/N4MM APIs are separate and unchanged.

Value

List with executable adapter, manifest, workdir and audit_path containing lifecycle metadata.


Construct aligned datasets and replay complete multimodal state

Description

Normalize a raw dataset through native IO, compose the supported four-source scaler/tensor-PCA/mixed-column/Ridge profile through n4m, and persist complete native N4MF state with its IO schemas. Prediction requires a target-free prediction cohort. Native archive replay additionally uses Core and a persistent DAG-ML R adapter; this process route requires POSIX. Native numerical algorithms and parsers stay in their upstream packages.

Usage

nirs4all_dataset(value, core_cli = Sys.which("nirs4all-core-archive"))

nirs4all_multimodal_fit(recipe, dataset, core_cli = Sys.which("nirs4all-core-archive"))

nirs4all_multimodal_export(object, path = NULL)

nirs4all_multimodal_load(value, core_cli = Sys.which("nirs4all-core-archive"))

nirs4all_multimodal_archive_predict(path, dataset, core_cli = Sys.which("nirs4all-core-archive"), dag_cli = Sys.which("dag-ml-cli"),
    workdir = tempfile("nirs4all-raw-archive-"), adapter_script = system.file("adapters", "nirs4all_core_multimodal_adapter.R",
        package = "nirs4all"), entrypoint = NULL)

Arguments

value

Native dataset or predictor envelope, or its JSON file.

core_cli

Core archive executable; an executable name is resolved through PATH.

recipe

Complete native multimodal recipe for the supported four-source profile.

dataset

IO dataset record, dataset object, or native JSON dataset file.

object

Workflow, tuning result, multimodal predictor or result view returned by the corresponding API.

path

New output file, or an existing native archive when loading or replaying.

dag_cli

Installed DAG-ML executable for native process replay.

workdir

New or empty native working directory to retain.

adapter_script

Installed persistent R adapter script for target-free archive replay.

entrypoint

Optional named container entrypoint for native replay.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Define a polynomial detrend preprocessing step

Description

Use libn4m to remove a per-spectrum polynomial baseline.

Usage

nirs4all_detrend(polyorder = 1L)

Arguments

polyorder

Non-negative baseline polynomial order.

Value

A preprocessing step for nirs4all_pipeline().


Access upstream domain namespaces

Description

Compatibility accessors moved from the former nirs4all-core R facade.

Usage

formats()

io()

datasets()

methods()

dag_ml()

dag_ml_data()

Value

The loaded upstream R package namespace.


Define a train-fitted Extended Multiplicative Scatter Correction step

Description

Uses native n4m EMSC. Each fit learns a reference solely from its training rows; validation and prediction reuse that reference.

Usage

nirs4all_emsc(degree = 2L)

Arguments

degree

Positive polynomial degree; at least degree + 2 features are required.

Value

A nirs4all_step definition.


Native execution profiles and the R federation record

Description

Returns the profile registry published by nirs4all-core (nirs4all-core.execution-profiles.v1). It declares five native profiles at version 1: native-workflow@1, native-conformal@1, native-methods-package@1, native-n4a-canonical@1 and n4a-container@1, with per-operation supported/unsupported entries (compile, fit, predict, import, export) for each Core runtime surface, per-surface runtime requirements, and the current content declared per operation, surface and route (content_routes): which route returns a host object, which carries the Core wrapper JSON schema id nirs4all.calibrated.v1, and which transfers the native archive V2 bytes. external_federation holds the record for this package, which is outside Core's runtime surfaces and references those five profiles. The entries are a metadata contract: readability, execution support and scientific qualification are separate, and it is not a numerical certification.

Usage

nirs4all_execution_profiles()

Value

A fresh list decoded from the embedded registry; modifying it never changes later calls.


Expand a bounded Python-style generator recipe into R pipelines

Description

No-fit operation. The complete original definition is sent to the Core portable-pipeline-expand command, which owns the _or_ / _cartesian_ structural generators (left-to-right product, first axis slowest), the inclusive component ranges of each structural variant, the search bounds and the refusals (modifiers, nested generators, splitters, unknown roots or intents). R only builds one unfitted nirs4all_pipeline() per returned concrete definition, in the owner's order, with nirs4all_pipeline_from_portable(); it generates and enumerates nothing and has no local fallback. Requires a nirs4all-core-archive build that provides portable-pipeline-expand (no Methods library, no dataset, no fit). Pass the resulting named list to nirs4all_dag_cv_refit_predict() for native CV/OOF selection and refit.

Usage

nirs4all_expand_portable_pipelines(source, core_cli = NULL)

Arguments

source

Definition accepted by nirs4all_load_pipeline().

core_cli

Optional nirs4all-core-archive executable (or "" for NIRS4ALL_CORE_CLI/PATH).

Value

Named list (variant_0001, variant_0002, ...) of unfitted nirs4all_pipeline() variants.


Export a fitted native pipeline as portable N4MM bytes

Description

Accepts plain SIMPLS (format 1/3), a preprocessing-free n4m MethodResult affine predictor (format 1), or the native SNV to Savitzky-Golay to SIMPLS profile embedded in the model (format 2/3). Export the unfitted recipe separately with nirs4all_export_pipeline() when transferring it to another language. The affine bytes preserve prediction only; they do not attest the fitting algorithm or support retraining. These bytes are model state, not a full DAG-ML Archive V2/V3.

Usage

nirs4all_export_native_model(object)

Arguments

object

A fitted nirs4all_fit() result.

Value

Raw N4MM format-1, format-2 or format-3 bytes.


Export a qualified R pipeline recipe

Description

Exports n4m-backed preprocessing, including train-fitted n4m.SPA and the native dispatcher n4m.Selector, with Python's named feature-branch plus merge: features syntax. A closed train_augmentation prefix uses n4m.NativeXAugmentation, exact positional values and a required seed; R applies it only after splitting to training X. Other consumers must implement the same phase contract before claiming recipe portability. The generic selector carries its method, component count and native method parameters; it is an R/Python n4m fit recipe and does not assert per-method Core/WASM parity. The default cross-language scope accepts qualified native models and refuses non-default SNV because Core/WASM currently ignores its parameters. The R-native scope accepts selected ranger, glmnet and torch MLP controllers with explicitly R-namespaced model aliases but refuses train augmentation nodes. Those model aliases and their trained binaries are not portable to Python/WASM. This is a fit recipe, not trained model or fitted preprocessing state.

Usage

nirs4all_export_pipeline(pipeline, format = c("json", "yaml"),
                        file = NULL, name = "pipeline",
                        scope = c("cross_language", "r_native"))

Arguments

pipeline

An unfitted nirs4all_pipeline().

format

"json" or "yaml".

file

Optional output path. If omitted, serialized text is returned.

name

Pipeline name in the exported definition.

scope

"cross_language" for the qualified n4m-only recipe (the default), or "r_native" for an R-specific learner recipe. The latter is not a Python/WASM model alias and permits non-default SNV parameters.

Value

Serialized text, invisibly if file is provided.


Export a trained native pipeline for R/Python replay

Description

Serializes a portable n4m recipe, fitted preprocessing state and the exact N4MM model payload in one JSON document. No RDS, Python pickle or executable code is included. Versions 1–5 cover native PLS, sparse PLS-DA, selector and qualified affine profiles. Version 6 combines a fitted N4MP preprocessing chain and N4MM predictor. Version 7 adds an ordered train-only n4m.NativeXAugmentation recipe to that profile. Prediction skips augmentation; retraining reapplies it before fitting preprocessing. The N4MM payload does not attest the original augmentation or fitting-method history, so the recipe is an assertion rather than cryptographic provenance. Version 8 covers any recipe of generic n4m role steps (nirs4all_fit_role_recipe): each fitted step travels as its native N4ME state with a SHA-256 and a flag saying whether it keeps training rows, readable by every n4m binding; the input column names travel too when the pipeline was fitted on a matrix with column names.

Usage

nirs4all_export_trained_pipeline(object, file = NULL, allow_training_rows = FALSE)

Arguments

object

A fitted native n4m PLS, affine MethodResult, sparse PLS-DA or generic n4m role pipeline.

file

Optional output path. If omitted, returns JSON text.

allow_training_rows

Some fitted role steps (kernel and local models, for example) keep training rows in their state. Their export is refused unless this is TRUE, which copies those rows into the envelope. Other envelope versions carry no training rows.

Value

JSON text, invisibly when file is supplied.


Fit and predict with a local R pipeline

Description

Applies n4m preprocessing and delegates model fitting and prediction to the selected controller. This local fit/predict path is not a DAG-ML CV or HPO campaign.

Usage

nirs4all_fit(pipeline, X, y = NULL, preprocessing = c("legacy", "native_n4mp"))
nirs4all_predict(object, X)
nirs4all_predict_proba(object, X)
## S3 method for class 'nirs4all_fitted'
predict(object, newdata, ...)

Arguments

pipeline

Pipeline definition.

X

Finite numeric samples-by-features matrix or a nirs4all_dataset from nirs4all_from_formats().

y

Finite numeric regression targets or factor/character class labels, one element per row; omit for a dataset.

preprocessing

"legacy" preserves the existing path; "native_n4mp" fits a bounded, linear native N4MP chain for portable regression and rejects unsupported step semantics.

object

Fitted pipeline.

newdata

Prediction matrix or nirs4all_dataset.

...

Unused; retained for the S3 generic.

Value

nirs4all_fit returns a fitted pipeline. Regression prediction returns a numeric vector (a samples-by-responses matrix for an n4m role pipeline fitted on several responses, see nirs4all_fit_role_recipe); classification prediction returns a factor, and nirs4all_predict_proba returns a samples-by-classes probability matrix whose columns follow the training class order and are named by the class labels (the label table of an n4m role pipeline ending with a classifier).


Fit a recipe of generic n4m role steps

Description

Steps are "n4m:<catalog method id>" tokens (or list(class = token, params = list(...))): sample filters (they drop training rows), then transformers and selectors, then one regressor or classifier. The recipe is an n4m native role pipeline: n4m validates it, fits every step, routes every response column to the supervised steps, and stores the column names of X (a matrix without column names is positional). The result predicts with nirs4all_predict, retrains with nirs4all_retrain and exports with nirs4all_export_trained_pipeline as a version 8 envelope that the Python, JS/WASM and Rust n4m bindings replay identically.

Usage

nirs4all_fit_role_recipe(recipe, X, y)

Arguments

recipe

A recipe list, or JSON/YAML text or file (see nirs4all_load_pipeline).

X

Numeric samples-by-features matrix.

y

Responses (a numeric vector, or a matrix with one row per sample) for a final regressor, or class labels for a final classifier. Their length must equal nrow(X): nothing is recycled.

Value

A fitted pipeline.


Convert a nirs4all-formats spectral dataset for modelling

Description

The Rust-backed nirs4allformats package owns file detection and decoding. This function checks the rectangular R view, records explicit sample and spectral-axis identities, and selects one finite numeric target or categorical label from a target column or the reader's per-record metadata. Heterogeneous axes or multidimensional signals require the lossless records interface of nirs4allformats and are not silently flattened.

Usage

nirs4all_from_formats(source, target = NULL, signal = NULL)

Arguments

source

A file path or a nirs4allformats_dataset.

target

Name of one numeric or categorical target column, or a complete categorical metadata field; NULL for prediction.

signal

Optional signal name when source is a file path.

Value

A nirs4all_dataset containing X, optional y, sample IDs, spectral axis and source metadata. Pass it directly to nirs4all_fit() or predict().


Native group-sparse PLS regression controller

Description

Fits the n4m post-SIMPLS group-penalized coefficient model. This is a predictive-coefficient approximation, not sgPLS::gPLS. Group IDs must describe the columns after any preceding pipeline transformations.

Usage

nirs4all_group_sparse_pls(n_components = 2L, group_assignment,
                           group_lambda = 0.05)

Arguments

n_components

Positive number of SIMPLS components.

group_assignment

Non-negative integer group ID for each transformed feature; optional names must match transformed feature names in order.

group_lambda

Finite non-negative coefficient group penalty.


Import native N4MM pipeline state against an explicit R recipe

Description

The n4m decoder validates the bytes and any embedded preprocessing profile. A mismatched R recipe or feature width is refused. The caller supplies the recipe and, if relevant, the original ordered feature names. For plain PLS, scaling flags are caller assertions because the native descriptor does not expose those training flags. For an affine N4MM, the supplied MethodResult method and parameters are likewise caller assertions: the wire format identifies the predictor, not its training algorithm.

Usage

nirs4all_import_native_model(bytes, pipeline, feature_names = NULL)

Arguments

bytes

Raw N4MM format-1, format-2 or format-3 bytes.

pipeline

Matching unfitted nirs4all_pipeline() definition or its portable JSON/YAML recipe.

feature_names

Optional ordered feature names from training.

Value

A fitted pipeline that predicts directly on raw spectra.


Import a trained native pipeline from R or Python

Description

Validates the closed portable envelope, recipe, fitted references or selector indices, payload hashes and native N4MP/N4MM descriptors before returning a predictor. Version 7 requires a nonempty closed train-only augmentation prefix before the fitted N4MP chain; older schemas reject that prefix. Version 8 requires n_features to be a positive JSON integer equal to the width of the fitted states, and a classifier label table (class_names) to be a non-empty list of unique strings or finite numbers with a label for every native class ID; numeric labels stay numbers, compared by value, and an integer beyond 2^53 is refused. An envelope holding a NUL character (the JSON escape \u0000 or a NUL byte) is refused before parsing. The ordered augmentation recipe is retained for retraining but ignored during prediction. The source must be trusted as model data; no host-language code is deserialized.

Usage

nirs4all_import_trained_pipeline(source)

Arguments

source

JSON text or a path to a JSON document.

Value

A fitted pipeline accepted by nirs4all_predict().


Read a Python-style portable pipeline definition

Description

Reads the bounded portable PipelineConfigs subset inherited from the former nirs4all-core R binding. Unsupported operators are rejected when the definition is translated or run.

Usage

nirs4all_load_pipeline(source)

Arguments

source

Pipeline list, JSON/YAML text or path to a .json, .yaml or .yml file.

Value

A nirs4all_pipeline_definition.


Use the upstream DAG-ML loss and metric registry

Description

Delegates directly to dagml_local_implementation_registry() and verifies its required methods.

Usage

nirs4all_local_implementation_registry()

Value

The process-local dagml implementation registry.


Define a local SNV preprocessing step

Description

Use libn4m's sliding-window Standard Normal Variate transform.

Usage

nirs4all_local_snv(window = 11L, pad_mode = "reflect", constant_value = 0)

Arguments

window

Odd sliding-window length.

pad_mode

One of "reflect", "edge", or "constant".

constant_value

Padding value in constant mode.

Value

A preprocessing step for nirs4all_pipeline().


Optional mlr3 regression learner controller

Description

Clones the supplied learner before each fit so every fold owns independent mutable state. DAG-ML, not mlr3, controls the CV/OOF/refit phases. Only numeric one-target regression responses are currently supported.

Usage

nirs4all_mlr3(learner)

Arguments

learner

An untrained mlr3 LearnerRegr instance.


Optional mlr3 classification learner controller

Description

Clones the supplied learner for each fit and obtains class probabilities. DAG-ML, not mlr3, owns the CV/OOF/refit phases. The fitted learner remains an R-specific artifact.

Usage

nirs4all_mlr3_classifier(learner)

Arguments

learner

An untrained mlr3 LearnerClassif instance supporting probability prediction.


Define a train-fitted Multiplicative Scatter Correction step

Description

Learn a reference spectrum from training rows with the native n4m MSC operator, then reuse only that reference for validation and prediction. The reference is stored with the fitted R pipeline.

Usage

nirs4all_msc()

Value

A preprocessing step for nirs4all_pipeline().


Canonical V1 .n4a operations and owner-neutral exchange through the native Core CLI

Description

nirs4all_n4a_write and nirs4all_n4a_read exchange arbitrary owner-neutral content through the canonical container: data, recipes, results, scores and opaque models of any host. See the Details section.

These functions drive the canonical V1 .n4a container (manifest schema nirs4all.n4a.container.v1) through the n4a-inspect, n4a-produce, n4a-predict and n4a-retrain commands of nirs4all-core-archive. They are separate from the native package routes (nirs4all_core_archive*) and JSON Package routes and never fall back to them. R only transports file paths and decodes JSON: the Core, DAG and Methods owners decide which methods, targets and profiles are supported.

Usage

nirs4all_n4a_inspect(path,
  core_cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
  expected_sha256 = NULL, memory_budget_bytes = NULL)

nirs4all_n4a_produce(record_path, recipe, archive, source_id = "spectra",
  methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
  methods_library_sha256 = Sys.getenv("N4M_EXPECTED_LIBRARY_SHA256"),
  run_id = paste0("run:r:n4a:produce:", basename(tempfile())),
  container_id = paste0("r-n4a-", basename(tempfile())),
  embed_training_record = FALSE,
  core_cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
  memory_budget_bytes = NULL)

nirs4all_n4a_predict(object, record_path = NULL, partition = NULL,
  methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
  methods_library_sha256 = Sys.getenv("N4M_EXPECTED_LIBRARY_SHA256"),
  source_id = NULL, entrypoint = NULL,
  request_id = paste0("req:r:n4a:predict:", basename(tempfile())),
  run_id = paste0("run:r:n4a:predict:", basename(tempfile())),
  core_cli = NULL, memory_budget_bytes = NULL)

nirs4all_n4a_retrain(object, record_path, archive,
  methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
  methods_library_sha256 = Sys.getenv("N4M_EXPECTED_LIBRARY_SHA256"),
  run_id = paste0("run:r:n4a:retrain:", basename(tempfile())),
  container_id = paste0("r-n4a-", basename(tempfile())),
  embed_training_record = FALSE, core_cli = NULL, memory_budget_bytes = NULL)

nirs4all_n4a_write(manifest_path, members_path, destination, base = NULL,
  base_sha256 = NULL,
  core_cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
  memory_budget_bytes = NULL)

nirs4all_n4a_read(path, directory, expected_sha256 = NULL, member = NULL,
  artifact = NULL,
  core_cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
  memory_budget_bytes = NULL)

Arguments

path

Existing canonical V1 .n4a file.

core_cli

nirs4all-core-archive executable that provides the n4a-* commands. Objects remember the executable they were created with.

memory_budget_bytes

Optional allocation budget in bytes, forwarded to the CLI as the exact decimal text of --memory-budget-bytes; Core decides admission. NULL or "" (the default) sends no flag and this package adds no cap, default or memory detection. Accepted: a nonnegative whole number up to 253−12^{53}-1, or decimal digits (no sign or spaces; leading zeros are valid and forwarded as given) with a value up to "18446744073709551615". A larger number may already have been rounded and is refused: pass such budgets as text. Malformed values are refused before any CLI is resolved.

expected_sha256

Optional lowercase SHA-256 of the archive bytes to verify while inspecting or reading.

manifest_path

Existing file holding the exact manifest JSON. Lists are refused so that no array is re-encoded.

members_path

Existing JSON file holding an array of {path, file} objects: the path of each member inside the container and the binary file with its exact bytes. Relative file values resolve against the directory containing this list.

destination

New container file to create; it is never overwritten.

base

Optional existing container to update. It is never modified; the update is a new container at destination. Members that members_path does not list come from base.

base_sha256

Independently known lowercase SHA-256 of base. Required with base.

directory

New directory to receive the extracted files; it must not exist and its parent must.

member

Optional path of one member inside the container. Mutually exclusive with artifact.

artifact

Optional artifact ID whose members are extracted. Mutually exclusive with member.

record_path

Path of an IO dataset JSON file. Datasets and lists are refused because re-encoding would change the record bytes. For prediction, NULL selects the training record embedded in the container.

recipe

Native recipe: an existing JSON file, JSON text, or a list with steps and candidates. The owner validates it.

archive

New file to create; it must not exist and its parent directory must.

object

Reference returned by nirs4all_n4a_inspect, nirs4all_n4a_produce or nirs4all_n4a_retrain.

partition

Dataset partition to predict; default "predict" for an external record and "train" for the embedded one.

source_id

Data source identifier for prediction; default "spectra" or the one stored in object. Not an argument of retrain: the owner takes it from the validated package.

entrypoint

Container entrypoint; default "predict-external" with a record and "predict" without.

methods_library

Exact native libn4m file. Required.

methods_library_sha256

Independently attested lowercase SHA-256 of that library. Required; there is no default hash.

run_id, container_id, request_id

Explicit native identifiers.

embed_training_record

If TRUE, the training record is sealed into the container so that it can be predicted in-sample.

Details

nirs4all_n4a_inspect reports readability only. No Methods runtime is loaded and the executability field is always "not_evaluated"; a readable container may still be refused by an operation.

nirs4all_n4a_produce trains once through the owner and writes its sealed bytes. nirs4all_n4a_predict never refits. Its rows follow the physical row order of the record, aligned exactly once by the owner-provided sample IDs; a missing, repeated or extra ID is refused. Prediction on the embedded training record is in-sample, not a held-out score.

nirs4all_n4a_write sends the manifest file and the member list to the n4a-write command, which seals a container from those exact bytes. With base and base_sha256 it updates an immutable base: the base is verified against the given hash, left untouched, and the result is a new container. Nothing is overwritten. nirs4all_n4a_read extracts the bytes of the whole container, one member or one artifact into a new directory as member-000000.bin, member-000001.bin, ... plus the exact manifest.json. Paths inside the container are never used as operating-system paths; the owner report maps each numbered file to its archive path. Both functions return the owner report unchanged in report (decoded) and native_json (exact text), and do not rely on any particular report key. member_files and manifest_file list the extracted files. R reads no member, keeps no model and calls no Methods code: bytes in, bytes out.

Reports are decoded with jsonlite using bigint_as_char = TRUE, so integers beyond 53 bits are character strings in report; the exact numbers are always in native_json. The optional memory_budget_bytes is accepted by every n4a-* transport and only forwarded; R measures nothing and enforces nothing.

Readable is not executable: storing, reading and updating need no Methods runtime and no admission. A readable container, including one that holds an opaque host model, may still be refused by any operation that would execute it, and whether it can be executed is decided by its owner.

nirs4all_n4a_retrain calls the Core owner retrain_n4a_native: the source ID and the validated stored recipe both come from the container, so neither is an argument, and R runs no training. The source container is left untouched and owner errors are signalled unchanged as nirs4all_n4a_refusal.

Requirements: a nirs4all-core-archive that provides the n4a-* commands (otherwise a nirs4all_n4a_unavailable condition is signalled), and for produce, predict and retrain the real Methods library with its SHA-256. Refusals are signalled as conditions of class nirs4all_n4a_refusal that carry the native message in detail. The qualification test uses a standard_scale plus ridge recipe with two ordered targets; that is a profile witness, not universal support. Linux only; no Windows claim.

Value

nirs4all_n4a_write and nirs4all_n4a_read return a nirs4all_n4a_exchange list: path (written container) or directory, member_files and manifest_file, the owner report and the exact native_json.

nirs4all_n4a_inspect, nirs4all_n4a_produce and nirs4all_n4a_retrain return a nirs4all_n4a reference holding the path, the raw archive_sha256 and the native report. nirs4all_n4a_predict returns a nirs4all_n4a_prediction with sample_ids, target_names, target_units, a numeric values matrix (rownames = sample IDs, colnames = target names), source_id, partition, input_mode, and the unchanged owner replay and receipt.

Examples

## Not run: 
Sys.setenv(NIRS4ALL_CORE_CLI = "/path/to/nirs4all-core-archive")
model <- nirs4all_n4a_produce("train.json", "recipe.json", "model.n4a",
  methods_library = "/path/to/libn4m.so",
  methods_library_sha256 = "<attested sha256>", embed_training_record = TRUE)
nirs4all_n4a_inspect("model.n4a")$executability
pred <- nirs4all_n4a_predict(model, "future.json", partition = "predict",
  methods_library = "/path/to/libn4m.so",
  methods_library_sha256 = "<attested sha256>")
pred$values

## End(Not run)

Native n4m linear-method controller

Description

Exposes MethodResult regressors with affine held-out prediction. Most use (X - x_mean) %*% coefficients + y_mean; MB-PLS uses original-scale coefficients and an explicit intercept. Other n4m methods may need algorithm-specific prediction state and are deliberately excluded. MethodResult coefficients are wrapped as N4MM affine predictor bytes when serialized. These bytes preserve prediction, not the original fitting method. DI-PLS is local to this R API because its target-domain matrix is supplied as model data, not encoded in the portable recipe vocabulary. Group-sparse PLS applies native post-SIMPLS shrinkage of predictive coefficients; it is not the latent-direction estimator in sgPLS::gPLS.

Usage

nirs4all_n4m_method(method, n_components = 2L, params = list())

Arguments

method

One of ridge, ridge_pls, robust_pls, cppls, sparse_simpls, ecr, continuum_regression, mir_pls, fused_sparse_pls, bagging_pls, boosting_pls, random_subspace_pls, n_pls, mb_pls, di_pls, or group_sparse_pls.

n_components

Positive component count; ignored by ridge's solver.

params

Named method-specific parameter list. N-PLS requires positive mode_j and mode_k whose product equals the fitted feature width; MB-PLS requires positive integer block_sizes summing to the fitted feature width; boosting learning_rate must be in (0, 1]. DI-PLS requires a finite numeric X_target matrix in the same feature space the learner receives, with an optional non-negative di_lambda. Target-domain spectra are used at fit time; using evaluation spectra is transductive and must be intentional. Group-sparse PLS requires group_assignment: one non-negative integer ID per transformed feature; optional names must match transformed feature names in order. Its group_lambda is finite and non-negative.


Define a train-fitted native n4m variable selector

Description

The native selector sees only the training matrix and target. Its selected indices are validated and stored in the fitted pipeline. Later matrices are projected in original spectral order. The constructor accepts the native dispatcher selector vocabulary; cross-language parity must be established separately for each method.

Usage

nirs4all_n4m_selector(method, n_components = 2L, params = list())

Arguments

method

A supported n4m dispatcher selector name ending in _select.

n_components

Positive native component count.

params

Named list of native method parameters.


Specify a seeded n4m training-only augmentation

Description

Constructs an X-only, shape-preserving native augmentation specification. The numerical kernel runs in n4m during fit, never during validation or prediction. Mixed-Y and wavelength-axis-dependent augmenters are not exposed.

Usage

nirs4all_native_augmentation(kind, params = numeric(), seed = 0)

Arguments

kind

One of the 22 supported X-only native n4m kinds.

params

Finite positional parameter vector following the n4m native contract.

seed

Exact nonnegative integer seed, at most 2^53-1.

Value

A nirs4all_native_augmentation specification.


Run and replay the shared native archive workflow

Description

Transport an IO-owned dataset to the Core dense regression profile. Native DAG-ML owns CV, OOF selection and full-data refit; Methods owns SNV, Savitzky-Golay and PLS. Predictions use the portable archive without fitting. Export writes path-free metadata and an archive through Core's exclusive directory publisher. Loading verifies metadata against the archive's training outcome. Objects retain their CLI for subsequent operations.

Usage

nirs4all_native_run(dataset, archive, source_id = "spectra", components = c(1L, 2L), preprocessing = "snv_savgol", methods_library = Sys.getenv("N4M_LIBRARY_PATH",
    Sys.getenv("N4M_LIB_PATH")), run_id = paste0("run:r:", basename(tempfile())), results_directory = paste0(archive,
    ".results"), cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

nirs4all_native_predict(object, X, sample_ids = NULL, methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
    cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

nirs4all_native_retrain(object, dataset, archive, ..., cli = object$cli)

nirs4all_native_export(object, directory)

nirs4all_native_load(directory, cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

Arguments

preprocessing

Native preprocessing recipe, including the raw baseline and the SNV/Savitzky-Golay profile.

dataset

IO dataset record, dataset object, or native JSON dataset file.

archive

New output native archive path.

source_id

Selected dense source identifier; for structured uncertainty, optional source selection.

components

Distinct positive PLS component counts to compare by native OOF selection.

methods_library

Path to the installed native libn4m shared library.

run_id

Native run identifier.

results_directory

Directory for the native result triple emitted by the campaign.

cli

Core archive executable, or DAG-ML executable for the local workflow. Native objects retain the supplied runtime path.

object

Workflow, tuning result, multimodal predictor or result view returned by the corresponding API.

X

Finite samples-by-features matrix, or a structured dataset on uncertainty routes.

sample_ids

Ordered unique sample IDs. Structured uncertainty inputs use their own IDs instead.

...

Additional arguments forwarded to the corresponding native operation.

directory

New export directory, or an existing exported directory when loading.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Split sample identities with n4m's native engine

Description

Runs one n4m native split and returns its ordered train/test indices with corresponding sample IDs. String group labels are encoded as exact integer categories for the native engine; their original values remain available in the caller's data.

Usage

nirs4all_native_split(splitter, X, y = NULL, sample_ids = NULL,
  group_ids = NULL, fold = 1L)

Arguments

splitter

A nirs4all_native_splitter() specification.

X

Finite numeric samples-by-features matrix.

y

Finite numeric target vector for target-aware kinds.

sample_ids

Optional unique sample IDs aligned with X.

group_ids

Aligned character/factor group labels for group fold kinds only.

fold

One-based fold number for fold kinds.

Value

Native train/test indices and corresponding sample IDs.


Specify an n4m native sample splitter

Description

Creates a bounded splitter specification. n4m performs the numerical split. Only the three fold kinds can drive DAG cross-validation.

Usage

nirs4all_native_splitter(kind, ...)

Arguments

kind

One of kennard_stone, spxy, spxy_fold, spxy_group_fold, kmeans, kbins_stratified, binned_strat_group_fold, systematic_circular, or data_twinning.

...

Named kind-specific n4m parameters. Fold kinds require n_splits.

Value

A nirs4all_native_splitter specification.


Translate a portable pipeline definition

Description

Supports the bounded native subset, including Kennard-Stone holdout, a closed train_augmentation prefix, n4m preprocessing, n4m.Selector and PLS component sweeps. Augmentation nodes require n4m.NativeXAugmentation, kind, positional values and an exact seed; they must follow any splitter and precede preprocessing. The generic selector has a closed method vocabulary and native parameter schema; portable recipes require explicit top-k values and random seeds where applicable. Python-style classes, selected n4m.* aliases and language-neutral method IDs resolve to the same R n4m steps. Unsupported classes, parameters and steps after the model fail explicitly.

Usage

nirs4all_parse_execution_plan(source, core_cli = NULL)

Arguments

source

Definition accepted by nirs4all_load_pipeline().

core_cli

Optional nirs4all-core-archive executable (or "" for NIRS4ALL_CORE_CLI/PATH) used to project the no-fit owner admission.

Value

List containing the optional splitter, ordered training-only augmentations, preprocessing steps, model component variants, the declared profile (name), the admission source ("source_preflight" is only the host preflight, not a native admission; "owner" when core_cli is given) and, then, the unchanged owner admission in owner.


Optional parsnip regression controller

Description

Accepts a fully specified parsnip model specification. The model is fitted separately within every nirs4all training scope; preprocessing is not fitted on validation or prediction samples. Only one-column numeric regression predictions are supported.

Usage

nirs4all_parsnip(spec)

Arguments

spec

A parsnip regression model_spec with an engine selected.


Optional parsnip classification controller

Description

Fits a separate model in each training scope. Class predictions are factors; probability columns must match the training class labels and are validated by nirs4all_predict_proba(). The fitted engine remains an R-specific artifact.

Usage

nirs4all_parsnip_classifier(spec)

Arguments

spec

A parsnip classification model_spec with an engine selected.


Define a local R spectroscopy pipeline

Description

Constructs a preprocessing sequence and one learner controller. Built-in steps delegate their numerical work to the n4m C ABI. Pipelines can also run through the native DAG-ML campaign helper.

Usage

nirs4all_pipeline(steps = list(), learner = nirs4all_pls(),
  augmentations = list())
nirs4all_snv(ddof = 0L, with_mean = TRUE, with_std = TRUE)
nirs4all_savgol(window_length, polyorder = 2L, deriv = 0L,
               delta = 1, mode = "interp", cval = 0)

Arguments

steps

List of preprocessing steps.

learner

Learner controller.

augmentations

Ordered nirs4all_native_augmentation() specifications applied to training X only, before preprocessing. Y and prediction X are never augmented.

ddof

Degrees-of-freedom correction for row standard deviation.

with_mean

Center each row before SNV scaling.

with_std

Scale each row by standard deviation.

window_length

Odd Savitzky-Golay window size.

polyorder

Polynomial order.

deriv

Derivative order.

delta

Wavelength spacing.

mode

Boundary mode supported by n4m.

cval

Constant boundary fill value.

Value

nirs4all_pipeline returns a pipeline definition; the other functions return preprocessing steps.


Convert a portable JSON/YAML recipe into an R pipeline

Description

The bounded reader accepts native SNV, Savitzky-Golay, LSNV, RNV, area normalization, detrend, train-fitted MSC/EMSC/SPA, feature-only branches merged by concatenation, PLS components, sixteen qualified native affine n4m regressions and sparse PLS-DA classification. A closed prefix of native X-only augmentations is applied after splitting, never to prediction X or Y. Splitters and component sweeps are refused because a single fitted pipeline cannot represent an entire selection experiment.

Usage

nirs4all_pipeline_from_portable(source)

Arguments

source

Definition accepted by nirs4all_load_pipeline().

Value

An unfitted nirs4all_pipeline().


List classes in a portable pipeline definition

Description

Recursively collects class names for inspecting imported JSON/YAML definitions.

Usage

nirs4all_portable_class_names(definition)

Arguments

definition

Loaded or nested pipeline definition.

Value

Character vector of fully qualified class names.


Read an R-native ML/DL pipeline recipe

Description

Parses the same n4m preprocessing and feature-branch grammar as the cross-language reader, but requires an explicitly R-namespaced model alias: r.ranger.regression, r.ranger.classification, r.glmnet.regression, r.torch.mlp.regression, or r.torch.mlp.classification. These aliases are R-local recipes; they do not assert binary or numerical equivalence to Python frameworks. Model parameters are closed scalar data, never executable R code.

Usage

nirs4all_r_pipeline_from_recipe(source)

Arguments

source

JSON/YAML text, path or loaded pipeline definition.

Value

An unfitted nirs4all_pipeline().


Load an upstream domain namespace

Description

Loads the owning upstream package or fails explicitly if it is unavailable.

Usage

nirs4all_require(name)

Arguments

name

One domain key returned by nirs4all_upstreams().

Value

The loaded R package namespace.


Inspect native results and save verified experiment directories

Description

Expose stored candidate scores and identity-aligned prediction rows without calculating scores in R. Native archive objects are checked against their original training outcome. Experiment opening checks member hashes and invokes Core to verify the Parquet projection and optional model closure. Legacy local score views are explicitly marked unverified. Dataset and task display fields are descriptive and unattested.

Usage

nirs4all_result_view(object)

nirs4all_result_compare(object, variant_id = NULL, partition = NULL)

nirs4all_result_predictions(object, variant_id = NULL, partition = NULL, fold_id = NULL)

nirs4all_open_experiment(directory, cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

nirs4all_save_experiment(native_directory, destination, model_archive = NULL, cli = Sys.getenv("NIRS4ALL_CORE_CLI",
    "nirs4all-core-archive"))

Arguments

object

Workflow, tuning result, multimodal predictor or result view returned by the corresponding API.

variant_id

Optional exact candidate identifier to select.

partition

Optional native result partition to select.

fold_id

Optional native fold identifier to select.

directory

New export directory, or an existing exported directory when loading.

cli

Core archive executable, or DAG-ML executable for the local workflow. Native objects retain the supplied runtime path.

native_directory

Directory holding the native result manifest, score set and predictions Parquet.

destination

New experiment destination directory.

model_archive

Optional portable model archive to bind to the native results.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Retrain a fitted pipeline on fresh data

Description

Reuses only the recipe (preprocessing steps and learner configuration), not any fitted preprocessing state or model weights. The ordered input feature schema must match the original fit. This also accepts a pipeline imported with nirs4all_import_trained_pipeline().

Usage

nirs4all_retrain(object, X, y = NULL)

Arguments

object

A fitted nirs4all_fit() result.

X

Numeric samples-by-features matrix or a nirs4all_from_formats() dataset.

y

Target vector, or NULL when X is a nirs4all dataset.

Value

A newly fitted pipeline with independent state.


Define a robust SNV preprocessing step

Description

Use libn4m's median and robust-dispersion row normalization.

Usage

nirs4all_robust_snv(with_center = TRUE, with_scale = TRUE, k = 1.4826)

Arguments

with_center

Center each row by its median.

with_scale

Scale each row by robust dispersion.

k

Positive robust scale factor.

Value

A preprocessing step for nirs4all_pipeline().


Run and persist a local native DAG regression campaign

Description

Compare PLS component candidates by native out-of-fold RMSE, apply SNV or MSC within each fold, and refit the selected pipeline. Prediction uses the retained full-data refit. Exported directories contain trusted local R sidecars and are relocatable; they are distinct from portable Core archives.

Usage

nirs4all_run(X, y, components = c(1L, 2L, 3L), preprocessing = "snv", folds = 5L, sample_ids = NULL,
    cli = Sys.which("dag-ml-cli"), workdir = tempfile("nirs4all-workflow-"), root_seed = 1L)

nirs4all_workflow_predict(object, X)

nirs4all_workflow_retrain(object, X, y, sample_ids = NULL, cli = Sys.which("dag-ml-cli"), workdir = tempfile("nirs4all-workflow-"))

nirs4all_workflow_export(object, directory)

nirs4all_workflow_load(directory)

Arguments

X

Finite samples-by-features matrix, or a structured dataset on uncertainty routes.

y

Numeric target values aligned to the feature rows or explicit sample IDs.

components

Distinct positive PLS component counts to compare by native OOF selection.

preprocessing

Ordered local SNV/MSC steps; the shared archive workflow uses its native SNV/Savitzky-Golay profile.

folds

Number of cross-validation folds for the local DAG campaign.

sample_ids

Ordered unique sample IDs. Structured uncertainty inputs use their own IDs instead.

cli

Core archive executable, or DAG-ML executable for the local workflow. Native objects retain the supplied runtime path.

workdir

New or empty native working directory to retain.

root_seed

Native DAG root seed.

object

Workflow, tuning result, multimodal predictor or result view returned by the corresponding API.

directory

New export directory, or an existing exported directory when loading.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Native multimodal workflows with explicit source policies

Description

Transport a finite catalog-native recipe to Core and DAG for cross-validation, selection, full refit and prediction from captured native state.

Usage

nirs4all_run_multimodal(dataset, pipeline, source_policies,
 methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
 run_id = paste0("run:r:multimodal:", basename(tempfile())),
 cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))
nirs4all_multimodal_predict(object, dataset,
 methods_library = NULL,
 cli = object$cli)
nirs4all_native_multimodal_export(object, path)
nirs4all_native_multimodal_load(path,
 cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
  methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")))
nirs4all_multimodal_retrain(object, dataset,
 methods_library = NULL,
 run_id = paste0("run:r:retrain:", basename(tempfile())), cli = object$cli)

Arguments

dataset

A public dataset v2 record, exact JSON text, or dataset object. Prediction data must be target-free.

pipeline

Named list containing steps and candidates. Steps specify method_id, role and a named params list; candidates are parameter lists for the final model.

source_policies

Ordered source policy lists: source_id, encoder (identity or ragged_summary) and missing_policy (reject or zero_with_indicator).

methods_library

Path to the native Methods shared library. Prediction and retraining inherit the object runtime when NULL; an explicit path overrides it. Runtime paths are not serialized into model exports.

run_id

Fresh campaign identity.

cli

Core native CLI executable.

object

A native pipeline returned by run or load.

path

Native JSON envelope file. Export refuses overwrite.

Details

The transport is nirs4all.native-multimodal.v1 JSON containing one native Package V2 per target. It is separate from .n4a archive transport. Package fingerprints retain exact native JSON bytes. Numerical fitting and cold prediction execute in native Methods and DAG. Dependent origins and groups require declared leakage-safe folds. This API does not promise arbitrary Python model portability.

Value

Run, load and retrain return a native pipeline; predict returns native replay outputs; export invisibly returns its path.


Catalog native pipeline workflows

Description

Transport a finite catalog-native recipe to Core and DAG for cross-validation, selection, full refit and prediction from captured native state.

Usage

nirs4all_run_pipeline(dataset, pipeline, source_id = "spectra",
 methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
 run_id = paste0("run:r:pipeline:", basename(tempfile())),
 cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))
nirs4all_pipeline_predict(object, X, sample_ids = NULL,
 methods_library = NULL,
 cli = object$cli)
nirs4all_pipeline_export(object, path)
nirs4all_pipeline_load(path,
 cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"),
 methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")))
nirs4all_pipeline_retrain(object, dataset,
 methods_library = NULL,
 run_id = paste0("run:r:retrain:", basename(tempfile())), cli = object$cli)

Arguments

dataset

A public dataset record or dataset object.

pipeline

Named list containing steps and candidates. Steps specify method_id, role and a named params list; candidates are parameter lists for the final model.

source_id

Numeric source identity.

methods_library

Path to the native Methods shared library. Prediction and retraining inherit the object runtime when NULL; an explicit path overrides it. Runtime paths are not serialized into model exports.

run_id

Fresh campaign identity.

cli

Core native CLI executable.

object

A native pipeline returned by run or load.

X

Numeric prediction matrix.

sample_ids

Prediction sample identities.

path

Native JSON envelope file. Export refuses overwrite.

Details

The transport is nirs4all.native-pipeline.v1 JSON containing a native Package V2. It is separate from .n4a archive transport. Package fingerprints retain exact native JSON bytes. Numerical fitting and cold prediction execute in native Methods and DAG. Dependent origins and groups require declared leakage-safe folds. This API does not promise arbitrary Python model portability.

Value

Run, load and retrain return a native pipeline; predict returns native replay outputs; export invisibly returns its path.


Run a Python-style JSON/YAML portable pipeline

Description

The declared profile name is derived from the recipe before execution. Linear regression recipes (n4m preprocessing chain, PLS including opls_nipals, or an affine n4m model, optional Kennard-Stone holdout) and SparsePLS-DA classification recipes are admitted, split, fitted, scored and selected by the Core owner operation portable-pipeline-run; R serializes the complete original document and dataset and projects the result. Classification sends R's existing class codes as nonnegative integer ids on the dense y wire and decodes the returned ids with its own class domain (class_values); accuracy, the winner and unseen_validation_classes come from the owner. A missing Core CLI or Methods library, or an owner refusal, is an error: there is no R fallback for these profiles. A regression feature branch (branch + merge: features + terminal model, profile portable_feature_regression.v1) is owner-executed on the DAG per-estimator graph with a native feature join; the optional owner feature_blocks widths are copied unchanged, with no merged labels or axis and no fitted-model or replay scope. A standalone regression train_augmentation prefix and/or an MBPLS block_sizes / GroupSparsePLS group_assignment terminal use the same profile and are sent unchanged (values, exact seeds and arrays as declared; the owner resolves the augmenters, types the values and supplies the feature-axis inputs). A classifier with a feature branch or training augmentation (portable_feature_classification.v1) and a branch with MBPLS / GroupSparsePLS fit inputs (portable_feature_regression.v1, explicit arrays describing the joined feature axis) take the same owner graph route. Qualification here is limited to the named Linux/native profiles. Every declared profile is owner-executed; combinations no owner profile admits (augmentation with a branch) are refused by the portable grammar. There is no local runner. Kennard-Stone selection-validation scores are not independent test scores; without a splitter the scope is training. Use nirs4all_dag_cv_refit_predict() for general CV/OOF/refit.

Usage

nirs4all_run_portable_pipeline(source, dataset, core_cli = NULL, methods_library = NULL)

Arguments

source

Definition accepted by nirs4all_load_pipeline().

dataset

List with X, y and optional rows/cols, or a nirs4all_dataset from nirs4all_from_formats(). Classification labels may be factor, character or finite numeric class codes; numeric codes retain their type in the returned predictions. A record-backed nirs4all_dataset() is accepted by the owner-executed linear regression profile only.

core_cli

Optional nirs4all-core-archive executable. Defaults to the record-backed dataset's own CLI, NIRS4ALL_CORE_CLI, then PATH.

methods_library

Optional absolute path of libn4m. Defaults to N4M_LIB_PATH, then N4M_LIBRARY_PATH.

Value

Split indices (zero-based, owner order), variant predictions and task-specific RMSE or accuracy, selected variant, targets, evaluation scope and the declared profile. Owner runs add mode, identities and owner.


Save and load a fitted R pipeline

Description

Writes an RDS bundle. An n4m PLS model is converted to portable N4MM bytes; an R torch module is converted with torch's own serializer. The surrounding R object is not a cross-language pipeline bundle. Do not load untrusted RDS files.

Usage

nirs4all_save(object, file)
nirs4all_load(file)

Arguments

object

Fitted pipeline.

file

RDS file path.

Value

nirs4all_save invisibly returns the path; nirs4all_load returns a fitted pipeline.


Define a train-fitted n4m SPA variable-selection step

Description

Successive Projections Algorithm selects wavelengths from the training predictors and numeric target. Validation and prediction reuse the selected column indices unchanged.

Usage

nirs4all_spa(top_k, n_components = 2L)

Arguments

top_k

Number of input features to retain.

n_components

Number of PLS components used by the n4m selector.

Value

A nirs4all_step definition.


Native n4m sparse PLS-DA classification controller

Description

Fits sparse PLS-DA with the native n4m kernel. Out-of-sample class decisions use the native coefficients and centering state, as in the Python SparsePLSDAClassifier. predict_proba() applies softmax to the decision scores for DAG compatibility; its outputs are not calibrated probabilities.

Usage

nirs4all_sparse_pls_da(n_components = 2L, sparsity_lambda = 0.05)

Arguments

n_components

Positive number of latent components.

sparsity_lambda

Finite non-negative regularization strength.


R torch multilayer-perceptron regression controller

Description

Fits a one-hidden-layer CPU neural network with full-batch Adam and mean squared error. Feature and target scaling is estimated only from training rows. The trained module is R-specific and is serialized with torch, never with base RDS pointers alone.

Usage

nirs4all_torch_mlp(hidden = 32L, epochs = 100L,
                   learning_rate = 0.001, seed = 1L)

Arguments

hidden

Positive hidden-layer width.

epochs

Positive optimization epoch count.

learning_rate

Positive Adam learning rate.

seed

Non-negative torch random seed.

Value

A learner controller accepted by nirs4all_pipeline.


Optional R torch multilayer-perceptron classification controller

Description

Fits a CPU multilayer perceptron on factor class labels using cross-entropy. The output is a factor or a matrix of softmax class probabilities. Feature normalization is fitted only on training rows. Weights are R-torch artifacts, not portable Python or ONNX weights.

Usage

nirs4all_torch_mlp_classifier(hidden = 32L, epochs = 100L,
                                 learning_rate = 0.001, seed = 1L)

Arguments

hidden

Positive hidden-layer width.

epochs

Positive number of full-batch Adam epochs.

learning_rate

Positive Adam learning rate.

seed

Non-negative torch seed.

Value

A classification learner controller accepted by nirs4all_pipeline.


Optional R torch module regression controller

Description

The builder receives the number of input features and must return a fresh CPU-compatible torch nn_module whose forward pass maps an N x p float tensor to an N x 1 float tensor. Each DAG-ML fold invokes the builder anew, with independent normalization and optimizer state. Only trusted, self-contained R builder functions should be used: they are serialized into the R-specific process-adapter specification and are not portable Python weights, ONNX, or N4MM artifacts.

Usage

nirs4all_torch_module(builder, name = "custom", epochs = 100L,
                      learning_rate = 0.001, seed = 1L)

Arguments

builder

Function accepting one integer n_features and returning an untrained torch nn_module.

name

Stable model label recorded in the controller specification.

epochs

Positive number of full-batch Adam epochs.

learning_rate

Positive Adam learning rate.

seed

Non-negative torch seed.


Optional R torch module classification controller

Description

The builder must emit an N x n_classes raw-logits tensor. Each fit, including each DAG-ML fold, receives an independent module, optimizer and feature-normalization state. Only trusted R builder functions should be used: the builder and weights are R-specific and are not portable Python or ONNX artifacts.

Usage

nirs4all_torch_module_classifier(builder, name = "custom",
                                  epochs = 100L,
                                  learning_rate = 0.001, seed = 1L)

Arguments

builder

Function accepting integer n_features and n_classes and returning a fresh untrained CPU-compatible torch nn_module.

name

Stable model label recorded in the controller specification.

epochs

Positive number of full-batch Adam epochs.

learning_rate

Positive Adam learning rate.

seed

Non-negative torch seed.

Value

A classification learner controller accepted by nirs4all_pipeline.


Generate constrained candidates and run native resumable tuning

Description

Delegate candidate generation and OOF hyperparameter search to Core and DAG-ML. The bounded dense regression study searches PLS components 1 through 3. Resume accepts a total trial budget and preserves completed trials. Seeds must be exact nonnegative integers no greater than 2^53-1; generated variant seeds are returned as exact decimal strings. Exports preserve native archive and training identities.

Usage

nirs4all_generate(choices, strategy = "cartesian", constraints = list(), count = NULL, seed = 0, max_variants = 10000,
    cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

nirs4all_tune(data, trials = 8L, seed = 91L, sampler = "random", metric = "rmse", source_id = "spectra",
    checkpoint = NULL, methods_library = Sys.getenv("N4M_LIBRARY_PATH", Sys.getenv("N4M_LIB_PATH")),
    archive = tempfile("nirs4all-tuning-", fileext = ".n4a"), run_id = paste0("run:tuning:",
        basename(tempfile())), cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

nirs4all_tuning_predict(object, X, ...)

nirs4all_resume_tuning(object, data, trials, ...)

nirs4all_tuning_export(object, directory)

nirs4all_load_tuning(directory, cli = Sys.getenv("NIRS4ALL_CORE_CLI", "nirs4all-core-archive"))

Arguments

choices

Named lists of candidate values, including structured choices.

strategy

Native generation strategy: cartesian, zip or random.

constraints

Native constraint record, such as excluded combinations of dimension labels.

count

Optional number of variants for native random selection.

seed

Nonnegative exactly representable numeric seed in 0 through 2^53-1.

max_variants

Native upper bound on generated variants.

cli

Core archive executable, or DAG-ML executable for the local workflow. Native objects retain the supplied runtime path.

data

IO dataset record, dataset object, or native JSON dataset file.

trials

Total trial budget, an integer from 1 to 256.

sampler

Native tuning sampler identifier.

metric

Native selection metric identifier.

source_id

Selected dense source identifier; for structured uncertainty, optional source selection.

checkpoint

Optional previous tuning result or checkpoint archive.

methods_library

Path to the installed native libn4m shared library.

archive

New output native archive path.

run_id

Native run identifier.

object

Workflow, tuning result, multimodal predictor or result view returned by the corresponding API.

X

Finite samples-by-features matrix, or a structured dataset on uncertainty routes.

...

Additional arguments forwarded to the corresponding native operation.

directory

New export directory, or an existing exported directory when loading.

Value

The corresponding native workflow, tuning study, calibrated result, dataset, predictor, result view, or invisible output path.

See Also

nirs4all_core_archive


Discover upstream R packages

Description

Reports the six upstream domains without installing or loading unavailable packages.

Usage

nirs4all_upstreams()

Value

Data frame with domain key, package, availability and role.


Portable native sessions in a modern SDK workspace

Description

Validate, query, export and import an SDK SQLite/Parquet workspace containing portable native experiment archives. Predictions execute the SDK native session without fitting.

Usage

nirs4all_open_workspace(directory, python = Sys.getenv("NIRS4ALL_WORKSPACE_PYTHON", "python3"))
nirs4all_workspace_runs(object)
nirs4all_workspace_predictions(object, run_id)
nirs4all_workspace_session(object, run_id)
nirs4all_workspace_predict(session, X, sample_ids)
nirs4all_workspace_export(object, destination)
nirs4all_import_workspace(archive, destination, python = Sys.getenv("NIRS4ALL_WORKSPACE_PYTHON", "python3"))
nirs4all_workspace_close(object)

Arguments

directory

Existing validated workspace directory.

python

Python executable providing nirs4all-core, the full nirs4all SDK and the native runtime.

object

Open workspace or, for close, a workspace session.

run_id

Native run identifier returned by the workspace.

session

Open portable native workspace session.

X

Complete numeric predictor matrix.

sample_ids

Explicit sample identifiers in matrix row order.

destination

New output archive or workspace path; existing paths are refused.

archive

Validated exported workspace ZIP.

Details

Requires processx and jsonlite. Each operation uses argv to invoke the public Python workspace JSON CLI and closes SDK resources before returning. Closing a workspace also closes its child sessions. The workspace contains native models portable across qualified runtimes; arbitrary foreign host model weights and legacy DuckDB migration are outside this profile.

Value

Open and import return a closeable workspace environment. Session returns a closeable session environment. Runs and predictions return SDK records; predict returns native predictions and sample identity. Export returns the archive path. Close invisibly returns NULL.


Optional XGBoost regression and classification controllers

Description

Fits a fresh CPU XGBoost booster on each training scope. Classification supplies factor labels and a probability matrix with the original class levels. The fitted booster is stored as XGBoost model bytes within the R model sidecar, not as a cross-language n4m model.

Usage

nirs4all_xgboost(nrounds = 100L, max_depth = 6L, eta = 0.3,
                 seed = 1L, nthread = 1L)
nirs4all_xgboost_classifier(nrounds = 100L, max_depth = 6L,
                            eta = 0.3, seed = 1L, nthread = 1L)

Arguments

nrounds

Positive number of boosting rounds.

max_depth

Non-negative tree depth; zero means no depth limit.

eta

Learning rate in (0, 1].

seed

Non-negative XGBoost seed.

nthread

Positive number of CPU threads.

Value

A learner controller accepted by nirs4all_pipeline.