.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/disciplines/data_converter.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_disciplines_data_converter.py: Use a data converter ==================== .. GENERATED FROM PYTHON SOURCE LINES 22-28 .. code-block:: Python from __future__ import annotations from gemseo.core.data_converters.json import JSONGrammarDataConverter from gemseo.core.grammars.json_grammar import JSONGrammar .. GENERATED FROM PYTHON SOURCE LINES 29-39 Why? ---- By default, the types of the coupling variables can be either numbers or 1D NumPy array. With custom data converters, one can add support to other types. For instance, to support 2D NumPy arrays, the following specialized data converter could be derived. .. GENERATED FROM PYTHON SOURCE LINES 39-61 .. code-block:: Python class DataConverter(JSONGrammarDataConverter): """A data converter where some coupling variables are 2D NumPy arrays.""" # The names of the coupling variables that are 2D NumPy arrays. NAMES_WITH_2D_ARRAY = ("a_coupling_variable_name", "another_coupling_variable_name") # The shape of the 2D NumPy arrays. SHAPE = (2, 2) def convert_value_to_array(self, name, value): if name in self.NAMES_WITH_2D_ARRAY: return value.flatten() return super().convert_value_to_array(name, value) def convert_array_to_value(self, name, array_): if name in self.NAMES_WITH_2D_ARRAY: return array_.reshape(self.SHAPE) return super().convert_array_to_value(name, array_) .. GENERATED FROM PYTHON SOURCE LINES 62-70 Use the converter ----------------- In order to be used, the custom data converter shall be set to the grammar class. The above custom data converter is defined for grammars of type JSONGrammar since it derives from JSONGrammarDataConverter. Declare the custom data converter with .. GENERATED FROM PYTHON SOURCE LINES 70-75 .. code-block:: Python JSONGrammar.DATA_CONVERTER_CLASS = DataConverter # This shall be done the earliest, # before any grammar is instantiated. .. _sphx_glr_download_examples_disciplines_data_converter.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: data_converter.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: data_converter.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: data_converter.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_