API Reference
MaterForge - Materials Formulation Engine with Python
A high-performance Python library for material property modeling and analysis. MaterForge provides comprehensive tools for defining, processing, and evaluating material properties as functions of temperature and other dependencies.
Key Features: - Temperature-dependent material property modeling - Multiple property definition formats (YAML-based) - Symbolic mathematics integration with SymPy - Piecewise function creation and evaluation - Material property visualization - Regression and data analysis capabilities - Integration with numerical simulation frameworks
Main Components: - Core: Material definitions and fundamental data structures - Parsing: YAML configuration parsing and property processing - Algorithms: Mathematical operations and property computations - Visualization: Property plotting and analysis tools - Data: Material databases and physical constants
- class materforge.FitQuality(property, r_squared, rmse, mae, max_abs_error, n_points)[source]
Bases:
objectGoodness-of-fit summary for one property against its source data.
- Parameters:
- property
Property name.
- r_squared
Coefficient of determination (
1.0is a perfect fit).
- rmse
Root-mean-square error, in the property’s units.
- mae
Mean absolute error.
- max_abs_error
Largest single absolute error.
- n_points
Number of source data points compared.
-
mae:
float
-
max_abs_error:
float
-
n_points:
int
-
property:
str
-
r_squared:
float
-
rmse:
float
- class materforge.Material(name, properties=<factory>, sample_data=<factory>)[source]
Bases:
objectGeneric material container with fully dynamic property tracking. All material properties are assigned dynamically via setattr and tracked automatically.
- name
Human-readable material identifier.
- properties
Dictionary with all properties.
- sample_data
Source data points each data-backed property was built from, keyed by property name. Populated during
create_material(); empty for a material produced byevaluate(). Consumed by thematerforge.analysisand plotting helpers.
- compile(symbol=None)[source]
Builds a reusable evaluator with cached numeric callables.
Each property is lambdified once and reused, so sweeping many dependency values - or evaluating over a NumPy array in one call - is far faster than repeated symbolic
evaluate().- Parameters:
symbol (
Optional[Symbol]) – Dependency symbol to evaluate against. Inferred from the properties’ free symbols when omitted.- Return type:
MaterialEvaluator- Returns:
A
MaterialEvaluatorsnapshot of this material.
Example
>>> ev = material.compile() >>> ev(500.0) # {'density': 2634.5, ...} >>> ev(np.linspace(300, 900, 200)) # arrays, one call per property
- evaluate(symbol, value)[source]
Evaluates all properties by substituting symbol=value.
- Parameters:
symbol (
Symbol) – SymPy symbol to substitute (e.g. sp.Symbol(‘T’)).value – Value to substitute.
- Return type:
Material- Returns:
New Material instance with name ‘{name}@{symbol}={value}’ and all properties substituted at the given value. Properties that fail evaluation are silently excluded.
- Raises:
ValueError – If symbol is not sp.Symbol, or value is non-numeric.
-
name:
str
- class materforge.MaterialEvaluator(material, symbol=None)[source]
Bases:
objectCompiled, reusable numeric evaluator for a material’s properties.
Each property is lambdified once against the material’s dependency symbol and cached. Calling the evaluator with a scalar returns a
dictof floats; calling it with an array returns adictof NumPy arrays shaped like the input. Constant properties are broadcast to match.The evaluator is a snapshot taken at construction time: if the material’s properties change afterwards, build a fresh evaluator with
Material.compile().- Parameters:
material (
Material) – A fully processed Material instance.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against. If omitted, it is inferred from the free symbols of the material’s properties (the common case, where every property is a function of a single dependency). Pass it explicitly to disambiguate or to pin the variable for an all-constant material.
- Raises:
TypeError – symbol is given but is not a sympy Symbol.
ValueError – The properties depend on more than one symbol (multivariate materials are not yet supported), or on a symbol other than the one supplied.
- evaluate(value)[source]
Alias for calling the evaluator; see
__call__().
- function(name)[source]
Returns the cached numeric callable for a single property.
Useful when you only need one property, or want to hand the raw callable to another numerical routine.
- property symbol: Symbol | None
The dependency symbol this evaluator substitutes (None if all-constant).
- class materforge.PiecewiseBuilder[source]
Bases:
objectCentralised piecewise function creation with different build strategies.
- static build_from_data(dep_array, prop_array, dependency, config, prop_name)[source]
Builds a piecewise function from raw dependency-value arrays.
Handles ascending/descending input, optional pre-regression, and symbol substitution when the caller uses a non-placeholder symbol.
- Parameters:
- Return type:
Piecewise- Returns:
Symbolic piecewise function expressed in terms of dependency.
- Raises:
ValueError – On null/empty/mismatched arrays or build failure.
- static build_from_formulas(dep_points, equations, dependency, lower_bound_type='constant', upper_bound_type='constant')[source]
Builds a piecewise function from symbolic equations and breakpoints.
- Parameters:
dep_points (
ndarray) – Breakpoints defining segment boundaries (n+1 for n equations).equations (
List[Union[str,Expr]]) – Symbolic expressions as strings or SymPy Expr objects.dependency (
Symbol) – SymPy symbol used in the equations.lower_bound_type (
str) – Boundary behaviour below dep_points[0].upper_bound_type (
str) – Boundary behaviour above dep_points[-1].
- Return type:
Piecewise- Returns:
Symbolic piecewise function.
- Raises:
ValueError – On mismatched counts, invalid symbols, or parse failures.
- class materforge.PiecewiseInverter(tolerance=1e-12)[source]
Bases:
objectCreates inverse functions for linear piecewise functions (degree <= 1 only).
- Parameters:
tolerance (float)
- static create_inverse(piecewise_func, input_symbol, output_symbol, tolerance=1e-12)[source]
Creates the inverse of a linear piecewise function.
- Parameters:
piecewise_func (
Union[Piecewise,Expr]) – Original piecewise function f(input_symbol).input_symbol (
Union[Symbol,Basic]) – Independent variable of the original function.output_symbol (
Union[Symbol,Basic]) – Symbol for the inverse function’s argument.tolerance (
float) – Numerical tolerance for inversion stability.
- Return type:
Piecewise- Returns:
Inverse piecewise function expressed in terms of output_symbol.
- Raises:
ValueError – If any piece has degree > 1 or the function is non-monotonic.
Example
>>> dep = sp.Symbol("T") >>> E = sp.Symbol("E") >>> pw = sp.Piecewise((2*dep + 100, dep < 500), (3*dep - 400, True)) >>> inv = PiecewiseInverter.create_inverse(pw, dep, E)
- class materforge.PropertyProcessor[source]
Bases:
PropertyProcessorBaseOrchestrates property processing by delegating to specialised handlers.
Properties are processed in PropertyType enum definition order, which guarantees CONSTANT_VALUE is resolved before any type that may reference those scalars (STEP_FUNCTION, TABULAR_DATA, etc.).
- process_properties(material, dependency, properties, categorized_properties, base_dir, visualizer)[source]
Processes all properties for the material.
- Parameters:
material (
Material) – Target Material instance.dependency (
Symbol) – SymPy symbol (symbolic mode) or float (numeric mode).properties (
Dict[str,Any]) – Raw properties dict from the YAML config.categorized_properties (
Dict[PropertyType,List[Tuple[str,Any]]]) – Properties pre-grouped by PropertyType.base_dir (
Path) – Base directory for resolving relative file paths.visualizer – PropertyVisualizer instance, or None.
- Return type:
- class materforge.PropertySamples(x, y, prop_type)[source]
Bases:
objectThe source data points a data-backed property was built from.
Retained on the owning
Material(seeMaterial.sample_data) so fit-quality metrics and data-overlay plots can be computed after the build, without re-reading the original YAML or its data files.- x
Dependency-axis sample values, ascending.
- y
Corresponding property values.
- prop_type
Source property type, e.g.
'FILE_IMPORT'or'TABULAR_DATA'.
-
prop_type:
str
-
x:
ndarray
-
y:
ndarray
- class materforge.PropertyType(value)[source]
Bases:
EnumAn enumeration.
- COMPUTED_PROPERTY = 6
- CONSTANT_VALUE = 1
- FILE_IMPORT = 3
- INVALID = 7
- PIECEWISE_EQUATION = 5
- STEP_FUNCTION = 2
- TABULAR_DATA = 4
- class materforge.PropertyVisualizer(parser)[source]
Bases:
objectHandles visualization of material properties.
- initialize_plots()[source]
Initialises the figure and grid layout for all properties.
- Return type:
- is_visualization_enabled()[source]
Returns True if visualization is active and a figure exists.
- Return type:
- reset_visualization_tracking()[source]
Clears the set of already-visualized properties.
- Return type:
- save_property_plots()[source]
Saves the composed property figure to disk and closes it.
- Return type:
- visualize_property(material, prop_name, dependency, prop_type, x_data=None, y_data=None, has_regression=False, simplify_type=None, degree=1, segments=1, lower_bound=None, upper_bound=None, lower_bound_type='constant', upper_bound_type='constant')[source]
Visualizes a single material property on the next available subplot.
- Return type:
- Parameters:
material (Material)
prop_name (str)
dependency (float | Symbol)
prop_type (str)
x_data (ndarray | None)
y_data (ndarray | None)
has_regression (bool)
simplify_type (str | None)
degree (int)
segments (int)
lower_bound (float | None)
upper_bound (float | None)
lower_bound_type (str)
upper_bound_type (str)
- class materforge.SymbolRegistry[source]
Bases:
objectRegistry for SymPy symbols to ensure uniqueness.
- materforge.clear_cache()[source]
Removes all cached material builds from the on-disk cache.
The cache (used by
create_material(..., use_cache=True)) lives underMATERFORGE_CACHE_DIRif set, otherwise the XDG cache directory (~/.cache/materforge).- Return type:
- Returns:
Number of cache entries removed.
Example
>>> removed = clear_cache()
- materforge.compare_materials(materials, prop_name, *, labels=None, ax=None, symbol=None, num=300, show_data=False, dep_range=None)[source]
Overlay one property from several materials on a single axis.
Useful for comparing two alloys, or the same material built with different regression settings.
- Parameters:
materials (
Iterable[Material]) – Materials to overlay.prop_name (
str) – Property to compare (must exist in each material).labels (
Optional[Sequence[str]]) – Legend labels, one per material (defaults to eachname).ax (
Optional[Axes]) – Axes to draw on; a new one is created when omitted.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against; inferred when omitted.num (
int) – Number of points sampled along each curve.show_data (
bool) – Overlay each material’s source data points.dep_range (
Optional[Sequence[float]]) – Shared(lower, upper)plot range; per-material data range is used when omitted.
- Return type:
Axes- Returns:
The Axes drawn on.
- Raises:
ValueError – No materials given, or
labelslength mismatch.
- materforge.create_material(yaml_path, dependency, enable_plotting=False, use_cache=True)[source]
Creates a Material from a YAML configuration file.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file.dependency (
Symbol) – SymPy symbol used as the independent variable. YAML equations always use the placeholder ‘T’; it is substituted with this symbol at runtime.enable_plotting (
bool) – Write a composite PNG of every property to amaterforge_plotsdirectory next to the YAML file (default: False). Opt in when you want the figures; a plotting run always rebuilds (it exists to (re)produce the figures) and therefore bypasses the cache.use_cache (
bool) – Reuse a cached build when the YAML and its referenced data files are unchanged, skipping the piecewise regression (default: True). Consulted on every build except a plotting run (seeenable_plotting), so the default call is cached. Disable globally with theMATERFORGE_DISABLE_CACHEenvironment variable; relocate withMATERFORGE_CACHE_DIR.
- Return type:
Material- Returns:
Fully initialised Material instance.
- Raises:
FileNotFoundError – YAML file does not exist.
TypeError – dependency is not a sp.Symbol.
MaterialConfigError – YAML content is invalid or material creation fails.
PropertyConfigError – A specific property block is structurally invalid.
Example
>>> material = create_material('steel.yaml', sp.Symbol('T')) # built and cached >>> material = create_material('copper.yaml', sp.Symbol('u_C'), enable_plotting=True) # also writes plots
- materforge.ensure_ascending_order(dep_array, *value_arrays)[source]
Ensures dep_array is in ascending order, flipping all arrays together if needed.
- Parameters:
dep_array (
ndarray) – Dependency axis data.*value_arrays – Any number of paired value arrays to flip alongside dep_array.
- Return type:
- Returns:
Tuple of (dep_array,
*value_arrays), all in ascending dep order.- Raises:
ValueError – If the array is neither strictly ascending nor strictly descending.
- materforge.evaluate_material_properties(material, symbol, value)[source]
Evaluates all symbolic properties at a given numeric value.
- Parameters:
material (
Material) – A fully processed Material instance.symbol (
Symbol) – SymPy symbol to substitute.value – Numeric value to substitute.
- Return type:
Material- Returns:
New Material with all properties evaluated to numeric values.
- Raises:
TypeError – If material is not a Material instance.
Example
>>> evaluate_material_properties(material, T, 500.0)
- materforge.fit_quality(material, prop_name, *, symbol=None)[source]
Goodness-of-fit of a property against the data it was built from.
- Parameters:
- Return type:
FitQuality- Returns:
A
FitQualitysummary.- Raises:
Example
>>> fq = fit_quality(mat, 'heat_capacity') >>> print(fq.rmse, fq.r_squared)
- materforge.fit_report(material, *, symbol=None)[source]
Fit quality for every data-backed property of a material.
Compiles the material once and evaluates each property with retained source data. Properties that cannot be assessed are skipped with a warning.
- materforge.get_material_info(yaml_path)[source]
Extracts material metadata from a YAML file without full processing.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file.- Returns:
name, properties, total_properties, property_types, and any additional top-level YAML fields.
- Return type:
Dict with keys
- Raises:
FileNotFoundError – File does not exist.
PropertyConfigError – A specific property block is structurally invalid.
MaterialConfigError – Content is invalid or a required field is missing.
Example
>>> info = get_material_info('steel.yaml') >>> print(info['name'], info['total_properties'])
- materforge.get_material_path(name)[source]
Returns the path to a bundled material’s YAML file.
Matching is case-insensitive. Useful when you want to read or copy the YAML rather than load it directly.
- Parameters:
name (
str) – Name of a bundled material (seelist_materials()).- Return type:
- Returns:
Filesystem path to the material’s YAML file.
- Raises:
ValueError – If name does not match a bundled material; the message lists the available names.
- materforge.get_material_property_names(material)[source]
Returns all property names dynamically assigned to a material instance.
- Parameters:
material (
Material) – A fully processed Material instance.- Return type:
- Returns:
Property names assigned during processing.
- Raises:
TypeError – Argument is not a Material instance.
Example
>>> material = create_material('steel.yaml', sp.Symbol('T')) >>> print(get_material_property_names(material))
- materforge.interpolate_value(dep_value, dep_array, prop_array, lower_bound_type, upper_bound_type)[source]
Interpolates a property value at dep_value using the provided data arrays.
- Parameters:
dep_value – Dependency value at which to interpolate.
dep_array (
ndarray) – Dependency axis data (must be sorted ascending).prop_array (
ndarray) – Corresponding property values.lower_bound_type (
str) – Behaviour below dep_array[0]: CONSTANT_KEY or LINEAR_KEY.upper_bound_type (
str) – Behaviour above dep_array[-1]: CONSTANT_KEY or LINEAR_KEY.
- Returns:
Interpolated value.
- Raises:
ValueError – If dep_value is non-finite, arrays are empty or mismatched, or extrapolation is requested on a degenerate interval.
- materforge.list_materials()[source]
Returns the names of the bundled example materials, sorted alphabetically.
- materforge.load_material(name, dependency, enable_plotting=False)[source]
Loads a bundled example material by name.
A thin wrapper around
materforge.create_material()for the YAML files shipped with the package. Plotting is off by default so loading an example never writes plot files next to the installed package.- Parameters:
- Return type:
Material- Returns:
Fully initialised Material instance.
- Raises:
ValueError – If name does not match a bundled material.
TypeError – If dependency is not a sympy Symbol.
Example
>>> import sympy as sp >>> from materforge import load_material >>> steel = load_material('1.4301', sp.Symbol('T'))
- materforge.mae(y_true, y_pred)[source]
Mean absolute error between observations and predictions.
- Return type:
- materforge.max_abs_error(y_true, y_pred)[source]
Largest single absolute error between observations and predictions.
- Return type:
- materforge.plot_property(material, prop_name, *, ax=None, symbol=None, num=300, show_data=True, dep_range=None, label=None, **plot_kw)[source]
Plot a property’s fitted curve, optionally over its source data points.
- Parameters:
material (
Material) – A material built bymaterforge.create_material().prop_name (
str) – Property to plot.ax (
Optional[Axes]) – Axes to draw on; a new figure/axes is created when omitted.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against; inferred when omitted.num (
int) – Number of points sampled along the curve.show_data (
bool) – Overlay the retained source data points (when available).dep_range (
Optional[Sequence[float]]) –(lower, upper)plot range; defaults to the source data range. Required for a property with no retained data.label (
Optional[str]) – Legend label for the curve (defaults to"<prop> (fit)").**plot_kw – Forwarded to
Axes.plotfor the curve.
- Return type:
Axes- Returns:
The Axes drawn on (not saved or shown).
- Raises:
TypeError –
materialis not a Material.KeyError – The property could not be compiled to a numeric callable.
ValueError – No range is available and
dep_rangewas not given.
- materforge.plot_residuals(material, prop_name, *, ax=None, symbol=None, **scatter_kw)[source]
Plot per-point fit residuals (fit − data) with a zero reference line.
- Parameters:
- Return type:
Axes- Returns:
The Axes drawn on.
- Raises:
- materforge.r_squared(y_true, y_pred)[source]
Coefficient of determination,
1 - SS_res / SS_tot.SS_totis taken about the mean ofy_true. When the observations are constant (SS_tot == 0) there is no variance to explain: returns1.0if they are reproduced exactly (SS_res == 0), otherwise0.0.- Return type:
- materforge.residuals(material, prop_name, *, symbol=None)[source]
Per-point fit residuals of a property.
- Parameters:
- Return type:
- Returns:
(x, predicted - observed)at the property’s source data points.- Raises:
- materforge.rmse(y_true, y_pred)[source]
Root-mean-square error between observations and predictions.
- Return type:
- materforge.validate_yaml_file(yaml_path)[source]
Validates a YAML file without creating the material.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file to validate.- Return type:
- Returns:
True if the file is structurally valid.
- Raises:
FileNotFoundError – File does not exist.
PropertyConfigError – A specific property block is structurally invalid.
MaterialConfigError – Top-level YAML content is invalid.
Example
>>> is_valid = validate_yaml_file('steel.yaml')
Core Module
Core data structures and material definitions.
This module contains the fundamental classes and interfaces that define materials, and the core abstractions used throughout the MaterForge library.
- class materforge.core.Material(name, properties=<factory>, sample_data=<factory>)[source]
Bases:
objectGeneric material container with fully dynamic property tracking. All material properties are assigned dynamically via setattr and tracked automatically.
- name
Human-readable material identifier.
- properties
Dictionary with all properties.
- sample_data
Source data points each data-backed property was built from, keyed by property name. Populated during
create_material(); empty for a material produced byevaluate(). Consumed by thematerforge.analysisand plotting helpers.
- compile(symbol=None)[source]
Builds a reusable evaluator with cached numeric callables.
Each property is lambdified once and reused, so sweeping many dependency values - or evaluating over a NumPy array in one call - is far faster than repeated symbolic
evaluate().- Parameters:
symbol (
Optional[Symbol]) – Dependency symbol to evaluate against. Inferred from the properties’ free symbols when omitted.- Return type:
MaterialEvaluator- Returns:
A
MaterialEvaluatorsnapshot of this material.
Example
>>> ev = material.compile() >>> ev(500.0) # {'density': 2634.5, ...} >>> ev(np.linspace(300, 900, 200)) # arrays, one call per property
- evaluate(symbol, value)[source]
Evaluates all properties by substituting symbol=value.
- Parameters:
symbol (
Symbol) – SymPy symbol to substitute (e.g. sp.Symbol(‘T’)).value – Value to substitute.
- Return type:
Material- Returns:
New Material instance with name ‘{name}@{symbol}={value}’ and all properties substituted at the given value. Properties that fail evaluation are silently excluded.
- Raises:
ValueError – If symbol is not sp.Symbol, or value is non-numeric.
-
name:
str
- class materforge.core.SymbolRegistry[source]
Bases:
objectRegistry for SymPy symbols to ensure uniqueness.
Material Class
- class materforge.Material(name, properties=<factory>, sample_data=<factory>)[source]
Bases:
objectGeneric material container with fully dynamic property tracking. All material properties are assigned dynamically via setattr and tracked automatically.
- name
Human-readable material identifier.
- properties
Dictionary with all properties.
- sample_data
Source data points each data-backed property was built from, keyed by property name. Populated during
create_material(); empty for a material produced byevaluate(). Consumed by thematerforge.analysisand plotting helpers.
- compile(symbol=None)[source]
Builds a reusable evaluator with cached numeric callables.
Each property is lambdified once and reused, so sweeping many dependency values - or evaluating over a NumPy array in one call - is far faster than repeated symbolic
evaluate().- Parameters:
symbol (
Optional[Symbol]) – Dependency symbol to evaluate against. Inferred from the properties’ free symbols when omitted.- Return type:
MaterialEvaluator- Returns:
A
MaterialEvaluatorsnapshot of this material.
Example
>>> ev = material.compile() >>> ev(500.0) # {'density': 2634.5, ...} >>> ev(np.linspace(300, 900, 200)) # arrays, one call per property
- evaluate(symbol, value)[source]
Evaluates all properties by substituting symbol=value.
- Parameters:
symbol (
Symbol) – SymPy symbol to substitute (e.g. sp.Symbol(‘T’)).value – Value to substitute.
- Return type:
Material- Returns:
New Material instance with name ‘{name}@{symbol}={value}’ and all properties substituted at the given value. Properties that fail evaluation are silently excluded.
- Raises:
ValueError – If symbol is not sp.Symbol, or value is non-numeric.
-
name:
str
Bundled Materials
Helpers for the reference materials shipped with the package. See Load Bundled Example Materials for usage.
- materforge.list_materials()[source]
Returns the names of the bundled example materials, sorted alphabetically.
- materforge.load_material(name, dependency, enable_plotting=False)[source]
Loads a bundled example material by name.
A thin wrapper around
materforge.create_material()for the YAML files shipped with the package. Plotting is off by default so loading an example never writes plot files next to the installed package.- Parameters:
- Return type:
Material- Returns:
Fully initialised Material instance.
- Raises:
ValueError – If name does not match a bundled material.
TypeError – If dependency is not a sympy Symbol.
Example
>>> import sympy as sp >>> from materforge import load_material >>> steel = load_material('1.4301', sp.Symbol('T'))
- materforge.get_material_path(name)[source]
Returns the path to a bundled material’s YAML file.
Matching is case-insensitive. Useful when you want to read or copy the YAML rather than load it directly.
- Parameters:
name (
str) – Name of a bundled material (seelist_materials()).- Return type:
- Returns:
Filesystem path to the material’s YAML file.
- Raises:
ValueError – If name does not match a bundled material; the message lists the available names.
Fast Evaluation
A compiled, reusable evaluator for sweeping many dependency values or evaluating over a NumPy array. See Evaluate Properties Quickly for usage.
- class materforge.MaterialEvaluator(material, symbol=None)[source]
Bases:
objectCompiled, reusable numeric evaluator for a material’s properties.
Each property is lambdified once against the material’s dependency symbol and cached. Calling the evaluator with a scalar returns a
dictof floats; calling it with an array returns adictof NumPy arrays shaped like the input. Constant properties are broadcast to match.The evaluator is a snapshot taken at construction time: if the material’s properties change afterwards, build a fresh evaluator with
Material.compile().- Parameters:
material (
Material) – A fully processed Material instance.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against. If omitted, it is inferred from the free symbols of the material’s properties (the common case, where every property is a function of a single dependency). Pass it explicitly to disambiguate or to pin the variable for an all-constant material.
- Raises:
TypeError – symbol is given but is not a sympy Symbol.
ValueError – The properties depend on more than one symbol (multivariate materials are not yet supported), or on a symbol other than the one supplied.
- evaluate(value)[source]
Alias for calling the evaluator; see
__call__().
- function(name)[source]
Returns the cached numeric callable for a single property.
Useful when you only need one property, or want to hand the raw callable to another numerical routine.
- property symbol: Symbol | None
The dependency symbol this evaluator substitutes (None if all-constant).
Fit Quality
Goodness-of-fit metrics (R², RMSE, MAE, residuals) for data-backed properties. See Assess Fit Quality for usage.
Fit-quality metrics for a built Material.
A regression- or interpolation-backed property is an approximation of the data points it was built from. These helpers quantify how well that approximation reproduces its source data:
r_squared(),rmse(),mae(),max_abs_error()are plain array metrics (y_truevsy_pred) - usable on their own.fit_quality(),residuals(),fit_report()work directly on a material, using the source points it kept inmaterial.sample_dataand the compiled property callable fromMaterial.compile().
What “fit quality” means here: the stored property expression evaluated at
the source sample points, compared with the sample values. For a property with
regression: {simplify: pre, ...} this is the regression error, the number you
usually care about. For plain interpolation (or simplify: post) the stored
curve passes through every point, so the error is ~0 by construction - correct,
if not very informative.
Everything routes through MaterialEvaluator,
which currently supports a single dependency symbol; pass symbol= to pick one
explicitly.
- class materforge.analysis.FitQuality(property, r_squared, rmse, mae, max_abs_error, n_points)[source]
Bases:
objectGoodness-of-fit summary for one property against its source data.
- Parameters:
- property
Property name.
- r_squared
Coefficient of determination (
1.0is a perfect fit).
- rmse
Root-mean-square error, in the property’s units.
- mae
Mean absolute error.
- max_abs_error
Largest single absolute error.
- n_points
Number of source data points compared.
- materforge.analysis.fit_quality(material, prop_name, *, symbol=None)[source]
Goodness-of-fit of a property against the data it was built from.
- Parameters:
- Return type:
FitQuality- Returns:
A
FitQualitysummary.- Raises:
Example
>>> fq = fit_quality(mat, 'heat_capacity') >>> print(fq.rmse, fq.r_squared)
- materforge.analysis.fit_report(material, *, symbol=None)[source]
Fit quality for every data-backed property of a material.
Compiles the material once and evaluates each property with retained source data. Properties that cannot be assessed are skipped with a warning.
- materforge.analysis.mae(y_true, y_pred)[source]
Mean absolute error between observations and predictions.
- Return type:
- materforge.analysis.max_abs_error(y_true, y_pred)[source]
Largest single absolute error between observations and predictions.
- Return type:
- materforge.analysis.r_squared(y_true, y_pred)[source]
Coefficient of determination,
1 - SS_res / SS_tot.SS_totis taken about the mean ofy_true. When the observations are constant (SS_tot == 0) there is no variance to explain: returns1.0if they are reproduced exactly (SS_res == 0), otherwise0.0.- Return type:
- materforge.analysis.residuals(material, prop_name, *, symbol=None)[source]
Per-point fit residuals of a property.
- Parameters:
- Return type:
- Returns:
(x, predicted - observed)at the property’s source data points.- Raises:
Command-Line Interface
The materforge command wraps the public API for use from a shell. See the
Use the Command-Line Interface guide for the subcommands and examples.
- materforge.cli.main(argv=None)[source]
Runs the MaterForge CLI and returns a process exit code.
Algorithms Module
Core computational algorithms for materials property processing.
This module provides mathematical algorithms for processing material properties, including interpolation, regression, piecewise function construction, and property inversion operations.
- class materforge.algorithms.PiecewiseBuilder[source]
Bases:
objectCentralised piecewise function creation with different build strategies.
- static build_from_data(dep_array, prop_array, dependency, config, prop_name)[source]
Builds a piecewise function from raw dependency-value arrays.
Handles ascending/descending input, optional pre-regression, and symbol substitution when the caller uses a non-placeholder symbol.
- Parameters:
- Return type:
Piecewise- Returns:
Symbolic piecewise function expressed in terms of dependency.
- Raises:
ValueError – On null/empty/mismatched arrays or build failure.
- static build_from_formulas(dep_points, equations, dependency, lower_bound_type='constant', upper_bound_type='constant')[source]
Builds a piecewise function from symbolic equations and breakpoints.
- Parameters:
dep_points (
ndarray) – Breakpoints defining segment boundaries (n+1 for n equations).equations (
List[Union[str,Expr]]) – Symbolic expressions as strings or SymPy Expr objects.dependency (
Symbol) – SymPy symbol used in the equations.lower_bound_type (
str) – Boundary behaviour below dep_points[0].upper_bound_type (
str) – Boundary behaviour above dep_points[-1].
- Return type:
Piecewise- Returns:
Symbolic piecewise function.
- Raises:
ValueError – On mismatched counts, invalid symbols, or parse failures.
- class materforge.algorithms.PiecewiseInverter(tolerance=1e-12)[source]
Bases:
objectCreates inverse functions for linear piecewise functions (degree <= 1 only).
- Parameters:
tolerance (float)
- static create_inverse(piecewise_func, input_symbol, output_symbol, tolerance=1e-12)[source]
Creates the inverse of a linear piecewise function.
- Parameters:
piecewise_func (
Union[Piecewise,Expr]) – Original piecewise function f(input_symbol).input_symbol (
Union[Symbol,Basic]) – Independent variable of the original function.output_symbol (
Union[Symbol,Basic]) – Symbol for the inverse function’s argument.tolerance (
float) – Numerical tolerance for inversion stability.
- Return type:
Piecewise- Returns:
Inverse piecewise function expressed in terms of output_symbol.
- Raises:
ValueError – If any piece has degree > 1 or the function is non-monotonic.
Example
>>> dep = sp.Symbol("T") >>> E = sp.Symbol("E") >>> pw = sp.Piecewise((2*dep + 100, dep < 500), (3*dep - 400, True)) >>> inv = PiecewiseInverter.create_inverse(pw, dep, E)
- class materforge.algorithms.RegressionProcessor[source]
Bases:
objectHandles all regression-related functionality.
- static get_symbolic_conditions(pwlf_, dependency, lower_, upper_)[source]
Builds SymPy (expression, condition) pairs from a fitted PWLF model.
- Parameters:
- Return type:
- Returns:
List of (expr, condition) tuples suitable for sp.Piecewise.
- static get_symbolic_eqn(pwlf_, segment_number, dependency)[source]
Constructs the symbolic polynomial equation for a single PWLF segment.
- Parameters:
- Return type:
Expr- Returns:
SymPy expression for the segment.
- Raises:
ValueError – On invalid degree or out-of-range segment number.
- static process_regression(dep_array, prop_array, dependency, lower_bound_type, upper_bound_type, degree, segments, seed=13579)[source]
Fits a piecewise polynomial regression and returns a SymPy Piecewise.
- Parameters:
dep_array – Dependency axis data.
prop_array – Corresponding property values.
dependency (
Symbol) – SymPy symbol for the resulting expression.lower_bound_type (
str) – Boundary behaviour below dep_array[0].upper_bound_type (
str) – Boundary behaviour above dep_array[-1].degree (
int) – Polynomial degree per segment.segments (
int) – Number of piecewise segments.seed (
int) – Random seed for PWLF optimisation.
- Return type:
Piecewise- Returns:
Symbolic piecewise function expressed in terms of dependency.
- Raises:
ValueError – If PWLF fitting fails.
- static process_regression_params(prop_config, prop_name, data_length)[source]
Extracts and validates regression parameters from a property config dict.
- Parameters:
- Return type:
- Returns:
Tuple of (has_regression, simplify_type, degree, segments). All values are None when has_regression is False.
- Raises:
ValueError – On invalid or missing regression parameters.
- materforge.algorithms.ensure_ascending_order(dep_array, *value_arrays)[source]
Ensures dep_array is in ascending order, flipping all arrays together if needed.
- Parameters:
dep_array (
ndarray) – Dependency axis data.*value_arrays – Any number of paired value arrays to flip alongside dep_array.
- Return type:
- Returns:
Tuple of (dep_array,
*value_arrays), all in ascending dep order.- Raises:
ValueError – If the array is neither strictly ascending nor strictly descending.
- materforge.algorithms.interpolate_value(dep_value, dep_array, prop_array, lower_bound_type, upper_bound_type)[source]
Interpolates a property value at dep_value using the provided data arrays.
- Parameters:
dep_value – Dependency value at which to interpolate.
dep_array (
ndarray) – Dependency axis data (must be sorted ascending).prop_array (
ndarray) – Corresponding property values.lower_bound_type (
str) – Behaviour below dep_array[0]: CONSTANT_KEY or LINEAR_KEY.upper_bound_type (
str) – Behaviour above dep_array[-1]: CONSTANT_KEY or LINEAR_KEY.
- Returns:
Interpolated value.
- Raises:
ValueError – If dep_value is non-finite, arrays are empty or mismatched, or extrapolation is requested on a degenerate interval.
Parsing Module
Parsing and configuration modules for MaterForge.
This package handles YAML parsing, property type detection, validation, and material creation from configuration files.
- class materforge.parsing.MaterialYAMLParser(yaml_path)[source]
Bases:
YAMLFileParserParser for material YAML configuration files.
Validates and processes a schema-agnostic YAML file containing a name and a properties block. All thermophysical properties live in the properties block and are assigned dynamically to the Material instance.
- create_material(dependency, enable_plotting=True)[source]
Creates a Material instance from the parsed configuration.
- Parameters:
dependency (
Symbol) – SymPy symbol used as the independent variable in property expressions (e.g. sp.Symbol(‘T’)).enable_plotting (
bool) – Whether to generate and save property plots.
- Return type:
Material- Returns:
Fully initialised Material with all properties assigned.
- Raises:
MaterialConfigError – If configuration is invalid or property processing fails.
- class materforge.parsing.PropertyProcessor[source]
Bases:
PropertyProcessorBaseOrchestrates property processing by delegating to specialised handlers.
Properties are processed in PropertyType enum definition order, which guarantees CONSTANT_VALUE is resolved before any type that may reference those scalars (STEP_FUNCTION, TABULAR_DATA, etc.).
- process_properties(material, dependency, properties, categorized_properties, base_dir, visualizer)[source]
Processes all properties for the material.
- Parameters:
material (
Material) – Target Material instance.dependency (
Symbol) – SymPy symbol (symbolic mode) or float (numeric mode).properties (
Dict[str,Any]) – Raw properties dict from the YAML config.categorized_properties (
Dict[PropertyType,List[Tuple[str,Any]]]) – Properties pre-grouped by PropertyType.base_dir (
Path) – Base directory for resolving relative file paths.visualizer – PropertyVisualizer instance, or None.
- Return type:
- class materforge.parsing.PropertyType(value)[source]
Bases:
EnumAn enumeration.
- COMPUTED_PROPERTY = 6
- CONSTANT_VALUE = 1
- FILE_IMPORT = 3
- INVALID = 7
- PIECEWISE_EQUATION = 5
- STEP_FUNCTION = 2
- TABULAR_DATA = 4
- class materforge.parsing.PropertyTypeDetector[source]
Bases:
objectDetects and validates property types from YAML config values.
- DETECTION_RULES = [(<function PropertyTypeDetector.<lambda>>, PropertyType.FILE_IMPORT), (<function PropertyTypeDetector.<lambda>>, PropertyType.STEP_FUNCTION), (<function PropertyTypeDetector.<lambda>>, PropertyType.TABULAR_DATA), (<function PropertyTypeDetector.<lambda>>, PropertyType.PIECEWISE_EQUATION), (<function PropertyTypeDetector.<lambda>>, PropertyType.COMPUTED_PROPERTY)]
- static determine_property_type(prop_name, config)[source]
Determines the PropertyType for a config entry using rule-based detection.
- Parameters:
- Return type:
PropertyType- Returns:
The detected PropertyType.
- Raises:
ValueError – If config is not numeric, not a dict, or matches no rule.
- static validate_property_config(prop_name, config, prop_type)[source]
Performs strict structural validation for the detected property type.
- Parameters:
- Raises:
ValueError – If config structure is invalid for the given type.
NotImplementedError – If no validator exists for prop_type.
- Return type:
- materforge.parsing.create_material(yaml_path, dependency, enable_plotting=False, use_cache=True)[source]
Creates a Material from a YAML configuration file.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file.dependency (
Symbol) – SymPy symbol used as the independent variable. YAML equations always use the placeholder ‘T’; it is substituted with this symbol at runtime.enable_plotting (
bool) – Write a composite PNG of every property to amaterforge_plotsdirectory next to the YAML file (default: False). Opt in when you want the figures; a plotting run always rebuilds (it exists to (re)produce the figures) and therefore bypasses the cache.use_cache (
bool) – Reuse a cached build when the YAML and its referenced data files are unchanged, skipping the piecewise regression (default: True). Consulted on every build except a plotting run (seeenable_plotting), so the default call is cached. Disable globally with theMATERFORGE_DISABLE_CACHEenvironment variable; relocate withMATERFORGE_CACHE_DIR.
- Return type:
Material- Returns:
Fully initialised Material instance.
- Raises:
FileNotFoundError – YAML file does not exist.
TypeError – dependency is not a sp.Symbol.
MaterialConfigError – YAML content is invalid or material creation fails.
PropertyConfigError – A specific property block is structurally invalid.
Example
>>> material = create_material('steel.yaml', sp.Symbol('T')) # built and cached >>> material = create_material('copper.yaml', sp.Symbol('u_C'), enable_plotting=True) # also writes plots
- materforge.parsing.evaluate_material_properties(material, symbol, value)[source]
Evaluates all symbolic properties at a given numeric value.
- Parameters:
material (
Material) – A fully processed Material instance.symbol (
Symbol) – SymPy symbol to substitute.value – Numeric value to substitute.
- Return type:
Material- Returns:
New Material with all properties evaluated to numeric values.
- Raises:
TypeError – If material is not a Material instance.
Example
>>> evaluate_material_properties(material, T, 500.0)
- materforge.parsing.get_material_info(yaml_path)[source]
Extracts material metadata from a YAML file without full processing.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file.- Returns:
name, properties, total_properties, property_types, and any additional top-level YAML fields.
- Return type:
Dict with keys
- Raises:
FileNotFoundError – File does not exist.
PropertyConfigError – A specific property block is structurally invalid.
MaterialConfigError – Content is invalid or a required field is missing.
Example
>>> info = get_material_info('steel.yaml') >>> print(info['name'], info['total_properties'])
- materforge.parsing.get_material_property_names(material)[source]
Returns all property names dynamically assigned to a material instance.
- Parameters:
material (
Material) – A fully processed Material instance.- Return type:
- Returns:
Property names assigned during processing.
- Raises:
TypeError – Argument is not a Material instance.
Example
>>> material = create_material('steel.yaml', sp.Symbol('T')) >>> print(get_material_property_names(material))
- materforge.parsing.validate_yaml_file(yaml_path)[source]
Validates a YAML file without creating the material.
- Parameters:
yaml_path (
Union[str,Path]) – Path to the YAML configuration file to validate.- Return type:
- Returns:
True if the file is structurally valid.
- Raises:
FileNotFoundError – File does not exist.
PropertyConfigError – A specific property block is structurally invalid.
MaterialConfigError – Top-level YAML content is invalid.
Example
>>> is_valid = validate_yaml_file('steel.yaml')
Visualization Module
Parse-time plotting - the composite figure written during a build.
Visualization tools for material properties.
- class materforge.visualization.PropertyVisualizer(parser)[source]
Bases:
objectHandles visualization of material properties.
- initialize_plots()[source]
Initialises the figure and grid layout for all properties.
- Return type:
- is_visualization_enabled()[source]
Returns True if visualization is active and a figure exists.
- Return type:
- reset_visualization_tracking()[source]
Clears the set of already-visualized properties.
- Return type:
- save_property_plots()[source]
Saves the composed property figure to disk and closes it.
- Return type:
- visualize_property(material, prop_name, dependency, prop_type, x_data=None, y_data=None, has_regression=False, simplify_type=None, degree=1, segments=1, lower_bound=None, upper_bound=None, lower_bound_type='constant', upper_bound_type='constant')[source]
Visualizes a single material property on the next available subplot.
- Return type:
- Parameters:
material (Material)
prop_name (str)
dependency (float | Symbol)
prop_type (str)
x_data (ndarray | None)
y_data (ndarray | None)
has_regression (bool)
simplify_type (str | None)
degree (int)
segments (int)
lower_bound (float | None)
upper_bound (float | None)
lower_bound_type (str)
upper_bound_type (str)
Post-build plotting helpers that return a Matplotlib Axes (fit, residual, and
compare plots). See Visualize Properties for usage.
Post-build plotting helpers that return a Matplotlib Axes.
These complement the parse-time PropertyVisualizer
(which auto-saves a composite PNG during create_material(enable_plotting=True)).
Here, each function works on an already built material, draws onto an Axes
you pass (or a fresh one), and returns it without saving or closing - so a
Jupyter cell renders the figure inline and you stay in control of styling and
output.
plot_property()- the fitted curve, optionally over its source data.plot_residuals()- per-point fit residuals with a zero reference line.compare_materials()- the same property from several materials on one axis.
The curve comes from Material.compile(); the data points and the plot range
come from material.sample_data. Pass symbol= to pick the dependency for a
material whose properties could be read against more than one symbol.
- materforge.visualization.plots.compare_materials(materials, prop_name, *, labels=None, ax=None, symbol=None, num=300, show_data=False, dep_range=None)[source]
Overlay one property from several materials on a single axis.
Useful for comparing two alloys, or the same material built with different regression settings.
- Parameters:
materials (
Iterable[Material]) – Materials to overlay.prop_name (
str) – Property to compare (must exist in each material).labels (
Optional[Sequence[str]]) – Legend labels, one per material (defaults to eachname).ax (
Optional[Axes]) – Axes to draw on; a new one is created when omitted.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against; inferred when omitted.num (
int) – Number of points sampled along each curve.show_data (
bool) – Overlay each material’s source data points.dep_range (
Optional[Sequence[float]]) – Shared(lower, upper)plot range; per-material data range is used when omitted.
- Return type:
Axes- Returns:
The Axes drawn on.
- Raises:
ValueError – No materials given, or
labelslength mismatch.
- materforge.visualization.plots.plot_property(material, prop_name, *, ax=None, symbol=None, num=300, show_data=True, dep_range=None, label=None, **plot_kw)[source]
Plot a property’s fitted curve, optionally over its source data points.
- Parameters:
material (
Material) – A material built bymaterforge.create_material().prop_name (
str) – Property to plot.ax (
Optional[Axes]) – Axes to draw on; a new figure/axes is created when omitted.symbol (
Optional[Symbol]) – Dependency symbol to evaluate against; inferred when omitted.num (
int) – Number of points sampled along the curve.show_data (
bool) – Overlay the retained source data points (when available).dep_range (
Optional[Sequence[float]]) –(lower, upper)plot range; defaults to the source data range. Required for a property with no retained data.label (
Optional[str]) – Legend label for the curve (defaults to"<prop> (fit)").**plot_kw – Forwarded to
Axes.plotfor the curve.
- Return type:
Axes- Returns:
The Axes drawn on (not saved or shown).
- Raises:
TypeError –
materialis not a Material.KeyError – The property could not be compiled to a numeric callable.
ValueError – No range is available and
dep_rangewas not given.
- materforge.visualization.plots.plot_residuals(material, prop_name, *, ax=None, symbol=None, **scatter_kw)[source]
Plot per-point fit residuals (fit − data) with a zero reference line.
- Parameters:
- Return type:
Axes- Returns:
The Axes drawn on.
- Raises: