.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/discipline/plot_pydantic_grammar.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_discipline_plot_pydantic_grammar.py: Use a pydantic grammar ====================== .. GENERATED FROM PYTHON SOURCE LINES 22-33 .. code-block:: default from __future__ import annotations from gemseo.core.grammars.errors import InvalidDataError from gemseo.core.grammars.pydantic_grammar import PydanticGrammar from numpy import array from numpy import ndarray from numpy._typing import NDArray from pydantic import BaseModel from pydantic import Field .. GENERATED FROM PYTHON SOURCE LINES 34-42 Create the pydantic model ------------------------- The pydantic model is a class that describes the names and types of data to be validated. Descriptions are defined with docstrings, default values can be defined naturally. Mind that default values with a mutable object must be defined with the ``default_factory`` of a ``Field``. .. GENERATED FROM PYTHON SOURCE LINES 42-63 .. code-block:: default class Model(BaseModel): """The description of the model.""" a_int: int """The description of a_int.""" an_ndarray: ndarray """The description of an_ndarray.""" an_ndarray_of_int: NDArray[int] """The description of an_ndarray_of_int.""" an_ndarray_with_default: ndarray = Field(default_factory=lambda: array([0])) """The description of an_ndarray_with_default.""" a_str_with_default: str = "default" """The description of a_str.""" .. GENERATED FROM PYTHON SOURCE LINES 64-66 Create the grammar ------------------ .. GENERATED FROM PYTHON SOURCE LINES 66-68 .. code-block:: default grammar = PydanticGrammar("grammar", model=Model) .. GENERATED FROM PYTHON SOURCE LINES 69-70 Show the contents of the grammar. .. GENERATED FROM PYTHON SOURCE LINES 70-72 .. code-block:: default grammar .. raw:: html
Grammar name: grammar
  • Required elements:
    • a_int:
    • an_ndarray:
    • an_ndarray_of_int: numpy.ndarray[typing.Any, numpy.dtype[int]]
  • Optional elements:
    • an_ndarray_with_default:
      • default: [0]
    • a_str_with_default:
      • default: default


.. GENERATED FROM PYTHON SOURCE LINES 73-75 Validate data against the grammar --------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 77-79 Validating missing data will raise an error shows the missing required elements, here the first 3 elements are missing. .. GENERATED FROM PYTHON SOURCE LINES 79-84 .. code-block:: default try: grammar.validate({}) except InvalidDataError as error: print(error) .. rst-class:: sphx-glr-script-out .. code-block:: none Grammar grammar: validation failed. Missing required names: a_int, an_ndarray, an_ndarray_of_int. .. GENERATED FROM PYTHON SOURCE LINES 85-87 Validating data with bad type will raise an error shows the bad elements, here the first elements shall be an int and the third one shall be a ndarray of int. .. GENERATED FROM PYTHON SOURCE LINES 87-94 .. code-block:: default try: grammar.validate( {"a_int": 0.0, "an_ndarray": array([1]), "an_ndarray_of_int": array([1.0])} ) except InvalidDataError as error: print(error) .. rst-class:: sphx-glr-script-out .. code-block:: none Grammar grammar: validation failed. 2 validation errors for Model a_int value is not a valid integer (type=type_error.integer) an_ndarray_of_int value could not be parsed to a NumPy ndarray with dtype . (type=type_error.ndarray; dtype_info= with dtype ) .. GENERATED FROM PYTHON SOURCE LINES 95-96 Validating compliant data. .. GENERATED FROM PYTHON SOURCE LINES 96-100 .. code-block:: default grammar.validate( {"a_int": 0, "an_ndarray": array([1]), "an_ndarray_of_int": array([1])} ) .. GENERATED FROM PYTHON SOURCE LINES 101-105 Grammar defaults ---------------- As compared to the other types of grammars, the grammar defaults are be defined in the pydantic model and does not require to be manually defined from the grammar. .. GENERATED FROM PYTHON SOURCE LINES 105-107 .. code-block:: default grammar.defaults .. rst-class:: sphx-glr-script-out .. code-block:: none {'an_ndarray_with_default': array([0]), 'a_str_with_default': 'default'} .. GENERATED FROM PYTHON SOURCE LINES 108-113 Model inheritance ----------------- Since pydantic models are classes, one can easily build grammar via inheritance of the pydantic model. Here we change the type of one element, and we add a new one. .. GENERATED FROM PYTHON SOURCE LINES 113-127 .. code-block:: default class Model2(Model): """A model that inherits from a parent model.""" an_ndarray: NDArray[float] = Field(default_factory=lambda: array([1.0])) """The new description of an_ndarray.""" a_bool: bool = True """The description of a_bool.""" grammar = PydanticGrammar("grammar", model=Model2) .. GENERATED FROM PYTHON SOURCE LINES 128-129 Show the contents of the grammar. .. GENERATED FROM PYTHON SOURCE LINES 129-130 .. code-block:: default grammar .. raw:: html
Grammar name: grammar
  • Required elements:
    • a_int:
    • an_ndarray_of_int: numpy.ndarray[typing.Any, numpy.dtype[int]]
  • Optional elements:
    • an_ndarray: numpy.ndarray[typing.Any, numpy.dtype[float]]
      • default: [1.]
    • an_ndarray_with_default:
      • default: [0]
    • a_str_with_default:
      • default: default
    • a_bool:
      • default: True


.. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.010 seconds) .. _sphx_glr_download_examples_discipline_plot_pydantic_grammar.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_pydantic_grammar.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_pydantic_grammar.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_