### Set up a virtual environment and install metbit Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/getting-started/page.mdx Create and activate a Python virtual environment, upgrade pip, and install metbit. On Windows, use `.venv\Scripts\activate` instead of the Unix `source` command. ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate python -m pip install --upgrade pip pip install metbit ``` -------------------------------- ### Recommended project structure Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/getting-started/page.mdx A suggested directory layout for a metbit project, separating raw data, processed data, notebooks, results, and scripts. ```text project/ data/ raw_bruker/ processed/ notebooks/ results/ figures/ tables/ scripts/ run_preprocessing.py run_models.py ``` -------------------------------- ### Run the application Source: https://github.com/aeiwz/metbit/blob/main/src/page/STOCSY.md Start the STOCSY Dash app locally; it will be available at http://localhost:8051. ```bash python app.py ``` -------------------------------- ### Install metbit with pip Source: https://github.com/aeiwz/metbit/blob/main/README.rst Install the metbit package using pip. ```bash pip install metbit ``` -------------------------------- ### Start from a feature table: PCA and OPLS-DA Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/getting-started/page.mdx Load a CSV feature table, separate features (X) from labels (y), normalize with PQN, then fit PCA for exploration and OPLS-DA for binary class modeling. The example uses pareto scaling, 2 components, and 3-fold cross-validation for OPLS-DA. ```python import pandas as pd from metbit import Normalization, pca, opls_da df = pd.read_csv("spectra.csv") y = df["Group"] X = df.drop(columns=["Group"]) features = X.columns.astype(float) X_norm = Normalization.pqn_normalization(X) pca_model = pca( X=X_norm, label=y, features_name=features, n_components=2, scaling_method="pareto", ) pca_model.fit() pca_model.plot_pca_scores().show() opls_model = opls_da( X=X_norm, y=y, features_name=features, n_components=2, scaling_method="pareto", kfold=3, estimator="opls", auto_ncomp=True, ) opls_model.fit() opls_model.plot_oplsda_scores().show() opls_model.vip_plot(threshold=1.0).show() ``` -------------------------------- ### Install metbit with ML extras Source: https://github.com/aeiwz/metbit/blob/main/README.md Install command to add XGBoost support to metbit. ```bash pip install metbit[ml] # adds XGBoost support ``` -------------------------------- ### Start from Bruker FID folders with nmr_preprocessing Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/getting-started/page.mdx Use nmr_preprocessing to import a Bruker project folder containing sample directories with fid files. Configure bin size, auto-phasing, baseline correction, and TSP calibration, then extract data, ppm, and metadata, and apply PQN normalization. ```python from metbit import nmr_preprocessing, Normalization nmr = nmr_preprocessing( data_path="path/to/bruker_project", bin_size=0.0005, auto_phasing=True, fn_="acme", baseline_correction=True, baseline_type="corrector", calibration=True, calib_type="tsp", align=False, ) X = nmr.get_data() ppm = nmr.get_ppm() metadata = nmr.get_metadata() X_norm = Normalization.pqn_normalization(X) ``` -------------------------------- ### Install required libraries Source: https://github.com/aeiwz/metbit/blob/main/src/page/STOCSY.md Install Dash, dash-bootstrap-components, Plotly, and Pandas using pip. ```bash pip install dash dash-bootstrap-components plotly pandas ``` -------------------------------- ### Install metbit with deep learning extras Source: https://github.com/aeiwz/metbit/blob/main/README.md Install the package with the `dl` extra to enable the PyTorch-based deep learning models. ```bash pip install metbit[dl] ``` -------------------------------- ### Install optional GPU acceleration (CuPy or PyTorch with CUDA) Source: https://github.com/aeiwz/metbit/blob/main/README.md Installs CuPy or PyTorch with CUDA support for GPU acceleration. The example shows installing cupy-cuda12x, but torch with CUDA is also an option. ```bash pip install cupy-cuda12x # or torch with CUDA ``` -------------------------------- ### Install optional metbit extras (ml, dl, all) Source: https://github.com/aeiwz/metbit/blob/main/README.md Installs optional dependencies: XGBoost classifier support with [ml], PyTorch deep-learning models with [dl], or both with [all]. ```bash pip install metbit[ml] # XGBoost classifier support ``` ```bash pip install metbit[dl] # PyTorch deep-learning models ``` ```bash pip install metbit[all] # both of the above ``` -------------------------------- ### Verify active compute backend with metbit.backend_info() Source: https://github.com/aeiwz/metbit/blob/main/README.md Checks the active compute backend after installation. The output shows whether native C, OpenMP threads, GPU (CuPy or PyTorch) are enabled. ```bash # Verify the active compute backend after installation python -c "import metbit; print(metbit.backend_info())" # {'native_c': True, 'openmp_threads': 8, 'gpu_cupy': False, 'gpu_torch': False, ...} ``` -------------------------------- ### Example usage of STOCSY_app Source: https://github.com/aeiwz/metbit/blob/main/src/page/STOCSY.md Load NMR spectra from a CSV file, extract spectra and ppm values, then run the STOCSY Dash app on port 8051. ```python import pandas as pd from metbit import STOCSY_app df = pd.read_csv("path_to_your_file.csv") spectra = df.iloc[:,1:] # depend on number of meta data and spectra data ppm = spectra.columns.astype(float).to_list() stocsy_app = STOCSY_app(spectra, ppm) app = stocsy_app.run_ui() app.run_server(debug=True, port=8051) ``` -------------------------------- ### Quick Start: PCA, OPLS-DA, and STOCSY with metbit Source: https://github.com/aeiwz/metbit/blob/main/README.md Loads a preprocessed spectral matrix and binary class labels, then runs PCA for exploratory overview, OPLS-DA for supervised discrimination with VIP scoring, and STOCSY for correlation from a VIP anchor peak. Requires a CSV with spectral columns and a 'Group' column; the spectral matrix is taken from column index 2 onward. ```python import pandas as pd from metbit import nmr_preprocessing, pca, opls_da, STOCSY # 1. Load a preprocessed spectral matrix (samples x variables) df = pd.read_csv("nmr_data.csv") X = df.iloc[:, 2:] # spectral matrix y = df["Group"] # binary class label ppm = X.columns.astype(float).tolist() # 2. PCA - exploratory overview pca_mod = pca(X=X, label=y, features_name=ppm, n_components=3) pca_mod.fit() pca_mod.plot_pca_scores(pc=["PC1", "PC2"]) # 3. OPLS-DA - supervised discrimination model = opls_da(X=X, y=y, features_name=ppm, scale="uv", auto_ncomp=True) model.fit() model.plot_oplsda_scores() model.vip_scores() model.vip_plot(threshold=2) # 4. STOCSY - correlation from a VIP anchor peak stocsy = STOCSY(X=X, ppm=ppm) stocsy.fit(driver=3.05) stocsy.plot() ``` -------------------------------- ### Launch Interactive Dash Applications (stocsy_app, opls_app) Source: https://github.com/aeiwz/metbit/blob/main/README.md Starts the STOCSY and OPLS Dash apps locally on ports 8050 and 8051. All apps run locally; no data is uploaded to external servers. ```python from metbit.apps import stocsy_app, opls_app, pca_app, spectra_app stocsy_app(X=spectra_df, ppm=ppm, port=8050) opls_app(model=model, port=8051) ``` -------------------------------- ### get_intensity.run_ui() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/take_intensity/page.mdx Launches the Dash application for visualizing and selecting NMR spectral peaks. This method starts the interactive user interface. ```APIDOC ## get_intensity.run_ui() ### Description Launches the Dash application for visualizing and selecting NMR spectral peaks. This method starts the interactive user interface. ### Method run_ui ### Parameters None ``` -------------------------------- ### pickie_peak.run_ui() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/ui_picky_peak/page.mdx Launches the Dash application for visualizing and selecting NMR spectral peaks. This method starts the interactive UI that allows users to pick peaks from the spectral plot. ```APIDOC ## pickie_peak.run_ui() ### Description Launches the Dash application for visualizing and selecting NMR spectral peaks. ### Method run_ui ### Parameters None ### Returns None ``` -------------------------------- ### Install required packages Source: https://github.com/aeiwz/metbit/blob/main/src/page/box-plot.md Install the required Python packages for the boxplot_stats function using pip. ```bash pip install pandas numpy scipy plotly pingouin statsmodels ``` -------------------------------- ### Usage example for annotate_peak Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/annotate_peak/page.mdx Shows how to load NMR spectra data from a CSV file, extract spectra, ppm values, and labels, then create and run the annotate_peak Dash application. Assumes the first column is not part of spectra and 'Group' is the label column. ```python import pandas as pd df = pd.read_csv('path_to_your_data.csv') spectra = df.iloc[:, 1:] # Assuming first column is not part of spectra ppm = spectra.columns.astype(float).to_list() label = df['Group'] # Assuming 'Group' is the label column annotator = annotate_peak(label, spectra, ppm, label) annotator.run(debug=True, port=8050) ``` -------------------------------- ### opls_da.get_oplsda_model() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get OPLS-DA model. ```APIDOC ## opls_da.get_oplsda_model() ### Description Get OPLS-DA model. ### Method Method ### Parameters None. ### Response Returns the fitted OPLS-DA model. ``` -------------------------------- ### annotate_peak.run(debug, port) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/annotate_peak/page.mdx Runs the Dash application server with optional debug mode and port specification. This method starts the interactive annotation interface. ```APIDOC ## annotate_peak.run(debug, port) ### Description Runs the Dash application server with optional debug mode and port specification. This method starts the interactive annotation interface. ### Method Run ### Parameters - **debug** (bool) - Optional - Enable debug mode. - **port** (int) - Optional - Port number for the server. ### Usage Example ```python annotator.run(debug=True, port=8050) ``` ``` -------------------------------- ### Memory estimation with MemoryEstimator and memory_report Source: https://github.com/aeiwz/metbit/blob/main/README.md Estimates peak memory usage for a given dataset size and dtype, and prints a memory report. The example shows peak_gb for float64 and recommended float32. ```python from metbit import MemoryEstimator, memory_report est = MemoryEstimator() info = est.estimate(n_samples=10_000, n_features=65_536, dtype="float64") print(info) # {'peak_gb': 4.88, 'recommended_dtype': 'float32', 'float32_peak_gb': 2.44} memory_report(X) ``` -------------------------------- ### OPLS-DA model fitting with metbit.opls_da Source: https://github.com/aeiwz/metbit/blob/main/README.md Fits an OPLS-DA model using the metbit.opls_da function. The example uses unit-variance scaling and automatic component selection via cross-validation. After fitting, the model object provides methods for plotting scores, loadings, and S-plots, as well as validation and metrics. ```python from metbit import opls_da model = opls_da( X=X, y=y, features_name=ppm, scale="uv", # unit-variance scaling auto_ncomp=True, # automatic component selection via cross-validation ) model.fit() ``` -------------------------------- ### CrossValidation.reset_optimal_num_component(k) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/cross_validation/page.mdx Resets the optimal number of components for manual setup based on the error plot. ```APIDOC ## CrossValidation.reset_optimal_num_component(k) ### Description Resets the optimal number of components for manual setup based on the error plot. ### Method reset_optimal_num_component ### Parameters - `k` (int) - Required - Number of components according to the error plot. ``` -------------------------------- ### OPLS-DA: prepare X, ppm, and y Source: https://github.com/aeiwz/metbit/blob/main/README.rst Sets up the feature matrix X (columns from index 2 onward), ppm as the float-converted column names, and y as the group series. ```python X = df.iloc[:, 2:] ppm = X.columns.astype(float).to_list() y = df["Group"] ``` -------------------------------- ### Run docs:sync to refresh versioned documentation Source: https://github.com/aeiwz/metbit/blob/main/docs/README.md Executes the sync script that reads GitHub Releases and local Git tags to generate release and API documentation. Run `git fetch --tags` first when new releases have been published. ```bash npm run docs:sync ``` -------------------------------- ### opls_da.get_s_scores() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get S scores. ```APIDOC ## opls_da.get_s_scores() ### Description Get S scores. ### Method Method ### Parameters None. ### Response Returns S scores. ``` -------------------------------- ### opls_da.get_permutation_scores() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get permutation scores. ```APIDOC ## opls_da.get_permutation_scores() ### Description Get permutation scores. ### Method Method ### Parameters None. ### Response Returns permutation scores. ``` -------------------------------- ### __init__(spectra, ppm) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/ui_stocsy/page.mdx Initializes the STOCSY_app with NMR spectra and corresponding PPM values. ```APIDOC ## __init__(spectra, ppm) ### Description Initializes the STOCSY_app with NMR spectra and corresponding PPM values. ### Method Constructor ### Parameters - **spectra** (array-like) - Required - NMR spectra data. - **ppm** (array-like) - Required - Corresponding PPM values. ``` -------------------------------- ### opls_da.get_cv_model() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get cross-validation model. ```APIDOC ## opls_da.get_cv_model() ### Description Get cross-validation model. ### Method Method ### Parameters None. ### Response Returns the cross-validation model. ``` -------------------------------- ### Backend info and availability checks Source: https://github.com/aeiwz/metbit/blob/main/README.md Prints backend configuration (native C, OpenMP threads, GPU availability, job count, default chunk size) and checks native and GPU availability. ```python import metbit print(metbit.backend_info()) # {'native_c': True, 'openmp_threads': 8, 'gpu_cupy': False, 'gpu_torch': False, # 'n_jobs': 8, 'default_chunk': 50000} print(metbit.native_available()) print(metbit.gpu_available()) ``` -------------------------------- ### OPLS-DA: create model with auto_ncomp Source: https://github.com/aeiwz/metbit/blob/main/README.rst Creates an OPLS-DA model with UV scaling and automatic number of components. ```python opls_da_mod = opls_da(X=X, y=y, features_name=ppm, scale='uv', auto_ncomp=True) ``` -------------------------------- ### opls_da.get_oplsda_scores() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get OPLS-DA scores. ```APIDOC ## opls_da.get_oplsda_scores() ### Description Get OPLS-DA scores. ### Method Method ### Parameters None. ### Response Returns OPLS-DA scores. ``` -------------------------------- ### opls_da.get_vip_scores(filter_, threshold) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get VIP score. ```APIDOC ## opls_da.get_vip_scores(filter_, threshold) ### Description Get VIP score. ### Method Method ### Parameters - `filter_` (bool) - Optional - If True, filter VIP score based on threshold. - `threshold` (int) - Optional - Threshold of VIP score. ### Response Returns VIP scores. ``` -------------------------------- ### Display first 10 rows and columns Source: https://github.com/aeiwz/metbit/blob/main/README.rst Use .iloc or df.head(10)[df.columns[:10]] to display 10 rows and 10 columns first. ```python df.iloc[:10, :10] ``` -------------------------------- ### opls_da.vip_scores(model, features_name) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Get VIP score. ```APIDOC ## opls_da.vip_scores(model, features_name) ### Description Get VIP score. ### Method Method ### Parameters - `model` (object) - Optional - OPLS-DA model. - `features_name` (array-like) - Optional - Name of features. ### Response Returns VIP scores. ``` -------------------------------- ### Load metabolomics data from CSV Source: https://github.com/aeiwz/metbit/blob/main/README.rst Read the tutorial dataset into a pandas DataFrame. ```python df = pd.read_csv("metbit_tutorial_data.csv") ``` -------------------------------- ### Initialize lazy_opls_da model Source: https://github.com/aeiwz/metbit/blob/main/README.rst Creates a lazy OPLS-DA model with auto component selection, permutation testing, VIP scores, and linear regression enabled. The working directory is set to '/path/to/working/directory/'. ```python working_dir = "/path/to/working/directory/" lazy_mod = lazy_opls_da(data=X, groups=y,working_dir=working_dir, auto_ncomp=True, permutation=True, VIP=True, linear_regression=True) ``` -------------------------------- ### Assign and fit PCA model Source: https://github.com/aeiwz/metbit/blob/main/README.rst Creates a PCA model with the prepared data and fits it. The model is configured with 3 components and uses the provided features_name (ppm) and label (color_). ```python pca_mod = pca(X=X, label=color_, features_name=ppm, n_components=3) pca_mod.fit() ``` -------------------------------- ### Example usage of boxplot_stats Source: https://github.com/aeiwz/metbit/blob/main/src/page/box-plot.md Create a sample DataFrame and generate an enhanced box plot with statistical annotations using the boxplot_stats function. ```python import pandas as pd # Sample data data = { "treatment": ["A"] * 10 + ["B"] * 10 + ["C"] * 10, "score": [0.5, 0.6, 0.7, 0.8, 0.9, 0.7, 0.8, 0.9, 0.6, 0.5, 0.4, 0.5, 0.6, 0.7, 0.8, 0.6, 0.7, 0.8, 0.5, 0.4, 0.5, 0.6, 0.5, 0.4, 0.5, 0.6, 0.4, 0.5, 0.6, 0.4], } df = pd.DataFrame(data) # Generate the plot fig = boxplot_stats( df, x_col="treatment", y_col="score", stats_options=["t-test", "effect-size"], custom_colors={"A": "red", "B": "blue", "C": "green"}, correct_p="bonferroni", annotate_style="symbol" ) fig.show() ``` -------------------------------- ### __init__(data, groups, working_dir, feature_names, n_components, scaling, estimator, kfold, random_state, auto_ncomp, permutation, n_permutation, n_jobs, VIP, VIP_threshold, linear_regression, FC_threshold, p_val_threshold) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/lazy_opls_da/page.mdx Initializes the lazy_opls_da model with the provided dataset and parameters. This constructor sets up the OPLS-DA model for subsequent fitting and analysis. ```APIDOC ## __init__(data, groups, working_dir, feature_names, n_components, scaling, estimator, kfold, random_state, auto_ncomp, permutation, n_permutation, n_jobs, VIP, VIP_threshold, linear_regression, FC_threshold, p_val_threshold) ### Description Initializes the lazy_opls_da model with the provided dataset and parameters. This constructor sets up the OPLS-DA model for subsequent fitting and analysis. ### Parameters - `data` (pd.DataFrame) - Required - DataFrame containing the dataset. - `groups` (list) - Required - List of class labels for each data sample. - `working_dir` (str) - Required - Directory path for storing output files. - `feature_names` (list, optional) - Optional - Names of features, defaults to None. - `n_components` (int, optional) - Optional - Number of components for OPLS-DA, defaults to 2. - `scaling` (str, optional) - Optional - Scaling method ('pareto'), defaults to 'pareto'. - `estimator` (str, optional) - Optional - Model estimator, defaults to 'opls'. - `kfold` (int, optional) - Optional - Number of folds in cross-validation, defaults to 3. - `random_state` (int, optional) - Optional - Random seed, defaults to 94. - `auto_ncomp` (bool, optional) - Optional - Automatically choose the optimal number of components, defaults to True. - `permutation` (bool, optional) - Optional - Conduct permutation tests, defaults to True. - `n_permutation` (int) - Required - Number of permutations for permutation tests. - `n_jobs` (int) - Required - Number of parallel jobs. - `VIP` (bool, optional) - Optional - Calculate VIP scores, defaults to True. - `VIP_threshold` (float) - Required - Threshold for VIP scores. - `linear_regression` (bool, optional) - Optional - Conduct linear regression analysis, defaults to True. - `FC_threshold` (float) - Required - Fold change threshold. - `p_val_threshold` (float) - Required - P-value threshold. ### Usage Example ```python lazy_opls_da(data, y, n_components).fit() ``` ``` -------------------------------- ### Import pandas and metbit.pca Source: https://github.com/aeiwz/metbit/blob/main/README.rst Import the required libraries for PCA analysis. ```python import pandas as pd from metbit import pca ``` -------------------------------- ### OPLS-DA visualisation: plot loading Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a loading plot for the fitted OPLS-DA model. ```python opls_da_mod.plot_loading() ``` -------------------------------- ### metbit.backend_info() Source: https://github.com/aeiwz/metbit/blob/main/README.md Returns information about the active compute backend, including native C availability, OpenMP threads, GPU support, and worker count. ```APIDOC ## metbit.backend_info() ### Description Returns information about the active compute backend, including native C availability, OpenMP threads, GPU support, and worker count. ### Returns - **dict**: Dictionary with keys: `native_c` (bool), `openmp_threads` (int), `gpu_cupy` (bool), `gpu_torch` (bool), `n_jobs` (int), `default_chunk` (int). ### Example ```python import metbit print(metbit.backend_info()) ``` ``` -------------------------------- ### Workflow Overview: Raw Bruker FID to Interactive Dash Apps Source: https://github.com/aeiwz/metbit/blob/main/README.md Shows the end-to-end pipeline from raw Bruker FID through preprocessing, normalization, alignment, multivariate analysis, statistics, machine learning, STOCSY, and interactive Dash apps. Each stage lists the relevant metbit functions or classes; the final Dash apps run locally in the browser without uploading data. ```text Raw Bruker FID │ ▼ nmr_preprocessing # digital filter removal, zero-fill, FFT, │ # ACME phase correction, arPLS baseline correction, │ # TSP/DSS calibration, region exclusion ▼ Normalization # PQN / MSC / TSP-area │ ▼ icoshift_align # segment-wise spectral alignment │ ▼ pca / lda / plsr / ica / hca # exploratory and supervised multivariate │ ▼ opls_da # supervised binary classification │ # VIP scoring, permutation test, CV-ANOVA ▼ VolcanoPlot / ANOVAStats / KruskalStats # group comparison statistics │ ▼ MLClassifier # RF / SVM / XGBoost / ElasticNet with CV SpectralAutoencoder # PyTorch deep-learning models │ ▼ STOCSY / ChunkedSTOCSY # structural correlation from anchor peaks │ ▼ Interactive Dash apps # local browser exploration, no data upload ``` -------------------------------- ### PCA.__init__(X, label, features_name, n_components, scaling_method, random_state, test_size) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Initializes the PCA model with training data, labels, feature names, number of components, scaling method, random state, and test size. ```APIDOC ## PCA.__init__(X, label, features_name, n_components, scaling_method, random_state, test_size) ### Description Initializes the PCA model with training data, labels, feature names, number of components, scaling method, random state, and test size. ### Method Constructor ### Parameters - `X` (array-like) - Required - Training data, shape (n_samples, n_features). - `label` (array-like) - Required - Target data, shape (n_samples,). - `features_name` (array-like) - Optional - Name of features, shape (n_features,), default=None. - `n_components` (int) - Optional - Number of components to keep, default=2. - `scale` (str) - Optional - Method of scaling: 'pareto', 'mean', or 'uv', default='pareto'. - `random_state` (int) - Optional - Random state for permutation test, default=42. - `test_size` (float) - Optional - Size of test set, default=0.3. ### Request Example ```python pca = PCA(X, label, features_name=None, n_components=2, scale='pareto', random_state=42, test_size=0.3) ``` ### Response #### Success Response - No return value. ``` -------------------------------- ### Scaler.__init__ Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/scaler/page.mdx Initializes the Scaler object with parameters for scaling power, copy behavior, centering, and scaling. ```APIDOC ## Scaler.__init__ ### Description Initializes the Scaler object with parameters for scaling power, copy behavior, centering, and scaling. ### Method Constructor ### Parameters - **scale_power** (float) - Required - The power to raise the standard deviation to when scaling. - **copy** (bool) - Optional - Whether to copy the input data. - **with_mean** (bool) - Optional - Whether to center the data before scaling. - **with_std** (bool) - Optional - Whether to scale the data to unit variance. ### Request Example ```python scaler = Scaler(scale_power=1.0, copy=True, with_mean=True, with_std=True) ``` ``` -------------------------------- ### Benchmark directory layout Source: https://github.com/aeiwz/metbit/blob/main/Benchmark/README.md Directory structure for the Benchmark module, showing the shared metrics file, per-dataset folders, and documentation. ```text Benchmark/ metrics.py # shared scoring, self-checked (python Benchmark/metrics.py) README.md # this file MTBLS1/ # existing end-to-end + performance + reproducibility tier / # one dir per dataset: benchmark_.py + result/ + README.md ``` -------------------------------- ### Run Test Suite with pytest (full, fast, perf) Source: https://github.com/aeiwz/metbit/blob/main/README.md Commands to run the full test suite, exclude slow and performance tests for faster runs, or run only performance benchmarks. ```bash # Run full suite pytest # Run without slow/performance tests (faster) pytest -m "not slow and not perf" # Run performance benchmarks only pytest -m perf ``` -------------------------------- ### Prepare X and y for lazy OPLS-DA Source: https://github.com/aeiwz/metbit/blob/main/README.rst Extracts feature matrix X, converts column names to float for ppm, and creates class labels by combining Group and Time point columns. ```python X = df.iloc[:, 2:] ppm = X.columns.astype(float).to_list() # Perform class by combind Group and Time point df["Class"] = df["Group"] + ", " + df["Time point"].astype(str) y = df["Class"] ``` -------------------------------- ### Use SpectralAutoencoder, SpectralMLP, and SpectralCNN Source: https://github.com/aeiwz/metbit/blob/main/README.md Shows how to instantiate and use the three deep learning models for unsupervised representation learning and classification. Requires `metbit[dl]`. ```python from metbit import SpectralAutoencoder, SpectralMLP, SpectralCNN # Autoencoder - unsupervised representation learning ae = SpectralAutoencoder(input_dim=X.shape[1], latent_dim=32) ae.fit(X, epochs=100) latent = ae.transform(X) # compressed representation reconstructed = ae.reconstruct(X) # MLP classifier mlp = SpectralMLP(input_dim=X.shape[1], n_classes=len(y.unique())) mlp.fit(X, y, epochs=50) labels = mlp.predict(X_new) proba = mlp.predict_proba(X_new) # 1-D CNN classifier cnn = SpectralCNN(input_dim=X.shape[1], n_classes=len(y.unique())) cnn.fit(X, y, epochs=50) labels = cnn.predict(X_new) ``` -------------------------------- ### run_ui() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/ui_stocsy/page.mdx Runs the Dash application UI for the STOCSY analysis. ```APIDOC ## run_ui() ### Description Runs the Dash application UI for the STOCSY analysis. ### Method Method ``` -------------------------------- ### Generate Performance Report (perf_report.py) Source: https://github.com/aeiwz/metbit/blob/main/README.md Runs the performance benchmark script to reproduce the reported speedup and memory reduction figures. ```bash python scripts/perf_report.py ``` -------------------------------- ### OPLS-DA: permutation test Source: https://github.com/aeiwz/metbit/blob/main/README.rst Runs a permutation test with 100 permutations using all available cores. ```python opls_da_mod.permutation_test(n_permutations=100, n_jobs=-1) ``` -------------------------------- ### Scaler.__init__(scaler) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/pretreatment/page.mdx Initializes a Scaler object with a specified scaler configuration. This constructor sets up the scaler for subsequent fitting and scaling operations. ```APIDOC ## Scaler.__init__(scaler) ### Description Initializes a Scaler object with a specified scaler configuration. This constructor sets up the scaler for subsequent fitting and scaling operations. ### Method Constructor ### Parameters - **scaler** (type not specified) - Required - The scaler configuration or instance to use. ``` -------------------------------- ### Train/Test split and cross-validation with metbit Source: https://github.com/aeiwz/metbit/blob/main/README.md Demonstrates stratified train/test splitting and cross-validation with any sklearn-compatible estimator. Shows available CV strategies and how to retrieve scores. ```python from metbit import TrainTestSplit, CrossValidator, available_cv_strategies # Simple stratified train/test split splitter = TrainTestSplit(X=X, y=y, test_size=0.2, stratify=True, random_state=42) X_train, X_test, y_train, y_test = splitter.split() splitter.plot_split() # bar chart of class distribution in each split print(splitter.get_summary()) # DataFrame: class, train_n, test_n, train_pct, test_pct # Cross-validation with any sklearn-compatible estimator print(available_cv_strategies()) # ["kfold", "stratified", "loo", "repeatedstratified"] from sklearn.ensemble import RandomForestClassifier cv = CrossValidator( X=X, y=y, estimator=RandomForestClassifier(n_estimators=100), strategy="stratified", n_splits=5, ) cv.fit() print(cv.get_scores()) # DataFrame with per-fold accuracy, balanced_accuracy, roc_auc ``` -------------------------------- ### Run the MTBLS1 benchmark script Source: https://github.com/aeiwz/metbit/blob/main/Benchmark/MTBLS1/README.md Executes the full metbit pipeline benchmark on the MTBLS1 dataset. Requires the raw FID archive and sample metadata at the specified paths. ```bash python Benchmark/MTBLS1/benchmark_mtbls1.py ``` -------------------------------- ### Import pandas and metbit lazy_opls_da Source: https://github.com/aeiwz/metbit/blob/main/README.rst Imports the required libraries for using the lazy OPLS-DA functionality. ```python import pandas as pd from metbit import lazy_opls_da ``` -------------------------------- ### OPLS-DA: fit model Source: https://github.com/aeiwz/metbit/blob/main/README.rst Fits the OPLS-DA model. The output shows the fitting time in seconds. ```python opls_da_mod.fit() ``` -------------------------------- ### Visualisation: plot 3D PCA and save as SVG Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a 3D PCA plot with marker size 10 and symbol_ labels, then saves it as '3d_pca.svg'. ```python pca_mod.plot_3d_pca(marker_size=10, symbol_=symbol_).write_image("3d_pca.svg") ``` -------------------------------- ### metbit.native_available() Source: https://github.com/aeiwz/metbit/blob/main/README.md Checks if the native C extension is available. ```APIDOC ## metbit.native_available() ### Description Checks if the native C extension is available. ### Returns - **bool**: True if native C extension is available, False otherwise. ### Example ```python import metbit print(metbit.native_available()) ``` ``` -------------------------------- ### nmr_preprocessing.__init__ Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/nmr_preprocess/page.mdx Initializes the nmr_preprocessing class with parameters for data path, bin size, auto-phasing, zero-filling, baseline correction, and calibration settings. ```APIDOC ## nmr_preprocessing.__init__ ### Description Initializes the nmr_preprocessing class with parameters for data path, bin size, auto-phasing, zero-filling, baseline correction, and calibration settings. ### Method Constructor ### Parameters - **data_path** (string) - Required - Path to the NMR data files. - **bin_size** (float) - Required - Bin size for data binning. - **auto_phasing** (bool) - Required - Whether to perform automatic phasing. - **fn_** (int) - Required - Zero-filling factor. - **baseline_correction** (bool) - Required - Whether to apply baseline correction. - **baseline_type** (string) - Required - Type of baseline correction method. - **calibration** (bool) - Required - Whether to perform calibration. - **calib_type** (string) - Required - Type of calibration method. ### Response No return value. ``` -------------------------------- ### opls_da.__init__(X, y, features_name, n_components, scaling_method, kfold, estimator, random_state, auto_ncomp) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/metbit/page.mdx Initializes the OPLS-DA model, validates the inputs, and preprocesses the data for further analysis. ```APIDOC ## opls_da.__init__(X, y, features_name, n_components, scaling_method, kfold, estimator, random_state, auto_ncomp) ### Description Initializes the OPLS-DA model, validates the inputs, and preprocesses the data for further analysis. ### Method Constructor ### Parameters - `X` (array-like) - Required - Input data. - `y` (array-like) - Required - Target labels. - `features_name` (array-like) - Optional - Names of features. - `n_components` (int) - Optional - Number of components. - `scaling_method` (str) - Optional - Scaling method. - `kfold` (int) - Optional - Number of folds for cross-validation. - `estimator` (object) - Optional - Estimator for cross-validation. - `random_state` (int) - Optional - Random state for reproducibility. - `auto_ncomp` (bool) - Optional - Automatically determine number of components. ### Response No return value. ``` -------------------------------- ### Normalization and alignment with Normalise and icoshift_align Source: https://github.com/aeiwz/metbit/blob/main/README.md Shows three preprocessing steps: Probabilistic Quotient Normalization (pqn), Multiplicative Scatter Correction (msc), and Icoshift spectral alignment. The alignment uses n_intervals="whole" and operates on the normalized DataFrame. ```python from metbit import Normalise, icoshift_align # Probabilistic Quotient Normalization normalised = Normalise(spectra_df).pqn() # Multiplicative Scatter Correction normalised = Normalise(spectra_df).msc() # Icoshift spectral alignment aligned = icoshift_align(normalised, n_intervals="whole") ``` -------------------------------- ### Typical Workflow: Preprocess, Normalize, and Model with OPLS-DA Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/overview/page.mdx Shows the core metbit workflow: load spectra, normalize with PQN, fit an OPLS-DA model, and plot scores and VIP. Requires a CSV with a 'Group' column and numeric feature columns. ```python import pandas as pd from metbit import Normalization, opls_da df = pd.read_csv("spectra.csv") y = df["Group"] X = df.drop(columns=["Group"]) features = X.columns.astype(float) X_norm = Normalization.pqn_normalization(X) model = opls_da( X=X_norm, y=y, features_name=features, n_components=2, scaling_method="pareto", kfold=3, estimator="opls", random_state=42, auto_ncomp=True, ) model.fit() model.plot_oplsda_scores().show() model.vip_plot(threshold=1.0).show() ``` -------------------------------- ### Fit lazy OPLS-DA model Source: https://github.com/aeiwz/metbit/blob/main/README.rst Fits the lazy OPLS-DA model. The output shows progress bars and timing for permutation tests and feature processing. ```python lazy_mod.fit() ``` -------------------------------- ### Assign object to perform PCA: prepare X, features_name, color_, symbol_, time_order Source: https://github.com/aeiwz/metbit/blob/main/README.rst Prepares the data structures required for the PCA object: X is the feature data frame (columns from index 2 onward), features_name is the column names converted to float, color_ is the group series, symbol_ is the time point series, and time_order maps time points to symbol order. ```python X = df.iloc[:, 2:] features_name = X.columns.astype(float).to_list() color_ = df["Group"] symbol_ = df["Time point"] time_order = {1:0, 2:1, 3:2, 4:2} ``` -------------------------------- ### Visualisation: plot PCA trajectory (PC1 vs PC3) Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a time trajectory plot of PCA scores for PC1 and PC3, using the time_ and time_order parameters. ```python pca_mod.plot_pca_trajectory(time_=symbol_, time_order=time_order, pc=["PC1", "PC3"]) ``` -------------------------------- ### PLS.__init__() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/pls/page.mdx Constructor for the PLS class. Initializes a new PLS model instance. ```APIDOC ## PLS.__init__() ### Description Constructor for the PLS class. Initializes a new PLS model instance. ### Method Constructor ### Signature `__init__()` ### Parameters None documented. ``` -------------------------------- ### Visualisation: plot cumulative variance Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a plot of cumulative explained variance from the fitted PCA model. ```python pca_mod.plot_cumulative_observed() ``` -------------------------------- ### Backend dispatch hierarchy Source: https://github.com/aeiwz/metbit/blob/main/README.md Shows the four-tier auto-dispatch backend used by all v9.1.0 modules. The backend selects GPU (CuPy/PyTorch CUDA) for >500M elements, C+OpenMP for >10M, multiprocessing+NumPy when C extension is absent, and chunked NumPy as universal fallback. ```text GPU (CuPy / PyTorch CUDA) >500 M elements, GPU memory fits ↓ C + OpenMP >10 M elements, C extension compiled ↓ Multiprocessing + NumPy C extension absent, many cores available ↓ Chunked NumPy universal fallback, bounded memory ``` -------------------------------- ### Visualisation: plot PCA trajectory (PC1 vs PC2) Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a time trajectory plot of PCA scores for PC1 and PC2, using the time_ and time_order parameters. ```python pca_mod.plot_pca_trajectory(time_=symbol_, time_order=time_order, pc=["PC1", "PC2"]) ``` -------------------------------- ### OPLS-DA visualisation: plot OPLS-DA scores Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a scores plot for the fitted OPLS-DA model. ```python opls_da_mod.plot_oplsda_scores() ``` -------------------------------- ### Visualisation: plot PCA scores (PC1 vs PC2) Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates a PCA scores plot for PC1 and PC2, using the symbol_ series to label time points. ```python pca_mod.plot_pca_scores(pc=["PC1", "PC2"], symbol_=symbol_) ``` -------------------------------- ### OPLS-DA: import metbit.opls_da and pandas Source: https://github.com/aeiwz/metbit/blob/main/README.rst Imports the opls_da function from metbit and pandas for data handling. ```python from metbit import opls_da import pandas as pd ``` -------------------------------- ### SpectraPlot: overlay, mean_sd, stacked, single views Source: https://github.com/aeiwz/metbit/blob/main/README.md Creates an interactive Plotly figure from NMR spectra with four view methods: overlay (colored by group), mean±SD ribbon, stacked, and single-sample. Requires a spectra DataFrame, ppm array, and optional labels. ```python from metbit import SpectraPlot sp = SpectraPlot(X=spectra_df, ppm=ppm, label=y) sp.overlay() # all spectra overlaid, colored by group sp.mean_sd() # group mean with shaded ±1 SD ribbon sp.stacked() # vertically stacked spectra sp.single(idx=0) # single sample spectrum ``` -------------------------------- ### annotate_peak.__init__(meta, spectra, ppm, label, colour_dict) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/annotate_peak/page.mdx Initializes the annotate_peak Dash application with the provided NMR spectra data, ppm values, labels, and optional colour dictionary. This constructor sets up the interactive annotation environment. ```APIDOC ## annotate_peak.__init__(meta, spectra, ppm, label, colour_dict) ### Description Initializes the annotate_peak Dash application with the provided NMR spectra data, ppm values, labels, and optional colour dictionary. This constructor sets up the interactive annotation environment. ### Method Constructor ### Parameters - **meta** (DataFrame) - Required - Metadata for the spectra. - **spectra** (DataFrame) - Required - NMR spectra data. - **ppm** (list) - Required - List of ppm values corresponding to the spectra. - **label** (Series or DataFrame) - Required - Labels for the spectra. - **colour_dict** (dict) - Optional - Dictionary mapping labels to colours. ### Usage Example ```python annotator = annotate_peak(label, spectra, ppm, label) ``` ``` -------------------------------- ### oplsda_path Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/utility/page.mdx Class for managing OPLS-DA paths. ```APIDOC ## Class: oplsda_path ### Description Class for managing OPLS-DA paths. ### Methods #### __init__(data_path) #### make_path() #### get_path() ``` -------------------------------- ### metbit.gpu_available() Source: https://github.com/aeiwz/metbit/blob/main/README.md Checks if GPU support (CuPy or PyTorch CUDA) is available. ```APIDOC ## metbit.gpu_available() ### Description Checks if GPU support (CuPy or PyTorch CUDA) is available. ### Returns - **bool**: True if GPU support is available, False otherwise. ### Example ```python import metbit print(metbit.gpu_available()) ``` ``` -------------------------------- ### pickie_peak.__init__(spectra, ppm, label) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/ui_picky_peak/page.mdx Initializes the pickie_peak class with NMR spectral data. This constructor sets up the object with the provided spectra, ppm values, and an optional label for the plot. ```APIDOC ## pickie_peak.__init__(spectra, ppm, label) ### Description Initializes the pickie_peak class with NMR spectral data. ### Method Constructor ### Parameters - **spectra** (type not specified) - Required - The NMR spectral data. - **ppm** (type not specified) - Required - The ppm values for the spectral data. - **label** (type not specified) - Required - A label for the plot. ### Returns None ``` -------------------------------- ### OPLS-DA visualisation: plot S-scores Source: https://github.com/aeiwz/metbit/blob/main/README.rst Generates an S-scores plot for the fitted OPLS-DA model. ```python opls_da_mod.plot_s_scores() ``` -------------------------------- ### OPLS-DA: load data and exclude baseline (Time point 1) Source: https://github.com/aeiwz/metbit/blob/main/README.rst Loads the tutorial data from CSV and removes rows where 'Time point' equals 1 (baseline). ```python df = pd.read_csv("metbit_tutorial_data.csv") #Exclude base line (Time point 1) df.drop(df.loc[df["Time point"]==1].index, inplace=True) ``` -------------------------------- ### gen_page.__init__(data_path) Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/genpage/page.mdx Initializes the gen_page class with the path to the data folder. This constructor prepares the object to generate HTML files for OPLS-DA plots. ```APIDOC ## gen_page.__init__(data_path) ### Description Initializes the gen_page class with the path to the data folder. This constructor prepares the object to generate HTML files for OPLS-DA plots. ### Method Constructor ### Parameters - `data_path` (str) - Required - The path to the data folder. ### Usage Example ```python gen_page(data_path).get_files() ``` ``` -------------------------------- ### OPLS.__init__() Source: https://github.com/aeiwz/metbit/blob/main/docs/app/docs/api/opls/page.mdx Initializes the OPLS model. The method is currently a placeholder with a TODO for adding an argument to specify the PLS method. ```APIDOC ## OPLS.__init__() ### Description Initializes the OPLS model. The method is currently a placeholder with a TODO for adding an argument to specify the PLS method. ### Method Constructor ### Parameters None documented. ```