bloc.io#

I/O utilities — batch import, YAML validation, Boulder bridge.

Submodules#

Attributes#

Classes#

Simulation

Thin wrapper around a solved STONE YAML network.

Functions#

build_network_from_yaml(yaml_path)

Build a network and results from a STONE YAML file.

build_simulation_from_yaml(yaml_path)

Build a Simulation from STONE YAML.

load_config_boulder(yaml_path)

Load and normalise a STONE config using Bloc's runner.

load_data_for_mops_config(path)

Load a data_for_mops.yaml-shaped config file and return validated mapping.

mops_case_output_path(x0, temperature_K, path_hint, *, ...)

Build {prefix}_CH4_XX%_{T}K{suffix} in the directory of path_hint.

plot_mops(result, output_path, *[, ...])

Plot MOPS mole fractions, wdotA4 rate, mass fractions, and carbon volume fraction on one PNG.

run_mops(X0, temperature, residence_time[, P_bar, ...])

Run isothermal pyrolysis and write MOPS .inp file.

expand_scenarios(base_raw)

Expand a STONE YAML's inline scenarios: / sweep: blocks.

import_simulation(module_name)

Import a Bloc Simulation.

resolve_dotted(path)

Import module:attr and return attr.

extract_comment_metadata(data[, section])

Extract inline comment metadata from a YAML section.

extract_header_comments(path)

Extract leading comments from a YAML file (before the first key).

extract_nested_param_hints(path)

Extract nested-parameter display hints from inline YAML comments.

extract_notes_from_yaml(path)

Extract note comments from YAML file.

get_bloc_version_info()

Get Bloc version and git commit hash.

load_scenario(base_path[, overlay_path])

Load a scenario by deep-merging an optional overlay onto a base YAML.

load_yaml_raw(path)

Load a YAML file preserving comments (ruamel.yaml round-trip mode).

validate_yaml_directory([directory, pattern])

Validate all YAML files in a directory.

validate_yaml_file(path)

Run all YAML validations on a single file.

validate_yaml_note_syntax(path)

Validate note syntax in YAML file and report inconsistencies.

validate_yaml_unit_brackets(path)

Validate that units in comments are enclosed in brackets.

validate_yaml_units(path, *[, section, strict])

Validate that units in YAML comments match INPUT_VARIABLE_MAP.

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 SimulationResult as result for typed access to the staged network, trajectory, per-reactor states and plugin scalars.

The central object is network, a StagedReactorNet — 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 StagedReactorNet facade.

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) where network is the raw visualization ReactorNet produced by build() (before solve() upgrades it to the StagedReactorNet facade).

Callers that need the typed staged network facade should use build_simulation_from_yaml() instead and access sim.network (a StagedReactorNet). If a raw ReactorNet is needed downstream, use sim.network.visualization_network.

bloc.io.build_simulation_from_yaml(yaml_path)#

Build a Simulation from STONE YAML.

All loading, normalisation, validation, mechanism resolution, and plugin registration flow through BlocRunner.

sim.network is a StagedReactorNet — a ReactorNet-compatible staged network facade that owns both the global visualization ReactorNet (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_png set output directories; filenames are derived as gasphase_CH4_XX%_{T}K.inp and mops_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 (str or Path, 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:attr and return attr.

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 (from load_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 (str or Path) – Path to the YAML file.

Returns:

Each line of header comments (with # prefix stripped).

Return type:

list of str

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 (str or Path) – 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 from key, it must match the base filename (e.g. from: SPRING_A3_BG_20260212.yaml when base is that file); otherwise a ValueError is raised. The from key is not merged into the result (metadata only).

Parameters:
  • base_path (str or Path) – Path to the base YAML file.

  • overlay_path (str or Path or None) – 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 (str or Path) – 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:
  • directory (str or Path, optional) – Directory to search for YAML files (default: “models”)

  • pattern (str, optional) – Glob pattern for finding YAML files (default: “**/*.yaml”)

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 (str or Path) – 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 (str or Path) – 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 (str or Path) – 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 (and bloc.yaml_utils.NESTED_INPUT_MAP for 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 (str or Path) – Path to the YAML file.

  • section (str) – Top-level YAML section to inspect (default "initial").

  • strict (bool) – If True, raise a ValueError when 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 name

  • yaml_unit – unit found in the YAML comment

  • expected_unit – unit declared in the variable map

  • issue – human-readable description

Return type:

list[dict]

Raises:

ValueError – Only when strict is True and at least one mismatch is found.