dataclass.results

Classes

class dataclass.results.ResultModel

Base class for structured calculation results with per-field unit and title support.

Subclass this and annotate fields with :func:UnitField to attach ``title``, ``unit``, and ``description`` metadata to each result value. This class provides the same convenience interface as :class:SingleResult (``export_doc_context``, ``convert_to_table_data``, dict-style access, etc.) while being fully typed and Pydantic-native.

For fields that do not need a unit, the standard :func:pydantic.Field can be used directly alongside :func:UnitField fields — they work together seamlessly.

Serialization uses :meth:serialize / :meth:deserialize to preserve all field metadata (title, unit, description) for full round-trip fidelity. Plain ``model_dump()`` / ``model_validate()`` can still be used when only the field values are needed.

Examples

>>> from pydantic import Field
>>> class BearingCapacityResult(ResultModel):
...     bearing_capacity: float = UnitField(title="承载力特征值", unit=Units.kPa)
...     safety_factor: float    = UnitField(title="安全系数")
...     note: str               = Field(default="", title="备注")
...
>>> result = BearingCapacityResult(bearing_capacity=150.0, safety_factor=2.5)
>>> result
BearingCapacityResult(bearing_capacity[承载力特征值]=150.0 kPa, safety_factor[安全系数]=2.5, note[备注]='')
>>> result.model_dump()
{'bearing_capacity': 150.0, 'safety_factor': 2.5, 'note': ''}
Inherits from:

BaseModel

Methods:

get_unit(field_name: str) Units

Parameters

field_namestr

Name of the field.

Returns

Any
Units
    The unit attached to the field, or ````Units.UNITLESS```` if none was set.
get_title(field_name: str) str

Parameters

field_namestr

Name of the field.

Returns

Any
str
    The field title from :func:``UnitField``, or the field name as a fallback.
get_description(field_name: str) str | None

Parameters

field_namestr

Name of the field.

get(key: str | int, default: Any = None) Any

Get a field value by name, title, or index; return default if not found.

Parameters

keystr | int

Field name, display title, or integer index.

defaultAny, default: None

Value returned when key is not found.

convert_to_table_data(joiner: str = ',') TableData

Convert the result to a single-row :class:~gdi.dataclass.tables.TableData.

Returns

Any
TableData
    A one-row table whose columns match the model's field names, with
    ````title```` and ````unit```` metadata preserved via :class:``~gdi.dataclass.tables.FieldMetadata``.
resolve_field_name(key: str) str

Resolve a field name or display title to the internal field name.

Parameters

keystr

Field name or :meth:get_title string.

to_plain_text(keys: list[str] | None = None, value_separator: str = '\n\n', json_indent: int | None = 2) str

Render this model as one plain-text string for display or file output.

When keys is ``None``, every field whose value passes :meth:_plain_text_value_is_serializable is included, in field definition order. When keys is set, only those fields are written (names or titles, in order); values that are not JSON-serialisable fall back to :func:str.

value_separator joins sequence elements and joins successive field blocks. json_indent is passed to :func:json.dumps for ``dict`` values and other JSON-encoded scalars.

See also :class:~gdi.modules.writers.TextWriter.

export_doc_context(precision: int | dict[str, int | None] | None = None, datetime_format: str | dict[str, str | None] | None = None, joiner: str = ',') dict[str, Any]

Export the result as a flat dict for filling a ``.docx`` template.

Returns

Any
dict[str, Any]
    Flat dict keyed by field name. A special key ````"doc_keys_struct"```` is
    appended describing each field's ````title````, ````unit````, ````description````,
    and ````column_keys````.
from_dict(cls, values: dict[str, Any]) ResultModel

Create a :class:ResultModel instance dynamically from a plain dict.

This is a convenience wrapper around :func:pydantic.create_model that removes the need to work with Pydantic internals directly. Use it when the field names or their count are only known at runtime (e.g. when merging multiple upstream results, or wrapping a single computed value whose key is configurable).

Parameters

model_namestr, default: ``"DynamicResultModel"``

Class name of the dynamically created model. Only affects ``repr`` and ``type(result).__name__``; it does not need to be unique. fields_meta : dict[str, FieldInfo] | dict[str, FieldMetadata] | None, default: None Optional per-field metadata from :func:UnitField, the standard :func:pydantic.Field, or :class:~gdi.dataclass.tables.FieldMetadata. The ``default`` inside each ``FieldInfo`` is ignored — defaults are always taken from values. Keys that are present in fields_meta but absent from values are silently ignored.

Returns

Any
ResultModel
    A fully constructed instance whose type is a dynamic subclass of
    the class this method is called on (````cls````).

Examples

Simple usage  values only:

>>> result = ResultModel.from_dict({"fa": 180.0, "sf": 2.1})

With per-field metadata:

>>> from gdisdk.dataclass.results import ResultModel, UnitField
>>> from gdisdk.dataclass.terminologies import Units
>>> result = ResultModel.from_dict(
...     {"bearing_capacity": 180.0, "safety_factor": 2.1},
...     model_name="BearingResult",
...     fields_meta={
...         "bearing_capacity": UnitField(title="承载力特征值", unit=Units.KPA),
...         "safety_factor":    UnitField(title="安全系数"),
...     },
... )

Calling on a subclass inherits from that subclass:

>>> class MyResult(ResultModel):
...     extra: str = Field(default="ok")
>>> instance = MyResult.from_dict({"x": 1.0})
>>> isinstance(instance, MyResult)
True
serialize() dict

Serialize this instance to a dict that preserves all field metadata.

Unlike plain ``model_dump()``, this captures per-field title, unit, and description so the instance can be faithfully reconstructed via :meth:deserialize. The format mirrors the ``serialize()``/ ``deserialize()`` contract used by :class:~gdi.dataclass.tables.TableData and :class:~gdi.dataclass.results.SingleResult.

Returns

Any
dict
    A dict with the following structure::

        {
            "model_name": str,         # class name (cosmetic)
            "fields": [
                {
                    "name": str,
                    "title": str,
                    "unit": str,       # Units enum value string, e.g. "kPa"
                    "description": str | None,
                    "value": Any       # raw field value
                },
                ...
            ],
            "title_to_name": {str: str}
        }

Notes

Field values are included as-is (no recursive serialization).  Complex
field types (e.g. ````np.ndarray````) should be handled by the outer
serializer (e.g. :func:``~routers.utils._serialize_data_value`` or
:class:``~routers.commonRequestBody.CustomJSONEncoder``).

See also
deserialize : reconstruct an instance from the dict produced here.
deserialize(cls, data_dict: dict) ResultModel

Reconstruct a :class:ResultModel from a dict produced by :meth:serialize.

Parameters

data_dictdict

Dict produced by :meth:serialize.

Returns

Any
ResultModel
    A dynamic subclass of *cls* whose field values, titles, units, and
    descriptions match the original instance.

Examples

>>> original = BearingCapacityResult(bearing_capacity=150.0, safety_factor=2.5)
>>> restored = ResultModel.deserialize(original.serialize())
>>> restored["bearing_capacity"]
150.0
>>> restored.get_title("bearing_capacity")
'承载力特征值'

Notes

Statically defined subclasses (e.g. ````BearingCapacityResult````) are **not**
reconstructed by class name; a new dynamic model with identical field
metadata is returned instead.  The result is functionally equivalent for
all data-access operations.

See also
serialize : produce the dict consumed here.

Properties:

names

Field names in definition order.

titles

Display titles in definition order.

units

Units in definition order.

values

Field values in definition order.

descriptions

Field descriptions in definition order.

name_values
title_values
title_to_name

Attributes:

model_config = <ast.Call object at 0x0000028E22124B50>
class dataclass.results.UnitResult

Save calculation result in a single value format.

Inherits from:

BaseModel

Methods:

model_post_init(__context: Any) None
convert_numpy_number(cls, v)

Attributes:

name: str = <ast.Call object at 0x0000028E2171AC20>
title: str | None = <ast.Call object at 0x0000028E2171BB80>
unit: Units = <ast.Call object at 0x0000028E2171B640>
value: GeneralValue = <ast.Call object at 0x0000028E2171A950>
description: str | None = <ast.Call object at 0x0000028E2171B610>
model_config = <ast.Dict object at 0x0000028E2171AEC0>
class dataclass.results.SingleResult

Save calculation result in a dictionary format. It’s used to save a single value result.

Methods:

__init__(result: list[UnitResult] | dict[str, GeneralValue])
get(key: str | int, default: UnitResult | None = None) UnitResult | None

Get the UnitResult object by name, title, or index, returning default if not found.

Parameters

keystr | int

The name, title, or index of the result to retrieve.

defaultUnitResult | None, default: None

The value to return if the key is not found.

Returns

Any
UnitResult | None
    The UnitResult object if found, otherwise the default value.
convert_to_table_data(joiner: str = ',') TableData

Convert the SingleResult to a TableData object.

export_doc_context(precision: int | dict[str, int | None] | None = None, datetime_format: str | dict[str, str | None] | None = None, joiner: str = ',') dict[str, SingleValue]

Export the result to a dictionary list text for documentation.

Returns

Any
dict[str, Any]
    The context of the result.
    The key is the name of the result, the value is the value of the result.
    A special key "doc_keys_strcut" is added to the context, which is used to describe the structure of the keys for the result.

Examples

- "%Y-%m-%d": "2024-01-15"
    - "%Y年%m月%d日": "2024年01月15日"
    - "%Y/%m/%d %H:%M": "2024/01/15 14:30"

Notes

If the value is a list, the value will be joined by the joiner. So each value of the keys can only be a single value.
serialize() dict

Serialize the SingleResult object to a dictionary.

This method converts the SingleResult object into a dictionary format that can be easily serialized to JSON or other formats. All UnitResult objects and their metadata are preserved.

Returns

Any
dict
    A dictionary containing all SingleResult information:
    - 'results': List of serialized UnitResult objects
    - 'title_to_name': Mapping of titles to names

Examples

>>> result = SingleResult(...)
>>> serialized = result.serialize()
>>> # Can be saved to JSON
>>> import json
>>> json_str = json.dumps(serialized)
deserialize(cls, data_dict: dict) SingleResult

Deserialize a SingleResult object from a dictionary.

This class method reconstructs a SingleResult object from a dictionary created by the serialize() method. All UnitResult objects and metadata are properly restored.

Parameters

data_dictdict

Dictionary containing serialized SingleResult information, typically created by the serialize() method

Returns

Any
SingleResult
    Reconstructed SingleResult object with all UnitResult objects preserved

Examples

>>> # Load from serialized data
>>> result = SingleResult.deserialize(serialized_data)
>>>
>>> # Or from JSON
>>> import json
>>> data_dict = json.loads(json_str)
>>> result = SingleResult.deserialize(data_dict)

Properties:

result
title_to_name
name_values
title_values
values
names
titles
units
descriptions
class dataclass.results.ComplexResult

Used to save combination of tabledata result, tablecollection result and single result.

Methods:

__init__(table_data: TableData | None = None, table_collection: TableCollection | None = None, single_result: SingleResult | None = None)
export_doc_context(key_type: Literal[name, title] = 'name', table_key: str = 'table_value', precision: dict[str, int | None] | None = None) dict[Any]

Export the table result and single result to a dictionary list text for documentation.

Parameters

table_keystr, default: “table_value”

The key name for the table data. precision: dict[str, int | None], default: None The precision used to format the values to string. The keys are the names of the result.

class dataclass.results.ToGdimJsonTable

Convert a TableData, TableCollection or SingleResult to a json format so that it can be rendered on Gdim.

Methods:

__init__(data: TableData | TableCollection | SingleResult | None = None, columns: list[str] | None = None, precision: dict[str, int] | None = None, group_by: str | None = None, main_table: str | None = None)

Initialize the ToGdimJsonTable object.

Parameters

dataSingleResult | TableData | TableCollection | None, default: None

The data to be converted to a json format.

columnslist[str] | None, default: None

The columns to be converted to a json format. It should be the column names of the result. precision: dict[str, int] | None, default: None The precision to be converted to a json format. The keys are the column names of the result.

group_bystr | None, default: None

The column name to be grouped by. If None, the “group_by” will be the first column with the same name in all tables.

main_tablestr | None, default: None

The name of the main table. If None, the table with the least number of rows will be used as the main table.

Notes

This class can only general a json table each time which means for TableCollection, it will be merged into a single table by
columns, group_by and main_table.
convert() GdimJsonTable

Convert the result to a GdimJsonTable object.

class dataclass.results.DocData

Save the result in a format that can be used to generate a .docx document.

Inherits from:

BaseModel

Methods:

to_json_serializable() dict[str, Any]

Returns

Any
dict[str, Any]
    A dictionary with 'data' and 'doc_keys_struct' keys,
    where all Path objects have been converted to strings.
export_data_to_json(file_path: str) None

Export the data to a JSON file with Path objects converted to strings.

Parameters

file_pathstr

The path where to save the JSON file.

export_keys_to_json(file_path: str) None

Export the doc keys structure to a JSON file with Path objects converted to strings.

Parameters

file_pathstr

The path where to save the JSON file.

export_all_to_json(file_path: str) None

Export both data and doc keys structure to a JSON file with Path objects converted to strings.

Parameters

file_pathstr

The path where to save the JSON file.

Attributes:

data: dict[(str, Any)] = <ast.Call object at 0x0000028E224D1B40>
doc_keys_struct: dict[(str, Any)] = <ast.Call object at 0x0000028E224D1D80>
class dataclass.results.CoordinateSystem

The model defined a coordinate system.

Inherits from:

BaseModel

Attributes:

name: Literal[(WGS84_UTM_S, WGS84_UTM_N, CGCS2000_3, CGCS2000_6, Xian1980_3, Xian1980_6, Beijing1954_3, Beijing1954_6, WGS84, RELATIVE_CRS)] | None = <ast.Call object at 0x0000028E2242C400>
zoneMethod: Literal[(manualInput, autoInput)] | None = <ast.Call object at 0x0000028E2242C6D0>
zoneNumber: int | None = <ast.Call object at 0x0000028E2242C8E0>
centralMeridian: float | None = <ast.Call object at 0x0000028E2242CAF0>
refPointLongitude: float | None = <ast.Call object at 0x0000028E2242CD00>
refPointLatitude: float | None = <ast.Call object at 0x0000028E2242CF10>
refPointX: float | None = <ast.Call object at 0x0000028E2242D120>
refPointY: float | None = <ast.Call object at 0x0000028E2242D330>
elevationDatum: str | None = <ast.Call object at 0x0000028E2242D540>
yAxisDirection: Literal[(east, north)] | None = <ast.Call object at 0x0000028E2242D810>
class dataclass.results.GeoReferenceInfo

The geo reference information of a dataset, such as a picture.

Inherits from:

BaseModel

Attributes:

file_name: str | None = <ast.Call object at 0x0000028E2242DAE0>
bounds: dict[(Literal[(left, bottom, right, top)], float)] | None = <ast.Call object at 0x0000028E2242DED0>
transform: list[float] | None = <ast.Call object at 0x0000028E2242E140>
raster_size: dict[(Literal[(width, height)], int)] | None = <ast.Call object at 0x0000028E2242E4D0>
nodata_value: float | None = <ast.Call object at 0x0000028E2242E6E0>
time_info: str | None = <ast.Call object at 0x0000028E2242E8F0>

Functions

dataclass.results.UnitField(default: Any = Ellipsis) Any

Create a Pydantic Field with unit metadata for use in :class:ResultModel subclasses.

Parameters

defaultAny

The default value. Use ``...`` (Ellipsis) for required fields.

titlestr | None, default: None

Human-readable display title for the field. Defaults to the field name if omitted.

unitUnits, default: Units.UNITLESS

Physical unit of the field value.

descriptionstr | None, default: None

A short description of what the field represents. **kwargs Additional keyword arguments forwarded to :func:pydantic.Field.

Returns

Any
FieldInfo
    A Pydantic ````FieldInfo```` with ````unit```` stored in ````json_schema_extra````.

Examples

>>> from pydantic import Field
>>> class MyResult(ResultModel):
...     bearing_capacity: float = UnitField(title="承载力特征值", unit=Units.kPa)
...     safety_factor: float    = UnitField(title="安全系数")        # unit defaults to UNITLESS
...     note: str               = Field(default="", title="备注")    # plain Field is fine too

Notes

If a field does not need a unit, you can use the standard :func:``pydantic.Field``
directly — ````UnitField```` is only required when you want to attach a
:class:``~gdi.dataclass.terminologies.Units`` value.  Fields declared with
plain ````Field```` will report ````Units.UNITLESS```` from :meth:``ResultModel.get_unit``.