PK xSksٽ plot_analyticdiscipline.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Create a discipline from analytical expressions\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import division, unicode_literals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from numpy import array\n\nfrom gemseo.api import configure_logger, create_discipline\n\nconfigure_logger()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\nA simple :class:`.MDODiscipline` can be created\nusing analytic formulas, e.g. $y_1=2x^2$ and $y_2=5+3x^2z^3$,\nthanks to the :class:`.AnalyticDiscipline` class\nwhich is a quick alternative to model a simple analytic MDO problem.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the dictionary of analytic outputs\nFirst of all, we have to define the output expressions in a dictionary\nwhere keys are output names and values are formula with :code:`string`\nformat:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"expressions_dict = {\"y_1\": \"2*x**2\", \"y_2\": \"5+3*x**2+z**3\"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create the discipline\nThen, we create and instantiate the corresponding\n:class:`.AnalyticDiscipline`,\nwhich is a particular :class:`.MDODiscipline`.\nFor that, we use the API function :meth:`~gemseo.api.create_discipline` with:\n\n- :code:`discipline_name=\"AnalyticDiscipline\"`,\n- :code:`name=\"analytic\"`,\n- :code:`expressions_dict=expr_dict`.\n\nIn practice, we write:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"disc = create_discipline(\"AnalyticDiscipline\", expressions_dict=expressions_dict)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
Note
|g| takes care of the grammars and\n :meth:`!MDODiscipline._run` method generation\n from the :code:`expressions_dict` argument.\n In the background, |g| considers that :code:`x` is a monodimensional\n float input parameter and :code:`y_1` and :code:`y_2` are\n monodimensional float output parameters.
\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Execute the discipline\nLastly, we can execute this discipline any other:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"input_data = {\"x\": array([2.0]), \"z\": array([3.0])}\nout = disc.execute(input_data)\nprint((\"y_1 =\", out[\"y_1\"]))\nprint((\"y_2 =\", out[\"y_2\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## About the analytic jacobian\nThe discipline will provide analytic derivatives (Jacobian) automatically\nusing the `sympy library `_.\n\nThis can be checked easily using\n:meth:`.MDODiscipline.check_jacobian`:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"disc.check_jacobian(\n input_data, derr_approx=disc.FINITE_DIFFERENCES, step=1e-5, threshold=1e-3\n)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK xS:S6Ԣ plot_autopydiscipline.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Create a discipline from a Python function\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import division, unicode_literals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from numpy import array, empty\n\nfrom gemseo.api import configure_logger, create_discipline\n\nconfigure_logger()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Build a discipline from a simple Python function\nLet's consider a simple Python function, e.g.:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def f(x=0.0, y=0.0):\n \"\"\"A simple Python function.\"\"\"\n z = x + 2 * y\n return z"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Create and instantiate the discipline\nThen, we can consider the\n:class:`.AutoPyDiscipline` class\nto convert it into an :class:`.MDODiscipline`.\nFor that, we can use the :meth:`~gemseo.api.create_discipline` API function\nwith :code:`'AutoPyDiscipline'` as first argument:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"disc = create_discipline(\"AutoPyDiscipline\", py_func=f)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Execute the discipline\nThen, we can execute it easily, either considering default inputs:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(disc.execute())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or using new inputs:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(disc.execute({\"x\": array([1.0]), \"y\": array([-3.2])}))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Optional arguments\nThe optional arguments passed to the constructor are:\n\n- :code:`py_jac=None`: pointer to the jacobian function which must returned\n a 2D numpy array (see below),\n- :code:`use_arrays=False`: if :code:`True`, the function is expected to take\n arrays as inputs and give outputs as arrays,\n- :code:`write_schema=False`: if :code:`True`, write the json schema on the\n disk.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Define the jacobian function\nHere is an example of jacobian function:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def dfdxy(x=0.0, y=0.0):\n \"\"\"Jacobian function of f.\"\"\"\n jac = empty((2, 1))\n jac[0, 0] = 1\n jac[1, 0] = 2\n return jac"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"that we can execute with default inputs for example:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(dfdxy())"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK xS^u plot_interface_exec.ipynb{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Create a discipline from an external executable\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from __future__ import division, unicode_literals\n\nimport os\nimport subprocess\n\nfrom numpy import array\n\nfrom gemseo.api import configure_logger\nfrom gemseo.core.discipline import MDODiscipline\n\nconfigure_logger()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction\n\nLet's consider a binary software computing the float output\n$c = a^2 + b^2$ from two float inputs : :code:`'a'` and :code:`'b'`.\n\nThe inputs are read in the :code:`'inputs.txt'` file\nwhich looks like: `a=1 b=2` and\nthe output is written to: :code:`'outputs.txt'` which looks like `c=5`.\n\nThen, the executable can be run using the shell command :code:`'python run.py'`.\nLet's make a discipline out of this from an initial :code:`'inputs.txt'`.\n\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implementation of the discipline\n\nThe construction of :class:`.MDODiscipline` consists in three steps:\n\n1. Instantiate the :class:`.MDODiscipline` using the super constructor,\n2. Initialize the grammars using the\n :meth:`.JSONGrammar.initialize_from_data_names` method,\n3. Set the default inputs from the initial :code:`'inputs.txt'`\n\nThe :class:`!MDODiscipline._run` method consists in three steps:\n\n1. Get the input data from :attr:`!MDODiscipline.local_data` and write the\n :code:`'inputs.txt'` file,\n2. Run the executable using the :code:`subprocess.run()` command (`see more\n `_),\n3. Get the output values and store them to :attr:`!MDODiscipline.local_data`.\n\nNow you can implement the discipline in the following way:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def parse_file(file_path):\n data = {}\n with open(file_path) as inf:\n for line in inf.readlines():\n if len(line) == 0:\n continue\n name, value = line.replace(\"\\n\", \"\").split(\"=\")\n data[name] = array([float(value)])\n\n return data\n\n\ndef write_file(data, file_path):\n with open(file_path, \"w\") as outf:\n for name, value in list(data.items()):\n outf.write(name + \"=\" + str(value[0]) + \"\\n\")\n\n\nclass ShellExecutableDiscipline(MDODiscipline):\n def __init__(self):\n super(ShellExecutableDiscipline, self).__init__(\"ShellDisc\")\n self.input_grammar.initialize_from_data_names([\"a\", \"b\"])\n self.output_grammar.initialize_from_data_names([\"c\"])\n self.default_inputs = {\"a\": array([1.0]), \"b\": array([2.0])}\n\n def _run(self):\n cwd = os.getcwd()\n inputs_file = os.path.join(cwd, \"inputs.txt\")\n outputs_file = os.path.join(cwd, \"outputs.txt\")\n write_file(self.local_data, inputs_file)\n subprocess.run(\"python run.py\".split(), cwd=cwd)\n outputs = parse_file(outputs_file)\n self.local_data.update(outputs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Execution of the discipline\nNow we can run it with default input values:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"shell_disc = ShellExecutableDiscipline()\nprint(shell_disc.execute())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"or run it with new input values:\n\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"print(shell_disc.execute({\"a\": array([2.0]), \"b\": array([3.0])}))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
}
},
"nbformat": 4,
"nbformat_minor": 0
}PK xSksٽ plot_analyticdiscipline.ipynbPK xS:S6Ԣ plot_autopydiscipline.ipynbPK xS^u % plot_interface_exec.ipynbPK 9