Output Module¶
This section documents the output components of the Nextmv Python SDK.
output
¶
Module for handling output destinations and data.
This module provides classes and functions for handling the output of decision problems, including formatting, serialization, and writing to various destinations.
CLASS | DESCRIPTION |
---|---|
RunStatistics |
Statistics about a general run. |
ResultStatistics |
Statistics about a specific result. |
DataPoint |
A data point representing a 2D coordinate. |
Series |
A series of data points for visualization or analysis. |
SeriesData |
Data container for multiple series of data points. |
Statistics |
Complete statistics container for a solution, including run metrics and result data. |
OutputFormat |
Enumeration of supported output formats. |
VisualSchema |
Enumeration of supported visualization schemas. |
Visual |
Visual schema definition for an asset. |
Asset |
Represents downloadable information that is part of the |
Output |
A class for representing the output of a decision problem. |
OutputWriter |
Base class for writing outputs to different destinations. |
LocalOutputWriter |
Class for writing outputs to local files or stdout. |
FUNCTION | DESCRIPTION |
---|---|
write |
Write the output to the specified destination. |
Asset
¶
Bases: BaseModel
Represents downloadable information that is part of the Output
.
You can import the Asset
class directly from nextmv
:
An asset contains content that can be serialized to JSON and optionally includes visual information for rendering in the Nextmv Console.
PARAMETER | DESCRIPTION |
---|---|
|
Name of the asset.
TYPE:
|
|
Content of the asset. The type must be serializable to JSON.
TYPE:
|
|
Content type of the asset. Only "json" is currently supported. Default is "json".
TYPE:
|
|
Description of the asset. Default is None.
TYPE:
|
|
Visual schema of the asset. Default is None.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the content_type is not "json". |
Examples:
>>> from nextmv.output import Asset, Visual, VisualSchema
>>> visual = Visual(visual_schema=VisualSchema.CHARTJS, label="Solution Progress")
>>> asset = Asset(
... name="optimization_progress",
... content={"iterations": [1, 2, 3], "values": [10, 8, 7]},
... description="Optimization progress over iterations",
... visual=visual
... )
>>> asset.name
'optimization_progress'
DataPoint
¶
Bases: BaseModel
A data point representing a 2D coordinate.
You can import the DataPoint
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
X coordinate of the data point.
TYPE:
|
|
Y coordinate of the data point.
TYPE:
|
Examples:
LocalOutputWriter
¶
Bases: OutputWriter
Class for writing outputs to local files or stdout.
You can import the LocalOutputWriter
class directly from nextmv
:
This class implements the OutputWriter interface to write output data to local files or stdout. The destination and format depend on the output format and the provided path.
Examples:
>>> from nextmv.output import LocalOutputWriter, Output, Statistics
>>> writer = LocalOutputWriter()
>>> output = Output(solution={"result": 42}, statistics=Statistics())
>>> # Write to stdout
>>> writer.write(output, path=None)
>>> # Write to a file
>>> writer.write(output, path="results.json")
FILE_WRITERS
class-attribute
instance-attribute
¶
FILE_WRITERS = {
JSON: _write_json,
CSV_ARCHIVE: _write_archive,
}
Dictionary mapping output formats to writer functions.
write
¶
write(
output: Union[Output, dict[str, Any], BaseModel],
path: Optional[str] = None,
skip_stdout_reset: bool = False,
) -> None
Write the output to the local filesystem or stdout.
This method writes the provided output to the specified path or to stdout, depending on the output format and the path parameter.
PARAMETER | DESCRIPTION |
---|---|
|
Output data to write. Can be an Output object, a dictionary, or a BaseModel.
TYPE:
|
|
Path to write the output data to. The interpretation depends on the output format: - For OutputFormat.JSON: File path for the JSON output. If None or empty, writes to stdout. - For OutputFormat.CSV_ARCHIVE: Directory path for CSV files. If None or empty, writes to a directory named "output" in the current working directory.
TYPE:
|
|
Skip resetting stdout before writing the output data. Default is False.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the Output.output_format is not supported. |
TypeError
|
If the output is of an unsupported type. |
Notes
This function detects if stdout was redirected and resets it to avoid unexpected behavior. If you want to skip this behavior, set the skip_stdout_reset parameter to True.
If the output is a dict or a BaseModel, it will be written as JSON. If the output is an Output object, it will be written according to its output_format.
Examples:
>>> from nextmv.output import LocalOutputWriter, Output
>>> writer = LocalOutputWriter()
>>> # Write JSON to a file
>>> writer.write(Output(solution={"result": 42}), path="result.json")
>>> # Write JSON to stdout
>>> writer.write({"simple": "data"})
Source code in nextmv/nextmv/output.py
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 |
|
Output
dataclass
¶
Output(
options: Optional[
Union[Options, dict[str, Any]]
] = None,
output_format: Optional[OutputFormat] = JSON,
solution: Optional[
Union[
Union[dict[str, Any], Any],
dict[str, list[dict[str, Any]]],
]
] = None,
statistics: Optional[
Union[Statistics, dict[str, Any]]
] = None,
csv_configurations: Optional[dict[str, Any]] = None,
json_configurations: Optional[dict[str, Any]] = None,
assets: Optional[
list[Union[Asset, dict[str, Any]]]
] = None,
)
Output of a decision problem.
You can import the Output
class directly from nextmv
:
This class is used to structure the output of a decision problem that can later be written to various destinations. It supports different output formats and allows for customization of the serialization process.
PARAMETER | DESCRIPTION |
---|---|
|
Options that the
TYPE:
|
|
Format of the output data. Default is
TYPE:
|
|
The solution to the decision problem. The type must match the
TYPE:
|
|
Statistics of the solution. Default is None.
TYPE:
|
|
Configuration for writing CSV files. Default is None.
TYPE:
|
|
Configuration for writing JSON files. Default is None.
TYPE:
|
|
List of assets to be included in the output. Default is None.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the solution is not compatible with the specified output_format. |
TypeError
|
If options, statistics, or assets have unsupported types. |
Notes
The solution's type must match the output_format
:
OutputFormat.JSON
: the data must bedict[str, Any]
orAny
.OutputFormat.CSV_ARCHIVE
: the data must bedict[str, list[dict[str, Any]]]
. The keys represent the file names where the data should be written. The values are lists of dictionaries, where each dictionary represents a row in the CSV file.
Examples:
>>> from nextmv.output import Output, OutputFormat, Statistics, RunStatistics
>>> run_stats = RunStatistics(duration=30.0, iterations=100)
>>> stats = Statistics(run=run_stats)
>>> solution = {"routes": [{"vehicle": 1, "stops": [1, 2, 3]}, {"vehicle": 2, "stops": [4, 5]}]}
>>> output = Output(
... output_format=OutputFormat.JSON,
... solution=solution,
... statistics=stats,
... json_configurations={"indent": 4}
... )
>>> output_dict = output.to_dict()
>>> "solution" in output_dict and "statistics" in output_dict
True
assets
class-attribute
instance-attribute
¶
assets: Optional[list[Union[Asset, dict[str, Any]]]] = None
Optional list of assets to be included in the output. These assets can be of
type Asset
or a simple dictionary. If the assets are of type Asset
, they
will be serialized to a dictionary using the to_dict
method. If they are a
dictionary, they will be used as is. If the assets are not provided, an
empty list will be used.
csv_configurations
class-attribute
instance-attribute
¶
Optional configuration for writing CSV files, to be used when the
output_format
is OutputFormat.CSV_ARCHIVE
. These configurations are
passed as kwargs to the DictWriter
class from the csv
module.
json_configurations
class-attribute
instance-attribute
¶
Optional configuration for writing JSON files, to be used when the
output_format
is OutputFormat.JSON
. These configurations are passed as
kwargs to the json.dumps
function.
options
class-attribute
instance-attribute
¶
Options that the Output
was created with. These options can be of type
Options
or a simple dictionary. If the options are of type Options
,
they will be serialized to a dictionary using the to_dict
method. If
they are a dictionary, they will be used as is. If the options are not
provided, an empty dictionary will be used. If the options are of type
dict
, then the dictionary should have the following structure:
output_format
class-attribute
instance-attribute
¶
output_format: Optional[OutputFormat] = JSON
Format of the output data. Default is OutputFormat.JSON
.
solution
class-attribute
instance-attribute
¶
The solution to the decision problem.
statistics
class-attribute
instance-attribute
¶
statistics: Optional[Union[Statistics, dict[str, Any]]] = (
None
)
Statistics of the solution. These statistics can be of type Statistics
or a
simple dictionary. If the statistics are of type Statistics
, they will be
serialized to a dictionary using the to_dict
method. If they are a
dictionary, they will be used as is. If the statistics are not provided, an
empty dictionary will be used.
to_dict
¶
Convert the Output
object to a dictionary.
RETURNS | DESCRIPTION |
---|---|
dict[str, Any]
|
The dictionary representation of the |
Source code in nextmv/nextmv/output.py
OutputFormat
¶
Bases: str
, Enum
Enumeration of supported output formats.
You can import the OutputFormat
class directly from nextmv
:
This enum defines the different formats that can be used for outputting data. Each format has specific requirements and behaviors when writing.
ATTRIBUTE | DESCRIPTION |
---|---|
JSON |
JSON format, utf-8 encoded.
TYPE:
|
CSV_ARCHIVE |
CSV archive format: multiple CSV files.
TYPE:
|
OutputWriter
¶
Base class for writing outputs.
You can import the OutputWriter
class directly from nextmv
:
This is an abstract base class that defines the interface for writing outputs
to different destinations. Subclasses should implement the write
method.
Examples:
>>> class CustomOutputWriter(OutputWriter):
... def write(self, output, path=None, **kwargs):
... # Custom implementation for writing output
... print(f"Writing output to {path}")
write
¶
Write the output data.
This is an abstract method that should be implemented by subclasses.
PARAMETER | DESCRIPTION |
---|---|
|
The output data to write.
TYPE:
|
|
Variable length argument list.
DEFAULT:
|
|
Arbitrary keyword arguments.
DEFAULT:
|
RAISES | DESCRIPTION |
---|---|
NotImplementedError
|
This method must be implemented by subclasses. |
Source code in nextmv/nextmv/output.py
ResultStatistics
¶
Bases: BaseModel
Statistics about a specific result.
You can import the ResultStatistics
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
Duration of the run in seconds.
TYPE:
|
|
Value of the result.
TYPE:
|
|
Custom statistics created by the user. Can normally expect a
TYPE:
|
Examples:
>>> from nextmv.output import ResultStatistics
>>> result_stats = ResultStatistics(duration=5.2, value=42.0)
>>> result_stats.value
42.0
>>> result_stats.custom = {"gap": 0.05}
>>> result_stats.to_dict()
{'duration': 5.2, 'value': 42.0, 'custom': {'gap': 0.05}}
RunStatistics
¶
Bases: BaseModel
Statistics about a general run.
You can import the RunStatistics
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
Duration of the run in seconds.
TYPE:
|
|
Number of iterations.
TYPE:
|
|
Custom statistics created by the user. Can normally expect a
TYPE:
|
Examples:
>>> from nextmv.output import RunStatistics
>>> stats = RunStatistics(duration=10.5, iterations=100)
>>> stats.duration
10.5
>>> stats.custom = {"convergence": 0.001}
>>> stats.to_dict()
{'duration': 10.5, 'iterations': 100, 'custom': {'convergence': 0.001}}
Series
¶
Bases: BaseModel
A series of data points for visualization or analysis.
You can import the Series
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
Name of the series.
TYPE:
|
|
Data points of the series.
TYPE:
|
Examples:
SeriesData
¶
Bases: BaseModel
Data container for multiple series of data points.
You can import the SeriesData
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
A series for the value of the solution.
TYPE:
|
|
A list of series for custom statistics.
TYPE:
|
Examples:
>>> from nextmv.output import SeriesData, Series, DataPoint
>>> value_series = Series(name="Solution Value", data_points=[DataPoint(x=0, y=10), DataPoint(x=1, y=5)])
>>> custom_series = [Series(name="Gap", data_points=[DataPoint(x=0, y=0.5), DataPoint(x=1, y=0.1)])]
>>> series_data = SeriesData(value=value_series, custom=custom_series)
>>> series_data.value.name
'Solution Value'
>>> len(series_data.custom)
1
Statistics
¶
Bases: BaseModel
Complete statistics container for a solution, including run metrics and result data.
You can import the Statistics
class directly from nextmv
:
PARAMETER | DESCRIPTION |
---|---|
|
Statistics about the run.
TYPE:
|
|
Statistics about the last result.
TYPE:
|
|
Series data about some metric.
TYPE:
|
|
Schema (version). This class only supports
TYPE:
|
Examples:
>>> from nextmv.output import Statistics, RunStatistics, ResultStatistics
>>> run_stats = RunStatistics(duration=10.0, iterations=50)
>>> result_stats = ResultStatistics(value=100.0)
>>> stats = Statistics(run=run_stats, result=result_stats, statistics_schema="v1")
>>> stats.run.duration
10.0
>>> stats.result.value
100.0
result
class-attribute
instance-attribute
¶
result: Optional[ResultStatistics] = None
Statistics about the last result.
run
class-attribute
instance-attribute
¶
run: Optional[RunStatistics] = None
Statistics about the run.
series_data
class-attribute
instance-attribute
¶
series_data: Optional[SeriesData] = None
Data of the series.
statistics_schema
class-attribute
instance-attribute
¶
statistics_schema: Optional[str] = Field(
serialization_alias="schema",
validation_alias=AliasChoices(
"schema", "statistics_schema"
),
default="v1",
)
Schema (version). This class only supports v1
.
Visual
¶
Bases: BaseModel
Visual schema definition for an asset.
You can import the Visual
class directly from nextmv
:
This class defines how an asset is plotted in the Nextmv Console, including the schema type, label, and display type.
PARAMETER | DESCRIPTION |
---|---|
|
Schema of the visual asset.
TYPE:
|
|
Label for the custom tab of the visual asset in the Nextmv Console.
TYPE:
|
|
Defines the type of custom visual. Default is "custom-tab".
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If an unsupported schema or visual_type is provided. |
Examples:
>>> from nextmv.output import Visual, VisualSchema
>>> visual = Visual(visual_schema=VisualSchema.CHARTJS, label="Performance Chart")
>>> visual.visual_schema
<VisualSchema.CHARTJS: 'chartjs'>
>>> visual.label
'Performance Chart'
label
instance-attribute
¶
Label for the custom tab of the visual asset in the Nextmv Console.
visual_schema
class-attribute
instance-attribute
¶
visual_schema: VisualSchema = Field(
serialization_alias="schema",
validation_alias=AliasChoices(
"schema", "visual_schema"
),
)
Schema of the visual asset.
visual_type
class-attribute
instance-attribute
¶
visual_type: Optional[str] = Field(
serialization_alias="type",
validation_alias=AliasChoices("type", "visual_type"),
default="custom-tab",
)
Defines the type of custom visual, currently there is only one type:
custom-tab
. This renders the visual in its own tab view of the run
details.
VisualSchema
¶
Bases: str
, Enum
Enumeration of supported visualization schemas.
You can import the VisualSchema
class directly from nextmv
:
This enum defines the different visualization libraries or rendering methods that can be used to display custom asset data in the Nextmv Console.
ATTRIBUTE | DESCRIPTION |
---|---|
CHARTJS |
Tells Nextmv Console to render the custom asset data with the Chart.js library.
TYPE:
|
GEOJSON |
Tells Nextmv Console to render the custom asset data as GeoJSON on a map.
TYPE:
|
PLOTLY |
Tells Nextmv Console to render the custom asset data with the Plotly library.
TYPE:
|
CHARTJS
class-attribute
instance-attribute
¶
Tells Nextmv Console to render the custom asset data with the Chart.js library.
GEOJSON
class-attribute
instance-attribute
¶
Tells Nextmv Console to render the custom asset data as GeoJSON on a map.
PLOTLY
class-attribute
instance-attribute
¶
Tells Nextmv Console to render the custom asset data with the Plotly library.
write
¶
write(
output: Union[Output, dict[str, Any], BaseModel],
path: Optional[str] = None,
skip_stdout_reset: bool = False,
writer: Optional[OutputWriter] = _LOCAL_OUTPUT_WRITER,
) -> None
Write the output to the specified destination.
You can import the write
function directly from nextmv
:
This is a convenience function for writing output data using a provided writer.
By default, it uses the LocalOutputWriter
to write to files or stdout.
PARAMETER | DESCRIPTION |
---|---|
|
Output data to write. Can be an Output object, a dictionary, or a BaseModel.
TYPE:
|
|
Path to write the output data to. The interpretation depends on the output format:
TYPE:
|
|
Skip resetting stdout before writing the output data. Default is False.
TYPE:
|
|
The writer to use for writing the output. Default is a
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the Output.output_format is not supported. |
TypeError
|
If the output is of an unsupported type. |
Examples:
>>> from nextmv.output import write, Output, OutputFormat
>>> # Write JSON to a file
>>> write(Output(solution={"result": 42}), path="result.json")
>>> # Write CSV archive
>>> data = {"vehicles": [{"id": 1, "capacity": 100}, {"id": 2, "capacity": 150}]}
>>> write(Output(output_format=OutputFormat.CSV_ARCHIVE, solution=data), path="output_dir")
Source code in nextmv/nextmv/output.py
write_local
¶
write_local(
output: Union[Output, dict[str, Any]],
path: Optional[str] = None,
skip_stdout_reset: bool = False,
) -> None
Warning
write_local
is deprecated, use write
instead.
Write the output to the local filesystem or stdout.
This is a convenience function for instantiating a LocalOutputWriter
and
calling its write
method.
PARAMETER | DESCRIPTION |
---|---|
|
Output data to write. Can be an Output object or a dictionary.
TYPE:
|
|
Path to write the output data to. The interpretation depends on the output format:
TYPE:
|
|
Skip resetting stdout before writing the output data. Default is False.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the Output.output_format is not supported. |
TypeError
|
If the output is of an unsupported type. |
Notes
This function detects if stdout was redirected and resets it to avoid unexpected behavior. If you want to skip this behavior, set the skip_stdout_reset parameter to True.
Examples:
>>> from nextmv.output import write_local, Output
>>> # Write JSON to a file
>>> write_local(Output(solution={"result": 42}), path="result.json")
>>> # Write JSON to stdout
>>> write_local({"simple": "data"})