Module_Examples - vorcyc/Vorcyc.Mathematics GitHub Wiki

Location: Home / Examples

Examples - Examples

The Examples/ folder at the repository root contains standalone runnable sample projects. These projects reference the main library Vorcyc.Mathematics (targets/dotNET10_Portable) and demonstrate how to use each module's API in real-world scenarios; they are not included in the NuGet package and must be built and run from source.

Project Path Primary Modules Description
Audio WAV + MFCC Examples/Audio_example/ SignalProcessing, DeepLearning, NAudio NAudio read/write WAV, MFCC analysis, training and inference
Core / linear algebra / statistics Examples/Core_example/ ComputingContext, LinearAlgebra, Statistics MatrixFp32 multiply, Span statistics, VectorSpan, scope resolution
Machine learning Examples/MachineLearning_example/ MachineLearning 0.9 classification/regression pipelines, trees/forests, ensemble learning, CV/grid search
Image colorization Examples/Colorization_example/ DeepLearning, LinearAlgebra ColorNet / ChromaGAN black-and-white image colorization
Signal processing Examples/SignalProcessing_example/ SignalProcessing Signal synthesis, FFT, filtering, MFCC, effects, parallel features
Deep learning Examples/DeepLearning_example/ DeepLearning XOR/batch training/CNN+MLP/audio classification, serialization, MlpRegressor curve fitting
Calculus Examples/Calculus_example/ Calculus Integration, derivatives, ODE, root finding, series

πŸ“’Contents


Directory Layout Convention

Examples/
└── <example_name>_example/
    β”œβ”€β”€ <example_name>_example.csproj   # References dotNET10_Portable
    β”œβ”€β”€ Program.cs                # CLI entry point
    β”œβ”€β”€ models/                   # Exported .vmdl (optional, copied to output on build)
    └── …                         # Model definitions, serialization, image I/O, etc.

When adding a new example:

  1. Create a standalone .csproj under Examples/ with TargetFramework matching the main library (net10.0).
  2. Add the project to the /Examples/ folder in Vorcyc.Mathematics.slnx.
  3. Append a row to the table on this page and add a corresponding section.

Audio_example β€” NAudio Audio Pipeline

End-to-end demo: NAudio read/write WAV β†’ Vorcyc Signal β†’ MFCC β†’ BatchSequential training/inference. Closer to real projects than the audio command in DeepLearning_example (.wav files on disk rather than in-memory synthesized waves).

Dependencies

Package Version Purpose
NAudio 2.2.1 AudioFileReader / WaveFileWriter read/write channel WAV
Vorcyc.Mathematics Project reference Signal, MFCC, AudioTrainingSamples, ModelSerializer

Command-Line Usage

# Full pipeline: generate demo WAV β†’ train β†’ analyze β†’ infer
dotnet run --project Examples/Audio_example

dotnet run --project Examples/Audio_example -- prepare
dotnet run --project Examples/Audio_example -- analyze data/class_low/tone_220hz.wav
dotnet run --project Examples/Audio_example -- analyze my.wav --csv mfcc.csv
dotnet run --project Examples/Audio_example -- train --epochs 3000
dotnet run --project Examples/Audio_example -- predict data/class_high/tone_1200hz.wav
dotnet run --project Examples/Audio_example -- help

Data directory (default under output directory bin/.../net10.0/data/):

data/
β”œβ”€β”€ class_low/    # Label low: low-frequency demo tones (replace with your own WAV files)
└── class_high/   # Label high: high-frequency demo tones
models/
└── pitch_mfcc.vmdl   # BatchSequential weights saved after train

Code Structure

Examples/Audio_example/
β”œβ”€β”€ Program.cs
β”œβ”€β”€ PitchClassifierConfig.cs
β”œβ”€β”€ Io/
β”‚   └── WavBridge.cs              # NAudio ↔ Signal (with resampling)
└── Pipeline/
    β”œβ”€β”€ DemoDataFactory.cs        # Generate 16-bit PCM demo WAV
    β”œβ”€β”€ LabeledWavDataset.cs      # Load labeled dataset by folder
    β”œβ”€β”€ MfccFileAnalyzer.cs       # analyze: RMS / FFT / MFCC
    └── PitchClassifierTrainer.cs # train / predict + ModelSerializer

Differences from DeepLearning_example audio

Audio_example DeepLearning_example -- audio
Input Disk WAV (NAudio) In-memory GenerateWave
External dependencies NAudio None
Model persistence .vmdl save/load None
Best for File I/O + deployed inference Quick API wiring validation

Core_example β€” Core and ComputingContext

Demonstrates ComputingContext, MatrixFp32.Multiply, Span statistics extensions, and VectorSpan hot-path APIs. No extra NuGet packages; runs cross-platform. Complements the Module_ComputingContext manual.

Command-Line Usage

dotnet run --project Examples/Core_example
dotnet run --project Examples/Core_example -- matrix
dotnet run --project Examples/Core_example -- statistics
dotnet run --project Examples/Core_example -- vector
dotnet run --project Examples/Core_example -- context
dotnet run --project Examples/Core_example -- help

Code Structure

Examples/Core_example/
β”œβ”€β”€ Program.cs
β”œβ”€β”€ MatrixDemo.cs           # MatrixFp32.Multiply + ComputingScope
β”œβ”€β”€ StatisticsDemo.cs       # Sum / Average / StandardDeviation
β”œβ”€β”€ VectorDemo.cs           # Dot / Norm / Axpy
└── ComputingContextDemo.cs # Explicit parameters vs Scope priority

MachineLearning_example β€” Tabular Learning

Demonstrates typical 0.9 machine learning module workflows: synthetic three-cluster 2D data, DataSplit partitioning, training and evaluation with multiple IClassifier<double> implementations, ClassificationPipeline, grid search and K-fold cross-validation, plus regression pipeline examples. No extra NuGet dependencies; runs cross-platform.

Command-Line Usage

# Overview (default): classification + regression
dotnet run --project Examples/MachineLearning_example

# Classification only
dotnet run --project Examples/MachineLearning_example -- classify

# Regression: KnnRegressor, RegressionPipeline batch prediction, ridge regression, K-fold CV
dotnet run --project Examples/MachineLearning_example -- regression

dotnet run --project Examples/MachineLearning_example -- help

Code Structure

Examples/MachineLearning_example/
β”œβ”€β”€ Program.cs              # classify / regression CLI
β”œβ”€β”€ BlobDataset.cs          # Three-cluster synthetic classification data
└── RegressionDataset.cs    # Synthetic regression data

For batch inference performance comparison, see `benchmarks/basic_benchmark/MachineLearning_batch_benchmark.cs` (uncomment in `Program.cs` to run).

Full API documentation and copy-paste snippets: Machine Learning Module β€” 0.9 classifier walkthrough.


Colorization_example β€” Image Colorization

Colorizes grayscale or color photos, ported from the NeuralColor / Colorization approach in Vorcyc.AwesomeAI, rewritten with the 0.9 DeepLearning Modules API (Convolution2DLayer, BatchNormLayer, ReLUActivation, etc.) and custom model containers; image I/O uses Emgu.CV.

Models and Scenarios

Scenario CLI --scenario Network Best for
Realistic realistic (default) ColorNet Landscapes, architecture, natural scenes
People people ChromaGAN Portraits, group photos

Both networks use dual-branch or encode-fusion structures that cannot be described by a single BatchSequential, so the sample project implements ColorNetModel / ChromaGanModel; weights are saved via sample-specific serializers as VMDL v3 variants (ModelKind = 4 / 5, see VmdlTensorArchive).

File Format Description
*.HModel Half-precision binary (legacy) Original ColorfulSoft weights
*.vmdl VMDL v3 (float64 tensors) Exported new format used for inference

Default paths (overridable on the command line):

  • ColorNet: models/Colornet.vmdl, legacy model model_zoo/vision/colorization/Colornet.HModel
  • ChromaGAN: models/ChromaGAN.vmdl, legacy model model_zoo/vision/colorization/ChromaGAN.HModel

Dependencies

In addition to the main library, the sample project references:

Package Version Purpose
Emgu.CV 4.9.0.5494 Read images, resize, color spaces
Emgu.CV.runtime.windows 4.9.0.5494 Windows native OpenCV runtime

Runtime must be Windows (Emgu runtime package). On Linux/macOS, replace with the corresponding Emgu runtime or rewrite image I/O.

Export from Legacy HModel

If you only have .HModel, export to .vmdl first:

cd Examples/Colorization_example

# ColorNet
dotnet run -- export colornet <Colornet.HModel path> models/Colornet.vmdl

# ChromaGAN
dotnet run -- export chromagan <ChromaGAN.HModel path> models/ChromaGAN.vmdl

Export flow: half-precision decode (Legacy/HalfHelper) β†’ populate ColorNetModel / ChromaGanModel Parameter β†’ ColorNetSerializer / ChromaGanSerializer write VMDL.

If the target .vmdl does not exist when running colorize and the corresponding .HModel exists at the default path, the program auto-exports before inference.

Command-Line Usage

# Realistic colorization (ColorNet)
dotnet run --project Examples/Colorization_example -- colorize photo.jpg result.jpg --scenario realistic

# People colorization (ChromaGAN)
dotnet run --project Examples/Colorization_example -- colorize photo.jpg result.jpg --scenario people

# Specify model file
dotnet run --project Examples/Colorization_example -- colorize photo.jpg out.jpg --scenario people --model models/ChromaGAN.vmdl

Command summary

Command Description
export <colornet|chromagan> [hmodel] [vmdl] Legacy weights β†’ VMDL
colorize <image> [output] [--scenario realistic|people] [--model path] Colorize and save JPEG

Code Structure

Examples/Colorization_example/
β”œβ”€β”€ Program.cs                 # export / colorize CLI
β”œβ”€β”€ ColorizationEnhancer.cs      # Unified entry (Scenario + model loading)
β”œβ”€β”€ Models/
β”‚   β”œβ”€β”€ ColorNetModel.cs       # ColorNet forward (Modules API)
β”‚   β”œβ”€β”€ ChromaGanModel.cs      # ChromaGAN forward
β”‚   β”œβ”€β”€ SpatialLinearLayer.cs  # GFN / global2 spatial fully connected
β”‚   └── ModelWeightUtils.cs    # Weight copy helpers
β”œβ”€β”€ Legacy/
β”‚   β”œβ”€β”€ HalfHelper.cs          # half β†’ float
β”‚   β”œβ”€β”€ HModelReader.cs        # ColorNet HModel
β”‚   └── HModelChromaGanReader.cs
β”œβ”€β”€ Serialization/
β”‚   β”œβ”€β”€ VmdlTensorArchive.cs   # Shared VMDL tensor read/write
β”‚   β”œβ”€β”€ ColorNetSerializer.cs  # ModelKind = 4
β”‚   └── ChromaGanSerializer.cs # ModelKind = 5
└── Vision/
    β”œβ”€β”€ ColorNetIo.cs          # Emgu preprocessing / LAB compositing
    └── ChromaGanIo.cs

Programmatic usage example

using Colorization_example;
using Emgu.CV;

using var enhancer = new ColorizationEnhancer(
    ColorizationEnhancer.Scenario.RealisticView,
    @"models/Colornet.vmdl");

using var input = new Mat(@"photo.jpg");
using var output = enhancer.Colorize(input);
CvInvoke.Imwrite(@"result.jpg", output);

Relationship to the Deep Learning Module

Capability Main library ModelSerializer v3 This sample
Supported containers Sequential, BatchSequential, CnnMlp, BatchParallelConcat Custom ColorNetModel / ChromaGanModel
Layer API Modules.* Same + legacy Layers.JoinLayer / Fusion / Upsample2D
Serialization Architecture LayerDescriptor + weights Fixed topology; read/write named tensors in order

Full training stack documentation: Deep Learning Module. This sample demonstrates inference and legacy weight migration only; to train similar networks, implement Forward / Backward on top of main library containers or extend ModelSerializer.


SignalProcessing_example β€” Signal Processing

Demonstrates 0.9 Signal main API: waveform synthesis, TransformToFrequencyDomain, Butterworth low-pass, MfccExtractor (HTK preset), and TremoloEffect. No extra NuGet packages; runs cross-platform.

Command-Line Usage

dotnet run --project Examples/SignalProcessing_example
dotnet run --project Examples/SignalProcessing_example -- synth
dotnet run --project Examples/SignalProcessing_example -- fft
dotnet run --project Examples/SignalProcessing_example -- filter
dotnet run --project Examples/SignalProcessing_example -- mfcc --csv mfcc.csv
dotnet run --project Examples/SignalProcessing_example -- effect
dotnet run --project Examples/SignalProcessing_example -- context
dotnet run --project Examples/SignalProcessing_example -- help

Code Structure

Examples/SignalProcessing_example/
β”œβ”€β”€ Program.cs
β”œβ”€β”€ SynthDemo.cs
β”œβ”€β”€ FftDemo.cs
β”œβ”€β”€ FilterDemo.cs
β”œβ”€β”€ MfccDemo.cs
β”œβ”€β”€ EffectDemo.cs
└── ContextDemo.cs      # GetRms, ParallelComputeFrom(MFCC)

FftDemo and ContextDemo demonstrate ComputingContext / ComputingScope (FFT, RMS, parallel MFCC).


DeepLearning_example β€” Deep Learning

Demonstrates the differentiable training stack: Sequential / BatchSequential + Trainer (XOR, batch XOR, CNN+MLP, MFCC audio classification), computingContext parameters, ModelSerializer v3 round-trip, and MlpRegressor (DeepLearning.Training) curve fitting (y=x^2).

Command-Line Usage

dotnet run --project Examples/DeepLearning_example
dotnet run --project Examples/DeepLearning_example -- xor
dotnet run --project Examples/DeepLearning_example -- classify
dotnet run --project Examples/DeepLearning_example -- batch
dotnet run --project Examples/DeepLearning_example -- cnn
dotnet run --project Examples/DeepLearning_example -- audio
dotnet run --project Examples/DeepLearning_example -- serialize
dotnet run --project Examples/DeepLearning_example -- curvefit
dotnet run --project Examples/DeepLearning_example -- help
Command Highlights
batch FitBatched + ComputingContext.Parallel
cnn CnnMlpModel + FitCnnMlp (4Γ—4 left/right patterns)
audio AudioTrainingSamples.FeatureMeanClassification + FitBatchSequential

Code Structure

Examples/DeepLearning_example/
β”œβ”€β”€ Program.cs
β”œβ”€β”€ XorDemo.cs
β”œβ”€β”€ ClassifyDemo.cs
β”œβ”€β”€ BatchTrainDemo.cs
β”œβ”€β”€ CnnMlpDemo.cs
β”œβ”€β”€ AudioClassifyDemo.cs
β”œβ”€β”€ SerializeDemo.cs
└── CurveFitDemo.cs

Calculus_example β€” Calculus

Demonstrates numerical integration (trapezoidal / Romberg / Gauss-Legendre), derivatives and gradients, RK4 ODE solving, Newton/Brent root finding, and Taylor / Fourier series.

Command-Line Usage

dotnet run --project Examples/Calculus_example
dotnet run --project Examples/Calculus_example -- integrate
dotnet run --project Examples/Calculus_example -- derivative
dotnet run --project Examples/Calculus_example -- ode
dotnet run --project Examples/Calculus_example -- root
dotnet run --project Examples/Calculus_example -- series
dotnet run --project Examples/Calculus_example -- help

Code Structure

Examples/Calculus_example/
β”œβ”€β”€ Program.cs
β”œβ”€β”€ IntegrationDemo.cs
β”œβ”€β”€ DerivativeDemo.cs
β”œβ”€β”€ OdeDemo.cs
β”œβ”€β”€ RootFindingDemo.cs
└── SeriesDemo.cs

⚠️ **GitHub.com Fallback** ⚠️