bloc.io#
I/O utilities — batch import, YAML validation, Boulder bridge.
Submodules#
Attributes#
Classes#
Thin wrapper around a solved STONE YAML network. |
Functions#
|
Build a network and results from a STONE YAML file. |
|
Build a |
|
Load and normalise a STONE config using Bloc's runner. |
Load a |
|
|
Build |
|
Plot MOPS mole fractions, wdotA4 rate, mass fractions, and carbon volume fraction on one PNG. |
|
Run isothermal pyrolysis and write MOPS .inp file. |
|
Expand a STONE YAML's inline |
|
Import a Bloc Simulation. |
|
Import |
|
Extract inline comment metadata from a YAML section. |
|
Extract leading comments from a YAML file (before the first key). |
Extract nested-parameter display hints from inline YAML comments. |
|
|
Extract note comments from YAML file. |
Get Bloc version and git commit hash. |
|
|
Load a scenario by deep-merging an optional overlay onto a base YAML. |
|
Load a YAML file preserving comments (ruamel.yaml round-trip mode). |
|
Validate all YAML files in a directory. |
|
Run all YAML validations on a single file. |
Validate note syntax in YAML file and report inconsistencies. |
|
Validate that units in comments are enclosed in brackets. |
|
|
Validate that units in YAML comments match |
Package Contents#
- class bloc.io.Simulation(config, results, result=None)#
Thin wrapper around a solved STONE YAML network.
Provides a minimal, stable API for downstream scripts and notebooks, and exposes a
SimulationResultasresultfor typed access to the staged network, trajectory, per-reactor states and plugin scalars.The central object is
network, aStagedReactorNet— a ReactorNet-compatible staged network facade. It is not a single global CVODE integrator; staged solves with mechanism switches and custom PFR solvers are not one monolithic ODE problem.Key accessor pattern:
sim.network # StagedReactorNet sim.network.draw(...) # delegates to viz network sim.network.get_stage("default") # PFRHomogeneousShellNet / DesignTubeFurnaceNet sim.network.networks # {stage_id: stage solver} sim.network.visualization_network # raw ct.ReactorNet (Sankey etc.)
- config#
- results#
- result = None#
- solve()#
Return the staged network facade and results captured during build.
- property network: boulder.staged_network.StagedReactorNet#
The
StagedReactorNetfacade.
- property reactors#
Convenience delegate to
network.reactors.
- property trajectory#
Convenience delegate to
network.trajectory.
- property scalars: Dict[str, Any]#
Convenience delegate to
network.scalars.
- bloc.io.build_network_from_yaml(yaml_path)#
Build a network and results from a STONE YAML file.
Returns
(network, results)wherenetworkis the raw visualizationReactorNetproduced bybuild()(beforesolve()upgrades it to theStagedReactorNetfacade).Callers that need the typed staged network facade should use
build_simulation_from_yaml()instead and accesssim.network(aStagedReactorNet). If a rawReactorNetis needed downstream, usesim.network.visualization_network.
- bloc.io.build_simulation_from_yaml(yaml_path)#
Build a
Simulationfrom STONE YAML.All loading, normalisation, validation, mechanism resolution, and plugin registration flow through
BlocRunner.sim.networkis aStagedReactorNet— a ReactorNet-compatible staged network facade that owns both the global visualizationReactorNet(sim.network.visualization_network) and the stage solver networks (sim.network.networks).- Parameters:
yaml_path – Path to a STONE-standard YAML config defining components and connections.
- bloc.io.load_config_boulder(yaml_path)#
Load and normalise a STONE config using Bloc’s runner.
Returns a Boulder-normalised config dict (including Bloc-specific deprecated-key validation).
- bloc.io.DEFAULT_MECHANISM = 'CRECK_2003_TOT_HT_SOOT_kinetics.yaml'#
- bloc.io.MOPS_SPECIES = ['N2', 'CH4', 'C2H2', 'A1', 'A2', 'A3', 'A4', 'OH', 'H', 'H2', 'H2O', 'A5', 'O2']#
- bloc.io.RHO_SOLID_SOOT_DEFAULT = 1800.0#
- bloc.io.SPECIES_MAP: dict[str, dict[str, str | list[str]]]#
- bloc.io.load_data_for_mops_config(path)#
Load a
data_for_mops.yaml-shaped config file and return validated mapping.Expected keys: x0, temperature_K, residence_time_s, pressure_bar, mechanism, output_inp, plot_png, rho_solid_soot_kg_m3. Optional: plot_suptitle (str or null).
output_inp/plot_pngset output directories; filenames are derived asgasphase_CH4_XX%_{T}K.inpandmops_plot_CH4_XX%_{T}K.png.
- bloc.io.mops_case_output_path(x0, temperature_K, path_hint, *, prefix, suffix)#
Build
{prefix}_CH4_XX%_{T}K{suffix}in the directory of path_hint.
- bloc.io.plot_mops(result, output_path, *, rho_solid_soot_kg_m3=RHO_SOLID_SOOT_DEFAULT, suptitle=None)#
Plot MOPS mole fractions, wdotA4 rate, mass fractions, and carbon volume fraction on one PNG.
Four panels: (1) MOPS mole fractions vs time (no N2), (2) wdotA4 in mol/(s·cm³), (3) Mass fractions of MOPS_SPECIES (no N2), (4) Volume fraction of carbon solid (BIN species).
- Parameters:
rho_solid_soot_kg_m3 – Mass density of solid carbon for BIN volume fraction (kg/m³).
suptitle – Figure suptitle; if None, a default title from the mechanism name is used.
- bloc.io.run_mops(X0, temperature, residence_time, P_bar=1.0, mechanism=None, output_inp=None)#
Run isothermal pyrolysis and write MOPS .inp file.
- Parameters:
X0 (
str) – Initial composition as Cantera mole fraction string, e.g. “CH4:0.1,N2:0.9”.temperature (
float) – Isothermal reactor temperature in Kelvin.residence_time (
float) – Residence time in seconds.P_bar (
float) – Pressure in bar. Default 1.0.mechanism (
str, optional) – Cantera mechanism name/path. Default:DEFAULT_MECHANISM. Use SPECIES_MAP to add mappings for other mechanisms.output_inp (
strorPath, optional) – If set, write MOPS .inp file (space-separated, scientific format).
- Returns:
“states”: Cantera SolutionArray “gas”: final gas state “inp_path”: path of written .inp or None
- Return type:
dict
- bloc.io.ELEMENT_BALANCE_DEFAULT_C: float = 0.95#
- bloc.io.ELEMENT_BALANCE_DEFAULT_H: float = 0.95#
- bloc.io.ENERGY_THERMAL_INLET_KEYS: list[str] = ['G_PW_IN (kW)', 'HHV_torch_input (kW)', 'HHV_2nd_inj_input (kW)']#
- bloc.io.ENERGY_THERMAL_OUTLET_KEYS: list[str] = ['Heat_residual (kW)', 'HHV_pre_quench (kW)', 'Heat_losses_reactor (kW)', 'Torch_generator_losses (kW)']#
- bloc.io.INPUT_CATEGORIES: dict[str, list[str]]#
- bloc.io.INPUT_VARIABLE_MAP: dict[str, tuple[str, str, str]]#
- bloc.io.NESTED_INPUT_MAP: dict[str, dict[str, tuple[str, str, str]]]#
- bloc.io.OUTPUT_CATEGORIES: dict[str, list[str]]#
- bloc.io.OUTPUT_VARIABLE_MAP: dict[str, tuple[str, str, str]]#
- bloc.io.SIM_FIGURE_GENERATORS: dict[str, Any]#
- bloc.io.SIM_KPI_EXTRACTORS: dict[str, Any]#
- bloc.io.STONE_FIGURE_GENERATORS: dict[str, Any]#
- bloc.io.TF_DEFAULT_CONSTRAINTS: list[dict]#
- bloc.io.TF_INPUT_CATEGORIES: dict[str, list[str]]#
- bloc.io.TF_INPUT_VARIABLE_MAP: dict[str, tuple[str, str, str]]#
- bloc.io.TF_OUTPUT_CATEGORIES: dict[str, list[str]]#
- bloc.io.TF_OUTPUT_VARIABLE_MAP: dict[str, tuple[str, str, str]]#
- bloc.io.expand_scenarios(base_raw)#
Expand a STONE YAML’s inline
scenarios:/sweep:blocks.Thin wrapper over
boulder.runset.expand_scenarios()— the reference implementation of the union run-set semantics, upstreamed from Bloc — that plugs in Bloc’s sweep-id symbols and its schema accessor (bloc.core.runner.BlocRunner.schema_entry(), which registers Bloc’s reactor schemas on first use so short-form sweep paths resolve without any prior Boulder plugin discovery). See the Boulder function for the full semantics; behavior is unchanged.
- bloc.io.import_simulation(module_name)#
Import a Bloc Simulation.
Accepts either a Python module name (e.g. “pkg.mod”) or a filesystem path to a Python file (e.g. “../simulation_non_isothermal_reactors.py”).
Returns the imported module object.
- bloc.io.resolve_dotted(path)#
Import
module:attrand returnattr.Used by the STONE calculation-note entry point to resolve
export.kpi_fn: <dotted>into a callable without requiring a Python caller to import and pass it in.- Parameters:
path (
str) – Dotted path of the form"package.module:attribute".- Returns:
The resolved attribute.
- Return type:
Any- Raises:
ValueError – If path does not contain a
:separator.ImportError – If the module cannot be imported.
AttributeError – If the module does not define the requested attribute.
- bloc.io.extract_comment_metadata(data, section='initial')#
Extract inline comment metadata from a YAML section.
Parses comments following the convention
# [unit] description [| remark].- Parameters:
data (
CommentedMap) – Parsed YAML data (fromload_yaml_raw()).section (
str) – The top-level section to extract from (default"initial").
- Returns:
{key: {"value": ..., "unit": str, "description": str, "remark": str}}- Return type:
dict
- bloc.io.extract_header_comments(path)#
Extract leading comments from a YAML file (before the first key).
These are typically the file description, update log, etc.
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
Each line of header comments (with
#prefix stripped).- Return type:
listofstr
- bloc.io.extract_nested_param_hints(path)#
Extract nested-parameter display hints from inline YAML comments.
The parser looks for comments on nested keys with the format:
child_key: {...} # [unit] description text
Returned structure is:
{ "parent_key": { "child_key": {"unit": "...", "description": "..."}, }, }
- bloc.io.extract_notes_from_yaml(path)#
Extract note comments from YAML file.
Searches for comments in the following formats:
# .. note: This is a note about the parameter (preceding line) parameter: value parameter: value # .. note: This is an inline note # note: This is a note about the parameter (preceding line) parameter: value parameter: value # note: This is an inline note
Returns a dictionary mapping parameter names to their notes. Multiple notes for the same parameter are collected in a list.
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
Dictionary mapping parameter names to lists of note strings.
- Return type:
dict[str,list[str]]
Examples
>>> notes = extract_notes_from_yaml("config.yaml") >>> notes["X_torch_input"] ["Chose to use worst case gas composition..."]
- bloc.io.get_bloc_version_info()#
Get Bloc version and git commit hash.
- Returns:
{"version": str, "commit": str}- Return type:
dict
- bloc.io.load_scenario(base_path, overlay_path=None)#
Load a scenario by deep-merging an optional overlay onto a base YAML.
If the overlay has a top-level
fromkey, it must match the base filename (e.g.from: SPRING_A3_BG_20260212.yamlwhen base is that file); otherwise a ValueError is raised. Thefromkey is not merged into the result (metadata only).- Parameters:
base_path (
strorPath) – Path to the base YAML file.overlay_path (
strorPathorNone) – Path to the overlay YAML file. If None, only the base is returned.
- Returns:
The merged configuration dictionary (plain dict, no comments).
- Return type:
dict
- bloc.io.load_yaml_raw(path)#
Load a YAML file preserving comments (ruamel.yaml round-trip mode).
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
The parsed YAML data with comments preserved.
- Return type:
CommentedMap
- bloc.io.validate_yaml_directory(directory='models', pattern='**/*.yaml')#
Validate all YAML files in a directory.
- Parameters:
- Returns:
Dictionary with summary statistics and detailed results: - ‘total_files’: Number of files checked - ‘files_with_issues’: Number of files with issues - ‘total_issues’: Total number of issues across all files - ‘details’: List of per-file validation results
- Return type:
dict
Examples
>>> result = validate_yaml_directory("models") >>> print(f"Checked {result['total_files']} files") >>> print( ... f"Found {result['total_issues']} issues in {result['files_with_issues']} files" ... ) >>> for detail in result["details"]: ... if detail["total_issues"] > 0: ... print(f" {detail['file']}: {detail['total_issues']} issues") ...
- bloc.io.validate_yaml_file(path)#
Run all YAML validations on a single file.
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
Dictionary with validation results: - ‘file’: Path to the file - ‘note_issues’: List of note syntax issues - ‘bracket_issues’: List of unit bracket issues - ‘total_issues’: Total number of issues found
- Return type:
dict
Examples
>>> result = validate_yaml_file("config.yaml") >>> if result["total_issues"] > 0: ... print(f"Found {result['total_issues']} issues in {result['file']}") ...
- bloc.io.validate_yaml_note_syntax(path)#
Validate note syntax in YAML file and report inconsistencies.
Checks for common errors: - Incorrect capitalization: “.. Note:”, “.. NOTE:” - Extra spaces: “ .. note : “, “. . note:” - Missing colon: “.. note”
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
List of validation issues. Each issue is a dict with: - ‘line_no’: Line number (1-indexed) - ‘line’: The problematic line - ‘issue’: Description of the issue - ‘suggestion’: Corrected syntax
- Return type:
list[dict]
Examples
>>> issues = validate_yaml_note_syntax("config.yaml") >>> for issue in issues: ... print(f"Line {issue['line_no']}: {issue['issue']}") ... print(f" Found: {issue['line'].strip()}") ... print(f" Use: {issue['suggestion']}") ...
- bloc.io.validate_yaml_unit_brackets(path)#
Validate that units in comments are enclosed in brackets.
Checks for units that should be in brackets but aren’t, such as: - # kW -> should be # [kW] - # °C -> should be # [°C] - # kg/d -> should be # [kg/d]
- Parameters:
path (
strorPath) – Path to the YAML file.- Returns:
List of validation issues. Each issue is a dict with: - ‘line_no’: Line number (1-indexed) - ‘line’: The problematic line - ‘issue’: Description of the issue - ‘suggestion’: Corrected syntax
- Return type:
list[dict]
Examples
>>> issues = validate_yaml_unit_brackets("config.yaml") >>> for issue in issues: ... print(f"Line {issue['line_no']}: Unit not in brackets") ... print(f" Found: {issue['line'].strip()}") ... print(f" Use: {issue['suggestion']}") ...
- bloc.io.validate_yaml_units(path, *, section='initial', strict=False)#
Validate that units in YAML comments match
INPUT_VARIABLE_MAP.Cross-references the inline comment unit of each parameter in the given YAML section against the expected unit declared in
bloc.yaml_utils.INPUT_VARIABLE_MAP(andbloc.yaml_utils.NESTED_INPUT_MAPfor dict-valued parameters).Only parameters that (a) appear in the YAML and (b) have a corresponding entry in the variable map are checked. Parameters without an inline comment are silently skipped.
- Parameters:
path (
strorPath) – Path to the YAML file.section (
str) – Top-level YAML section to inspect (default"initial").strict (
bool) – If True, raise aValueErrorwhen any mismatch is found. If False (default), return the list of issues without raising.
- Returns:
Each element is a dict with keys:
parameter– YAML parameter nameyaml_unit– unit found in the YAML commentexpected_unit– unit declared in the variable mapissue– human-readable description
- Return type:
list[dict]- Raises:
ValueError – Only when strict is True and at least one mismatch is found.