Skip to content

Result files

save_result(result, path) writes a FieldResult to a versioned JSON file and load_result(path) reads it back; world_fingerprint(world) is the hash of a world that every solve records in its provenance. A parameter study can therefore store each solve and later check which world, engine and package versions produced it.

Format

One UTF-8 JSON document (standard JSON: no NaN / Infinity tokens, no pickle) with an envelope:

{
  "format": "groundfield.result",
  "schema_version": 1,
  "written_by": "groundfield <version>",
  "provenance": {"groundfield_version": "...", "engine": {...}, "world_fingerprint": "...", "solved_at_utc": "..."},
  "result": {...}
}

result is the lossless JSON of the FieldResult: complex numbers are strings, non-finite floats of typed fields are "Infinity" / "NaN" strings, and metadata values JSON cannot express are tagged objects (arrays with dtype and shape, tuples, complex numbers). provenance repeats the solve provenance (groundfield, numpy, scipy, pydantic and Python versions, platform, engine configuration, world fingerprint, UTC time stamp) so it can be read without parsing the result.

Compatibility. load_result reads every schema version up to RESULT_SCHEMA_VERSION and raises ResultFormatError for a newer one instead of guessing. The loader reads only what the writer writes (plain numeric and string arrays with bounded size and nesting), so a file from an untrusted source cannot make it allocate arbitrary memory or construct objects. Files are written atomically; overwrite=False (default) refuses to replace an existing file.

The world is not part of the file. Save it alongside with world.model_dump_json() (exact round trip) and compare it with world_fingerprint(world) against provenance["world_fingerprint"].

Example

import groundfield as gf

world = gf.create_world(soil=gf.HomogeneousSoil(rho=100.0))
gf.create_electrode(world, "rod", name="g1", position=(0.0, 0.0, 0.0), length=3.0)
gf.create_source(world, attached_to="g1", magnitude=1.0)
result = gf.create_engine(frequencies=[50.0, 1000.0]).solve(world)

path = gf.save_result(result, "rod.result.json")
loaded = gf.load_result(path)

assert loaded.input_impedance() == result.input_impedance()        # bit-identical
assert loaded.metadata["provenance"]["world_fingerprint"] == gf.world_fingerprint(world)

API reference

results

Versioned on-disk format of a FieldResult.

A result file is one UTF-8 JSON document (standard JSON, no NaN / Infinity tokens, no pickle) with an envelope::

{
  "format": "groundfield.result",
  "schema_version": 1,
  "written_by": "groundfield <version>",
  "provenance": {...},        # FieldResult.metadata["provenance"] or null
  "result": {...}             # FieldResult JSON (lossless, see below)
}

provenance repeats the solve provenance of the result (groundfield / numpy / scipy / Python versions, platform, engine configuration, world_fingerprint and the UTC timestamp), so it can be read without parsing the result. It is null for results that were not produced by Engine.solve (hand-built results).

The result body is FieldResult.model_dump_json(), which round-trips losslessly: complex numbers are strings, non-finite floats of typed fields are "Infinity" / "NaN" strings, and the metadata uses tagged objects for values JSON cannot express (see groundfield.solver.result).

Schema versions

schema_version increases whenever a reader of the previous version could misread a file. load_result() reads every version up to RESULT_SCHEMA_VERSION and raises ResultFormatError for a newer one, instead of guessing.

The world itself is not part of the file; save it alongside with world.model_dump_json() (exact round trip) and compare it with world_fingerprint() against provenance["world_fingerprint"].

RESULT_FORMAT module-attribute

RESULT_FORMAT = 'groundfield.result'

Value of the format key of a result file.

RESULT_SCHEMA_VERSION module-attribute

RESULT_SCHEMA_VERSION = 1

Schema version written by save_result().

ResultFormatError

Bases: ValueError

A file is not a readable groundfield result file.

load_result

load_result(path: str | PathLike[str]) -> FieldResult

Read a result file written by save_result().

Parameters:

Name Type Description Default
path str | PathLike[str]

File to read.

required

Returns:

Type Description
FieldResult

The stored result, equal to the one that was saved.

Raises:

Type Description
ResultFormatError

If the file is not UTF-8 JSON (or nests too deeply for the JSON parser), not a groundfield result file, uses a schema version newer than RESULT_SCHEMA_VERSION, or lacks the result body.

ValidationError

If the result body does not validate as a FieldResult, including malformed tagged metadata (see groundfield.solver.result). Both error types subclass ValueError.

Notes

The reader accepts only what save_result() writes, so a file from an untrusted source cannot make it allocate more than a small multiple of the file size or create object, datetime or void arrays. No pickle is involved at any point.

Source code in src/groundfield/io/results.py
def load_result(path: str | os.PathLike[str]) -> FieldResult:
    """Read a result file written by :func:`save_result`.

    Parameters
    ----------
    path
        File to read.

    Returns
    -------
    FieldResult
        The stored result, equal to the one that was saved.

    Raises
    ------
    ResultFormatError
        If the file is not UTF-8 JSON (or nests too deeply for the JSON
        parser), not a groundfield result file, uses a schema version
        newer than :data:`RESULT_SCHEMA_VERSION`, or lacks the
        ``result`` body.
    pydantic.ValidationError
        If the ``result`` body does not validate as a
        :class:`FieldResult`, including malformed tagged metadata (see
        :mod:`groundfield.solver.result`). Both error types subclass
        :class:`ValueError`.

    Notes
    -----
    The reader accepts only what :func:`save_result` writes, so a file
    from an untrusted source cannot make it allocate more than a small
    multiple of the file size or create object, datetime or void
    arrays. No pickle is involved at any point.
    """
    source = Path(path)
    try:
        text = source.read_text(encoding="utf-8")
    except UnicodeDecodeError as exc:
        raise ResultFormatError(f"{source} is not UTF-8 text: {exc}") from exc
    try:
        payload = json.loads(text)
    except RecursionError as exc:
        raise ResultFormatError(
            f"{source} nests JSON values too deeply to be a result file."
        ) from exc
    except ValueError as exc:  # json.JSONDecodeError and over-long integers
        raise ResultFormatError(f"{source} is not a JSON file: {exc}") from exc
    if not isinstance(payload, dict) or "format" not in payload:
        raise ResultFormatError(
            f"{source} is not a groundfield result file (no 'format' key, "
            f"expected '{RESULT_FORMAT}'). Result files are written by "
            "groundfield.io.save_result; a bare FieldResult JSON loads with "
            "FieldResult.model_validate_json."
        )
    if payload["format"] != RESULT_FORMAT:
        raise ResultFormatError(
            f"{source}: format {payload['format']!r} is not {RESULT_FORMAT!r}."
        )
    version = payload.get("schema_version")
    if not isinstance(version, int) or isinstance(version, bool) or version < 1:
        raise ResultFormatError(
            f"{source}: invalid schema_version {version!r} (expected an integer >= 1)."
        )
    if version > RESULT_SCHEMA_VERSION:
        writer = payload.get("written_by", "a newer groundfield")
        raise ResultFormatError(
            f"{source} uses schema_version {version}, newer than the "
            f"supported {RESULT_SCHEMA_VERSION} (written by {writer}); "
            "upgrade groundfield to read it."
        )
    if "result" not in payload:
        raise ResultFormatError(f"{source} has no 'result' body.")
    return FieldResult.model_validate(payload["result"])

save_result

save_result(result: FieldResult, path: str | PathLike[str], *, overwrite: bool = False, indent: int | None = None) -> Path

Write a result to a versioned JSON file.

Parameters:

Name Type Description Default
result FieldResult

The result to store.

required
path str | PathLike[str]

Target file. The parent directory must exist.

required
overwrite bool

Replace an existing file. Default False: an existing file raises FileExistsError.

False
indent int | None

Indentation of the JSON text; None (default) writes it compactly.

None

Returns:

Type Description
Path

The written path.

Raises:

Type Description
TypeError

If result is not a FieldResult.

FileExistsError

If path exists and overwrite is false.

ValueError

If the result holds values that cannot be stored (the message names the metadata key).

Notes

The file is written to a temporary file in the target directory and moved into place with os.replace(), so an interrupted write never leaves a truncated result file behind. Its permissions are those of a plain open(path, "w"): a new file gets 0o666 reduced by the process umask (0o644 under the usual 022), a replaced file keeps its mode.

Source code in src/groundfield/io/results.py
def save_result(
    result: FieldResult,
    path: str | os.PathLike[str],
    *,
    overwrite: bool = False,
    indent: int | None = None,
) -> Path:
    """Write a result to a versioned JSON file.

    Parameters
    ----------
    result
        The result to store.
    path
        Target file. The parent directory must exist.
    overwrite
        Replace an existing file. Default ``False``: an existing file
        raises :class:`FileExistsError`.
    indent
        Indentation of the JSON text; ``None`` (default) writes it
        compactly.

    Returns
    -------
    pathlib.Path
        The written path.

    Raises
    ------
    TypeError
        If ``result`` is not a :class:`FieldResult`.
    FileExistsError
        If ``path`` exists and ``overwrite`` is false.
    ValueError
        If the result holds values that cannot be stored (the message
        names the metadata key).

    Notes
    -----
    The file is written to a temporary file in the target directory and
    moved into place with :func:`os.replace`, so an interrupted write
    never leaves a truncated result file behind. Its permissions are
    those of a plain ``open(path, "w")``: a new file gets ``0o666``
    reduced by the process umask (``0o644`` under the usual ``022``), a
    replaced file keeps its mode.
    """
    if not isinstance(result, FieldResult):
        raise TypeError(
            f"save_result expects a FieldResult, got {type(result).__name__}."
        )
    target = Path(path)
    if target.exists() and not overwrite:
        raise FileExistsError(f"{target} exists; pass overwrite=True to replace it.")
    from groundfield import __version__

    body: dict[str, Any] = json.loads(result.model_dump_json())
    envelope = {
        "format": RESULT_FORMAT,
        "schema_version": RESULT_SCHEMA_VERSION,
        "written_by": f"groundfield {__version__}",
        "provenance": body.get("metadata", {}).get("provenance"),
        "result": body,
    }
    text = json.dumps(envelope, allow_nan=False, indent=indent, ensure_ascii=False)
    directory = target.parent if str(target.parent) else Path(".")
    fd, tmp_name = _create_temporary(directory, target.name)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            if target.exists():  # overwrite: keep the mode of the replaced file
                os.chmod(tmp_name, stat.S_IMODE(target.stat().st_mode))
            handle.write(text)
            handle.write("\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(tmp_name, target)
    except BaseException:
        if os.path.exists(tmp_name):
            os.unlink(tmp_name)
        raise
    return target

world_fingerprint

world_fingerprint(world: World) -> str

SHA-256 fingerprint of the canonical JSON of a world.

The canonical form is json.dumps(world.model_dump(mode="json"), sort_keys=True, separators=(",", ":")). Pydantic writes floats in their shortest round-trip form, so equal worlds give equal fingerprints, also after a JSON round trip of the world. The fingerprint depends on the world schema of the installed version: renamed or added model fields change it.

Parameters:

Name Type Description Default
world World

The world to fingerprint.

required

Returns:

Type Description
str

"sha256:" followed by 64 hexadecimal digits.

Source code in src/groundfield/solver/result.py
def world_fingerprint(world: World) -> str:
    """SHA-256 fingerprint of the canonical JSON of a world.

    The canonical form is ``json.dumps(world.model_dump(mode="json"),
    sort_keys=True, separators=(",", ":"))``. Pydantic writes floats in
    their shortest round-trip form, so equal worlds give equal
    fingerprints, also after a JSON round trip of the world. The
    fingerprint depends on the world schema of the installed version:
    renamed or added model fields change it.

    Parameters
    ----------
    world
        The world to fingerprint.

    Returns
    -------
    str
        ``"sha256:"`` followed by 64 hexadecimal digits.
    """
    canonical = json.dumps(
        world.model_dump(mode="json"), sort_keys=True, separators=(",", ":")
    )
    return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()