Class MultiScalePINN<T>
- Namespace
- AiDotNet.PhysicsInformed.PINNs
- Assembly
- AiDotNet.dll
Implements a Multi-Scale Physics-Informed Neural Network for solving PDEs with multiple scales.
public class MultiScalePINN<T> : NeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable
Type Parameters
TThe numeric type used for calculations.
- Inheritance
-
MultiScalePINN<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
For Beginners: Multi-scale problems are challenging because features span vastly different sizes. A single neural network struggles to capture both large-scale trends and fine details.
Solution: Multi-Scale PINN Uses multiple sub-networks, each specialized for a different scale:
- Coarse network: Captures large-scale, smooth variations
- Fine network(s): Capture small-scale details and fluctuations
Architecture: Input (x,t) → [Coarse Net] → u_coarse(x,t) → [Fine Net 1] → u_fine1(x,t) → [Fine Net 2] → u_fine2(x,t) → ...
Total solution: u(x,t) = u_coarse + u_fine1 + u_fine2 + ...
Training Strategy:
- Progressive Training: Train coarse first, then add finer scales
- Simultaneous Training: Train all scales together with adaptive weights
- Alternating Training: Alternate between scales during training
Key Features:
- Fourier feature encoding at different frequencies for each scale
- Adaptive loss weighting to balance scale contributions
- Scale coupling terms to ensure consistency
- Progressive activation of finer scales during training
Applications:
- Turbulence modeling (large eddies + small vortices)
- Composite materials (macroscopic + fiber-scale behavior)
- Multi-physics problems (thermal + mechanical + chemical)
- Climate modeling (global + regional + local scales)
Constructors
MultiScalePINN(NeuralNetworkArchitecture<T>, IMultiScalePDE<T>, IBoundaryCondition<T>[], IInitialCondition<T>?, int, MultiScaleTrainingOptions<T>?, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?)
Initializes a new instance of the Multi-Scale PINN.
public MultiScalePINN(NeuralNetworkArchitecture<T> architecture, IMultiScalePDE<T> multiScalePDE, IBoundaryCondition<T>[] boundaryConditions, IInitialCondition<T>? initialCondition = null, int numCollocationPointsPerScale = 5000, MultiScaleTrainingOptions<T>? trainingOptions = null, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? optimizer = null)
Parameters
architectureNeuralNetworkArchitecture<T>The base neural network architecture.
multiScalePDEIMultiScalePDE<T>The multi-scale PDE specification.
boundaryConditionsIBoundaryCondition<T>[]Boundary conditions for the problem.
initialConditionIInitialCondition<T>Initial condition for time-dependent problems (optional).
numCollocationPointsPerScaleintNumber of collocation points per scale.
trainingOptionsMultiScaleTrainingOptions<T>Options for multi-scale training.
optimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optimization algorithm.
Remarks
For Beginners:
This creates separate neural networks for each scale:
- Coarse network: Wider/shallower, larger learning rate
- Fine networks: Deeper, smaller learning rate, Fourier features
The collocation points are generated at different densities:
- Fewer points for coarse scale (smooth variations)
- More points for fine scales (detailed features)
Properties
NumberOfScales
Gets the number of scales in this multi-scale PINN.
public int NumberOfScales { get; }
Property Value
ParameterCount
Gets the total number of parameters in the model.
public override int ParameterCount { get; }
Property Value
Remarks
For Beginners: This tells you how many adjustable values (weights and biases) your neural network has. More complex networks typically have more parameters and can learn more complex patterns, but also require more data to train effectively. This is part of the IFullModel interface for consistency with other model types.
Performance: This property uses caching to avoid recomputing the sum on every access. The cache is invalidated when layers are modified.
ScaleCharacteristicLengths
Gets the characteristic length scales.
public T[] ScaleCharacteristicLengths { get; }
Property Value
- T[]
SupportsJitCompilation
Gets whether this model currently supports JIT compilation.
public override bool SupportsJitCompilation { get; }
Property Value
- bool
True if the model can be JIT compiled, false otherwise.
Remarks
Some models may not support JIT compilation due to: - Dynamic graph structure (changes based on input) - Lack of computation graph representation - Use of operations not yet supported by the JIT compiler
For Beginners: This tells you whether this specific model can benefit from JIT compilation.
Models return false if they:
- Use layer-based architecture without graph export (e.g., current neural networks)
- Have control flow that changes based on input data
- Use operations the JIT compiler doesn't understand yet
In these cases, the model will still work normally, just without JIT acceleration.
SupportsTraining
Indicates whether this network supports training (learning from data).
public override bool SupportsTraining { get; }
Property Value
Remarks
For Beginners: Not all neural networks can learn. Some are designed only for making predictions with pre-set parameters. This property tells you if the network can learn from data.
Methods
CreateNewInstance()
Creates a new instance of the same type as this neural network.
protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()
Returns
- IFullModel<T, Tensor<T>, Tensor<T>>
A new instance of the same neural network type.
Remarks
For Beginners: This creates a blank version of the same type of neural network.
It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.
DeserializeNetworkSpecificData(BinaryReader)
Deserializes network-specific data that was not covered by the general deserialization process.
protected override void DeserializeNetworkSpecificData(BinaryReader reader)
Parameters
readerBinaryReaderThe BinaryReader to read the data from.
Remarks
This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.
For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.
Forward(Tensor<T>)
Forward pass through all scale networks.
public Tensor<T> Forward(Tensor<T> input)
Parameters
inputTensor<T>Input coordinates [batch, inputDim].
Returns
- Tensor<T>
Combined output from all scales [batch, outputDim].
ForwardWithMemory(Tensor<T>)
Performs a forward pass through the network while storing intermediate values for backpropagation.
public override Tensor<T> ForwardWithMemory(Tensor<T> input)
Parameters
inputTensor<T>The input data to the network.
Returns
- Tensor<T>
The output of the network.
Remarks
For Beginners: This method passes data through the network from input to output, but also remembers all the intermediate values. This is necessary for the learning process, as the network needs to know these values when figuring out how to improve.
API Change Note: The signature changed from Vector<T> to Tensor<T> to support multi-dimensional inputs. This is a breaking change. For backward compatibility, consider adding an overload that accepts Vector<T> and converts it internally to Tensor<T>.
Exceptions
- InvalidOperationException
Thrown when the network doesn't support training.
GetGradients()
Gets the gradients from all layers in the neural network.
public override Vector<T> GetGradients()
Returns
- Vector<T>
A vector containing all gradients from all layers concatenated together.
Remarks
This method collects the gradients from every layer in the network and combines them into a single vector. This is useful for optimization algorithms that need access to all gradients at once.
For Beginners: During training, each layer calculates how its parameters should change (the gradients). This method gathers all those gradients from every layer and puts them into one long list.
Think of it like:
- Each layer has notes about how to improve (gradients)
- This method collects all those notes into one document
- The optimizer can then use this document to update the entire network
This is essential for the learning process, as it tells the optimizer how to adjust all the network's parameters to improve performance.
GetModelMetadata()
Gets the metadata for this neural network model.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
GetParameters()
Gets all trainable parameters of the network as a single vector.
public override Vector<T> GetParameters()
Returns
- Vector<T>
A vector containing all parameters of the network.
Remarks
For Beginners: Neural networks learn by adjusting their "parameters" (also called weights and biases). This method collects all those adjustable values into a single list so they can be updated during training.
InitializeLayers()
Initializes the layers of the neural network based on the architecture.
protected override void InitializeLayers()
Remarks
For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.
Predict(Tensor<T>)
Makes a prediction using the neural network.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>The input data to process.
Returns
- Tensor<T>
The network's prediction.
Remarks
For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe BinaryWriter to write the data to.
Remarks
This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.
For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.
Solve(int, double, bool)
Solves the multi-scale PDE using physics-informed training.
public TrainingHistory<T> Solve(int epochs = 1000, double learningRate = 0.001, bool verbose = true)
Parameters
epochsintNumber of training epochs.
learningRatedoubleLearning rate.
verboseboolWhether to print progress.
Returns
- TrainingHistory<T>
Training history.
Train(Tensor<T>, Tensor<T>)
Trains the neural network on a single input-output pair.
public override void Train(Tensor<T> input, Tensor<T> expectedOutput)
Parameters
inputTensor<T>The input data.
expectedOutputTensor<T>The expected output for the given input.
Remarks
This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.
For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)
The network then:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- Adjusts its internal values to do better next time
After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.
UpdateParameters(Vector<T>)
Updates the network's parameters with new values.
public override void UpdateParameters(Vector<T> parameters)
Parameters
parametersVector<T>The new parameter values to set.
Remarks
For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.
This is typically used by optimization algorithms that calculate better parameter values based on training data.