Python API#
The Python API is contained in the idaes_connectivity.base module. The basic workflow is:
Create an instance of the Connectivity class from a model.
Format the connectivity information with one of the subclasses of the Formatter class, writing to a file or returning the value as a string.
You can output CSV for viewing in a text editor or spreadsheet program.
You can also output a text-based diagram specification for viewing in a tool such as Mermaid or D2. Find more details on the diagrams page.
The rest of this page provides some examples of API usage and details of the Connectivity and Formatter classes.
Examples#
In these examples, we will assume we have an instance of Connectivity for a given model.
from idaes_connectivity.tests.example_flowsheet import build
model = build()
conn = Connectivity(input_model=model)
Thenm, to create a CSV file:
from idaes_connectivity.base import Connectivity, CSV
# get connectivity
conn =
# format as CSV
csv_fmt = CSV(conn)
csv_fmt.write("myfile.csv")
Creating D2 and Mermaid diagrams follows the same pattern:
from idaes_connectivity.base import Mermaid, D2
mermaid_fmt = Mermaid(conn)
mermaid_fmt.write("myfile.mmd")
d2_fmt = D2(conn)
d2_fmt.write("myfile.d2")
Returning as a string requires None
as the file argument (full example to show output):
from idaes_connectivity.base import D2, Connectivity
from idaes_connectivity.tests.example_flowsheet import build
conn = Connectivity(input_model=build())
print(D2(conn).write(None))
Ouput:
direction: right
Unit_B: M01
Unit_C: H02
Unit_D: F03
Unit_B -> Unit_C
Unit_C -> Unit_D
A convenience method, display_connectivity
, displays the Mermaid diagram inline in a Jupyter Notebook.
This requires JupyterLab 4.1 or Notebook 7.1, or later.
from idaes_connectivity.base import Connectivity
from idaes_connectivity.jupyter import display_connectivity
conn = Connectivity(input_module="idaes_connectivity.tests.example_flowsheet")
display_connectivity(conn)
Results are output in the next cell, in Markdown, like:
Model connectivity#
The Connectivity
class represents the connectivity of the model.
It also provides some methods to add key/value pairs to the streams or units in the model.
You can fetch values from the model itself using the utility function idaes_connectivity.util.get_stream_display_values()
.
- class idaes_connectivity.base.Connectivity(units: Dict = None, streams: Dict = None, connections: Dict = None, input_file: str | Path | TextIO = None, input_data: List[List[str | int]] = None, input_module: str = None, input_model=None, model_flowsheet_attr: str = '', model_build_func: str = 'build', unit_class=False)#
Represent connectivity of a Pyomo/IDAES model.
Once built, the connectivity is represented by three attributes, units, streams, and connections.
- units#
Dictionary with keys being the unit name (in the model instance) and values being the unit abbreviation (for Mermaid, etc.)
- Type:
dict
- streams#
Dictionary with keys being the stream name (in the model instance) and values being the stream abbreviation (for Mermaid, etc.)
- Type:
dict
- connections#
Dictionary with keys being the stream abbreviation and values being a list of length 2, each element of which can contain a unit abbreviation or be empty. If the first item in the list has a unit abbreviation, then this stream connects to the outlet of that unit; similarly, if the 2nd item has a unit abbr then this stream connects to the inlet. Thus each item in this dict describes an arc, or a line in a diagram, with a stream connecting two units (usual case) or coming into or out of a unit as an unconnected feed or outlet for the flowsheet (possible).
- Type:
dict
- __init__(units: Dict = None, streams: Dict = None, connections: Dict = None, input_file: str | Path | TextIO = None, input_data: List[List[str | int]] = None, input_module: str = None, input_model=None, model_flowsheet_attr: str = '', model_build_func: str = 'build', unit_class=False)#
Create from existing data or one of the valid input types.
Either all three of units, streams, and connections must be given OR one of the input_* arguments must not be None. They will be looked at in the order: model, module, file, data.
- Parameters:
units – See attributes description
streams – See attributes description
connections – See attributes description
input_file – Input CSV file
input_data – List of input rows.
input_module – Module from which to load model
input_model – Existing model object
model_flowsheet_attr – Attribute on model object with flowsheet. If empty, use the model object as the flowsheet.
model_build_func – Name of function in input_module to invoke to build and return the model object.
- Raises:
ModelLoadError – Couldn’t load the model/module
ValueError – Invalid inputs
- property stream_values#
Get current stream values.
This returns a copy, that can be modified without changing the underlying values in the class.
- set_stream_value(stream_name: str, key: str, value)#
Set a value for a stream.
- Parameters:
stream_name – Name of the stream
key – Name of the value
value – The value. Accepts Pyomo value objects with a .value attribute, or “plain” values (string or numeric).
- Raises:
KeyError – If the stream_name is not a valid stream.
- set_stream_values_map(stream_values_map: Dict[str, Dict[str, str]])#
Set multiple stream values using a mapping.
- Parameters:
stream_values_map – Mapping with keys being stream names and values being another mapping of stream value names to the value.
- Raises:
KeyError – If any of the stream names is not a valid stream.
- clear_stream_values()#
Remove all stream values.
- property unit_values#
Get current unit values.
This returns a copy, that can be modified without changing the underlying values in the class.
- set_unit_value(unit_name: str, key: str, value)#
Set a value for a unit. This method has the same semantics as
set_stream_value()
.
- set_unit_values_map(unit_values_map: Dict[str, Dict[str, str]])#
Set multiple unit values using a mapping. This method has the same semantics as
set_stream_values_map()
.
- clear_unit_values()#
Remove all unit values.
Formatters#
All formatters have a write
method, defined in their base class, Formatter
.
The basic usage is:
Create the formatter, passing an instance of Model connectivity.
Call
formatter.write()
to generate the text.
Formatter base class#
- class idaes_connectivity.base.Formatter(connectivity: Connectivity, **kwargs)#
Base class for formatters, which write out the matrix in a way that can be more easily visualized or processed by other tools.
- abstract write(output_file: str | TextIO | None) str | None #
Write the formatted output.
- Parameters:
output_file – The output file. It can be a filename or file object. The special value None means return the text as a string.
- Returns:
If None was given as the output_file, return the text as a string. Otherwise, return None.
CSV formatter#
The CSV formatter writes out text as comma-separated values.
It ignores the direction
argument in the Formatter
base class constructor.
- class idaes_connectivity.base.CSV(connectivity: Connectivity, **kwargs)#
Write out the data as CSV.
- __init__(connectivity: Connectivity, **kwargs)#
- write(output_file: str | TextIO | None) str | None #
Write the formatted output.
- Parameters:
output_file – The output file. It can be a filename or file object. The special value None means return the text as a string.
- Returns:
If None was given as the output_file, return the text as a string. Otherwise, return None.
Mermaid formatter#
The Mermaid formatter writes out a Mermaid text description.
- class idaes_connectivity.base.Mermaid(connectivity: Connectivity, **kwargs)#
Create output in Mermaid syntax.
- __init__(connectivity: Connectivity, **kwargs)#
Constructor. See class defaults for default values.
- Parameters:
connectivity (Connectivity) – Model connectivity
kwargs (dict) – See Mermaid.defaults for keywords
- Raises:
ValueError – Invalid direction argument.
- write(output_file: str | TextIO | None) str | None #
Write Mermaid text description.
Jupyter#
Mermaid is supported by newer versions of Jupyter Notebooks and Jupyter Lab. The display_connectivity function allows one to easily display a diagram in a Jupyter notebook. This function is also shown in the Jupyter Notebook example.
- idaes_connectivity.jupyter.display_connectivity(conn: Connectivity = None, input_model=None, mermaid_options: Dict = None, jb=False) Markdown #
Display connectivity in a Jupyter Notebook using the built-in MermaidJS capabilities. Requires JupyterLab >= 4.1 or Jupyter Notebook >= 7.1.
- Parameters:
conn – Constructed Connectivity of a model
input_model – If present, create Connectivity instance from this model instead
mermaid_options – Keyword args for {py:class}`idaes_connectivity.base.Mermaid`
jb – Workaround for rendering in Jupyterbook
- Returns:
Markdown object, containing Mermaid graph, for Jupyter Notebook to render
This function
D2 formatter#
The D2 formatter writes out a D2 text description.
- class idaes_connectivity.base.D2(connectivity: Connectivity, **kwargs)#
Create output in Terraform D2 syntax.
- __init__(connectivity: Connectivity, **kwargs)#
Constructor.
- Parameters:
connectivity (Connectivity) – Model connectivity
kwargs (dict) – See D2.defaults for keywords
- Raises:
ValueError – Invalid direction.
- write(output_file: str | TextIO | None) str | None #
Write D2 text description.
Utility#
Utility functions.
Utility functions and classes.
- idaes_connectivity.util.get_stream_display_values(stream_table: DataFrame, value_map: Dict[str | Pattern, str | Tuple[str, str]]) Dict[str, Dict[str, str]] #
Select and format stream values in the stream_table.
- Parameters:
stream_table – A pandas.DataFrame with streams in the columns and values in the rows. The first column is the Units for the value. This is the default format returned by the IDAES flowsheet stream_table() method.
value_map –
Select and format values using this mapping from a stream value name (or regular expression that will match names) to a tuple with the units and format specifier. For example:
{ "temperature": ("K", ".3g"), re.compile("conc_mass_comp.*"): ("kg/m^3", ".4g") } If the units are None, the value from the "Units" column in the stream table is used. Also, giving a string instead of a tuple will set the units to None. A shorthand for a Pattern is to make the first character in the name of the value whatever `re_prefix_chr` is set to, by default a tilde ("~") character. Thus, the following is equivalent to the above:: {"temperature": ".3g", "~conc.mass.comp.*": ".4g"}
- Returns:
Mapping with keys being stream names and values being another mapping of stream value names to the formatted display value. For example:
{"stream1": { "temperature": "305.128 K", "conc_mass_comp HSO4": "2.71798 kg/m^3" }, "stream2": { "temperature": "305.128 K", "conc_mass_comp HSO4": "2.71798 kg/m^3" }, ... }
- Raises:
KeyError – Stream name given as a string is not found