.. _dip-python: Python ====== Parse DIPL text or load a source, DIPfile project, or DIPH5 snapshot. Basic examples -------------- Parse a small parameter model and read a derived value: .. code-block:: python from scinumtools3.dip import DIP parser = DIP() parser.add_string( "distance float = 12 m\n" "duration float = 3 s\n" "speed float = ({?distance} / {?duration}) m/s\n" ) env = parser.parse() print(env["speed"].value, env["speed"].units) # 4.0 m*s-1 Override an input before evaluation: .. code-block:: python from scinumtools3.dip import DIP parser = DIP() parser.add_string("simulation.steps int = 100") parser.add_override_string("simulation.steps = 200") env = parser.parse() print(env["simulation.steps"].value) # 200 Common workflows ---------------- .. list-table:: :header-rows: 1 * - Task - Call chain - Result * - Load one artifact - ``DIP.load(path)`` - ``Environment`` * - Compose live inputs - ``DIP()``; ``add_string``/``add_file``/``add_project``; ``parse()`` - ``Environment`` * - Apply overrides before evaluation - ``add_override_string``/``add_override_file``; ``parse()`` - ``Environment`` * - Read a known path - ``env[path]``; ``value``, ``units``, ``metadata`` - ``Cursor`` and value properties * - Discover values by path or tag - ``env.select(...)``; ``env.select_paths(...)`` - ``list[ValueNode]``; ``list[str]`` * - Describe or preview changes - ``describe``; ``preview`` with ``PreviewOverride`` - ``Description``; ``PreviewResult`` * - Persist or export - ``env.save``; ``env.generate(ExportFormat, path)`` - DIPH5 or generated parameter file * - Generate a report - ``env.generate_report(ReportFormat, path, ...)`` - Report file * - Compare snapshots - ``compare_diph5``; ``render_comparison`` - ``Comparison``; rendered text * - Run an adapter - ``run_adapter_project(DIPfile, adapter, output, snapshot)`` - Written paths and optional DIPH5 snapshot .. code-block:: python from scinumtools3.dip import ( DIP, ExportFormat, PreviewOverride, PreviewOverrideKind, compare_diph5, describe, preview, render_comparison, ) env = DIP.load("DIPfile") # Environment speed = env["physics.speed"] # Cursor print(speed.value, speed.units) print(env.select_paths("?physics.", tags_all=["runtime"])) print(describe(env, "physics.speed").value_text) candidate = preview( "parameters.dip", [PreviewOverride(PreviewOverrideKind.Text, "physics.speed = 3 m/s")], ) # PreviewResult print(candidate.candidate_valid, candidate.comparison.changed) env.save("run.diph5") env.generate(ExportFormat.JSON, "parameters.json") changes = compare_diph5("before.diph5", "run.diph5") print(render_comparison(changes, max_details=10)) ``DIP.load()`` and the parser calls return native Python objects; no manual cleanup is required. Invalid DIPL, missing paths, and failed writes raise exceptions. Use ``diagnostic_from_exception(error)`` when structured parser diagnostics are needed. See the :doc:`Python binding guide <../../../integrations/python>` and :doc:`Python API reference <../../../api/python_dip>` for environments, cursors, adapters, comparison, and reports. **DIPL developer tools.** The Python binding evaluates DIPL through the native parser, so invalid input raises a parse error. It does not currently expose standalone formatter, validator, or linter helpers. Use ``snt dip format``, ``snt dip validate``, and ``snt dip lint``, or the C++ tooling API, for those workflows. Current limitations and differences ----------------------------------- Compared with the canonical C++ implementation: - Python wraps parsing, inspection, callbacks, adapters, persistence, and reports, but does not wrap the C++ ``EditSession``, ``ArchiveEditSession``, ``SetupSession``, or ``Experiment`` classes. - Original block retention can be requested through ``DIP.load(..., retain_block_inputs=True)``. The Python ``parse()`` method only exposes the dependency-graph recording option. - Standalone formatter, validator, and linter helpers are not exposed. Parsing still validates the model. Use ``snt dip format``, ``snt dip validate``, ``snt dip lint``, or the C++ tooling API for those operations. Binding reference ----------------- This is a lookup index, not a sequence to read from top to bottom. Use `Common workflows` above to choose a task, then find the exact Python name for that task below. Properties are shown without parentheses; callable names include their arguments. The linked API reference documents complete signatures and result fields. Parser and input registration ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ``DIP()`` and ``DIP.load(path, record_dependency_graph=False, retain_block_inputs=False)``. - ``add_string(source_code)``, ``add_file(path, source_name="")``, and ``add_source(source_name, source_file)``. - ``add_project(project_file)`` and ``add_unit(name, unit)``. - ``add_schema_string(name, source_code)`` and ``add_schema_file(name, source_file)``. - ``add_override_string(source_code)`` and ``add_override_file(source_file)``. - ``add_function_value(name, callback)`` and ``add_function_nodes(name, callback)``. - ``parse(record_dependency_graph=False)``, ``to_string()``, and the context manager methods ``enter()`` and ``exit()``. Environment and persistence ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ``env[path]`` returns a ``Cursor``. - ``env.nodes``, ``env.size``, ``env.schemas``, ``env.schema_manifest``, ``env.source_manifest``, and ``env.output_plan``. - ``env.applied_schemas(path)`` and ``env.contributing_schema(path)``. - ``env.select(...)``, ``env.select_paths(...)``, ``env.request_group(...)``, and ``env.request_value(path, to_units="", as_numpy=False)``. - ``env.load(file)``, ``env.save(file)``, ``env.generate(format, file)``, and ``env.generate_report(format, file, ...)``. - ``ExportFormat`` values ``CPP``, ``C``, ``FORTRAN``, ``RUST``, ``R``, ``JULIA``, ``JSON``, ``TOML``, and ``YAML``. - ``ReportFormat`` values ``TEX``, ``PDF``, ``MARKDOWN``, ``RST``, ``HTML``, ``TYPST``, ``TEXT``, and ``JSON`` where report support is built. - ``generate_report`` keywords ``input_label``, ``intro_file``, ``tex_compiler``, ``title``, ``author``, ``date``, ``version``, and ``include_cheatsheet``. - ``env.to_string()``, ``str(env)``, and ``repr(env)``. Cursor traversal ~~~~~~~~~~~~~~~~ - ``cursor[name]`` and ``cursor[index]``; ``name in cursor`` tests a named child. - ``children()``, ``entries()``, ``entry_names()``, ``elements()``, ``items()``, and ``has_item(name)``. - Properties ``path``, ``kind``, ``node_type``, ``shape``, ``value``, ``units``, ``metadata``, ``provenance``, ``link_source``, and ``link_target``. - ``to_numpy()`` and ``to_string()``. Selected value nodes ~~~~~~~~~~~~~~~~~~~~ - Properties ``name``, ``node_type``, ``dtype``, ``value``, ``units``, ``shape``, ``tags``, ``schema_id``, ``override``, ``metadata``, ``link_source``, and ``link_target``. - ``to_numpy()`` and ``to_string()``. Inspection ~~~~~~~~~~ - ``detect_artifact(path)``, ``open_artifact(path, record_dependency_graph=False)``, and ``reload_artifact(env, path, ...)``. - ``inspect_value(env, path)``, ``inspect_values(env)``, and ``inspect_capabilities(env, path)``. - ``inspect_dependency_graph(env)``, ``inspect_table(env, path)``, and ``inspect_tables(env)``. - ``read_value_slice(env, path, ranges, as_numpy=False)``. - ``describe(env, path, max_value_elements=16)``, ``list_descriptions(env, query="?", ...)``, ``schema_hierarchy(env)``, ``override_contract(env, path)``, and ``preview(input, overrides, ...)``. - ``diagnostic_from_exception(error)`` returns the structured diagnostic attached to a DIP exception, when present. - ``ValueNode``, ``ValueNodeData``, ``CursorEntry``, ``PathKind``, ``ArtifactKind``, ``ValueChangeKind``, ``ValueChange``, ``ValueInspection``, and ``InspectionCapabilities``. - ``CompositionKind``, ``OperationType``, ``CompositionNode``, ``CompositionGraph``, ``DependencyEventKind``, ``DependencyEdge``, ``DependencyEvent``, and ``DependencyGraph``. - ``TableColumnInspection``, ``TableInspection``, ``SourceLocation``, ``DiagnosticSeverity``, and ``Diagnostic``. - ``SemanticDescription``, ``OverrideTargetKind``, ``OverrideContract``, ``SemanticList``, ``SchemaMemberInspection``, ``MetadataConstraintInspection``, ``SchemaDefinitionInspection``, ``SchemaApplicationInspection``, ``SchemaValueAssociation``, and ``SchemaHierarchyInspection``. - ``PreviewOverrideKind``, ``PreviewOverride``, and ``PreviewResult``. Comparison, adapters, and command facade ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ``compare(before, after, options)``, ``compare_diph5(before, after, options)``, and ``render_comparison(result, max_details=50)``. - ``ComparisonOptions`` fields ``scope`` and ``max_array_examples``; ``ComparisonScope.Effective`` and ``Full``. - ``Adapter``, ``AdapterContext``, ``OutputPlan``, ``resolve_output_plan``, ``run_adapter``, ``run_adapter_project``, and ``run_adapter_snapshot``. - ``Adapter.plan(env, context)``, ``plan_resolved(env, outputs, context)``, and ``describe_outputs(env, outputs)``. - ``AdapterContext.add_text(path, text)``, ``add_binary(path, data)``, and ``add_stream(path, callback)``. - ``OutputPlan.add_node``, ``replace_node``, ``add_value``, ``replace_value``, ``select``, and ``mappings``; ``OutputMapping`` exposes ``id``, ``target``, ``key``, ``source_path``, ``rule``, ``origin``, ``replacements``, ``dependencies``, ``active``, ``value``, and ``value_node``. - ``ExistingOutputPolicy.Reject``, ``ReplaceRegistered``, and ``SyncRegistered``. - ``scinumtools3.api.dip.DIPParse()`` provides ``argument_add(add_type, values)``, ``argument_request(path)``, ``argument_load(file)``, ``argument_save(file)``, ``argument_generate(format, file)``, ``argument_tags(tags)``, ``argument_print()``, ``argument_value(type="")``, and ``execute() -> str``. - ``DIPCompare(before, after)`` provides ``set_options(options)``, ``set_max_details(count)``, ``compare() -> ComparisonResult``, and ``execute() -> str``.