.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/disciplines/grammars/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_disciplines_grammars_plot_pydantic_grammar.py: Use a pydantic grammar ====================== .. GENERATED FROM PYTHON SOURCE LINES 22-33 .. code-block:: Python from __future__ import annotations from numpy import array from pydantic import BaseModel from pydantic import Field from gemseo.core.grammars.errors import InvalidDataError from gemseo.core.grammars.pydantic_grammar import PydanticGrammar from gemseo.core.grammars.pydantic_ndarray import NDArrayPydantic .. GENERATED FROM PYTHON SOURCE LINES 34-48 Create the pydantic model ------------------------- The pydantic model is a class deriving from ``pydantic.BaseModel`` that describes the names and types of the 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``. By default, pydantic does not handle the typing of NumPy arrays. To support it, a special type shall be used, ``NDArrayPydantic``. Like the standard NumPy type for ``ndarray``, ``NDArray``, this type can be specialized with the dtype like ``NDArrayPydantic[int]``. .. GENERATED FROM PYTHON SOURCE LINES 48-69 .. code-block:: Python class Model(BaseModel): """The description of the model.""" a_int: int """The description of an integer.""" an_ndarray: NDArrayPydantic """The description of an ndarray.""" an_ndarray_of_int: NDArrayPydantic[int] """The description of an ndarray of integers.""" an_ndarray_with_default: NDArrayPydantic = Field(default_factory=lambda: array([0])) """The description of an ndarray with a default value.""" a_str_with_default: str = "default" """The description of a string with a default value.""" .. GENERATED FROM PYTHON SOURCE LINES 70-72 Create the grammar ------------------ .. GENERATED FROM PYTHON SOURCE LINES 72-74 .. code-block:: Python grammar = PydanticGrammar("grammar", model=Model) .. GENERATED FROM PYTHON SOURCE LINES 75-76 Show the contents of the grammar. .. GENERATED FROM PYTHON SOURCE LINES 76-78 .. code-block:: Python grammar .. raw:: html
Grammar name: grammar
  • Required elements:
    • a_int:
      • Type: <class 'int'>
    • an_ndarray:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[+_ScalarType_co]]
    • an_ndarray_of_int:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[int]]
  • Optional elements:
    • an_ndarray_with_default:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[+_ScalarType_co]]
      • Default: [0]
    • a_str_with_default:
      • Type: <class 'str'>
      • Default: default


.. GENERATED FROM PYTHON SOURCE LINES 79-81 Validate data against the grammar --------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 83-85 Validating missing data will raise an error shows the missing required elements, here the first 3 elements are missing. .. GENERATED FROM PYTHON SOURCE LINES 85-90 .. code-block:: Python 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 91-93 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 93-102 .. code-block:: Python 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 Input should be a valid integer [type=int_type, input_value=0.0, input_type=float] For further information visit https://errors.pydantic.dev/2.6/v/int_type an_ndarray_of_int Value error, Input dtype should be : got the dtype [type=value_error, input_value=array([1.]), input_type=ndarray] For further information visit https://errors.pydantic.dev/2.6/v/value_error .. GENERATED FROM PYTHON SOURCE LINES 103-104 Validating compliant data. .. GENERATED FROM PYTHON SOURCE LINES 104-110 .. code-block:: Python grammar.validate({ "a_int": 0, "an_ndarray": array([1]), "an_ndarray_of_int": array([1]), }) .. GENERATED FROM PYTHON SOURCE LINES 111-115 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 115-117 .. code-block:: Python 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 118-123 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 123-137 .. code-block:: Python class Model2(Model): """A model that inherits from a parent model.""" an_ndarray: NDArrayPydantic[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 138-139 Show the contents of the grammar. .. GENERATED FROM PYTHON SOURCE LINES 139-140 .. code-block:: Python grammar .. raw:: html
Grammar name: grammar
  • Required elements:
    • a_int:
      • Type: <class 'int'>
    • an_ndarray_of_int:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[int]]
  • Optional elements:
    • an_ndarray:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[float]]
      • Default: [1.]
    • an_ndarray_with_default:
      • Type: gemseo.core.grammars.pydantic_ndarray._NDArrayPydantic[typing.Any, numpy.dtype[+_ScalarType_co]]
      • Default: [0]
    • a_str_with_default:
      • Type: <class 'str'>
      • Default: default
    • a_bool:
      • Type: <class 'bool'>
      • Default: True


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