diff --git a/.buildinfo b/.buildinfo index fcf662b91..4518e6934 100644 --- a/.buildinfo +++ b/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 9b2396149ba99a3b57333a4fc690fbee -tags: fbb0d17656682115ca4d033fb2f83ba1 +config: 78622614d38d5e86877da85b28af1606 +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/CNAME b/CNAME new file mode 100644 index 000000000..d7b3e6030 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +fuelcycle.org \ No newline at end of file diff --git a/_images/AnlLogo.png b/_images/AnlLogo.png new file mode 100755 index 000000000..4ff7e157c Binary files /dev/null and b/_images/AnlLogo.png differ diff --git a/_images/CVT-logo-250pix1.png b/_images/CVT-logo-250pix1.png new file mode 100755 index 000000000..60ebe8b7f Binary files /dev/null and b/_images/CVT-logo-250pix1.png differ diff --git a/_images/RIF_tutorial.png b/_images/RIF_tutorial.png new file mode 100755 index 000000000..f1c5db8a0 Binary files /dev/null and b/_images/RIF_tutorial.png differ diff --git a/_images/USNRC.png b/_images/USNRC.png new file mode 100755 index 000000000..2f4e870b9 Binary files /dev/null and b/_images/USNRC.png differ diff --git a/_images/antipode-bike.jpg b/_images/antipode-bike.jpg new file mode 100755 index 000000000..89bdc59de Binary files /dev/null and b/_images/antipode-bike.jpg differ diff --git a/_images/arche_ribbon.png b/_images/arche_ribbon.png new file mode 100755 index 000000000..7ab445e37 Binary files /dev/null and b/_images/arche_ribbon.png differ diff --git a/_images/bicyclelady.jpg b/_images/bicyclelady.jpg new file mode 100755 index 000000000..6f5857a48 Binary files /dev/null and b/_images/bicyclelady.jpg differ diff --git a/_images/cep-0001-1.png b/_images/cep-0001-1.png new file mode 100755 index 000000000..51eb2b258 Binary files /dev/null and b/_images/cep-0001-1.png differ diff --git a/_images/cep-0002-1.svg b/_images/cep-0002-1.svg new file mode 100755 index 000000000..ec0bdc41e --- /dev/null +++ b/_images/cep-0002-1.svg @@ -0,0 +1,42 @@ + + + + + + + + + blockdiag + + + + + + + + Dynamic Resource + Exchange Simulation + + Analysis & + Visualization + + Domain Models + + Simulation + Orchestration + + + + + + + + + + + + + + + + diff --git a/_images/cep-0002-2.svg b/_images/cep-0002-2.svg new file mode 100755 index 000000000..704bb2557 --- /dev/null +++ b/_images/cep-0002-2.svg @@ -0,0 +1,64 @@ + + + + + + + + + blockdiag + + + + + + + + + + + + + + + Cyclus + + Cycamore + + Cyder + + Bright-lite + + Cyborg + + CyclusJS + + Cycic + + Rickshaw + + + + + + + + + + + + + + + + + + + + + + Resource Exchange + Domain Models + Analysis & Visualization + Orchestration + diff --git a/_images/cep-0003-1.svg b/_images/cep-0003-1.svg new file mode 100755 index 000000000..616195926 --- /dev/null +++ b/_images/cep-0003-1.svg @@ -0,0 +1,112 @@ + + + + + + + + + + image/svg+xml + + + + + + + + topical + + v4.2-release + + master + + diff --git a/_images/cep-0018-2.svg b/_images/cep-0018-2.svg new file mode 100755 index 000000000..cd822323b --- /dev/null +++ b/_images/cep-0018-2.svg @@ -0,0 +1,40 @@ + + + + + + + + + blockdiag + + + + + + + + + + + Query Requesters + + Query Suppliers + + Requester Prefs + + Inst Prefs + + Region Prefs + + + + + + + + + RFB + RRFB + PA + diff --git a/_images/cep-0018-3.png b/_images/cep-0018-3.png new file mode 100755 index 000000000..978240aea Binary files /dev/null and b/_images/cep-0018-3.png differ diff --git a/_images/cep-0018-4.png b/_images/cep-0018-4.png new file mode 100755 index 000000000..6addc11ea Binary files /dev/null and b/_images/cep-0018-4.png differ diff --git a/_images/cep-0018-5.png b/_images/cep-0018-5.png new file mode 100755 index 000000000..38fc212e8 Binary files /dev/null and b/_images/cep-0018-5.png differ diff --git a/_images/cep-0026-1.png b/_images/cep-0026-1.png new file mode 100755 index 000000000..d0ebbef29 Binary files /dev/null and b/_images/cep-0026-1.png differ diff --git a/_images/core-team-2014-05-30.jpg b/_images/core-team-2014-05-30.jpg new file mode 100755 index 000000000..3017b2dc6 Binary files /dev/null and b/_images/core-team-2014-05-30.jpg differ diff --git a/_images/crest.png b/_images/crest.png new file mode 100755 index 000000000..3198d44df Binary files /dev/null and b/_images/crest.png differ diff --git a/_images/cumulative_iso_dist.png b/_images/cumulative_iso_dist.png new file mode 100755 index 000000000..5463af7be Binary files /dev/null and b/_images/cumulative_iso_dist.png differ diff --git a/_images/cyclist_tour_annotated.png b/_images/cyclist_tour_annotated.png new file mode 100755 index 000000000..ec02cd5de Binary files /dev/null and b/_images/cyclist_tour_annotated.png differ diff --git a/_images/cyclus_in_IP.png b/_images/cyclus_in_IP.png new file mode 100755 index 000000000..822bfe18f Binary files /dev/null and b/_images/cyclus_in_IP.png differ diff --git a/_images/cycrun.png b/_images/cycrun.png new file mode 100755 index 000000000..87934d1d0 Binary files /dev/null and b/_images/cycrun.png differ diff --git a/_images/cycrun_final.png b/_images/cycrun_final.png new file mode 100755 index 000000000..14a3c31f1 Binary files /dev/null and b/_images/cycrun_final.png differ diff --git a/_images/data-explore-annotated.png b/_images/data-explore-annotated.png new file mode 100755 index 000000000..e874b27a2 Binary files /dev/null and b/_images/data-explore-annotated.png differ diff --git a/_images/disc_arche.png b/_images/disc_arche.png new file mode 100755 index 000000000..7212bdb09 Binary files /dev/null and b/_images/disc_arche.png differ diff --git a/_images/dre-1.svg b/_images/dre-1.svg new file mode 100755 index 000000000..8127cb3d6 --- /dev/null +++ b/_images/dre-1.svg @@ -0,0 +1,26 @@ + + + + + + + + + blockdiag + + + + + + + + Region + + Institution + + Facility (Trader) + + + + + diff --git a/_images/enrich-commods.png b/_images/enrich-commods.png new file mode 100755 index 000000000..6a169c1fd Binary files /dev/null and b/_images/enrich-commods.png differ diff --git a/_images/enrich-max-inv-annotated.png b/_images/enrich-max-inv-annotated.png new file mode 100755 index 000000000..d251a4b7b Binary files /dev/null and b/_images/enrich-max-inv-annotated.png differ diff --git a/_images/first_proto.png b/_images/first_proto.png new file mode 100755 index 000000000..2317a7990 Binary files /dev/null and b/_images/first_proto.png differ diff --git a/_images/flow-01-01.png b/_images/flow-01-01.png new file mode 100755 index 000000000..71bf65ea9 Binary files /dev/null and b/_images/flow-01-01.png differ diff --git a/_images/flow-01-02.png b/_images/flow-01-02.png new file mode 100755 index 000000000..f52499d37 Binary files /dev/null and b/_images/flow-01-02.png differ diff --git a/_images/flow-01-03.png b/_images/flow-01-03.png new file mode 100755 index 000000000..22d831101 Binary files /dev/null and b/_images/flow-01-03.png differ diff --git a/_images/flow-01-04-annotated.png b/_images/flow-01-04-annotated.png new file mode 100755 index 000000000..c484777ad Binary files /dev/null and b/_images/flow-01-04-annotated.png differ diff --git a/_images/flow-01-05.png b/_images/flow-01-05.png new file mode 100755 index 000000000..b313f5fa8 Binary files /dev/null and b/_images/flow-01-05.png differ diff --git a/_images/flying_gears.jpg b/_images/flying_gears.jpg new file mode 100755 index 000000000..182a8db52 Binary files /dev/null and b/_images/flying_gears.jpg differ diff --git a/_images/fuel_com.png b/_images/fuel_com.png new file mode 100755 index 000000000..164e3c0de Binary files /dev/null and b/_images/fuel_com.png differ diff --git a/_images/inst-add-mine.png b/_images/inst-add-mine.png new file mode 100755 index 000000000..6a921029e Binary files /dev/null and b/_images/inst-add-mine.png differ diff --git a/_images/inst-all-added.png b/_images/inst-all-added.png new file mode 100755 index 000000000..3649bc5ea Binary files /dev/null and b/_images/inst-all-added.png differ diff --git a/_images/inst-corral-annotated.png b/_images/inst-corral-annotated.png new file mode 100755 index 000000000..fbfb21fbd Binary files /dev/null and b/_images/inst-corral-annotated.png differ diff --git a/_images/ipython_tour.png b/_images/ipython_tour.png new file mode 100755 index 000000000..35a15669c Binary files /dev/null and b/_images/ipython_tour.png differ diff --git a/_images/logo2_bike.gif b/_images/logo2_bike.gif new file mode 100755 index 000000000..7d6d0fc63 Binary files /dev/null and b/_images/logo2_bike.gif differ diff --git a/_images/logo2_bike1.gif b/_images/logo2_bike1.gif new file mode 100644 index 000000000..7d6d0fc63 Binary files /dev/null and b/_images/logo2_bike1.gif differ diff --git a/_images/main_view_annotated.png b/_images/main_view_annotated.png new file mode 100755 index 000000000..fff1452cf Binary files /dev/null and b/_images/main_view_annotated.png differ diff --git a/_images/mine_commod.png b/_images/mine_commod.png new file mode 100755 index 000000000..0c00db02f Binary files /dev/null and b/_images/mine_commod.png differ diff --git a/_images/neup_logo_large.png b/_images/neup_logo_large.png new file mode 100755 index 000000000..1549ca321 Binary files /dev/null and b/_images/neup_logo_large.png differ diff --git a/_images/nnsa.png b/_images/nnsa.png new file mode 100755 index 000000000..9098d9c50 Binary files /dev/null and b/_images/nnsa.png differ diff --git a/_images/nsf_logo.png b/_images/nsf_logo.png new file mode 100755 index 000000000..5a9e52c90 Binary files /dev/null and b/_images/nsf_logo.png differ diff --git a/_images/pennyfarthing-jack.jpg b/_images/pennyfarthing-jack.jpg new file mode 100755 index 000000000..0c89eac1f Binary files /dev/null and b/_images/pennyfarthing-jack.jpg differ diff --git a/_images/plot-01-01.png b/_images/plot-01-01.png new file mode 100755 index 000000000..a43b62213 Binary files /dev/null and b/_images/plot-01-01.png differ diff --git a/_images/plot-01-02.png b/_images/plot-01-02.png new file mode 100755 index 000000000..a28e7db04 Binary files /dev/null and b/_images/plot-01-02.png differ diff --git a/_images/plot-01-03.png b/_images/plot-01-03.png new file mode 100755 index 000000000..f2fa06b6c Binary files /dev/null and b/_images/plot-01-03.png differ diff --git a/_images/plot-01-04.png b/_images/plot-01-04.png new file mode 100755 index 000000000..9d55a984f Binary files /dev/null and b/_images/plot-01-04.png differ diff --git a/_images/plot-01-05-annotated.png b/_images/plot-01-05-annotated.png new file mode 100755 index 000000000..f66121573 Binary files /dev/null and b/_images/plot-01-05-annotated.png differ diff --git a/_images/plot-01-06.png b/_images/plot-01-06.png new file mode 100755 index 000000000..28d2ae2f8 Binary files /dev/null and b/_images/plot-01-06.png differ diff --git a/_images/plot-01-07.png b/_images/plot-01-07.png new file mode 100755 index 000000000..e7e543d49 Binary files /dev/null and b/_images/plot-01-07.png differ diff --git a/_images/plot-01-08.png b/_images/plot-01-08.png new file mode 100755 index 000000000..8518eb736 Binary files /dev/null and b/_images/plot-01-08.png differ diff --git a/_images/recipe-builder-drag.png b/_images/recipe-builder-drag.png new file mode 100755 index 000000000..cf949c649 Binary files /dev/null and b/_images/recipe-builder-drag.png differ diff --git a/_images/recipe-natU-235-only.png b/_images/recipe-natU-235-only.png new file mode 100755 index 000000000..e6566d8b2 Binary files /dev/null and b/_images/recipe-natU-235-only.png differ diff --git a/_images/recipe-natU-finished-assigned.png b/_images/recipe-natU-finished-assigned.png new file mode 100755 index 000000000..76d2c328d Binary files /dev/null and b/_images/recipe-natU-finished-assigned.png differ diff --git a/_images/region-complete.png b/_images/region-complete.png new file mode 100755 index 000000000..95f1dbed9 Binary files /dev/null and b/_images/region-complete.png differ diff --git a/_images/region-corral-annotated.png b/_images/region-corral-annotated.png new file mode 100755 index 000000000..e50073507 Binary files /dev/null and b/_images/region-corral-annotated.png differ diff --git a/_images/repo-complete.png b/_images/repo-complete.png new file mode 100755 index 000000000..6fb7e8a4a Binary files /dev/null and b/_images/repo-complete.png differ diff --git a/_images/running-job-annotated.png b/_images/running-job-annotated.png new file mode 100755 index 000000000..1445274c7 Binary files /dev/null and b/_images/running-job-annotated.png differ diff --git a/_images/rxtr-complete.png b/_images/rxtr-complete.png new file mode 100755 index 000000000..9afe96625 Binary files /dev/null and b/_images/rxtr-complete.png differ diff --git a/_images/sim_detail.png b/_images/sim_detail.png new file mode 100755 index 000000000..63885475f Binary files /dev/null and b/_images/sim_detail.png differ diff --git a/_images/simple_cycle.svg b/_images/simple_cycle.svg new file mode 100755 index 000000000..2fa484125 --- /dev/null +++ b/_images/simple_cycle.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_images/sp_sketch.jpg b/_images/sp_sketch.jpg new file mode 100755 index 000000000..ba854f61f Binary files /dev/null and b/_images/sp_sketch.jpg differ diff --git a/_images/storage_capacity.svg b/_images/storage_capacity.svg new file mode 100755 index 000000000..de8f7ecc2 --- /dev/null +++ b/_images/storage_capacity.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_images/storage_capacity1.svg b/_images/storage_capacity1.svg new file mode 100755 index 000000000..de8f7ecc2 --- /dev/null +++ b/_images/storage_capacity1.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_images/storage_diagram.svg b/_images/storage_diagram.svg new file mode 100755 index 000000000..0fca5efc8 --- /dev/null +++ b/_images/storage_diagram.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_images/storage_diagram1.svg b/_images/storage_diagram1.svg new file mode 100755 index 000000000..0fca5efc8 --- /dev/null +++ b/_images/storage_diagram1.svg @@ -0,0 +1,4 @@ + + + + diff --git a/_images/timeseries-01.png b/_images/timeseries-01.png new file mode 100755 index 000000000..6c349faf2 Binary files /dev/null and b/_images/timeseries-01.png differ diff --git a/_images/timeseries-02.png b/_images/timeseries-02.png new file mode 100755 index 000000000..b57fe6e16 Binary files /dev/null and b/_images/timeseries-02.png differ diff --git a/_images/timeseries-03.png b/_images/timeseries-03.png new file mode 100755 index 000000000..5541bc005 Binary files /dev/null and b/_images/timeseries-03.png differ diff --git a/_images/timeseries-04-annotated.png b/_images/timeseries-04-annotated.png new file mode 100755 index 000000000..dbab66934 Binary files /dev/null and b/_images/timeseries-04-annotated.png differ diff --git a/_images/trade.png b/_images/trade.png new file mode 100755 index 000000000..9144ae130 Binary files /dev/null and b/_images/trade.png differ diff --git a/_images/tut_nucid_mass.png b/_images/tut_nucid_mass.png new file mode 100755 index 000000000..e096e450b Binary files /dev/null and b/_images/tut_nucid_mass.png differ diff --git a/_images/u-ore-enrich.png b/_images/u-ore-enrich.png new file mode 100755 index 000000000..adf279ab2 Binary files /dev/null and b/_images/u-ore-enrich.png differ diff --git a/_images/user-level-1-power-annotated.png b/_images/user-level-1-power-annotated.png new file mode 100755 index 000000000..3572f98b7 Binary files /dev/null and b/_images/user-level-1-power-annotated.png differ diff --git a/_images/user-level-1.png b/_images/user-level-1.png new file mode 100755 index 000000000..b2704a5de Binary files /dev/null and b/_images/user-level-1.png differ diff --git a/_sources/arche/cli.rst.txt b/_sources/arche/cli.rst.txt new file mode 100755 index 000000000..c7edb670b --- /dev/null +++ b/_sources/arche/cli.rst.txt @@ -0,0 +1,100 @@ +.. _cli: + +Archetype Command Line Interface +======================================= +There are a few archetype-specific |Cyclus| CLI commands that allow +introspecting details of archetypes that |Cyclus| can find. Most expose data +that is automatically generated by the Cyclus preprocessor. For example, +member variables added with ``#pragma cyclus var`` are added to the generated +input XML schema. Agents are referenced on the command line by their +single-string form ``spec`` (e.g. ``:cycamore:Source``) which is discussed +:ref:`here `. + +To view the auto-generated XML schema used for validating archetype +configuration parameters in input files: + + .. code-block:: bash + + $ cyclus --agent-schema :agents:Source + + + + + + + + + + + + + + +To view a JSON structured output of all the data generated and collected from +``#pragma cyclus`` annotations for a particular archetype: + + .. code-block:: bash + + $ cyclus --agent-annotations :cycamore:Source + { + "all_parents": [ + "cyclus::Agent", + "cyclus::Facility", + "cyclus::Ider", + "cyclus::StateWrangler", + "cyclus::TimeListener", + "cyclus::Trader", + "cyclus::toolkit::AgentManaged", + "cyclus::toolkit::CommodityProducer" + ], + "doc": "This facility acts as a source of material with a fixed... + ... + +And to list all archetypes inside a particular library: + + .. code-block:: bash + + $ cyclus --agent-listing :cycamore + :cycamore:DeployInst + :cycamore:Enrichment + :cycamore:FuelFab + :cycamore:GrowthRegion + :cycamore:ManagerInst + :cycamore:Reactor + :cycamore:Separations + :cycamore:Sink + :cycamore:Source + :cycamore:Storage + +Archetype Versioning +-------------------- +The ``cyclus::Agent`` class exposes a ``version()`` member function which can be +queried with the |Cyclus| CLI. For example, + +.. code-block:: bash + + $ cyclus --agent-version :agents:Source + 1.3.1-7-g9a2c9c9 + +This is generated from some ``git`` version control information. You can make +your own version tag information for some archetype like + +**C++:** + +.. code-block:: c++ + + virtual std::string version() { return "My Version"; } + +**Python:** + +.. code-block:: Python + + def version(self): + return "My Version" + +and then access the version with + +.. code-block:: bash + + $ cyclus --agent-version my/path:my_library:MyArchetype + My Version diff --git a/_sources/arche/cmake.rst.txt b/_sources/arche/cmake.rst.txt new file mode 100755 index 000000000..430e96393 --- /dev/null +++ b/_sources/arche/cmake.rst.txt @@ -0,0 +1,151 @@ +.. _cmake_build: + +Building Modules with CMake +=========================== + +If you haven't follow the initial example in :ref:`hello_world_cpp`, you should get +the `Cycstub repo `_ by either `cloning the +repository `_ or by `downloading the zip +file `_ (see +:ref:`hello_world_cpp` for further instructions). + +The Cycstub repo provides a number of critical tools for building your own +module: + +* ``install.py``: a basic installation script + +* ``cmake``: a directory of `CMake `_ modules + (e.g. finding |Cyclus| and its dependencies on your system) + +* ``cmake/UseCyclus.cmake``: a CMake module that defines important |Cyclus| + module build/install macros + +* ``CMakeLists.txt``: a generic CMake driver that will work for most build + configurations out of the box + +* ``src/CMakeLists.txt``: a starter file that determines how the module build is + executed (utilizing the macros in ``UseCyclus.cmake``) + +The remaining portion of this page covers the various features provided in +``UseCyclus.cmake`` and their use in the ``src`` directory's ``CMakeLists.txt`` +file. + +Using UseCyclus +--------------- + +``UseCyclus.cmake`` defines the following macros for building and installing +|Cyclus| modules: + +* ``USE_CYCLUS``: informs the build system of the source files related to an + :term:`archetype` implementation and its tests, if tests exist + +* ``INSTALL_CYCLUS_MODULE``: install a collection of :term:`archetypes + ` that all belong to the same :term:`module` + +* ``INSTALL_CYCLUS_STANDALONE``: install an :term:`archetype` as a standalone + module + +UseCyclus Vocabulary +++++++++++++++++++++ + +The ``UseCyclus.cmake`` macro suite uses the following terms: + +* ``lib_root``: The root name for the to-be-installed library (e.g., ``MyAgent`` + for a standalone install or ``my_module`` for a module install). + +* ``src_root``: The common prefix for all source files required to implement and + test an :term:`archetypes `. For example if your ``src_root`` is + ``my_agent``, the macro suite will be aware of the following files: + + * ``my_agent.cc`` + * ``my_agent.h`` + * ``my_agent_tests.cc`` + * ``my_agent_tests.h`` + +* ``lib_dir``: The install directory relative the |Cyclus| library installation + directory. For example, if ``lib_dir`` is blank (i.e. ""), the module will be + installed in ``$CYCLUS_INSTALL_PREFIX/lib/cyclus/``; if ``lib_dir`` is + something else, e.g. ``my_module_dir``, the module will be installed in + ``$CYCLUS_INSTALL_PREFIX/lib/cyclus/my_module_dir/``. The value of + ``$CYCLUS_INSTALL_PREFIX`` can be queried by + + .. code-block:: bash + + $ cyclus --install-path + +* ``test_driver``: (optional) A custom `GTest + `_ test driver. This is an advanced + feature which will not be needed by most archetype developers. + +UseCyclus Macro Arguments ++++++++++++++++++++++++++ + +Each ``UseCyclus.cmake`` macro has arguments included in the above vocabulary +listing: + +* ``USE_CYCLUS``:: + + USE_CYCLUS(lib_root src_root) + +* ``INSTALL_CYCLUS_STANDALONE``:: + + INSTALL_CYCLUS_STANDALONE(lib_root src_root lib_dir [test_driver]) + +* ``INSTALL_CYCLUS_MODULE``:: + + INSTALL_CYCLUS_MODULE(lib_root lib_dir [test_driver]) + +Examples +-------- + +Standalone Installation ++++++++++++++++++++++++ + +Through the :ref:`hello_world` example, three standalone modules are installed +using a ``src/CMakeLists.txt`` file that looks something like + +.. literalinclude:: standalone-cmake + +This setup will install three shared object libraries in +``$CYCLUS_INSTALL_PREFIX/lib/cyclus/tutorial``: + +* ``libTutorialFacility.so`` (\*nix) or ``libTutorialFacility.dylib`` (mac) + +* ``libTutorialInstitution.so`` (\*nix) ``libTutorialInstitution.dylib`` (mac) + +* ``libTutorialRegion.so`` (\*nix) ``libTutorialRegion.dylib`` (mac) + +and three unit test executables in ``$CYCLUS_INSTALL_PREFIX/bin``: + +* ``TutorialFacility_unit_tests`` + +* ``TutorialInstitution_unit_tests`` + +* ``TutorialRegion_unit_tests`` + +Module Installation ++++++++++++++++++++ + +A valid criticism of the hello world standalone approach is that a lot of +libraries and executables are generated for three modules that are grouped +together. We can do better! + +What if we wanted to install one module named ``helloworld``? Specifically, we +would want: + +* a single shared object library in ``$CYCLUS_INSTALL_PREFIX/lib/cyclus/tutorial`` + named ``libhelloworld.so`` (\*nix) or ``libhelloworld.dylib`` (mac) + +* a single unit test executable in ``$CYCLUS_INSTALL_PREFIX/bin`` named + ``helloworld_unit_tests`` + +where both incorporate the ``TutorialFacility``, ``TutorialInstitution``, and +``TutorialRegion`` :term:`archetypes `. + +Such behavior is pretty simple to achieve. We first must call ``UseCyclus`` on +each of our source file roots to inform the build system of their presence and +follow up with a call to ``INSTALL_CYCLUS_MODULE``: + +.. literalinclude:: module-cmake + + diff --git a/_sources/arche/custom_tables.rst.txt b/_sources/arche/custom_tables.rst.txt new file mode 100755 index 000000000..473530b69 --- /dev/null +++ b/_sources/arche/custom_tables.rst.txt @@ -0,0 +1,181 @@ +Custom Database Tables +======================= + +Agents are allowed to write their own custom output into the database during +simulations. The interface for recording this data is accessible through the +agent's :term:`context`. Data may be logged via the Context::NewDatum function: + +**C++:** + +.. code-block:: c++ + + MyReactor::Tick() { + ... + double monthly_water = ...; + double monthly_op_cost = ...; + + context()->NewDatum("MyReactorData") + ->AddVal("AgentID", id()) + ->AddVal("Time", context()->time()) + ->AddVal("WaterUsage", monthl_water) + ->AddVal("OperatingCost", monthly_op_cost) + ->Record(); + ... + } + +**Python:** + +.. code-block:: python + + from cyclus.agents import Facility + import cyclus.typesystem as ts + + class MyReactor(Facility): + + def tick(self): + ... + d = self.context.new_datum("MyReactorData") + d.add_val("AgentID", self.id, type=ts.INT) + d.add_val("Time", self.context.time, type=ts.INT) + d.add_val("WaterUsage", self.monthl_water, type=ts.DOUBLE) + d.add_val("OperatingCost", self.monthly_op_cost, type=ts.DOUBLE) + d.record() + ... + +This would create a table in the output database named "MyReactorData". The +table would get a new row entry every time step with four columns named +"AgentID", "Time", "WaterUsage" and "OperatingCost". "Add value" calls can be chained +any number of times for an arbitrary number of columns. Record must be +called once for each datum after all values have been added. Any custom +tables created in this manner will appear in the output database alongside the +|cyclus| core tables. Because there may be several agent instances of a +single agent class, tables should generally include a column that adds their +ID; and for similar reasons, it is often desirable to include the simulation +time as a column in these tables: + +**C++:** + +.. code-block:: c++ + + context()->NewDatum("MyReactorData") + ->AddVal("AgentID", id()) + ->AddVal("Time", context()->time()) + ->AddVal(... + ... + +**Python:** + +.. code-block:: python + + d = self.context.new_datum("MyReactorData") + d.add_val("AgentID", self.id, type=ts.INT) + d.add_val("Time", self.context.time, type=ts.INT) + d.add_val(... + ... + +Datums with the same table name must have the same schema (e.g. same field +names and value types). It is the responsibility of the developer to +enforce this in their code. + + +.. warning:: + + Database formats only support a finite number of datum value-types. Do not + add values to database tables that are not supported by the backend(s) in + use. For information on which c++ types the backends support, you can check + :doc:`here `. + +.. note:: If you require a datatype that isn't currently supported, please + ask the kernel developers and they will help as soon as possible. + +Table Data Shapes +------------------ + +All added values can optionally take a `std::vector*` shape argument that +is used as maximum dimensions for the value being added. The :doc:`dbtypes` +page lists the rank of the shape of different C++ types. A +``std::vector`` has rank two - the first shape element being the +length of the vector, the second element being the length of each string in +the vector. When the shape argument is ommitted, the default is to treat all +elements in the value as variable-length. An entry of `-1` in the shape +vector indicates variable length also. It is an error to pass in a shape +vector with the wrong rank (number of elements) for that type. An example of +using the shape vector follows: + +**C++:** + +.. code-block:: c++ + + std::vector colors; + colors.push_back("green"); + colors.push_back("blue"); + colors.push_back("chartreuse"); + + std::vector shape; // this should usually be a class member variable + shape->push_back(5); // maximum number of elements in the color vector + shape->push_back(8); // maximum character length of each color + + context()->NewDatum("DecorPreferences") + ->AddVal("AgentID", id()) + ->AddVal("Time", context()->time()) + ->AddVal("FavoriteColors", colors, shape) + ->Record(); + +**Python:** + +.. code-block:: c++ + + colors = ["green", "blue", "chartreuse"] + shape = [5, 8] + d = self.context.new_datum("DecorPreferences") + d.add_val("AgentID", self.id, type=ts.INT) + d.add_val("Time", self.context.time, type=ts.INT) + d.add_val("FavoriteColors", colors, shape, ts.VECTOR_STRING) + d.record() + +In the example above, the "chartreuse" color is longer than the 8 characters +specified in the shape. So it will be truncated to "chartreu" in the +database. Shape vectors should generally be stored as class member variables +to avoid excessive memory [de]allocation and should be set correctly from +construction to destruction of your agent. + +Reserved Table Names +--------------------- + +The |cyclus| kernel creates several of its own tables. The names of these +tables are reserved, and you are responsible to avoid using them for custom +table names. The reserved table names are (all case combos upper and lower): + +* all names starting with the prefixes: + + * Cyclus + * Agent + * VL\ _ + * Pair + * String + * Vector + * Map + * List + * Set + * Blob + +* Resources +* Products +* Transactions +* Info +* Finish +* InputFiles +* Prototypes +* Recipes +* Snapshots +* MaterialInfo +* Compositions +* NextIds +* ResCreators +* CommodPriority + +.. warning:: + + Table names may only contain alphanumeric characters and underscores and + must not start with a number. + diff --git a/_sources/arche/cycpp.rst.txt b/_sources/arche/cycpp.rst.txt new file mode 100755 index 000000000..2d65ec888 --- /dev/null +++ b/_sources/arche/cycpp.rst.txt @@ -0,0 +1,709 @@ +.. _cycpp: + +Using the Cyclus Preprocessor +================================== + +.. |cycpp| replace:: ``cycpp`` + +.. raw:: html + + + +
+ +A key part of the |Cyclus| agent and module development infrastructure is +a |Cyclus|-aware C++ preprocessor called |cycpp|. This preprocessor +inspects the agents that you write and then - based on the directives you +have given it - generates code that conforms to the |cyclus| agent API. +This allows you to focus on coding up the desired agent behavior rather +than worrying about the tedious and error-prone process of making your +agents conform to the |Cyclus| kernel. + +Before we continue there are a couple of noteworthy points about |cycpp|: + +* Even when using the preprocessor, agents are still completely valid C++ + and may be compiled without running |cycpp| - though they probably + won't do the correct thing in a simulation. +* If your module is compiled with the CMake macros found in UseCyclus, + |cycpp| is run automatically for you on all relevant files. + +Without further ado, let's dive in! + +.. raw:: html + + + +.. image:: ../astatic/pennyfarthing-jack.jpg + :align: center + :width: 300px + +.. raw:: html + +
+ +Pragma |Cyclus| +----------------- +The preprocessor functions by defining a suite of |cyclus|-directives that +|cycpp| picks up (but that plain old ``cpp`` ignores). These all start +with the prefix ``#pragma cyclus`` and fall into one of two broad categories: + +1. **Annotation directives** and +2. **Code generation directives**. + +The annotation directives allow you specify information and metadata +(documentation, default values, maximum shape sizes, etc.) about your agents. +The code generation directives replace themselves with C++ code inside of the +agents based on the annotations provided. *The use of these directives is +entirely optional.* However, in their absence you must implement the +corresponding agent API yourself. + +.. _pragma-cyclus-var: + +Annotation Directives +----------------------- + +|Cyclus| agents are based on the notion of **state variables**. These are +member variables of your agents whose values (should) fully determine the +state of the your agent at any time step. State variables are important +because they are what is written to and read from the database, they may be +specified in the input file and have an associated schema, and they define the +public interface for the agent. + +Thus, the most important annotation directive is the **state variable +directive**. This must be written within the agent's class declaration and +applies to the next member variable declaration that it sees. This directive +not only defines the annotations for a variable, but also declares it as being +a state variable. It has the following signature: + +**State variable annotation signature:** + +.. code-block:: c++ + + #pragma cyclus var + +Here, the ```` argument must evaluate to a Python dictionary (or other mapping). +For example, + +**State variable annotation example:** + +.. code-block:: c++ + + #pragma cyclus var {"default": 42.0, "units": "n/cm2/s"} + double flux; + +These two lines declare that the member variable ``flux`` is in fact a state +variable of type double with the given metadata. The keys of this dictionary +may be anything you desire. Though because they are eventually persisted to +JSON the keys must be strings. Certain keys have special semantic +meaning. Furthermore, there are two keys - ``type`` and ``index`` - that are set by +|cycpp| itself and should not be specified explicitly. State variables may have any +C++ type that is allowed by the database backend that is being used. For a listing of +valid types please refer to the :doc:`dbtypes` page. :ref:`cycpp-table-1` +contains a listing of all special keys and their meanings. + +.. rst-class:: centered + +.. _cycpp-table-1: + +.. table:: **Table I.** Special State Variable Annotations + :widths: 1 9 + :column-alignment: left left + :column-wrapping: true true + :column-dividers: none single none + + ============ ============================================================== + key meaning + ============ ============================================================== + type The C++ type. Valid types may be found on the :doc:`dbtypes` + page. **READ ONLY:** Do not set this key in + ``#pragma cyclus var {...}`` as it is set automatically by + cycpp. Feel free to use this downstream in your class or in a + post-process. + index Which number state variable is this, 0-indexed. + **READ ONLY:** Do not set this key in + ``#pragma cyclus var {...}`` as it is set automatically by + cycpp. Feel free to use this downstream in your class or in a + post-process. + default The default value for this variable that is used if otherwise + unspecified. The value must match the type of the variable. + internal ``True`` if this state variable is only for + archetype-internal usage. Although the variable will still + be persisted in the database and initialized normally (e.g. + with any default), it will not be included in the XML schema + or input file. + shape The shape of a variable length datatypes. If present this must + be a list of integers whose length (rank) makes sense for this + type. Specifying positive values will (depending on the + backend) turn a variable length type into a fixed length one + with the length of the given value. Putting a ``-1`` in the + shape will retain the variable length nature along that axis. + Fixed length variables are normally more performant so it is + often a good idea to specify the shape where possible. For + example, a length-5 string would have a shape of ``[5]`` and + a length-10 vector of variable length strings would have a + shape of ``[10, -1]``. + doc Documentation string. + tooltip Brief documentation string for user interfaces. + units The physical units, if any. + userlevel Integer from 0 - 10 for representing ease (0) or difficulty (10) + in using this variable, default 0. + alias The name of the state variable in the schema and input file. + If this is not present it defaults to the C++ variable name. + The alias may also be a nested list of strings that matches + the C++ template type. Each member of the hierarchy will + recieve the corresponding alias. For example, a + ``[std::map, int, double]`` could be aliased by + ``['recipe', 'id', 'mass']``. For maps, an additional item + tag is inserted. To also alias the item tag, make the top + alias into a 2-element list, whose first string represents + the map and whose second string is the item alias, e.g. + ``[['recipe', 'entry'], 'id', 'mass']`` + uilabel The text string a UI will display as the name of this input on + the UI input form. + uitype The type of the input field in reference in a UI, + currently supported types are; incommodity, outcommodity, + commodity, range, combobox, facility, prototype, recipe, nuclide, + and none. + For 'nuclide' when the type is an int, the values will be read in + from the input file in human readable string format ('U-235') and + automatically converted to results of ``pyne::nucname::id()`` + (922350000) in the database and on the archetype. + range This indicates the range associated with a range type. + It must take the form of ``[min, max]`` or + ``[min, max, (optional) step size]``. + categorical This indicates the decrete values a combobox Type can take. It + must take the form of ``[value1, value2, value3, etc]``. + schematype This is the data type that is used in the schema for input file + validation. This enables you to supply just the data type + rather than having to overwrite the full schema for this state + variable. In most cases - when the shape is rank 0 or 1 such + as for scalars or vectors - this is simply a string. In cases + where the rank is 2+ this is a list of strings. Please refer to + the `XML Schema Datatypes `_ + page for more information. *New in v1.1.* + initfromcopy Code snippet to use in the ``InitFrom(Agent* m)`` function for + this state variable instead of using code generation. + This is a string. + initfromdb Code snippet to use in the ``InitFrom(QueryableBackend* b)`` + function for this state variable instead of using code generation. + This is a string. + infiletodb Code snippets to use in the ``InfileToDb()`` function + for this state variable instead of using code generation. + This is a dictionary of string values with the two keys 'read' + and 'write' which represent reading values from the input file + writing them out to the database respectively. + schema Code snippet to use in the ``schema()`` function for + this state variable instead of using code generation. + This is an RNG string. If you supply this then you likely need + to supply ``infiletodb`` as well to ensure that your custom + schema is read into the database correctly. + snapshot Code snippet to use in the ``Snapshot()`` function for + this state variable instead of using code generation. + This is a string. + snapshotinv Code snippet to use in the ``SnapshotInv()`` function for + this state variable instead of using code generation. + This is a string. + initinv Code snippet to use in the ``InitInv()`` function for + this state variable instead of using code generation. + This is a string. + ============ ============================================================== + +.. raw:: html + +
+ +-------------- + +|Cyclus| also has a notion of class-level **agent annotations**. These are +specified by the **note directive**. Similarly to the state variable +annotations, agent annotations must be given inside of the class declaration. +They also have a very similar signature: + +**Note (agent annotation) signature:** + +.. code-block:: c++ + + #pragma cyclus note + +Again, the ```` argument here must evaluate to a Python dictionary. +For example, + +**Note (agent annotation) example:** + +.. code-block:: c++ + + #pragma cyclus note {"doc": "If I wanna be rich, I’ve got to find myself"} + +Unlike state variables, agent annotations only have a few special members. One of +this is ``vars`` which contains the state variable annotations! +:ref:`cycpp-table-2` contains a listing of all special keys and their meaning. + +.. rst-class:: centered + +.. _cycpp-table-2: + +.. table:: **Table II.** Special Agent Annotations + :widths: 1 9 + :column-alignment: left left + :column-wrapping: true true + :column-dividers: none single none + + ============ ============================================================== + key meaning + ============ ============================================================== + vars The state variable annotations, **READ ONLY**. + name C++ class name (string) of the archetype. **READ ONLY.** + *New in version 1.1.1.* + entity The kind of archetype that this is based on which class it + inherits from. If this inherits from ``cyclus::Region``, + ``cyclus::Institution``, or ``cyclus::Facility`` then this + will be the string 'region', 'institution', or 'facility' + respecively. If the class inherits from ``cyclus::Agent`` but + does not inherit from the previous three then this will be + the string 'archetype'. In the class does not even inherit + from ``cyclus::Agent``, then this will be 'unknown'. + **READ ONLY.** *New in version 1.1.1.* + parents List of string class names of the direct superclasses of this + archetype. **READ ONLY.** *New in version 1.1.1.* + all_parents List of string class names of all the superclasses of this + archetype. **READ ONLY.** *New in version 1.1.1.* + niche A string which names the group that the achetype belongs to + that defines how it is swappable with other archetypes. If + two archetypes have the same niche then they are partially or + wholly swappable. Niches may overlap and any string may be + used as the niche. Some example niches that are useful to + displaying user interfaces are: ``reactor``, ``reprocessing``, + ``repository``, ``mine``, and others. + doc Documentation string. + tooltip Brief documentation string for user interfaces. + userlevel Integer from 0 - 10 for representing ease (0) or + difficulty (10) in using this variable, default 0. + ============ ============================================================== + +.. raw:: html + +
+ +-------------- + +If you find dictionaries too confining, |cycpp| also has an **exec directive**. +This allows you to execute arbitrary Python code which is added to the global +namespace the state variables and agent annotations are evaluated within. This +directive may be placed anywhere and is not confined to the class declaration, +like above. However, it is only executed during the annotations phase of +preprocessing. The signature for this directive is: + +**Exec signature:** + +.. code-block:: c++ + + #pragma cyclus exec + +The ```` argument may be any valid Python code. A non-trivial example, + +**Exec example:** + +.. code-block:: c++ + + #pragma cyclus exec from math import pi + #pragma cyclus exec r = 10 + + #pragma cyclus var {"default": 2*pi*r} + float circumfrence; + +One possible use for this is to keep all state variable annotations in a +separate sidecar ``*.py`` file and then import and use them rather than +cluttering up the C++ source code. Such decisions are up to the style of the +developer. + +Code Generation Directives +--------------------------- + +Once all of the annotations have been accumulated, the preprocessor takes +*another* pass through the code. This time it ignores the annotations +directives and injects C++ code anytime it sees a valid code generation +directive. + +The simplest and most powerful of the code generators is known as **the prime +directive**. This engages all possible code generation routines and must live +within the public part of the class declaration. + +**The prime directive:** + +.. code-block:: c++ + + #pragma cyclus + +Unless you are doing something fancy such as manually writing any of the agent +member functions that |cycpp| generates, the prime directive should be all that +you ever need. For example, an agent that does nothing and has no state variables +would be completely defined by the following thanks to the prime directive: + +**The prime directive example:** + +.. code-block:: c++ + + class DoNothingCongress : public cyclus::Institution { + public: + DoNothingCongress(cyclus::Context* ctx) {}; + virtual ~DoNothingCongress() {}; + + #pragma cyclus + }; + +.. raw:: html + +
+ +-------------- + +For the times when you wish to break the prime directive, you may drill down +into more specific code generation routines. These fit into three broad +categories: + +1. **Declaration (decl) directives**, +2. **Definition (def) directives**, and +3. **Implementation (impl) directives**. + +The ``decl`` directives generate only the member function declaration and must +be used from within the public part of the agent's class declaration. The +``def`` generate the member function definition in its entirety including the +function signature. These may be used either in the class declaration or in +the source file (``*.cc``, ``*.cpp``, etc.). The ``impl`` directives generate +only the body of the member function, leaving off the function signature. +These are useful for intercepting default behavior while still benefiting from +code generation. These must be called from with the appropriate function +body. + +The signature for the targeted code generation directives is as follows: + +**Targeted code generation directive signatures:** + +.. code-block:: c++ + + #pragma cyclus [ []] + +The first argument must be one of ``decl``, ``def``, or ``impl``, which +determines the kind of code generation that will be performed. The second, +optional ```` argument is the member function name that code should be +generated for. The third and final and optional ```` argument is the +agent name to code generate for. This argument is useful in the face of +ambiguous or absent C++ scope. The ```` argument must be present if +```` needs to be specified. + +In the absence of optional arguments there are only: + +.. code-block:: c++ + + #pragma cyclus decl + #pragma cyclus def + +These generate all of the member function declarations and definitions, +respectively. Note that there is no corresponding ``#pragma cyclus impl`` +because function bodies cannot be strung together without the corresponding +signatures encapsulating them. + +When the ```` argument is provided the directive generates only the +definition, declaration, or implementation for the given agent API function. +For example the following would generate the definition for the ``schema()`` +function. + +.. code-block:: c++ + + #pragma cyclus def schema + +:ref:`cycpp-table-3` contains a listing of all available function flags and their +associated C++ information. + +.. rst-class:: centered + +.. _cycpp-table-3: + +.. table:: **Table III.** Member Function Flags and Their C++ Signatures + :widths: 1 6 3 + :column-alignment: left left left + :column-wrapping: true true true + :column-dividers: none single single none + + ============ ========================================= ======================= + func C++ Signature Return Type + ============ ========================================= ======================= + clone ``Clone()`` ``cyclus::Agent*`` + initfromcopy ``InitFrom(MyAgent* m)`` ``void`` + initfromdb ``InitFrom(cyclus::QueryableBackend* b)`` ``void`` + infiletodb ``InfileToDb(cyclus::InfileTree* tree, ``void`` + cyclus::DbInit di)`` + schema ``schema()`` ``std::string`` + annotations ``annotations()`` ``Json::Value`` + snapshot ``Snapshot(cyclus::DbInit di)`` ``void`` + snapshotinv ``SnapshotInv()`` ``cyclus::Inventories`` + initinv ``InitInv(cyclus::Inventories& inv)`` ``void`` + ============ ========================================= ======================= + +.. raw:: html + +
+ +-------------- + +Lastly, the agent's classname may be optionally passed the to the directive. +This is most useful in source files for the definition directives. This is +because such directives typically lack the needed class scope. For example, +for the snapshot definition of ``MyAgent`` living in ``mynamespace`` we would +use: + +.. code-block:: c++ + + #pragma cyclus def snapshot mynamespace::MyAgent + +Putting It Together +-------------------- + +|Cyclus| agents are written by declaring certain member variables to be +**state variables**. This means that they *define* the conditions of the +agent at the start of every time step. State variables are automatically are +saved and loaded to the database as well a dictating other important +interactions with the kernel. + +The preprocessor will generate the desired implementation of key member +functions for your agent. The easiest way to obtain these is through the +prime directive. + +As a simple example, consider a reactor model that has three state variables: +a flux, a power level, and a flag for whether it is shutdown or not. +This could be implemented as follows: + +.. code-block:: c++ + + class Reactor : public cyclus::Facility { + public: + Reactor(cyclus::Context* ctx) {}; + virtual ~Reactor() {}; + + #pragma cyclus + + private: + #pragma cyclus var {'default': 4e14, \ + 'doc': 'the core-average flux', \ + 'units': 'n/cm2/2'} + double flux; + + #pragma cyclus var {'default': 1000, 'units': 'MWe'} + float power; + + #pragma cyclus var {'doc': 'Are we operating?'} + bool shutdown; + }; + +Note that the state variables may be private or protected if desired. +Furthermore annotations may be broken up over many lines using trailing +backslashes to make the code more readable. It remains up to you - the module +developer - to implement the desired behavior and logic in the ``Tick()`` and +``Tock()`` member functions. Fancier tricks are available as needed but this +is the essence of how to write |cyclus| agents. + +Abusing the |Cyclus| Preprocessor +================================== +Now that you know how to use |cycpp|, it is useful to know about some of the +more advanced features and how they can be leveraged. + +Scope and Annotations +------------------------- + +Annotations dictionaries retain the C++ scope that they are defined in even +though they are written in Python. This allows state variables to refer to +the annotations for previously declared state variables. Since the scope is +retained, this allows annotations to refer to each other across agent/class +and namespace boundaries. + +Because the annotations are dictionaries, the scoping is performed with the +Python scoping operator (``.``) rather than the C++ scoping operator (``::``). +For example, consider the case where we have a ``Spy`` class that lives in the +``mi6`` namespace. Also in the namespace is the spy's ``Friend``. +Furthermore, somewhere out in global scope lives the Spy's arch-nemesis class +``Enemy``. + +The first rule of scoping is that two state variables on the same class +share the same scope. Thus they can directly refer to each other. + +.. code-block:: c++ + + namespace mi6 { + class Spy { + #pragma cyclus var {"default": 7} + int id; + + #pragma cyclus var {"default": "James Bond, {0:0>3}".format(id['default'])} + std::string name; + }; + }; // namespace mi6 + +In the above, ``id`` is used to help define the annotations for ``name``. +Note that from within the annotations, other state variables are the annotation +dictionary that was previously defined. They fo not take on the C++ default value. +This is why we could look up ``id['default']``. + +The second rule of scoping is that you are allowed to look into the annotations +of other classes. However, to do so you must specifiy the class you are looking +into. Looking at our spy's friend + +.. code-block:: c++ + + namespace mi6 { + class Friend { + #pragma cyclus var {"doc": "Normally helps {0}".format(Spy.name['default'])} + std::string help_first; + }; + }; // namespace mi6 + +Here, to access the annotations for Spy's name we had to use ``Spy.name``, +drilling into the Spy class. Inspecting in this way is not limited by C++ +access control (public, private, or protected). + +Lastly, if the agent we are trying to inspect lives in a completely different +namespace, we must first drill into that namespace. For example, the spy's +main enemy is not part of ``mi6``. Thus to access the spy's name annotations, +the enemy must write ``mi6.Spy.name``. For example: + +.. code-block:: c++ + + class Enemy { + #pragma cyclus var {'default': mi6.Spy.name['default']} + std::string nemesis; + }; + + +Inventories +------------ +In addition to the normal :doc:`dbtypes`, state variables may also be declared +with the ``cyclus::Inventories`` type. This is a special |cyclus| typedef +of ``std::map >`` that enables the +storing of an arbitrary of resources (map values) by the associated commodity +(map key). While the concept of a resource inventory may be implemented in many +ways, the advantage in using the ``cyclus::Inventories`` is that the |Cyclus| +kernel knows how to save and load this type as well as represent it in RNG. +Inventories may be used as normal state variables. For example: + +.. code-block:: c++ + + #pragma cyclus var {'doc': 'my stocks'} + cyclus::Inventories invs; + +It is therefore *hightly* recommended that you store resources in this +data structure. + +State Variable Code Generation Overrides +----------------------------------------- +A powerful feature of most of the code generation directives is that the +C++ code that is created for a state variable may be optionally replaced with a +code snippet writing in the annotations. This allows you to selectively +define the C++ behavior without the need to fully rewrite the member function. + +A potential use case is to provide a custom schema while still utilizing all other +parts of |cycpp|. For example: + +.. code-block:: c++ + + #pragma cyclus var {'schema': 'Famcy RNG here'} + std::set fibonacci; + +This will override the schema only for the Fibonacci state variable. For a +listing of all code generation functions that may be overridden, please see +:ref:`cycpp-table-1`. + +Implementation Hacks +--------------------- + +The ``impl`` code generation directives exist primarily to be abused. Unlike +the ``def`` directives, the implementation directives do not include the +function signature or return statement. The downside of this is that you must +provide the function signature and the return value yourself. The upside is +that you may perform any operation before & after the directive! + +For example, suppose that we wanted to make sure that the flux state variable +on the Reactor agent is always snapshotted to the database as the value 42. +However, we did not want to permanently alter the value of this variable. +This could be achieved through the following pattern: + +.. code-block:: c++ + + void Reactor::Snapshot(cyclus::DbInit di) { + double real_flux = flux; // copy the existing flux value. + flux = 42; // set the value to wat we want temporarily + + // fill in the code generated implementation of Shapshop() + #prama cyclus impl snapshot Reactor + + flux = real_flux; // reset the flux + } + +There are likely much more legitimate uses for this feature. For a complete +listing of the member function information, please see :ref:`cycpp-table-3`. + +Custom Schema & Initialization +------------------------------ +Suppose that you would like for the schema for a state variable to be different +than the default behavior provided by |cycpp|. Or perhaps you would like more +sophisticated input validation than can is provided by XML and RelaxNG for a +state variable. This may be easily done by supplying the state variable annotation +keys ``schema`` and ``infiletodb``. These allow you to inject code snippets +pertaining to the state variable without interfering with the rest of the +code generation. + +For example, let's say that we have an integer state variable called +``material_identifier`` that we know always should be even. This name is +a bit long to make users type in, so we would prefer to expose this in the +input file as ``matid``. The RNG snippet that you would use for the ``schema`` +is thus: + +.. code-block:: python + + {'schema': '' \ + ' ' \ + ''} + +You can change the data type or any other valid RNG here. + +.. note:: Whenever a state variable name is changed in the ``schema``, you + must supply an accompanying ``infiletodb``. + +Providing a custom ``infiletodb`` is slightly more complicated because you +must give C++ snippets for reading from the input file and for persisting to +the database. The value for ``infiletodb`` is thus not a simple string +but a dict that has ``read`` and ``write`` keys. Continuing with the +example we can ensure that ``matid`` is even after it has been read in. +Here, we do not change the name of the state variable on the agent in +memory or in the database. + +.. code-block:: python + + {'infiletodb': { \ + 'read': 'material_identifier = cyclus::Query(tree, "matid");\n' \ + 'if (material_identifier%2 == 1)\n' \ + ' material_identifier++;\n', \ + 'write': '->AddVal("material_identifier", material_identifier)\n' \ + }} + +For more examples and explanation of what the ``InfileToDb()`` function +does please refer to other code generated samples and refer to other parts +of the documentation. +Pulling this all together, we can write our custom schema and initialization +as follows: + +.. code-block:: c++ + + #pragma cyclus var {'schema': '' \ + ' ' \ + '', \ + 'infiletodb': { \ + 'read': 'material_identifier = cyclus::Query(tree, "matid");\n' \ + 'if (material_identifier%2 == 1)\n' \ + ' material_identifier++;\n', \ + 'write': '->AddVal("material_identifier", material_identifier)\n' \ + }\ + } + int material_identifier; + +Other state variable annotation keys allow you to provide code snippets +in much the same way. + diff --git a/_sources/arche/dbtypes.rst.txt b/_sources/arche/dbtypes.rst.txt new file mode 100755 index 000000000..c69d55872 --- /dev/null +++ b/_sources/arche/dbtypes.rst.txt @@ -0,0 +1,160 @@ +.. _dbtypes: + +Database Types +============== + +Here is a listing of all supported data types that the various backends have +implemented, by |cyclus| version number. If your agents need a type that is not +yet supported, please let us know and we'll get to it as soon as possible! + +**Description of fields:** + +:id: enum identifier (value) for database type in the ``cyclus::DbTypes`` enum. +:name: enum name for database type in the ``cyclus::DbTypes`` enum. +:C++ type: the cooresponding C++ type. +:shape rank: the maximum rank (length) of the ``shape`` vector. +:backend: the database backend type. +:version: the |cyclus| version. +:supported: flag for if the backend supported this type in this release. + +.. raw:: html + +
+ + + + + + + + + + + + + + + + + + + +
+
+ +
+
+
+ diff --git a/_sources/arche/decay.rst.txt b/_sources/arche/decay.rst.txt new file mode 100755 index 000000000..e593bbe58 --- /dev/null +++ b/_sources/arche/decay.rst.txt @@ -0,0 +1,126 @@ +.. summary Documentation for the |Cyclus| Decay Method + +Radioactive Decay in |Cyclus| +============================= +.. warning:: Decay in |cyclus| is experimental. + +Radioactive decay of a group of isotopes over time can be described by the +following first order differential equation: + +.. math:: + + \frac{d}{dt}\mathbf{N(\mathit{t})}=\textrm{A}\: \mathbf{N(\mathit{t})} + +where the vector `N(t)` contains the number density of all the +isotopes being considered at time `t`, and A is called the decay +matrix. The solution to this differential equation can be expressed in terms +of a matrix exponential: + +.. math:: + + \mathbf{N(\mathit{to+\Delta t})}=e^{\Delta t \textrm{A}}\: \mathbf{N(\mathit{to})} + +The decay method currently implemented in |cyclus| computes this matrix +exponential solution at any given time using a series approximation known as +the Uniformization Method. This implementation was written by Kerry Dunn, and +is explained in more detail below. + +The Uniformization Method +------------------------- +The Uniformization Method is essentially a modification of the truncated Taylor +Series expansion of the matrix exponential solution, which can be described by +the following summation: + +.. math:: + + \mathbf{N(\mathit{to+\Delta t})}\approx \sum_{k=0}^{p}\frac{\left (\Delta t \right )^k}{k!}\: \textrm{A}^k\: \mathbf{N(\mathit{to})} + +The primary disadvantage of using this Taylor Series expansion to compute the +matrix exponential solution is that it can be subject to cancellation error as +a result of summing terms with alternating signs. These terms with alternating +signs occur because the diagonal elements in the decay matrix that represent +the decay constants are all negative. Therefore, in order to eliminate the +potential for cancellation error, the decay matrix must be modified so that it +no longer contains these negative elements. This modification process is known +as the uniformization technique. + +The first step in applying the uniformization technique is to define +`alpha` to be equal to the absolute value of the maximum diagonal +element of `A`: + +.. math:: + + \alpha=max_i\left | {a_i}_i \right | + +Then, given `alpha`, the next step is to redefine the matrix +exponential solution using a different matrix `P`: + +.. math:: + + \textrm{P}=\frac{1}{\alpha}\textrm{A}+\textrm{I} + +where I is the identity matrix. Note that `P` is completely non-negative, so a +Taylor Series expansion of this matrix exponential is not subject to the same +cancellation error that occurs with the original decay matrix. By replacing `A` +with `P`, the matrix exponential solution can now be expressed by the following +summation: + +.. math:: + + \mathbf{N(\mathit{to+\Delta t})}=e^{-\alpha \Delta t}\: e^{\Delta t (\alpha \textrm{P})}\: \mathbf{N(\mathit{to})}\approx e^{-\alpha \Delta t}\sum_{k=0}^{p}\frac{\left (\Delta t \right )^k}{k!}\: (\alpha \textrm{P})^k\: \mathbf{N(\mathit{to})} + +Note that this modified Taylor Series expansion can also be expressed in terms +of the original matrix A by substituting the definition for `P`: + +.. math:: + + \mathbf{N(\mathit{to+\Delta t})}\approx e^{-\alpha\Delta t}\sum_{k=0}^{p}\frac{\left (\Delta t \right )^k}{k!}\: (\textrm{A}+\alpha \textrm{I})^k\: \mathbf{N(\mathit{to})} + + +Implementation in |Cyclus| +-------------------------- + +Adding New Isotopes +------------------- + +Limitations ++++++++++++ + +When adding a new isotope, the most important thing to take into account is its +half-life or decay constant. The isotope with the smallest half-life, or +largest decay constant, will be the limiting factor for the time scale over +which |cyclus| can decay _all_ materials in one step. This occurs because the +Uniformization Method requires the computation of an exponential term, which is +limited by the size of a long double on the system being used to run |cyclus|. +To determine the maximum time scale that will be valid for a particular group +of isotopes, the following equation can be used: + +.. math:: + + {t_{max} = \frac{ln(\textrm{LDBL\_MAX})}{min(\lambda)}} + +where `LDBL_MAX` is the size of a long double and :math:`\lambda` is the +largest decay constant of the group of isotopes being considered. + +As an example, suppose that the isotope with the smallest half-life being +considered is Cm-232. This particular isotope has a decay constant of 1.5532 +nuclei per year. If the size of a long double is limited to LDBL_MAX = +1.18973e+4932, then all materials can only be decayed for a maximum of 7311 +years. Adding any isotopes with a half-life smaller than Cm-232 would result +in an even lower maximum time scale. + +References +---------- + +#. Cleve Moler and Charles van Loan, "Nineteen Dubious Ways to Compute the + Exponential of a Matrix, Twenty-Five Years Later," *SIAM Review*, *45*, + 3-49 (2003) + +#. Erwin Muller, Frederik Reitsma and Paulus P. Kruger, "A Stable Nuclide + Transmutation Procedure Free of Numerical Roundoff," *PHYSOR 2006*, September + 10-14, Vancouver, Canada (2006) + +#. R. B. Sidje and W. J. Stewart, "A numerical study of large sparse matrix + exponentials arising in Markov chains," *Computational Statistics & Data + Analysis*, *29*, 345-368 (1999) + diff --git a/_sources/arche/dre.rst.txt b/_sources/arche/dre.rst.txt new file mode 100755 index 000000000..b85c7d138 --- /dev/null +++ b/_sources/arche/dre.rst.txt @@ -0,0 +1,815 @@ +.. _dre: + +Dynamic Resource Exchange +========================= +The Dynamic Resource Exchange (DRE) is the heart of a |cyclus| simulation time +step. Every ``Trader`` that is registered with the ``Context`` +is automatically included in the exchange. |cyclus| agents can either implement +the ``Trader`` interface as a mixin or can be composed of one or more +traders. Note that the ``Facility`` class derives the +``Trader`` interface, and therefore all agents that derive from +``Facility`` are also traders. + +On each time step, there is a separate ``ResourceExchange`` +instance for each concrete ``Resource`` (i.e. ``Materials`` and ``Products``) of which +the kernel is aware. For example, there is an exchange for ``Material`` +resources and another for ``Product`` resources. + +The DRE is comprised of five phases which execure in series: + +* :ref:`rfb` +* :ref:`rrfb` +* :ref:`adj` +* :ref:`solve` +* :ref:`trade` +* :ref:`examples` + +.. _rfb: + +Request For Bids Phase +---------------------- +In the Request for Bids (RFB) phase, the exchange queries all registered traders +regarding their demand for a given resource type. Querying is provided through +the ``Trader`` interface's "get requests" for a given resource type, +e.g., ``GetMatlRequests()`` (C++) or ``get_material_requests()`` (Python) functions. + +Requests are modeled as collections of ``RequestPortfolio`` instances, where each +portfolio includes a collection of ``Request`` objects and a collection of +``CapacityConstraint`` objects. A portfolio is sufficiently met if one or more +of its constituent requests are met and all of its constraints are satisfied. + +A request provides a target resource, a commodity, and a preference for that +commodity-resource combination. A constraint provides a constraining value and a +conversion function that can convert a potential resource into the units of the +capacity (see :ref:`rrfb` for a more detailed example). + +For example, consider a facility of type ``FooFac`` that needs 10 kg fuel, +where the fuel is represented by a ``Material`` resource. It knows of two commodities in +the simulation that meet its demand, ``FuelA`` and ``FuelB``, and it prefers +``FuelA`` over ``FuelB``. A valid get material request implementation would then +be: + +**C++:** + +.. code-block:: c++ + + virtual std::set::Ptr> FooFac::GetMatlRequests() { + using cyclus::RequestPortfolio; + using cyclus::Material; + using cyclus::CapacityConstraint; + + double request_qty = 10; // kg + std::string recipeA = "recipeA"; + std::string commoda = "FuelA"; + Material::Ptr targetA = Material::CreateUntracked(request_qty, + context()->GetRecipe(recipeA)); + + std::string recipeB = "recipeB"; + std::string commodB = "FuelB"; + Material::Ptr targetB = Material::CreateUntracked(request_qty, + context()->GetRecipe(recipeB)); + + CapacityConstraint cc(request_qty); + + RequestPortfolio::Ptr port(new RequestPortfolio()); + port->AddRequest(targeta, this, commodA); + port->AddRequest(targetb, this, commodB); + port->AddConstraint(cc); + + std::set::Ptr> ports(); + ports.insert(port); + return ports; + + // In this example, both the FuelA and FuelB commodities can meet the + // material request, but FuelA is preferred. So we define a preference + // for each commodity as the fourth argument in the function. + // The larger the preference value, the more the commodity is preferred. + // The fifth argument here is if the request is exclusive: + std::set::Ptr> ports; + RequestPortfolio::Ptr port(new RequestPortfolio()); + + double prefA = 2; + double prefB = 1; + Request* r1 = port->AddRequest(targeta, this, commodA, prefA, true); + Request* r2 = port->AddRequest(targetb, this, commodB, prefB, true); + + // Additionally, we can create a vector of requests that are mutual: + std::vector*> mreqs; + mreqs = {r1, r2}; + port->AddMutualReqs(mreqs); + ports.insert(port); + return ports; + } + +**Python:** + +.. code-block:: python + + import cyclus.typesystem as ts + + def get_material_requests(self): + request_qty = 10.0 # kg + # Material Target A + recipe_a = self.context().get_recipe("recipeA") + target_a = ts.Material.create_untracked(request_qty, recipe_a) + # Material Target B + recipe_b = self.context().get_recipe("recipeB") + target_b = ts.Material.create_untracked(request_qty, recipe_b) + # commodity mapping to request target + commods = {"FuelA": target_a, "FuelB": target_b} + + # The Python interface allow you to return a few different structures, + # depending on your needs. In its simplest form, if you do not not have + # any capacity constraints, you can just return the commodity mapping! + return commods + + # If you do have a capacity constraint, you need to provide a portfolio + # dict. This is simply a dict with two keys: "commodities" and "constraints". + # The "commodities" value is the same as above. The "constraints" value is + # either a float or an iterable of floats. + # single constraint: + port = {"commodities": commods, "constraints": request_qty} + return port + # many constraints: + port = {"commodities": commods, "constraints": [request_qty, request_qty*2]} + return port + + # In this example, both the FuelA and FuelB commodities can meet the + # material request, but FuelA is preferred. So we define a preference + # for each commodity. The larger the preference value, the + # more the commodity is preferred. Placing the dictionaries in + # a list makes them mutual requests: + commods = [{"FuelA": target_a, "preference":2}, + {"FuelB": target_b, "preference":1}] + port = {"commodities":commods, "constraints":request_qty} + + # If you want the requests to be exclusive, then you have to indicate + # that: + commods = [{"FuelA": target_a, "preference":2, "exclusive":True}, + {"FuelB": target_b, "preference":1, "exclusive":True}] + port = {"commodities":commods, "constraints":request_qty} + + # lastly, if you need to return many portfolios, simply return a list of + # portfolio dictionaries! The "preference" and "exclusive" keys are optional + ports = [{"commodities": [{"FuelA": target_a, "preference": 2, "exclusive": True}], + "constraints": request_qty}, + {"commodities": [{"FuelB": target_b, "preference": 1, "exclusive": True}], + "constraints": request_qty}] + return ports + + +.. _rrfb: + +Response to Request For Bids Phase +---------------------------------- +In the Response to Request for Bids (RRFB) phase, the exchange queries all +registered traders regarding their supply for a given resource type. Querying is +provided through the ``Trader`` interface's "get bids" for a given +resource type, e.g. ``GetMatlBids()`` (C++) or ``get_material_bids()`` (Python). + +Bids are modeled as collections of ``BidPortfolio``, where each +portfolio includes a collection of ``Bid`` objects and a collection of +``CapacityConstraint`` objectss. A portfolio is not violated if any of its +constituent bids are connected to their requests and all of its constraints are +satisfied. + +A bid is comprised of a request to which it is responding and a resource that it is +offering in response to the request. + +Black Box Examples +++++++++++++++++++ +Consider a facility of type ``FooFac`` that has 10 kg of fuel of commodity type +``FuelA`` that it can provide. Furthermore, consider that its capacity to +fulfill orders is constrained by the total amount of a given nuclide. A valid +get material bids implementation would then be: + +**C++:** + +.. code-block:: c++ + + class NucConverter : public cyclus::Converter { + public: + NucConverter(int nuc) : nuc_(nuc) {}; + + virtual double convert(cyclus::Material::Ptr m, cyclus::Arc const * a = NULL, + cyclus::ExchangeTranslationContext const * ctx = NULL) const { + cyclus::MatQuery mq(m); + return mq.mass(nuc_); + } + + private: + int nuc_; + }; + + virtual std::set::Ptr> FooFac::GetMatlBids( + cyclus::CommodMap::type& commod_requests) { + using cyclus::BidPortfolio; + using cyclus::CapacityConstraint; + using cyclus::Converter; + using cyclus::Material; + using cyclus::Request; + + // respond to all requests of my commodity + std::string my_commodity = "FuelA"; + BidPortfolio::Ptr port(new BidPortfolio()); + std::vector*>& requests = commod_requests[my_commdoity]; + std::vector*>::iterator it; + for (it = requests.begin(); it != requests.end(); ++it) { + std::string recipe = "recipe"; + std::string commod = "Fuel"; + for (it = requests.begin(); it != requests.end(); ++it) { + Material::Ptr offer = Material::CreateUntracked(request_qty, + context()->GetRecipe(recipe)); + port->AddBid(*it, offer, this); + } + } + + // add a custom constraint for Pu-239 + int pu = 932390000; // Pu-239 + Converter::Ptr conv(new NucConverter(pu)); + double max_pu = 8.0; // 1 Signifigant Quantity of Pu-239 + CapacityConstraint constr(max_pu, conv); + port->AddConstraint(constr); + + std::set::Ptr> ports; + ports.insert(port); + return ports; + } + + +**Python:** + +.. code-block:: python + + # Note that the Python interface does not yet support custom constraint functions. + # these are fairly rare in practice and is a forth coming feature. + import cyclus.typesystem as ts + + def get_material_bids(self, requests): + """This function takes as input a requests dictionary, which maps + commodity names to tuples of Request instances. For example:: + + requests = { + "FuelA": (MaterialRequest1, MaterialRequest2), + "FuelB": (MaterialRequest3, MaterialRequest4), + } + + For more information on MaterialRequests and ProductRequests, please see + the cyclus.typesystem docs. + """ + # Like with get_material_requests(), many potential bid structures can be returned + # depending on you need. If the commodity that you trade in wasn't requested this + # time step, you can just return None. + if 'FuelA' not in requests: + return + + # Alternitavely, you may return a bid portfolio. Let's start by constructing the + # bids. If you don't want to offer a bid that is different than the request, + # you can just provide the requests. The bids are then a list of the request objects + reqs = requests['FuelA'] + bids = [req for req in reqs] + # Or if you do want to offer something different than the request, the bids list + # list contains dictionaries with "request" and "offer" keys + recipe_comp = self.context.get_recipe(self.recipe_name) + bids = [] + for req in reqs: + qty = min(req.target.quantity, self.capacity) + mat = ts.Material.create_untracked(qty, recipe_comp) + bids.append({'request': req, 'offer': mat}) + # now that we have the bids, we can add this to a bid portfolio dict, which + # contains a "bids" key. + port = {"bids": bids} + return port + + # if you need to add capcity constraint(s), also include a "constraints" key + # in the bids portfolio dict. + port = {"bids": bids, "constraints": self.capacity} + return port + + # Of course you may also return many bid portfolios by putting the many + # dicts in the above form in a list. + ports = [{"bids": bids[::2], "constraints": self.capacity}, + {"bids": bids[1::2], "constraints": self.capacity}] + return ports + + +White Box Examples ++++++++++++++++++++ +Consider a case where a facility's bid depends on the type of the requester's +``Agent``, and the bidder determines its offer based on the requester's +interface: + +**C++:** + +.. code-block:: c++ + + cyclus::Material::Ptr FooFac::SpecialFooOffer() { + std::string recipe = "recipe"; + double quantity = 10; + Material::Ptr target = Material::CreateUntracked(quantity, + context()->GetRecipe(recipe)); + return target; + }; + + virtual std::set::Ptr> FooFac::GetMatlBids( + cyclus::CommodMap::type& commod_requests) { + using cyclus::BidPortfolio; + using cyclus::Material; + using cyclus::Request; + + // respond to all requests of my commodity + std::string my_commodity = "FuelA"; + BidPortfolio::Ptr port(new BidPortfolio()); + std::vector*>& requests = commod_requests[my_commdoity]; + std::vector*>::iterator it; + for (it = requests.begin(); it != requests.end(); ++it) { + Material::Ptr offer; + Agent* agent = it->requester(); + FooFac* cast = dynamic_cast(agent); + if (cast != NULL) { + offer = cast->SpecialFooOffer(); // get a special response that the requester wants + } else { + double qty = it->quantity(); + std::string recipe = "some_other_recipe"; + Material::Ptr offer = Material::CreateUntracked(qty, context()->GetRecipe(recipe)); + } + port->AddBid(*it, offer, this); + } + + std::set::Ptr> ports; + ports.insert(port); + return ports; + } + + +**Python:** + +.. code-block:: python + + import cyclus.typesystem as ts + + def special_foo_offer(self): + recipe = self.context.get_recipe("recipe") + target = ts.Material.create_untracked(10, recipe) + return target + + def get_material_bids(self, requests): + reqs = requests["FuelA"] + bids = [] + for req in reqs: + if isinstance(req.requester, FooFac): + offer = self.special_foo_offer() + else: + qty = req.quantity + recipe = self.context.get_recipe("some_other_recipe") + offer = ts.Material.create_untracked(qty, recipe) + bids.append(req) + return {"bids": bids} + + +.. _adj: + +Preference Adjustment Phase +--------------------------- +In the Preference Adjustment (PA) phase, requesters are allowed to view which +bids were matched to their requests, and adjust their preference for the given +bid-request pairing. Querying is provided through the ``Agent`` interface, so all cyclus +archetypes may adjust preferences. The "adjust prefs: functions are based on a given resource +type, e.g. ``AdjustMaterialPrefs`` (C++) or ``adjust_material_prefs()`` (Python). + +Preferences are used by resource exchange solvers to inform their solution +method. The default preference for all bids is zero. Agents will only utilize +the PA phase if there is a reason to update preferences over the default +provided in their original request. + +Preferences can be adjusted by both the original ``Trader`` placing +requests as well as any parent ``Agent`` instances, with the trader adjusting +first and the most senior parent adjusting last. In the supported +Region-Institution-Facility agent relationship, Facilities adjust first, +followed by Institution and Region parent agents. The calling chain is shown in +Figure 1, with the orange box representing a call through the ``Trader`` +interface and a green box representing the ``Agent`` interface. + +.. figure:: dre-1.svg + :align: center + :height: 500 + + **Figure 1:** R-I-F Preference Adjustment Call Chain + +.. blockdiag code below + + http://interactive.blockdiag.com/?compression=deflate&src=eJxtjTELAjEMRvf7FeEmHQQdDofqKriKu9Q2tMHSHDGHiNx_t1cVRBzz8j3eObG7eLIBHg0AC2FWq8QZttCzqFjS8sjs8XQjr7HwVbc0HxaRQtQC193EDhgmd7OAfb4q6aDvs91ZR4n0DrOjWI8yb01ThCA89LUN_zaFjz8rx4mlBIMg5kpeUfOdNFUcn5VaRHw + + blockdiag { + orientation = portrait + node_width = 150; + node_height = 75; + Region <- Institution <- "Facility (Trader)"; + + group { + "Facility (Trader)" + } + group { + color = green + Region; Institution; + } + } + + +Black Box Examples +++++++++++++++++++ +For example, suppose that an agent prefers potential trades in which the bidder +has the same parent agent as it does. A valid adjust material preferences implementation +would then be: + +**C++:** + +.. code-block:: c++ + + virtual void FooFac::AdjustMatlPrefs(cyclus::PrefMap::type& prefs) { + cyclus::PrefMap::type::iterator pmit; + for (pmit = prefs.begin(); pmit != prefs.end(); ++pmit) { + std::map*, double>::iterator mit; + Request* req = pmit->first; + for (mit = pmit->second.begin(); mit != pmit->second.end(); ++mit) { + Bid* bid = mit->first; + if (parent() == bid->bidder()->manager()->parent()) + mit->second += 1; // bump pref if parents are equal + } + } + } + + +**Python:** + +.. code-block:: python + + def adjust_material_prefs(self, prefs): + """The adjustment methods have a single argument which is a prefernce dictionary. + It maps (Request, Bid) tuples to float valued prefernces. For example:: + + prefs = { + (Request1, Bid1): 1.0, + (Request1, Bid2): 2.0, + (Request2, Bid3): 1.0, + } + + This function may return None or a dictionary of the same form. Note that the + return value does not need to have all of the same keys as were passed in. Rather, + it can return only those request-bid pairs that it actually wants to update. + """ + # If you don't want to do any prefernce adjustment, just return None. + return None + + # Otherwise we can loop though and update those that matter. + updates = {} + for (req, bid), pref in prefs.items(): + # favor bids if the parents are the same + if self.parent_id == bid.bidder.parent_id: + updates[req, bid] = pref + 1.0 + return updates + + +Alternatively, an ``Institution`` managing a ``Facility`` could +adjust preferences as follows: + +**C++:** + +.. code-block:: c++ + + virtual void FooInst::AdjustMatlPrefs(cyclus::PrefMap::type& prefs) { + cyclus::PrefMap::type::iterator pmit; + for (pmit = prefs.begin(); pmit != prefs.end(); ++pmit) { + std::map*, double>::iterator mit; + Request* req = pmit->first; + for (mit = pmit->second.begin(); mit != pmit->second.end(); ++mit) { + Bid* bid = mit->first; + Agent* you = bid->bidder()->manager()->parent(); + Agent* me = this; + if (me == you) + mit->second += 1; // bump pref if the parent is me (institutions are equal) + } + } + } + + +**Python:** + +.. code-block:: python + + def adjust_material_prefs(self, prefs): + updates = {} + for (req, bid), pref in prefs.items(): + if self.id == bid.bidder.parent_id: + updates[req, bid] = pref + 1.0 + return updates + + +Finally, a ``Region`` managing a ``Institution`` could adjust +preferences as + +**C++:** + +.. code-block:: c++ + + virtual void FooRegion::AdjustMatlPrefs(cyclus::PrefMap::type& prefs) { + cyclus::PrefMap::type::iterator pmit; + for (pmit = prefs.begin(); pmit != prefs.end(); ++pmit) { + std::map*, double>::iterator mit; + Request* req = pmit->first; + for (mit = pmit->second.begin(); mit != pmit->second.end(); ++mit) { + Bid* bid = mit->first; + Agent* you = bid->bidder()->manager()->parent()->parent(); + Agent* me = this; + if (me == you) + mit->second += 1; // bump pref if the grandparent is me (regions are equal) + } + } + } + + +**Python:** + +.. code-block:: python + + def adjust_material_prefs(self, prefs): + updates = {} + for (req, bid), pref in prefs.items(): + if self.id == bid.bidder.parent.parent_id: + updates[req, bid] = pref + 1.0 + return updates + + + +White Box Examples +++++++++++++++++++ +Consider a scenario in which preferences will only be adjusted if the requester +and bidder are of the same type: + +**C++:** + +.. code-block:: c++ + + virtual void FooFac::AdjustMatlPrefs(cyclus::PrefMap::type& prefs) { + cyclus::PrefMap::type::iterator pmit; + for (pmit = prefs.begin(); pmit != prefs.end(); ++pmit) { + Request* req = pmit->first; + FooFac* cast = dynamic_cast(req->requester()->manager()); + if (cast != NULL) { + for (mit = pmit->second.begin(); mit != pmit->second.end(); ++mit) { + mit->second = pref + 10; // we like this trader! + } + } + } + } + + +**Python:** + +.. code-block:: python + + def adjust_material_prefs(self, prefs): + updates = {} + for (req, bid), pref in prefs.items(): + if not isinstance(req.requester, FooFac): + continue + updates[req, bid] = pref + 10.0 # we like this trader + return updates + + +.. _solve: + +Solution Phase +-------------- +The Solution Phase is straightforward from a module developer point of +view. Given requests, bids for those requests, and preferences for each +request-bid pairing, a ``ExchangeSolver`` selects request-bid pairs to +satisfy and the quantity each resource to assign to each satisfied request-bid +pairing. The solution times and actual pairings will depend on the concrete +solver that is employed by the |cyclus| kernel. + +.. _trade: + +Trade Execution Phase +--------------------- +When satisfactory request-bid pairings are determined, a final communication is +executed for each bidder and requester during the Trade Execution Phase. Bidders +are notified of their winning bids through the ``Trader`` "get trades" +functions (e.g. ``GetMatlTrades()`` in C++ and ``get_material_trades()`` in Python), +and requesters are provided their +satisfied requests through the ``Trader`` "accept trades" +functions (e.g. ``AcceptMatlTrades()`` in C++ and ``accept_material_trades()`` in Python). + +By convention in C++, traders can implement a ``TradeResponse()`` function that provides a +``Material::Ptr`` given a ``Trade``. It can then implement its +Trader interface as follows: + +**C++:** + +.. code-block:: c++ + + void FooFac::GetMatlTrades(const std::vector< cyclus::Trade >& trades, + std::vector, cyclus::Material::Ptr> >& responses) { + using cyclus::Material; + using cyclus::Trade; + + std::vector< Trade >::const_iterator it; + for (it = trades.begin(); it != trades.end(); ++it) { + Material::Ptr mat = it->bid->offer(); + Material::Ptr response = TradeResponse(mat); + responses.push_back(std::make_pair(*it, response)); + } + } + +**Python:** + +.. code-block:: python + + import cyclus.typesystem as ts + + def get_material_trades(self, trades): + """In Python, the get trades functions take a single trades aregument and + should return a responses dict. The trades is list of Trade objects, see the + cyclus.typesystem docs for more information. + + The reponses should be a dict whose keys are these trades and whose values + are tracked resource instances. For example, Materials. + """ + # here we respond with what the trade request was. + responses = {} + for trade in trades: + mat = ts.Material.create(self, trade.amt, trade.request.target.comp()) + responses[trade] = mat + return responses + + +Similarly, Traders can implement an "accept trade" function that accepts a +the resources from a ``Trade``. It can then implement its +Trader interface as follows: + +**C++:** + +.. code-block:: c++ + + void FooFac::AcceptMatlTrades(const std::vector< std::pair, cyclus::Material::Ptr> >& responses) { + std::vector< std::pair, cyclus::Material::Ptr> >::const_iterator it; + for (it = responses.begin(); it != responses.end(); ++it) { + AcceptTrade(it->second); + } + } + + +**Python:** + +.. code-block:: python + + def accept_material_trades(self, responses): + """In the Python interface, this accepts a responses dict that has the same format as + the responses returned from get_material_trades() above. That is, responses maps + Trades to Materials. This function is responsible for storing these traded materails + somewhere in the agent's inventories. This is the end of the dynamic resource + exchange and so this function shouldn't return anything. + """ + for mat in responses.values(): + self.inventory.push(mat) + + +The implementation logic for each of these functions is determined by how each +individual agent handles their resource inventories. Accordingly, their +implementation will be unique to each agent. Some initial examples can be found +in the ``Source`` and ``Sink`` agents, where ``Source`` +implements ``GetMatlTrades()`` or ``get_material_trades()`` as a bidder and ``Sink`` +implements ``AcceptMatlTrades()`` or ``accept_material_trades()`` as a requester. + +.. _examples: + +Examples +-------- + +Mixin-based Trader Behavior [C++] ++++++++++++++++++++++++++++++++++ + +.. note:: The Python interface can easily handle mix-in behavior for + Python agents via subclassing and using ``super()`` on any agent. + +Trader behavior can be specialized based on mixins that an archetype uses. For +example, consider an interface that helps determines preferences based on +the equality of the parent of a ``cyclus::Agent``. + +.. code-block:: c++ + + class PrefGetter { + public: + double GetPref(cyclus::Agent* mine, cyclus::Agent* yours) { + return (mine == yours) ? 1 : 0.5; + } + }; + +A trader who then wants behavior based on whether a bidder's manager inherits +from ``PrefGetter`` can then implement its preference adjustment as follows: + +.. code-block:: c++ + + virtual void FooFac::AdjustMatlPrefs(cyclus::PrefMap::type& prefs) { + cyclus::PrefMap::type::iterator pmit; + for (pmit = prefs.begin(); pmit != prefs.end(); ++pmit) { + std::map*, double>::iterator mit; + Request* req = pmit->first; + cyclus::Agent* reqagent = req->requester()->manager(); + for (mit = pmit->second.begin(); mit != pmit->second.end(); ++mit) { + Bid* bid = mit->first; + cyclus::Agent* bidagent = bid->bidder()->manager(); + PrefGetter* pg_cast = dynamic_cast(bidagent); + if (pg_cast != NULL) { + // special behavior for the mixin + mit->second = cast->GetPref(reqagent->parent(), + bidagent->parent()); + } else { + mit->second = 0; // choose any (reasonable) default behavior + } + } + } + } + +.. warning:: + + Using a dynamic-checking approach will limit the interoperability of your + archetype with others. Some mixins are provided by the |Cyclus| kernel in its + :ref:`toolkit `, which is part of the core library. + +.. warning:: + + Using a mixin-based approach will require special implementation of restart + related functions *if* the mixin has state associated with it (i.e., members + that are initialized from an input file and/or stored from timestep to + timestep). For further reading, see the ``pragma cyclus impl`` directive in + :ref:`cycpp`. + +.. _white_box: + +Non-Black Box Behavior [C++] +++++++++++++++++++++++++++++ + +.. note:: The Python interface can trivially handle non-black box behavior for + Python agents by using ``isinstance()`` on any agent. + +Cyclus provides a simulation framework that supports black-box entity +interaction, i.e., any entity in the simulation can interact with any other +entity through its ``Agent`` interface. However, there is nothing +stopping an archetype developer from implementing logic that is specific to a +implemented archetype. + +For example, take a facility that informs a trader what composition of material +it wants given another facility's inventory. + +.. code-block:: c++ + + class TradeInformer: public cyclus::Facility { + public: + #pragma cyclus + + cyclus::Material::Ptr IdealMatl(const cyclus::toolkit::ResBuf& buffer) { + // provide whatever implementation is desired + } + }; + +A provider of material can then implement its ``GetMatlBids`` as follows: + +.. code-block:: c++ + + virtual std::set::Ptr> + FooFac::GetMatlBids( + cyclus::CommodMap::type& commod_requests) { + using cyclus::BidPortfolio; + using cyclus::Material; + using cyclus::Request; + using cyclus::Agent; + + // respond to all requests of my commodity + std::string my_commodity = "FuelA"; + BidPortfolio::Ptr port(new BidPortfolio()); + std::vector*>& requests = commod_requests[my_commodity]; + std::vector*>::iterator it; + for (it = requests.begin(); it != requests.end(); ++it) { + Material::Ptr offer; + Agent* agent = it->requester(); + TradeInformer* cast = dynamic_cast(agent); + if (cast != NULL) { + offer = cast->IdealMatl(inventory); // inventory is a state variable ResBuf + } else { + double qty = it->quantity(); + std::string recipe = "recipe"; + Material::Ptr offer = Material::CreateUntracked(qty, context()->GetRecipe(recipe)); + } + port->AddBid(*it, offer, this); + } + + std::set::Ptr> ports; + ports.insert(port); + return ports; + } + +Further Reading +--------------- +For a more in depth (and historical) discussion, see `CEP 18 +`_. diff --git a/_sources/arche/dynamic_loading.rst.txt b/_sources/arche/dynamic_loading.rst.txt new file mode 100755 index 000000000..4220f94b1 --- /dev/null +++ b/_sources/arche/dynamic_loading.rst.txt @@ -0,0 +1,18 @@ +.. _dynamic_loading: + +Dynamic Loading Overview +========================== + +*Dynamic loading* is a term used to describe the action of loading +libraries at run time. This implies that knowledge of the structure +of the classes in these libraries is not known at compile time to +the executing program. In Linux, these libraries are denoted by the +suffix '.so', in Windows, '.dll', and in OSX, '.dylib'. + +In |cyclus|, every *module* is dynamically loaded. Modules include one or more +*agents*. Python moduels that contain archetypes are loaded dynamically by +|cyclus|'s loading system, which itself call out to Python's import mechanism. + +The internal process used by the |cyclus| core is very close to that +described in this +`article `_. diff --git a/_sources/arche/errors.rst.txt b/_sources/arche/errors.rst.txt new file mode 100755 index 000000000..9d17ef2cc --- /dev/null +++ b/_sources/arche/errors.rst.txt @@ -0,0 +1,148 @@ +Errors and Warnings [C++] +========================= +Module developers may also leverage the |Cyclus| error and warning system +within the code that they write. These are useful for failing gracefully from +undefined behavior or to signal that code is still experimental and under +development. + +.. note:: Python agents should just use the Python error and warning system. + +Errors +------ + +|Cyclus| uses `standard C++ execptions +`_ to throw and catch +errors. However, whenever you ``#include "cyclus.h"`` or ``#include +"error.h"`` you have access to a suite of exceptions that the kernel itself +knows about. :ref:`errors-table-1` displays all of the |Cyclus| errors which +live within the ``cyclus`` namespace and subclass from ``std::exception``. + +.. rst-class:: centered + +.. _errors-table-1: + +.. table:: **Table I.** Cyclus Error Classes + :widths: 1 9 + :column-alignment: left left + :column-wrapping: true true + :column-dividers: none single none + + =============== ============================================================== + Error Description + =============== ============================================================== + Error Base error for |Cyclus|. + ValueError For values that are too big, too small, etc. + KeyError For failed retrieval/insertion of key-based data into/from + data structures. + StateError For failed object state expectations. + IOError For failed reading/writing to files, network connections, etc. + CastError For failed casts that shouldn't. + ValidationError For validating files received via I/O or for indicating that + the software has not been properly benchmarked. + =============== ============================================================== + +.. raw:: html + +
+ +For example, if a reactor finds itself with a negative flux in its ``Tock()`` +function then it could choose to throw either a ValueError or a StateError. +If the flux happened to be a state variable a StateError would be more +appropriate. This would be implemented as follows: + +**Error example:** + +.. code-block:: c++ + + void Reactor::Tock(int time) { + if (flux < 0.0) + throw cyclus::StateError("negative fluxes are impossible!"); + } + +Warnings +-------- + +Along with errors, there are corresponding non-terminal warning messages that +modules may issue. These print messages to ``sdterr`` along with the kind of +warning that was given. All warnings are issued through the +``cyclus::Warn()`` function. This functions is templated on the +``cyclus::Warnings`` enum whose values and meanings may be seen in +:ref:`errors-table-2`. + +.. rst-class:: centered + +.. _errors-table-2: + +.. table:: **Table II.** Cyclus Warnings + :widths: 3 7 + :column-alignment: left left + :column-wrapping: true true + :column-dividers: none single none + + =========================== ================================================= + Warnings Description + =========================== ================================================= + WARNING Basic warning for |Cyclus|. + VALUE_WARNING For values that are too big, too small, etc. + KEY_WARNING For unexpected retrieval/insertion of key-based + data into/from data structures. + STATE_WARNING For unexpected object state. + IO_WARNING For unexpected reading/writing to files, network + connections, etc. + CAST_WARNING For unexpected casts. + VALIDATION_WARNING For validating files received via I/O or for + indicating that the software has not been + properly benchmarked. + DEPRECATION_WARNING For features, behaviors, or APIs that are no + longer supported. Expect removal in future + releases. + PENDING_DEPRECATION_WARNING For features, behaviors, or APIs that are + candidates for future deprecation. + EXPERIMENTAL_WARNING For features, behaviors, or APIs that are not + considered stable. Reasons for instability may + include a lack of benchmarking, uncertainty about + future needs, or known future API changes. + =========================== ================================================= + +.. raw:: html + +
+ +Revisiting the reactor error example from above, we could have issued a +warning instead. + +**Warning example:** + +.. code-block:: c++ + + void Reactor::Tock(int time) { + if (flux < 0.0) + cyclus::Warn("negative fluxes are impossible!"); + } + +Warnings have a number of advantages over errors. The first is that since +they do not stop the process they are fast to issue. They are also a great way +for communicating with users the expectations of using your module. + +Warnings also have two command line options that users can provide which +modify their behavior. The first is ``--warn-limit``. This changes the +maximum number of times a warning of each kind will be issued before further +warnings are suppressed. This defaults to 1. A value of zero means to +suppress all warnings and a very large number will print them all. For +example, if the user wished to print the first 42 warnings of each kind they +would call |cyclus| as follows: + +.. code-block:: bash + + $ cyclus --warn-limit 42 ... + +The second command line argument that alters warning behavior is +``--warn-as-error``. This turns all warnings into corresponding error types +and throws the error. This is useful for ensuring that only stable code is +executed or to help uncover what is causing a warning to be thrown. It takes +no arguments: + +.. code-block:: bash + + $ cyclus --warn-as-error ... + diff --git a/_sources/arche/hello_world_cpp.rst.txt b/_sources/arche/hello_world_cpp.rst.txt new file mode 100755 index 000000000..33b887a44 --- /dev/null +++ b/_sources/arche/hello_world_cpp.rst.txt @@ -0,0 +1,130 @@ +.. _hello_world_cpp: + +Hello, Cyclus! [C++] +==================== +This pages walks you through a very simple hello world example using +|cyclus| agents. First make sure that you have the dependencies installed, +namely |Cyclus|, CMake, and a recent version of Python (2.7 or 3.3+). + +First, you need to get the ``cycstub`` code. Cycstub is a skeleton code base +that you can use to quick-start new |cyclus| module development projects. +You can grab cycstub either by using git to +`clone the repository `_ or by +`downloading the zip file `_. +Let's put this code in a ``tutorial`` directory and go into it. + +**Getting cycstub via git:** + +.. code-block:: bash + + $ git clone https://github.com/cyclus/cycstub.git tutorial + $ cd tutorial + +**Getting cycstub via zip:** + +.. code-block:: bash + + $ curl -L https://api.github.com/repos/cyclus/cycstub/zipball > tutorial.zip + $ unzip tutorial.zip + $ mv cyclus-cycstub-* tutorial + $ cd tutorial + +------------ + +Since cycstub is a template project everything is named ``stub``. We need to +change this to reflect the name we want our new project to be called - +``tutorial`` here. Cycstub comes with a renaming tool to do just this! From +the command line, run Python in the following way: + +.. code-block:: bash + + tutorial $ python rename.py tutorial + +------------ + +Let's now change the behavior of the TutorialFacility's ``Tick()`` & +``Tock()`` member functions to print "Hello" and "World" respectively. To do +this, please open up the :file:`src/tutorial_facility.cc` file in your +favorite text editor (vim, emacs, gedit, `notepad++ `_). +Change the original functions to look like: + +**Original Tick() and Tock() in src/tutorial_facility.cc:** + +.. code-block:: c++ + + void TutorialFacility::Tick() {} + + void TutorialFacility::Tock() {} + +**New Tick() and Tock() in src/tutorial_facility.cc:** + +.. code-block:: c++ + + void TutorialFacility::Tick() {std::cout << "Hello, ";} + + void TutorialFacility::Tock() {std::cout << "World!\n";} + +------------ + +Now that we have altered the behavior of the TutorialFacility, let's compile and +install the ``tutorial`` project. This done with the install.py script. +The install script puts the project into your cyclus userspace, +``${HOME}/.local/lib/cyclus``. + +.. code-block:: bash + + tutorial $ python install.py + +------------ + +Let's run |cyclus| with the TutorialFacility! In the input directory there is +an :file:`example.xml`. Running |cyclus| on this file with the command +``cyclus input/example.xml`` should produce the following output. + +.. code-block:: bash + + tutorial $ cyclus input/example.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + Hello, World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 0ae730e0-a9a8-4576-afaa-d1db6399d5a2 + +If you look in the input file you'll see that the simulation duration was set +to 10. This is why "Hello, World!" is printed ten times. diff --git a/_sources/arche/hello_world_py.rst.txt b/_sources/arche/hello_world_py.rst.txt new file mode 100755 index 000000000..2e6c4a2dd --- /dev/null +++ b/_sources/arche/hello_world_py.rst.txt @@ -0,0 +1,130 @@ +.. _hello_world_py: + +Hello, Cyclus! [Python] +======================= +This pages walks you through a very simple hello world example using +|cyclus| agents. First make sure that you have the dependencies installed, +namely |Cyclus| and a recent version of Python (2.7 or 3.5+). + +|Cyclus| can read agents from any normal python package and module. If you are unsure of +how to start and install a Python project, please see the Python documentation. There are +also many high-quality guides and tools online. Here, we will assume that there is a +project called ``proj`` that has a module called ``agents`` that contains an archetype +class called ``MyFacility``. + +To start writing ``MyFacility``, open up ``agents.py``, import ``cyclus.agents``, +anf write the following: + +**proj/agents.py:** + +.. code-block:: Python + + from cyclus.agents import Facility + + class MyFacility(Facility): + """My first Cyclus archetype!""" + + +And that is it! The above is a fully-functional |Cyclus| facility. + +------------ + +Let's now change the behavior of the ``MyFacility``'s ``tick()`` and +``tock()`` methods to print "Hello" and "World" respectively. + +**proj/agents.py:** + +.. code-block:: Python + + from cyclus.agents import Facility + + class MyFacility(Facility): + """My first Cyclus archetype!""" + + def tick(self): + print("Hello,") + + def tock(self): + print("World!") + + +Now that we have altered the behavior of ``MyFacility``, reinstall the project +so that it is available to cyclus. + +------------ + +You can refer to this facility in a |cyclus| input file by using the Python package and +module name in the lib section of the archetypes spec, like you would write it if you +were importing a module. The class name goes in the +name section of the spec. + +.. code-block:: xml + + + proj.agentsMyFacility + + +------------ + +Let's run |cyclus| with this example! In the input directory there is +an :file:`example.xml`. First modify it to point to the archetype we just wrote. +Running |cyclus| on this file with the command +``cyclus input/example.xml`` should produce the following output. + +.. code-block:: bash + + tutorial $ cyclus input/example.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + Hello, + World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 0ae730e0-a9a8-4576-afaa-d1db6399d5a2 + +If you look in the input file you'll see that the simulation duration was set +to 10. This is why "Hello, World!" is printed ten times. diff --git a/_sources/arche/index.rst.txt b/_sources/arche/index.rst.txt new file mode 100755 index 000000000..62cce1128 --- /dev/null +++ b/_sources/arche/index.rst.txt @@ -0,0 +1,123 @@ +|Cyclus| Archetype Developer Guide +=================================== + +.. raw:: html + + + +
+ +.. image:: /astatic/antipode-bike.jpg + :align: center + :width: 300px + :alt: http://www.polyvore.com/cgi/img-thing?.out=jpg&size=l&tid=9361427 + +.. raw:: html + + + +Welcome! + +You are here because you have made (or are making) the transition from wanting +to run simulations to wanting to dig in and start dictating agent logic and +behavior on a more fundamental level. Perhaps existing archetypes are +insufficient for your needs, perhaps you are curious as to how it all works, or +are a devilishly handsome thrill-seeker. Whatever your reasons, you have come +to the right place! + +This guide assumes that you have |cyclus| installed, are familiar with running +simulations and understand user-level concepts. + +To get started please follow the instructions in :doc:`hello_world_cpp`. + +.. raw:: html + +
+ +Installation +------------- + +.. toctree:: + :maxdepth: 1 + + ../user/install + +Hello World +----------------- + +.. toctree:: + :maxdepth: 1 + + hello_world_cpp + tour_cpp + hello_world_py + + +Writing Agents & Modules +------------------------ + +Tutorial +++++++++ + +.. toctree:: + :maxdepth: 1 + + tutorial_cpp/index + tutorial_py/index + +Building, Installing and Testing [C++] +++++++++++++++++++++++++++++++++++++++ + +.. toctree:: + :maxdepth: 1 + + cmake + cycpp + testing + +Interfacing with the |Cyclus| Kernel +++++++++++++++++++++++++++++++++++++ + +.. toctree:: + :maxdepth: 1 + + timestep + resources + dre + dbtypes + custom_tables + errors + logger + cli + +A Word About Style +++++++++++++++++++ +Having a consistent style in your code is important. Python has a great style +guide encapsulated in `PEP8 `_. As +our code base is mostly C++, the kernel development team follows the `Google C++ +Style Guide `_ +(GCSG) as closely as possible, and we invite you to as well! A notable (and +required) exception to the GCSG used in |Cyclus| and Cycamore :term:`archetypes +` is the use of preprocessor-aware private member variables without a +trailing underscore, due to consistency requirements across input files, +implementation, and databases. Happy (well-styled) coding! + +Under the Hood +------------------------------ + +.. toctree:: + :maxdepth: 1 + + sim_init + dynamic_loading + decay +.. cyclus_env +.. materials_and_isotopes + +|Cyclus| Toolkit +---------------- + +.. toctree:: + :maxdepth: 1 + + toolkit diff --git a/_sources/arche/logger.rst.txt b/_sources/arche/logger.rst.txt new file mode 100755 index 000000000..487d4bca7 --- /dev/null +++ b/_sources/arche/logger.rst.txt @@ -0,0 +1,96 @@ +.. _logging: + +Logging +======================= + +.. code-block:: bash + + LOG(LogLevel level, std::string prefix) + +Built-in logging functionality has been provided to aid debugging. To use the +logger, you must include the *Logger.h* header file. `std::cout` statements +should be generally avoided. The `LOG(level, prefix)` macro should be used +for all logging/debugging needs. The LOG macro uses the Logger class to +provide this functionality. The Logger class should generally not be accessed +directly. The macro returns a string stream object that can be used exactly +as `std::cout` for printing output. Streamed in content is flushed to stdout +as soon as execution passes beyond the terminating semi-colon of the log +statement. + +A brief description of when to use which log level is given with the LogLevel +enum doxygen documentation. The following is a summary: + + * LEV_ERROR: Use for errors that require model code or input file + modification/fixing (use extremely sparingly) + + * LEV_WARN: Use to report questionable simulation state (use extremely + sparingly) + + * LEV_INFO1: Information helpful for simulation users and developers alike - + least verbose. + + * LEV_INFO[2, 3, 4] + + * LEV_INFO5: Information helpful for simulation users and developers alike - + most verbose. + + * LEV_DEBUG1: debugging information - least verbose + + * LEV_DEBUG[2, 3, 4] + + * LEV_DEBUG5: debugging information - most verbose + +Developers working on agents set the LOG prefix argument to a unique +archetype/agent-specific identifier (up to 6 characters long). This will allow +developers to more easily filter the logger output in order to isolate +information most relevant to their work. + +This macro does a check on the given LogLevel 'level' argument; if the +specified level is not higher than or equal to the report-level cutoff, the +macro does nothing, limiting the performance impact of logging statements. + +.. warning:: + + Do NOT place any state-changing expressions with the LOG + macro as they may not run if the report level excludes the specified LogLevel. + +.. note:: The Python interface should use the Python standard library logging system. + +Examples +-------- + +.. code-block:: cpp + + #include "Logger.h" + + void myfunc() { + + LOG(LEV_ERROR, "prefix") << "This is my error statement. " + << "and more info..."; + + LOG(LEV_DEBUG2, "prefix") << "This is my first debug statement. " + << "and more info..."; + LOG(LEV_DEBUG1, "prefix") << "This is another debug statement. " + << "and more info..."; + } + +The command-line specified verbosity is used to determine the logger +report-cutoff. Available levels are described in the LogLevel enum. In the +above example if the command line verbosity were set to *LEV_DEBUG1*, the +first and third statements would print, while the second would not. Output +would be something like this:: + + ERROR (prefix): This is my error statement. and more info... + DEBUG1(prefix): This is another debug statement. and more info... + +Any expression placed with a log statement that is not printed will not be +executed. An example of what NOT to do follows: + +.. code-block:: cpp + + LOG(LEV_DEBUG2, "module name") << "The expression myobject.setName(newname): " + << myobject.setName(newname) + << " might not ever execute" + << " depending on the verbosity level."; + + diff --git a/_sources/arche/resources.rst.txt b/_sources/arche/resources.rst.txt new file mode 100755 index 000000000..cf3ff36f4 --- /dev/null +++ b/_sources/arche/resources.rst.txt @@ -0,0 +1,392 @@ +Resources +========== + +One of the defining features of |Cyclus| among other fuel cycle simulators is +the treatment of resources/materials as discrete, quantized objects that can +be traded and tracked throughout the simulation. + +A primary motivation for discrete and quantized materials is the ability to +study the flow of material and the attribution of those materials through +prior ownership. One example is that of a nuclear fuel assembly. A nuclear +fuel assembly for a given reactor has a clear definition of material +properties (including mass) can be treated as a single unit. + +The |Cyclus| core provides two types of Resources that can be used/manipulated +by agents: + +* Material - a generic material object comprised of a mass and nuclide + composition. + +* Product - a general resource comprised of a quantity of a custom specified + quality/units. + +Conceptually, a resource can be anything that might be an interesting traded +item (e.g., electricity, money, or workers). By default, all changes to +resource objects (including creation) are tracked and recorded in the +database. Because of this, agents should handle resources carefully. For +more details about this, see :ref:`tracked-untracked`. + +In C++, all resource objects are created and managed as pointer types. For +convenience, each of the classes related to resources have a special pointer +type defined. In Python, they each have their own class that this available +in the ``cyclus.typesystem`` module. + +**C++:** + +.. code-block:: c++ + + cyclus::Resource::Ptr r; + cyclus::Product::Ptr p; + cyclus::Material::Ptr m; + +**Python:** + +.. code-block:: python + + import cyclus.typesystem as ts + ts.Resource + ts.Product + ts.Material + +These pointer types should be always be used instead of plain class instances +or raw pointers. The following sections describe basic creation and +manipulation of resource objects. The |Cyclus| kernel deals with resources in +terms of the ``cyclus::Resource`` superclass. So it will sometimes be +necessary to cast down to the appropriate resource subclass. |Cyclus| provides +an overloaded ResCast function for casting convenience: + +**C++:** + +.. code-block:: c++ + + // r is a Material object stored in a cyclus::Resource::Ptr var + cyclus::Material::Ptr m = cyclus::ResCast(r); + + // ResCast works on vectors too + std::vector rs; + ... + std::vector ps = cyclus::ResCast(rs); + +In Python, the situation is much simpler and you should only need to use ``Product`` and +``Material`` directly. They both inherit from ``Resource``. + + +Product Resources +------------------- + +Products in |Cyclus| have a quantity (no particular units) and a quality. +The quality is a ``std::string`` (C++) or ``str`` (Python) that describes what +the product is. A product's quality might be "apples", "kg apples", etc. Product +resources with different qualities may NOT be combined together. + +There are 3 basic operations that can be performed on product resources +(examples follow): + +* Create +* Extract +* Absorb + +**C++:** + +.. code-block:: c++ + + // create a "grapes" product holding 100 grapes. + cyclus::Product::Ptr p1 = cyclus::Product::Create(this, 100, "grapes"); + + // extract 7 grapes from p1 + cyclus::Product::Ptr p2 = p1->Extract(7); + // p1 now has 93 grapes + + // combine p2 back into p1 + p1->Absorb(p2); + // p2 now has 0 grapes. p1 has 100 grapes. + + +**Python:** + +.. code-block:: python + + # create a "grapes" product holding 100 grapes. + p1 = ts.Product.create(100, "grapes") + + # extract 7 grapes from p1 + p2 = p1.extract(7) + # p1 now has 93 grapes + + # combine p2 back into p1 + p1.absorb(p2) + # p2 now has 0 grapes. p1 has 100 grapes. + + +Material Resources +------------------- +Materials in |Cyclus| have a mass and an associated nuclide composition. The +composition is represented by a ``cyclus::Composition`` object (C++) or dict of +nuclide keys (str or int), float values (Python). Material +quantity is always represented in units of kg. Agents can either create a +composition manually (see the *Compositions* section below) or acquire one from +their Context which holds all recipes defined as part of the +simulation input. + +There are 4 basic operations that can be performed on material resources +(examples follow): + +* Create +* Extract [Qty/Comp] +* Absorb +* Transmute +* Decay (EXPERIMENTAL) - which is a special case of the Transmute operation + +**C++:** + +.. code-block:: c++ + + cyclus::Composition::Ptr c1 = context()->GetRecipe("nat_u"); + cyclus::Composition::Ptr c2 = context()->GetRecipe("enriched_u"); + + // create a 100 kg material from the nat_u recipe defined in the input file + cyclus::Material::Ptr m1 = cyclus::Material::Create(this, 100, c1); + + // extract 1 kg of enriched U from m1 + cyclus::Material::Ptr m2 = m1->ExtractComp(1, c2); + // mass of m1 is now 99 kg and its composition has changed + + // extract 1 kg from m1 of whatever composition it is + cyclus::Material::Ptr m3 = m1->ExtractQty(1); + // mass of m1 is now 98 kg and its composition. m1 and m3 have the same composition + + // combine m2 and m3 back into m1 + m1->Absorb(m2); + m1->Absorb(m3); + // m2 and m3 now have mass 0 kg. m1 has mass 100 kg with its original nat_u composition + + // decay composition m1 up to the current time step (EXPERIMENTAL) + m1->Decay(); // EXPERIMENTAL + +**Python:** + +.. code-block:: python + + c1 = self.context.get_recipe("nat_u") + c2 = self.context.get_recipe("enriched_u") + + # create a 100 kg material from the nat_u recipe defined in the input file + m1 = ts.Material.create(self, 100, c1) + + # extract 1 kg of enriched U from m1 + m2 = m1.extract_comp(1, c2) + # mass of m1 is now 99 kg and its composition has changed + + # extract 1 kg from m1 of whatever composition it is + m3 = m1.ExtractQty(1) + # mass of m1 is now 98 kg and its composition. m1 and m3 have the same composition + + # combine m2 and m3 back into m1 + m1.absorb(m2) + m1.absorb(m3) + # m2 and m3 now have mass 0 kg. m1 has mass 100 kg with its original nat_u composition + + # decay composition m1 up to the current time step (EXPERIMENTAL) + m1.decay() # EXPERIMENTAL + + +.. warning:: + + Decay functionality as currently implemented is experimental and may not + be correct. + +Compositions in C++ +++++++++++++++++++++ + +A ``cyclus::Composition`` is a massless, immutable nuclide composition. +Because it is immutable, a mutable ``cyclus::CompMap`` must be populated in +order to create a composition: + +**C++:** + +.. code-block:: c++ + + cyclus::CompMap m; + m[922350000] = 5; + m[922380000] = 95; + + // 5% U235, 95% U238 by mass + cyclus::Composition::Ptr c1 = cyclus::Composition::CreateFromMass(m); + + // 5% U235, 95% U238 by atom fraction + cyclus::Composition::Ptr c2 = cyclus::Composition::CreateFromAtom(m); + +Note that the ``cyclus::CompMap`` above has no notion of mass. Only the +relative nuclide ratios matter. Also notable is that ``c1`` and ``c2`` in the +above example have different compositions. + +Because compositions are immutable, it is desirable for performance and +database space reasons to avoid as much as possible creating multiple +compositions from equivalent ``cyclus::CompMap`` objects. Reusing +``cyclus::Composition`` objects helps avoid duplicate records in the +database and redundant decay calculations. + + +Compositions in Python ++++++++++++++++++++++++ +Compositions in Python are much simplier than in C++. They are represented by a simple +dict of nuclides to values. When a Material is created, you have to declare whether +the composition has a mass or atom basis. By default it has a mass basis, though +you may pass in the string ``"atom"`` to obtain an atom basis. + +**Python:** + +.. code-block:: python + + # 5% U235, 95% U238 by mass + m = {922350000: 5, 922380000: 95} + mat_mass = ts.Material.create_untracked(10, m) + + # 5% U235, 95% U238 by atom fraction + a = {"U235": 5, "U238": 95} + mat_atom = ts.Material.create_untracked(10, a, basis="atom") + + +.. _resource-ids: + +Resource IDs +--------------- +Every resource object has 3 different IDs. One of them, the ``qual_id``, is +generally not of use to agent developers and can be ignored. The other two +serve two different purposes, and it is important to understand their +difference: + +* ``state_id``: A unique identifier associated with the entire state of the + resource object. Any time a resource's state changes in any way (mass, + composition, etc.) this ID will be updated to a new, unique value + associated with the new state. When recording resource-related information + to the database in custom tables, this ID should generally be used. + +* ``obj_id``: A unique identifier associated with the resource object + instance. This ID does not ever change for the life of a resource instance. + Only newly created resource objects get new obj_id's. This ID should be + used when using resources as std::map keys and in other data structures when + resource objects need to be associated with some other information. + +Here are some examples of how these IDs work: + +**C++:** + +.. code-block:: c++ + + cyclus::Product::Ptr p1 = cyclus::Product::Create(this, 10, "bananas"); + // p1 gets new separate state_id and obj_id + + cyclus::Product::Ptr p2 = p1->ExtractQty(3); + // p1 gets new state_id and keeps same obj_id + // p2 gets new separate state_id and obj_id + + p1->Absorb(p2); + // p1 gets new state_id and keeps same obj_id + // p2 gets new state_id and keeps same obj_id + + cyclus::Product::Ptr p1_dup = p1; + // no new resource object is created, p1 and p1_dup point to same resource object + // p1 keeps same state_id and same obj_id + // p1 and p1_dup have idential state_id's + // p1 and p1_dup have idential obj_id's + + // want to associate some label with resource objects? - use the obj_id: + std::map rsrc_labels; + rsrc_labels[p1->obj_id()] = "fruit"; + rsrc_labels[p2->obj_id()] = "fruit"; + ... + +**Python:** + +.. code-block:: python + + # p1 gets new separate state_id and obj_id + p1 = ts.Product.create(self, 10, "bananas") + + # p1 gets new state_id and keeps same obj_id + # p2 gets new separate state_id and obj_id + p2 = p1.extract_qty(3) + + # p1 gets new state_id and keeps same obj_id + # p2 gets new state_id and keeps same obj_id + p1.absorb(p2) + + # no new resource object is created, p1 and p1_dup point to same resource object. + # In Python this is just an increase in the refcount anyway. + # p1 keeps same state_id and same obj_id + # p1 and p1_dup have idential state_id's + # p1 and p1_dup have idential obj_id's + p1_dup = p1 + + # want to associate some label with resource objects? Use the obj_id. + rsrc_labels = {} + rsrc_labels[p1.obj_id] = "fruit" + rsrc_labels[p2.obj_id] = "fruit" + ... + +.. warning:: + + When associating information with resources like the ``rsrc_labels`` + example above, you should **NEVER** use pointers (e.g. + ``std::map``). Pointers are unstable + and change across simulation snapshot+restart. + + +.. _tracked-untracked: + +Tracked and Untracked Resources +--------------------------------- +All changes to normal resource objects (including creation, splitting, +trasmutation, etc.) are tracked and recorded in the database. By default, all +resources are **tracked resources**. Because of this, agents should handle +resources carefully, being conscious of mass conservation among other things. +Anything done with resources is recorded in the database as having *actually* +happened in the simulation. If a new resource is created, it is instantly +recorded in the database as being a part of an agent's real/actual inventory. +Placeholder or "dummy" resources can also be created if necessary. No +information about these resources is recorded in the simulation database and +they are referred to as **untracked resources**. An agent's most common (and +likely only) need for untracked resources occurs when communicating details +about a desired/available resources for requests/bids during resource +exchange. Here untracked resources fulfill a communication roll only. + +Just like the functions for creating trakced resources, there are +corresponding function for creating both untracked materials and untracked +products: + +**C++:** + +.. code-block:: c++ + + cyclus::Composition::Ptr c = context()->GetRecipe("enriched_u"); + + // create an untracked 100 kg material from c (the enriched_u recipe) + cyclus::Material::Ptr m1 = cyclus::Material::CreateUntracked(100, c); + + // create an untracked "grapes" product holding 100 grapes. + cyclus::Product::Ptr p1 = cyclus::Product::CreateUntracked(100, "grapes"); + + // nothing about m1 and p1 will ever be recorded in the output data. + + +**Python:** + +.. code-block:: python + + c = self.context.get_recipe("enriched_u") + + # create an untracked 100 kg material from c (the enriched_u recipe) + m1 = ts.Material.create_untracked(100, c) + + # create an untracked "grapes" product holding 100 grapes. + p1 = ts.Product.create_untracked(100, "grapes") + + # nothing about m1 and p1 will ever be recorded in the output data. + +.. warning:: + + When a need for placeholder, dummy, or otherwise untracked + resource arises, use "untracked" resources. Do NOT create tracked + resources to use in resource exchange requests and bids. + diff --git a/_sources/arche/sim_init.rst.txt b/_sources/arche/sim_init.rst.txt new file mode 100755 index 000000000..c9e09d0de --- /dev/null +++ b/_sources/arche/sim_init.rst.txt @@ -0,0 +1,42 @@ +Initialization and Restart +============================ +|Cyclus| has built-in functionality for simulation snapshotting and restart. +All simulations are initialized from the database. In order to support +running from XML input files, the |Cyclus| kernel translates the input file +contents into the database and then initializes the simulation from the +database. In order for this to work correctly, agents must be able to record +the entirety of their internal state to the database and able to restore that +state exactly. The ``cyclus::Agent`` class provides a group of functions in +support of this functionality that must all be implemented carefully and +consistently. If possible, the :doc:`Cyclus preprocessor ` should be +used to automate the generation of code for the following functions: + +.. code-block:: c++ + + void InfileToDb(InfileTree* tree, DbInit di); + void InitFrom(cyclus::QueryableBackend*); + void InitInv(cyclus::Inventories& invs); + cyclus::Inventories SnapshotInv(); + void Snapshot(cyclus::Agent*); + std::string schema(); + Json::Value annotations(); + cyclus::Agent* Clone(); + void InitFrom(cyclus::Agent*); + +When the preprocessor isn't sufficient, read the `API documents +`_ for the functions +listed above VERY CAREFULLY. There are also a few other functions related to +initialization that are important to understand well: + +.. code-block:: c++ + + void Build(cyclus::Agent* parent); + void EnterNotify(); + void BuildNotify(cyclus::Agent* child); + void Decommission(cyclus::Agent* child); + +.. warning:: + + The functions mentioned on this page (except ``void InitFrom(cyclus::Agent*)``) + should NEVER be invoked directly by agents. + diff --git a/_sources/arche/testing.rst.txt b/_sources/arche/testing.rst.txt new file mode 100755 index 000000000..49aed51c5 --- /dev/null +++ b/_sources/arche/testing.rst.txt @@ -0,0 +1,373 @@ + +.. _testing: + +Testing and Debugging Archetypes +================================ + +Overview +-------- + +Writing `unit tests `_ for your +module is a prerequisite for its addition to any |cyclus| library, but it's +really a `good idea anyway +`_. + +|cyclus| makes use of the `Google Test +`_ framework. The `primer +`_ is recommended as an +introduction to the fundamental concepts of unit testing with Google Test. +Seriously, if you're unfamiliar with unit testing or Google Test, check out +the primer. + +Unit Tests Out of the Box +------------------------- + +The |cyclus| dev team provides a number of unit tests for free (as in +beer). Really! You can unit test your :term:`archetype` immediately to confirm +some basic functionality with the :term:`cyclus kernel`. We provide basic unit +tests for any class that inherits from one of: + +* ``cyclus::Agent`` +* ``cyclus::Facility`` +* ``cyclus::Institution`` +* ``cyclus::Region`` + +Note that ``cyclus::Agent`` is the base class for any object that acts as an +:term:`agent` in the simulation, so every archetype can invoke those unit tests. + +In order to get the provided unit tests in your archetype's tests, a few extra +lines must be added to your ``*_tests.cc`` file. For instance, the +``TutorialFacility`` in the :ref:`hello_world_cpp` example with the file structure +outline in :ref:`cmake_build` adds the following lines to +``tutorial_facility_tests.cc`` to get all of the free ``cyclus::Agent`` and +``cyclus::Facility`` unit tests: :: + + #include "tutorial_facility.h" + #include "facility_tests.h" + #include "agent_tests.h" + + #ifndef CYCLUS_AGENT_TESTS_CONNECTED + int ConnectAgentTests(); + static int cyclus_agent_tests_connected = ConnectAgentTests(); + #define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected + #endif // CYCLUS_AGENT_TESTS_CONNECTED + + cyclus::Agent* TutorialFacilityConstructor(cyclus::Context* ctx) { + return new TutorialFacility(ctx); + } + + INSTANTIATE_TEST_CASE_P(TutorialFac, FacilityTests, + ::testing::Values(&TutorialFacilityConstructor)); + + INSTANTIATE_TEST_CASE_P(TutorialFac, AgentTests, + ::testing::Values(&TutorialFacilityConstructor)); + +The above lines can be specialized to your case by replacing ``TutorialFac`` with +an appropriate moniker (anything that uniquely identifies your unit test +name). Also, if you're subclassing from ``cyclus::Institution`` or +``cyclus::Region``, replace all instances of facility in the above example with +the institution or region, respectively. + +Unit Test Example +----------------- + +Now we will provide an example of a very simple :term:`archetype` that keeps +track of how many :term:`ticks ` it has experienced. We'll call it +``TickTracker``. + +This tutorial assumes that you have a directory setup like that described in +:ref:`hello_world_cpp`, namely that there is a `src` directory in which +:term:`archetype` source files are housed and a `install.py` file that will +install them on your system. + +Make a file called ``tick_tracker.h`` in the ``src`` directory that has the +following lines: + +.. code-block:: cpp + + #include "cyclus.h" + + class TickTracker : public cyclus::Facility { + public: + TickTracker(cyclus::Context* ctx); + + #pragma cyclus + + /// increments n_ticks + virtual void Tick(); + + /// no-op + virtual void Tock() {}; + + /// query now many ticks the agent has experienced + inline int n_ticks() const {return n_ticks_;} + + private: + int n_ticks_; + }; + +Next, make a file called ``tick_tracker.cc`` in the ``src`` directory that has the +following lines: + +.. code-block:: cpp + + #include "tick_tracker.h" + + // we have to call the base cyclus::Facility class' constructor + // with a context argument + TickTracker::TickTracker(cyclus::Context* ctx) : n_ticks_(0), cyclus::Facility(ctx) {}; + + // tick experienced! + void TickTracker::Tick() {n_ticks_++;} + +Now, make a file called ``tick_tracker_tests.cc`` in the ``src`` directory that +has the following lines: + +.. code-block:: cpp + + // gtest deps + #include + + // cyclus deps + #include "facility_tests.h" + #include "agent_tests.h" + #include "test_context.h" + + // our deps + #include "tick_tracker.h" + + // write a unit test of our own + TEST(TickTracker, track_ticks) { + cyclus::TestContext ctx; + TickTracker fac(ctx.get()); + EXPECT_EQ(0, fac.n_ticks()); + fac.Tick(); + EXPECT_EQ(1, fac.n_ticks()); + fac.Tick(); + EXPECT_EQ(2, fac.n_ticks()); + } + + // get all the basic unit tests + #ifndef CYCLUS_AGENT_TESTS_CONNECTED + int ConnectAgentTests(); + static int cyclus_agent_tests_connected = ConnectAgentTests(); + #define CYCLUS_AGENT_TESTS_CONNECTED cyclus_agent_tests_connected + #endif // CYCLUS_AGENT_TESTS_CONNECTED + + cyclus::Agent* TickTrackerConstructor(cyclus::Context* ctx) { + return new TickTracker(ctx); + } + + INSTANTIATE_TEST_CASE_P(TicTrac, FacilityTests, + ::testing::Values(&TickTrackerConstructor)); + + INSTANTIATE_TEST_CASE_P(TicTrac, AgentTests, + ::testing::Values(&TickTrackerConstructor)); + +Add the following lines to the ``src/CMakeLists.txt`` file: :: + + INSTALL_CYCLUS_STANDALONE("TickTracker" "tick_tracker" "tutorial") + +Now we're ready to install the ``TickTracker`` module and run its tests. If you +haven't already, now is a good time to add the ``$CYCLUS_INSTALL_PATH`` to your +``PATH`` environment variable (|cyclus|' ``install.py`` defaults to +``~/.local``). Next, from your top level directory (where your ``install.py`` +file is), run: + +.. code-block:: bash + + $ ./install.py + $ TickTracker_unit_tests + +Which results in: :: + + [==========] Running 8 tests from 3 test cases. + [----------] Global test environment set-up. + [----------] 1 test from TickTracker + [ RUN ] TickTracker.track_ticks + [ OK ] TickTracker.track_ticks (19 ms) + [----------] 1 test from TickTracker (20 ms total) + + [----------] 5 tests from TicTrac/AgentTests + [ RUN ] TicTrac/AgentTests.Clone/0 + [ OK ] TicTrac/AgentTests.Clone/0 (8 ms) + [ RUN ] TicTrac/AgentTests.Print/0 + [ OK ] TicTrac/AgentTests.Print/0 (9 ms) + [ RUN ] TicTrac/AgentTests.Schema/0 + [ OK ] TicTrac/AgentTests.Schema/0 (9 ms) + [ RUN ] TicTrac/AgentTests.Annotations/0 + [ OK ] TicTrac/AgentTests.Annotations/0 (15 ms) + [ RUN ] TicTrac/AgentTests.GetAgentType/0 + [ OK ] TicTrac/AgentTests.GetAgentType/0 (8 ms) + [----------] 5 tests from TicTrac/AgentTests (49 ms total) + + [----------] 2 tests from TicTrac/FacilityTests + [ RUN ] TicTrac/FacilityTests.Tick/0 + [ OK ] TicTrac/FacilityTests.Tick/0 (9 ms) + [ RUN ] TicTrac/FacilityTests.Tock/0 + [ OK ] TicTrac/FacilityTests.Tock/0 (8 ms) + [----------] 2 tests from TicTrac/FacilityTests (17 ms total) + + [----------] Global test environment tear-down + [==========] 8 tests from 3 test cases ran. (86 ms total) + [ PASSED ] 8 tests. + +Testing Resource Exchange +-------------------------- + +One of the most important things to test is your archetype's resource exchange +behavior. Does it request/receive the right kinds of material? Does it offer/sell +resources at the right time? One of the best ways to test this is to actually +run a simulation with your archetype. Cyclus comes with a mock simulation +environment that makes it easy to write these kinds of tests in a way that +works well with gtest. + +``MockSim`` is a helper for running full simulations entirely in-code without +having to deal with input files, output database files, and other pieces of +the full Cyclus stack. All you have to do is initialize a MockSim indicating +the archetype you want to test and the simulation duration. Then add any +number of sources and/or sinks to transact with your agent. They can have +specific recipes (or not) and their deployment and lifetime (before +decommissioning) can be specified too. Here is an example using the +agents:Source archetype in Cyclus as the tested agent: + +.. code-block:: c++ + + // Define a composition to use as a simulation recipe. + cyclus::CompMap m; + m[922350000] = .05; + m[922380000] = .95; + cyclus::Composition::Ptr fresh = cyclus::Composition::CreateFromMass(m); + + // Define our archetype xml configuration. + // This is the info that goes + // "<[archetype-name]>here" + // in the input file. + std::string config = + "enriched_u" + "fresh_fuel" + "10"; + + // Create and run a 10 time step mock simulation + int dur = 10; + cyclus::MockSim sim(cyclus::AgentSpec(":agents:Source"), config, dur); + sim.AddRecipe("fresh_fuel", fresh); // with one composition recipe + sim.AddSink("enriched_u") // and one sink facility + .recipe("fresh_fuel") // requesting a particular recipe + .capacity(5) // with a 5 kg per time step receiving limit + .Finalize(); // (don't forget to call this for each source/sink you add) + + sim.AddSink("enriched_u") // And another sink facility + // requesting no particular recipe + // and with infinite capacity + .start(3) // that isn't built until the 3rd timestep. + .Finalize(); + int agent_id = sim.Run(); // capture the ID of the agent being tested + +The parameters that can be set (or not) for each source/sink are: + +* ``recipe(std::string r)``: The recipe to request/provide. Default is none - + sources provide requested material, sinks take anything. + +* ``capacity(double cap)``: The per time step throughput/capacity limit for + the source/sink. Default is infinite. + +* ``start(int t)``: Time the source/sink is initially built. Default is time + step zero. + +* ``lifetime(int)``: The number of time steps the source/sink is deployed + until automatic decommissioning. Default is infinite (never decommissioned). + +For more details, you can read the `MockSim API docs `_. +Querying simulation results can be accomplished by getting a reference to the +in-memory database generated. Not all data that is present in normal +full-stack simulations is available. However, most of the key core tables are +fully available. Namely the Transactions, Composition, Resources, +ResCreators, AgentEntry, and AgentExit tables are available. Any +custom-tables created by the tested archetype will also be available. Here is +a sample query and test you might write using the gtest framework: + +.. code-block:: c++ + + // return all transactions where our source facility is the sender + std::vector conds; + conds.push_back("SenderId", "==", agent_id); + cyclus::QueryResult qr = sim.db().Query("Transactions", &conds); + int n_trans = qr.rows.size(); + EXPECT_EQ(10, n_trans) << "expected 10 transactions, got " << n_trans; + + // reconstruct the material object for the first transaction + int res_id = qr.GetVal("ResourceId", 0); + cyclus::Material::Ptr m = sim.GetMaterial(res_id); + EXPECT_DOUBLE_EQ(10, m->quantity()); + + // confirm composition is as expected + cyclus::toolkit::MatQuery mq(m); + EXPECT_DOUBLE_EQ(0.5, mq.mass(922350000)); + EXPECT_DOUBLE_EQ(9.5, mq.mass(922380000)); + +You can read API documentation for the `queryable database +`_ and +`query results +`_ for more +details. + +Debugging +---------- + +If exceptions are being thrown when you try to use your archetype in +simulations, you can turn off Cyclus' main exception handling/catching by +setting the environment variable ``CYCLUS_NO_CATCH=1`` when you run cyclus. +This will prevent exceptions from being caught resulting in a core-dump. You +can then use a debugger (e.g. gdb or lldb) to run the failing simulation and +investigate the source of the crash in more detail. Something like this: + +.. code-block:: bash + + $ CYCLUS_NO_CATCH=1 gdb --args cyclus my-failing-sim.xml + + GNU gdb (GDB) 7.11 + Copyright (C) 2016 Free Software Foundation, Inc. + ... + (gdb) run + ... + +Cyclus has the ability to dump extra information about a simulation run's +resource exchange into the database. This information can be +particularly helpful for debugging and verifying your archetype's behavior +with respect to resource exchange. To turn on this debugging, simply run +cyclus with the environment variable ``CYCLUS_DEBUG_DRE`` set to any non-empty +value: + +.. code-block:: bash + + $ CYCLUS_DEBUG_DRE=1 cyclus my-sim.xml + +The database will then contain two extra tables with several columns each: + +* **DebugRequests**: record of every resource request made in the simulation. + + - ``SimId``: simulation UUID + - ``Time``: time step of the request + - ``ReqId``, simulation-unique identifier for this request + - ``RequesterID``: ID of the requesting agent + - ``Commodity``: the commodity of the request + - ``Preference``: agent's preference for this particular request + - ``Exclusive``: true (non-zero) if this request is all-or-nothing (integral) + - ``ResType``: resource type (e.g. "Material", "Product") + - ``Quantity``: amount of the request + - ``ResUnits``: units of the request (e.g. kg) + +* **DebugBids**: record of every resource bid made in the simulation. + + - ``SimId``: simulation UUID + - ``ReqId``: simulation-unique identifier for the bid's request + - ``BidderId``: ID of the the bidding agent + - ``BidQuantity``: amount of thd bid + - ``Exclusive``: true(non-zero) if this request is all-or-nothing (integral) + +Note that some information about bids can be inferred from corresponding +requests. A bid's time, commodity, resource type, and units are all identical +to those of the corresponding request. + + diff --git a/_sources/arche/timestep.rst.txt b/_sources/arche/timestep.rst.txt new file mode 100755 index 000000000..cfc7fd2a6 --- /dev/null +++ b/_sources/arche/timestep.rst.txt @@ -0,0 +1,145 @@ +Time Step Execution +=================== + +A |cyclus| simulation is composed of discrete time steps, and each time step is +subdivided into phases. Phases come in two flavors: kernel phases and agent +phases. Kernel phases include actions that have either been registered to occur +with the |cyclus| kernel (e.g., building a new facility agent) or are driven by +the |cyclus| kernel (e.g., the Resource Exchange). Agent phases are points +within a given time step that allow agents to query the current simulation +environment and perform any agent-specific actions, such as scheduling a new +agent to be built or scheduling a current agent to be decommissioned. + +The list of phases in order is: + +* :ref:`build` (kernel) +* :ref:`tick` (agent) +* :ref:`exchng` (kernel) +* :ref:`tock` (agent) +* :ref:`decom` (kernel) + +Agent phases are invoked using a method call of the same name, e.g., + +**C++:** + +.. code-block:: c++ + + virtual void MyAgent::Tick() { + // perform agent-phase Tick's work + } + +**Python:** + +.. code-block:: python + + def tick(self): + # perform agent-phase tick's work, no return value + +Importantly, the order in which agents' agent-phase methods are invoked is *not +guaranteed*. In other words, the execution of any given phase is conceptually +occurring *simultaneously among agents*. + +The duration of a time step can be set to custom values by users when running +simulations. Archetypes must be coded with this in mind. One easy method for +supporting arbitrary time step duration is to make all time-related quantities +and configuration in the archetype operate on a per-time-step basis (e.g. +reactor cycle length measured in time steps instead of days or months). If +archetypes do have constraints on the time step duration (e.g. they only +support approximately 1-month time steps), then they should throw an +exception as early as possible (i.e. in their constructor). The time step +duration can be queried from an the simulation context: + +**C++:** + +.. code-block:: c++ + + virtual void MyAgent::Tick() { + ... + double discharge_qty = discharge_rate * context()->dt(); + ... + } + +**Python:** + +.. code-block:: python + + def tick(self): + ... + discharge_qty = self.discharge_rate * self.context.dt + ... + +.. _build: + +Build Phase +----------- + +In the Build phase, agents that have been scheduled to be built are entered into +the simulation. The entry process includes creating the agent (cloning from a +:term:`prototype`), connecting it with the :term:`parent agent` that originally +registered the build, and calling its ``Build`` virtual member function. The +parent is informed that a new child has been built via the ``cyclus::Agent``'s +``BuildNotify`` member function. + +Future builds can be scheduled by any :term:`agent` using the +``cyclus::Context``'s ``SchedBuild`` member function. A build cannot be +scheduled for the current time step, but a build can be scheduled for any +future time step. + +.. _tick: + +Tick Phase +---------- + +The Tick phase allows agents to analyze the current status of the simulation +(e.g., the current number of built facilities) and perform any actions they so +choose *before* the execution of the Resource Exchange. For example, an agent +could schedule to build a new child agent or perform some process on its +available inventory of resources. + +.. _exchng: + +Dynamic Resource Exchange Phase +------------------------------- + +The Dynamic Resource Exchange phase is a :term:`kernel phase` in which the +supply and demand of resources is queried, solved, and the trading thereof is +executed. The supply and demand of each concrete resource type +(e.g. ``cyclus::Material`` and ``cyclus::Product``) are solved for +independently. A full discussion of this phase is provided in :ref:`dre`. + +.. _tock: + +Tock Phase +---------- + +The Tock phase allows agents to analyze the current status of the simulation +(e.g., the current number of built facilities) and perform any actions they so +choose *after* the execution of the Resource Exchange. For example, an agent +could schedule to decommission a child agent or perform some process on its +available inventory of resources. + +.. _decom: + +Decommission Phase +------------------ + +In the Decommission phase, agents that have been scheduled to be decommissioned +are removed from the simulation. The removal process includes informing the +:term:`parent agent` that one of its children is being decommissioned and +calling the child agent's ``Decommission`` function. The parent is informed that +a child is being decommissioned via the ``cyclus::Agent``'s ``DecomNotify`` +member function. + +Future decommissions can be scheduled by any :term:`agent` using the +``cyclus::Context``'s ``SchedDecom`` member function. A decommission can be +scheduled for the current time step or any future time step. + +Decommissioning occurs at the end of a time step. Therefore, an agent with a lifetime +of 1 would be decommissioned on the same time step it was built. The lifetime of an +agent can be back calculated by `1+exit_time-start_time`. + +Further Reading +--------------- + +For a more in depth (and historical) discussion, see `CEP 20 +`_. diff --git a/_sources/arche/toolkit.rst.txt b/_sources/arche/toolkit.rst.txt new file mode 100755 index 000000000..5194c28ec --- /dev/null +++ b/_sources/arche/toolkit.rst.txt @@ -0,0 +1,173 @@ +.. _toolkit: + +The (Experimental) Cyclus Toolkit +================================= +Currently in an experimental state, the |cyclus| toolkit aims to provide +functionality relevant to a variety of :term:`archetypes ` that do +not belong strictly in the :term:`cyclus kernel`. + +ResourceBuff +++++++++++++ +.. warning:: + + ResourceBuff will soon be deprecated in favor of ``ResBuf``. + +The ``cyclus::toolkit::ResourceBuff`` (C++) or ``cyclus.typesystem.ResourceBuff`` (Python) +class provides provides a canonical +methodology for dealing with collections of ``Resources``. +:term:`Archetypes ` in both |cyclus| and Cycamore make use of this +class. ``ResourceBuffs`` are usually used as member variables of +archetypes. The |Cyclus| preprocessor (C++) or |Cyclus| agents (Python) have special +handling for ``ResourceBuff`` +as it can generate all needed code for proper persistence and intiialization +of the buffer. For this to work, you must annotate the buffer member variable +with a Cyclus pre-processor :ref:`pragma ` (C++) or have a +special ``ResourceBuffInv`` class attribute (Python) in one of the +following ways: + +**C++:** + +.. code-block:: c++ + + // Option 1: minimum required annotation + #pragma cyclus var {} + cyclus::toolkit::ResourceBuff mybuf; + + // Option 2: you can set a specify buffer capacity + #pragma cyclus var {'capacity': 245.6} + cyclus::toolkit::ResourceBuff mybuf; + + // Option 3: you can reference another annotated member variable's value + // as the capacity + #pragma cyclus var {} + double buf_cap; + #pragma cyclus var {'capacity': 'buf_cap'} + cyclus::toolkit::ResourceBuff mybuf; + +**Python:** + +.. code-block:: python + + from cyclus.agents import Facility + import cyclus.typesystem as ts + + class MyFacility(Facility): + # Option 1: minimum required class attribute + mybuf = ts.ResourceBuffInv() + + # Option 2: you can set a specify buffer capacity + mybuf = ts.ResourceBuffInv(capacity=245.6) + + # Option 3: you can reference another annotated member variable's value + # as the capacity + buf_cap = ts.Double() + mybuf = ts.ResourceBuffInv(capacity='buf_cap') + +You can read the `ResourceBuff API documentation +`_ for +more details on how to use the buffer. + +ResBuf +++++++++++++ +The ``cyclus::toolkit::ResBuf`` (C++) or ``cyclus.typesystem.ResBuf`` (Python) class +provides provides a canonical +methodology for dealing with collections of Resources. ``ResBufs`` +are usually used as member variables of archetypes. The Cyclus preprocessor +has special handling for ``ResBuf`` as it can generate all needed code +for proper persistence and intiialization of the buffer. For this to work, +you must annotate the buffer member variable with a Cyclus pre-processor +:ref:`pragma ` (C++) or set a class attribute (Python) +in one of the following ways: + +**C++:** + +.. code-block:: c++ + + // Option 1: minimum required annotation + #pragma cyclus var {} + cyclus::toolkit::ResBuf mybuf; + + // Option 2: you can set a specify buffer capacity + #pragma cyclus var {'capacity': 245.6} + cyclus::toolkit::ResBuf mybuf; + + // Option 3: you can reference another annotated member variable's value + // as the capacity + #pragma cyclus var {} + double buf_cap; + #pragma cyclus var {'capacity': 'buf_cap'} + cyclus::toolkit::ResBuf mybuf; + +**Python:** + +.. code-block:: python + + from cyclus.agents import Facility + import cyclus.typesystem as ts + + class MyFacility(Facility): + # Option 1: minimum required annotation + mybuf = ts.ResBufMaterialInv() + + # Option 2: you can set a specify buffer capacity + mybuf = ts.ResBufMaterialInv(capacity=245.6) + + # Option 3: you can reference another annotated member variable's value + # as the capacity + buf_cap = ts.Double() + mybuf = ts.ResBufMaterialInv(capacity='buf_cap') + +You can read the `ResBuf API documentation +`_ for +more details on how to use the buffer. + +MatQuery [C++] +++++++++++++++ +The ``cyclus::toolkit::MatQuery`` class provides some easy-to-use functions that +interrogate the ``cyclus::Material`` object. For example, one can query the mass +or number of moles of a given nuclide. + +Enrichment [C++] +++++++++++++++++ +A number of functions are provided in ``toolkit/enrichment.h`` that assist in +enrichment-related calculations. Some highlights include a representation of +uranium assays in ``cyclus::toolkit::Assays``, as well as functions to calculate +feed, tails, and SWU quantity requirements. + +Commodity Recipe Context [C++] ++++++++++++++++++++++++++++++++ +The ``cyclus::toolkit::CommodityRecipeContext`` class provides a mapping between +commodities and recipes that can be updated as a simulation progresses. + +Symbolic Functions [C++] +++++++++++++++++++++++++ +The ``cyclus::toolkit::SymbolicFunction`` class and its derivatives provide an +object-oriented hierarchy to represent symbolic functions. Factory methods are +provided by the ``cyclus::toolkit::SymbFunctionFactory`` class. + +Agent Managed Classes [C++] ++++++++++++++++++++++++++++ +There are a number of interfaces provided in the |cyclus| toolkit that can be +used as either as `mixins `_ or as +composable, agent-managed state variables: + +* ``cyclus::toolkit::Builder``: an interface for adding information about agents + that can be built by the manager + +* ``cyclus::toolkit::BuildingManager``: an interface for making build decisions + based on supply, demand, and agents that can be built + +* ``cyclus::toolkit::CommodityProducer``: an interface for adding information + about commodities that can be produced by the manager + +* ``cyclus::toolkit::CommodityProducerManager``: an interface that allows an + agent to query a collection of ``cyclus::toolkit::CommodityProducers`` + +* ``cyclus::toolkit::SupplyDemandManager``: an interface for querying the supply + and demand on commodities + +Geographic Informasion System (GIS) Class [C++] ++++++++++++++++++++++++++++++++++++++++++++++++ + The ``cyclus::toolkit::GIS`` class provide an option to add geographic coordinates + of its friend classes. Haversine distance calculations between two facilities or + agents with GIS coordinates can be performed as well. diff --git a/_sources/arche/tour_cpp.rst.txt b/_sources/arche/tour_cpp.rst.txt new file mode 100755 index 000000000..a0ce51194 --- /dev/null +++ b/_sources/arche/tour_cpp.rst.txt @@ -0,0 +1,163 @@ +A Tour of Cycstub +================= + +This section will walk through the source files of the stub :term:`archetypes +` in `Cycstub `_. Cycstub provides +three stub archetypes: + +* ``StubFacility`` +* ``StubInstitution`` +* ``StubRegion`` + +We will walk through ``StubFacility``\ 's source specifically because its the +most complicated of the three. Before we begin, though, let's get a fresh copy +of Cycstub (or follow along on the `website +`_). + +**Getting cycstub via git:** + +.. code-block:: bash + + $ git clone https://github.com/cyclus/cycstub.git + $ cd cycstub + +**Getting cycstub via zip:** + +.. code-block:: bash + + $ curl -L https://api.github.com/repos/cyclus/cycstub/zipball > cycstub.zip + $ unzip cycstub.zip + $ mv cyclus-cycstub-* cycstub + $ cd cycstub + +Feel free to ``rm`` the cycstub directory when we're done (you can always get it +back!). + +StubFacility +------------ + +The ``StubFacility`` provides the minimal interface that an :term:`archetype` +that derives from ``cyclus::Facility`` must provide. We'll go through both the +header (``h``) and implementation (``cc``) files in conjunction, starting at the +top. + +``stub_facility.h`` has a single |cyclus|-based include + +.. code-block:: cpp + + #include "cyclus.h" + +which includes most :term:`cyclus kernel` headers as a convenience for new +:term:`archetype developers `. You're more than welcome to +include the specific kernel headers you need if you require a smaller +executable. + +Moving on in the header file we come to the class declaration + +.. code-block:: cpp + + class StubFacility : public cyclus::Facility { + +which simply states that the ``StubFacility`` inherits from ``cyclus::Facility``. + +We then come to the constructor declaration + +.. code-block:: cpp + + explicit StubFacility(cyclus::Context* ctx); + +and implementation + +.. code-block:: cpp + + StubFacility::StubFacility(cyclus::Context* ctx) + : cyclus::Facility(ctx) {}; + +The constructor takes a single ``cyclus::Context`` argument. The :term:`context` +is the mechanism by which :term:`agents ` can query and otherwise +communicate with the simulation environment. Because the base ``cyclus::Agent`` +class requires a ``cyclus::Context`` argument in its constructor, all derived +classes must pass the argument down its constructor chain, as ``StubFacility`` +does with its ``cyclus::Facility`` constructor above. + +Continuing with the header file, we next come to **the prime directive** + +.. code-block:: c++ + + #pragma cyclus + +In short, the prime directive allows an archetype developer to use the |cyclus| +preprocessor to autogenerate many member functions that are required for +|cyclus| features related to initialization and restart capabilities. For a +further explanation, see :ref:`cycpp`. + +The next line in ``stub_facility.h`` is also related to the preprocessor's +ability to help automate some documentation: + +.. code-block:: c++ + + #pragma cyclus note {"doc": "A stub facility is provided as a skeleton " \ + "for the design of new facility agents."} + +Again, ``#pragma cyclus note`` is explained further in :ref:`cycpp`. + +Continuing along, we reach the final three member functions, each of which are +defined on the base ``cyclus::Agent`` class and are overrode by the +``StubFacility``. + +str ++++ + +The declaration + +.. code-block:: c++ + + virtual std::string str(); + +and implementation + +.. code-block:: c++ + + std::string StubFacility::str() { + return Facility::str(); + } + +of the ``str`` method allows the ``StubFacility`` to customize its string +representation, which is printed at a variety of ``cyclus::Logger`` logging +levels, which is explained further in :doc:`/arche/logger`. + +Tick +++++ + +The declaration + +.. code-block:: c++ + + virtual void Tick(); + +and implementation + +.. code-block:: c++ + + void StubFacility::Tick() {} + +of the ``Tick`` member function allows the ``StubFacility`` to act during the +:term:`tick` :term:`agent phase`. + +Tock +++++ + +The declaration + +.. code-block:: c++ + + virtual void Tock(); + +and implementation + +.. code-block:: c++ + + void StubFacility::Tock() {} + +of the ``Tock`` member function allows the ``StubFacility`` to act during the +:term:`tock` :term:`agent phase`. diff --git a/_sources/arche/tutorial_cpp/cyclist.rst.txt b/_sources/arche/tutorial_cpp/cyclist.rst.txt new file mode 100755 index 000000000..1a9327844 --- /dev/null +++ b/_sources/arche/tutorial_cpp/cyclist.rst.txt @@ -0,0 +1,5 @@ + +Using the Cyclus GUI (Cyclist) with Your New Archetype +========================================================== + +foo \ No newline at end of file diff --git a/_sources/arche/tutorial_cpp/dre.rst.txt b/_sources/arche/tutorial_cpp/dre.rst.txt new file mode 100755 index 000000000..33511fe47 --- /dev/null +++ b/_sources/arche/tutorial_cpp/dre.rst.txt @@ -0,0 +1,5 @@ + +More Dynamic Resource Exchange Detail +======================================= + +foo \ No newline at end of file diff --git a/_sources/arche/tutorial_cpp/index.rst.txt b/_sources/arche/tutorial_cpp/index.rst.txt new file mode 100755 index 000000000..9b73e9bb0 --- /dev/null +++ b/_sources/arche/tutorial_cpp/index.rst.txt @@ -0,0 +1,43 @@ +Archetype Development Tutorial [C++] +==================================== +In this tutorial, we will work through a number of steps for creating a +Facility archetype for Cyclus. This tutorial assumes that the learner is +already reasonably familiar with programming in C++ and with the primary +vocabulary of Cyclus. We also assume that the learner has a Github account. + +Overview +--------- + +Through this tutorial, we will transform a copy of the Cycstub repository into +an open source Cyclus archetype module that includes an archetype to simulate +a very simple interim storage facility, named "Storage". Ultimately, this +facility will have the following characteristics, all definable by the user: + +* a fixed rate at which it can transfer material +* a minimum time that material stays in storage +* a fixed storage capacity + +This tutorial has the following steps: + +.. toctree:: + :maxdepth: 1 + + setup + state_var + toolkit + testing + input_files + +.. Given enough time, the following extra topics may be covered: + +.. toctree:: + :maxdepth: 1 + +.. cyclist +.. dre + +.. note:: + + If you ever see an error like ``ERROR(core ):SQL error [INSERT INTO + AgentState...`` simply remove the output database with ``$ rm + cyclus.sqlite`` and rerun the simulation diff --git a/_sources/arche/tutorial_cpp/input_files.rst.txt b/_sources/arche/tutorial_cpp/input_files.rst.txt new file mode 100755 index 000000000..2562274f1 --- /dev/null +++ b/_sources/arche/tutorial_cpp/input_files.rst.txt @@ -0,0 +1,314 @@ + +Making Input Files +=============================== + +In this lesson, we will: + +1. Make a basic input file +2. Run the file and analyze output +3. Make a more interesting input file +4. Run the file and analyze output + +Overview +---------- + +Cyclus uses XML as its input file format, and there is an extensive guide to +making input files on the `website +`_. Rather than getting into the +details of how to write input files, this lesson will focus instead on the +minimum information needed to get up and running with the Storage archetype. + +Make a Basic Input File +----------------------- + +The goal of this basic input file is to create the following facility set up. + +.. figure:: simple_cycle.svg + :width: 80 % + :align: center + + **Figure:** The target "cycle". + +Let's start with very simple dynamics, where the ``Source`` can send one unit of +fuel per time step, the ``Sink`` can take one unit of fuel per time step, and +the ``Storage`` stores fuel for one time step. + +First, make a new input file + +.. code-block:: console + + $ cp input/storage.xml input/basic.xml + +and open it with your favorite text editor. + +Add a Recipe ++++++++++++++ + +In this example, material is being transferred between facilities. As in real +life, in Cyclus, material must have some composition. For this example, we can +use an LEU-like composition. + +Add the following lines to the bottom of the input file (but before the close +tag ) + +.. code-block:: xml + + + LEU + mass + + U235 + 5 + + + U238 + 95 + + + +Adding New Archetypes ++++++++++++++++++++++ + +We need to add a ``Source`` archetype and a ``Sink`` archetype, which we can +find in the ``agents`` library of Cyclus. To do so, add the following lines to +the ```` block of your input file. + +.. code-block:: xml + + agentsSource + agentsSink + +The full block should now look like + +.. code-block:: xml + + + tutorialStorageStorage + tutorialTutorialRegionTutorialRegion + tutorialTutorialInstTutorialInst + agentsSource + agentsSink + + +Adding Prototypes ++++++++++++++++++ + +A configured archetype is called a *prototype* in Cyclus parlance. You can read +how to on the :ref:`cyclus_archetypes` and :ref:`cycamore_archetypes` +pages. + +Source +~~~~~~~~~~ + +Beginning with the Cyclus `Source +`_, you must, at +minimum, supply an entry for ```` and ````. This prototype +will also include a ```` entry. In this example, you want the +source facility to supply one unit of fuel per time step and you want it to be +connected to the ``incommod`` of the Storage prototype. Finally, let's name the +Source "FuelSource". + +Accordingly, add the following lines after the Storage prototype + +.. code-block:: xml + + + FuelSource + + + 1 + LEU + fuel + + + + +Sink +~~~~~~~~~~ + +Similarly, the Cyclus `Sink +`_, you must, at +minimum, supply an entry in the ```` tag and a ````. We +want a similar structure to the Source prototype, i.e., connection to the +Storage prototype and a demand for one unit of fuel per time step. We can also +name this Sink prototype "FuelSink". + +Accordingly, add the following lines after the Storage prototype + +.. code-block:: xml + + + FuelSink + + + 1 + + stored_fuel + + + + + +Storage +~~~~~~~~~ + +The Storage prototype is fine as it is. If you don't like the name +``OneFacility``, however, you are free to replace it with something more fitting +like ``FuelStorage``. + +.. warning:: + + Make sure to replace ``OneFacility`` everywhere though! + +Region & Institution +~~~~~~~~~~~~~~~~~~~~~~~ + +Deployment for facility agents must be declared in the input file. In order for +our source and sink to be deployed at the beginning of the simulation, they must +be added to the ````. Accordingly, add the following lines +below the ``OneFacility`` entry. Note that order here does not matter. + +.. code-block:: xml + + + FuelSink + 1 + + + FuelSource + 1 + + +So now, the full region and institution configuration should look something like + +.. code-block:: xml + + + + OneRegion + + + + + OneInst + + + OneFacility + 1 + + + FuelSink + 1 + + + FuelSource + 1 + + + + + + + + +Run the Basic File +-------------------- + +Run the file with a slightly higher verbosity + +.. code-block:: console + + $ cyclus -v 4 input/basic.xml + +.. note:: + + You'll get more helpful information for this run by upping the verbosity + from ``3`` to ``4``. + +What output do you see? Are things working as expected? + +You should see something like the following for a single time step + +.. code-block:: console + + INFO1(core ):Current time: 5 + INFO2(core ): Beginning Tick for time: 5 + INFO2(Storag): Quantity to be requested: 7 kg. + INFO2(Storag): Quantity to be offered: 1 kg. + INFO3(Sink ): FuelSink will request 1 kg of stored_fuel. + INFO3(Source): FuelSource will offer 1 kg of fuel. + INFO2(core ): Beginning DRE for time: 5 + INFO3(buypol): policy input (agent OneFacility-12): requesting 7 kg via 1 request(s) + INFO3(buypol): - one 7 kg request of fuel + INFO3(selpol): policy output (agent OneFacility-12): bidding out 1 kg + INFO3(selpol): - bid 1 kg on a request for stored_fuel + INFO3(selpol): policy output (agent OneFacility-12): sending 1 kg of stored_fuel + INFO3(buypol): policy input (agent OneFacility-12): got 1 kg of fuel + INFO2(core ): Beginning Tock for time: 5 + INFO2(Storag): The total inventory at time 5 is 1 kg of material. + INFO3(Sink ): FuelSink is holding 5 units of material at the close of month 5. + + +Make a More Interesting Input File +------------------------------------- + +The previous scenario employed very simple dynamics. A unit of material was sent +from the Source to Storage every time step. After the first time step, a unit of +material was also sent from Storage to the Sink every time step, having been +stored for the interim period. + +This consistent flow occurred because, given the storage time :math:`t_s`, +capacity :math:`c`, and throughput :math:`\tau`, the following relation is true + +.. math:: + + t_s < min(c, \tau) + +What happens when :math:`t_s > min(c, \tau)`? Let's find out! + +First, make a new input file + +.. code-block:: console + + $ cp input/basic.xml input/interesting.xml + +and open it with your favorite text editor. + +Update the Storage config block to look like + +.. code-block:: xml + + + + 10 + 5 + fuel + stored_fuel + 2 + + + +Note that now we have :math:`t_s = 5` and :math:`c = 2`. + +Run the Interesting File +-------------------------- + +Run the file + +.. code-block:: console + + $ cyclus -v 4 input/interesting.xml + +Exercise ++++++++++ + +Answer the following questions + +- When do trades occur? Why? +- How much material is in the Sink at the end of the simulation? Why? + +Exercise ++++++++++ + +Play with the all of the simulation parameters and get a feel for the various +dynamics of this scenario. \ No newline at end of file diff --git a/_sources/arche/tutorial_cpp/setup.rst.txt b/_sources/arche/tutorial_cpp/setup.rst.txt new file mode 100755 index 000000000..dc7a3f71d --- /dev/null +++ b/_sources/arche/tutorial_cpp/setup.rst.txt @@ -0,0 +1,134 @@ +Setup a New Project Based on Cycstub +============================================== + +In this lesson, we will: + +1. Do the tasks the the Cyclus Archetype Hello World! +2. Clean up the file system for the single storage facility +3. Install the storage facility +4. Run an input file that uses the new storage facility + +Follow the Hello Cyclus! Instructions +--------------------------------------------------- + +Follow all of the steps of :ref:`hello_world_cpp`. + +Make a Storage Facility +------------------------------------------ + +Next, make a new facility by copying the facility archetype from the Hello World! tutorial. + +Start by making sure you are in the correct directory + +.. code-block:: console + + $ cd ~/tutorial + +Then make the new archetype, updating all the files as needed + +.. note:: + + If you are on a Mac, replace all instances of ``sed -i`` with ``sed -i ''``. + +.. code-block:: console + + $ for file in `ls src/tutorial_facility*`; do cp "${file}" "${file/tutorial_facility/storage}"; done + $ sed -i "s/tutorial_facility/storage/g" src/storage* + $ sed -i "s/TutorialFacility/Storage/g" src/storage* + $ sed -i "s/TUTORIAL_FACILITY/STORAGE/g" src/storage* + +Finally, open -``src/CMakeLists.txt`` with your favorite text editor and add the +following line to the end of it + +.. code-block:: bash + + install_cyclus_standalone("Storage" "storage" "tutorial") + + +Install and Test +---------------------------------- + +Install the tutorial project + +.. code-block:: console + + $ ./install.py + +Run the unit tests + +.. code-block:: console + + $ Storage_unit_tests + +Make a new input file that is a copy of the test input file + +.. code-block:: console + + $ cp input/example.xml input/storage.xml + +Then change every instance of ``TutorialFacility`` with ``Storage``. This can be +done by hand or on the command line with + +.. code-block:: console + + $ sed -i "s/TutorialFacility/Storage/g" input/storage.xml + +Test the input file by running Cyclus + +.. code-block:: console + + $ cyclus -v 2 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 + diff --git a/_sources/arche/tutorial_cpp/state_var.rst.txt b/_sources/arche/tutorial_cpp/state_var.rst.txt new file mode 100755 index 000000000..78acfb0ab --- /dev/null +++ b/_sources/arche/tutorial_cpp/state_var.rst.txt @@ -0,0 +1,210 @@ +Adding State Variables +======================= + +In this lesson, we will: + +1. Add the necessary state variables to define this facility using the Cyclus + ``#pragma`` directives +2. Build and install the updated module +3. Modify the sample input file to include these variables + +Add State Variables with Cyclus #pragma +---------------------------------------------- + +The Cyclus preprocessor provides a ``#pragma`` that defines variables to +be part of the set of state variables and allows convenient annotations. + +First, we'll add the maximum monthly transfer capacity, called ``throughput``. +Open the file ``src/storage.h`` in your text editor. + +Immediately after the declaration of ``Tock()``, add the following: + +.. code-block:: c++ + + #pragma cyclus var { \ + "doc": "Maximum amount of material that can be transferred in or out each time step", \ + "tooltip": "Maximum amount of material that can be transferred in or out each time step", \ + "units": "kg", \ + "uilabel": "Maximum Throughput" \ + } + double throughput; + +Now, we'll add variables for the minimum amount of time that material is +stored and the input/output commodity names. + +.. code-block:: c++ + + #pragma cyclus var { \ + "doc": "Minimum amount of time material must be stored", \ + "tooltip": "Minimum amount of time material must be stored", \ + "units": "months", \ + "uilabel": "Storage Time" \ + } + int storage_time; + + #pragma cyclus var { \ + "tooltip": "Storage input commodity", \ + "doc": "Input commodity on which Storage requests material.", \ + "uilabel": "Input Commodity", \ + "uitype": "incommodity", \ + } + std::string incommod; + + #pragma cyclus var { \ + "tooltip": "Storage output commodity", \ + "doc": "Output commodity on which Storage offers material.", \ + "uilabel": "Output Commodity", \ + "uitype": "outcommodity", \ + } + std::string outcommod; + +Build and Install the Modified Module +--------------------------------------- + +To rebuild, reinstall, and test this module, just issue the same command as before: + +.. code-block:: console + + $ ./install.py + $ Storage_unit_tests + +Modify the Input File +------------------------- + +If you try to run the same input file with your modified module, you will get +errors because the sample input file no longer includes the necessary pieces +to define your module. It is missing the new variables. Try it: + +.. code-block:: console + + $ cyclus -v 2 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Entity: line 17: element Storage: Relax-NG validity error : Expecting an element throughput, got nothing + Entity: line 17: element Storage: Relax-NG validity error : Invalid sequence in interleave + Entity: line 17: element Storage: Relax-NG validity error : Element Storage failed to validate content + ERROR(core ):Document failed schema validation + +The simulation now fails because it does not match the schema. You can view the schema with + +.. code-block:: console + + $ cyclus --agent-schema tutorial:Storage:Storage + +Notice that you were able to take advantage of the input file validation simply by using the ``#pragma``. + +Our failed cyclus simulation produced an output file that will need to be deleted. + +.. code-block:: console + + $ rm cyclus.sqlite + +Now, we'll change that input file. Open the file ``input/storage.xml`` in +your text editor, and find the prototype configuration for the single facility +named "OneFacility" that looks like this. + +.. code-block:: xml + + + OneFacility + + + + + +We need to replace the ```` element with this: + +.. code-block:: xml + + + + 10 + 1 + fuel + stored_fuel + + + +Now we can try it again: + +.. code-block:: console + + $ cyclus -v 2 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 diff --git a/_sources/arche/tutorial_cpp/testing.rst.txt b/_sources/arche/tutorial_cpp/testing.rst.txt new file mode 100755 index 000000000..ca6cf9304 --- /dev/null +++ b/_sources/arche/tutorial_cpp/testing.rst.txt @@ -0,0 +1,135 @@ + +Adding a Test +================ + +In this lesson we will + +1. Write a unit test for the Storage archetype + +Overview +-------- + +Testing code is a fundamental `best practice +`_ of writing any kind of +software. While there are technically a few different `varieties +`_ of tests, this +lesson focuses on *unit tests*. + +Add a Test +----------- + +Cyclus uses the `GoogleTest `_ +testing framework. Using the stubs, Cyclus automatically provides you with some +basic archetype unit tests, specifically those that are in + +.. code-block:: console + + $ Storage_unit_tests + ... + [----------] 8 tests from TutorialFac/AgentTests + ... + [----------] 8 tests from TutorialFac/AgentTests (114 ms total) + + [----------] 3 tests from TutorialFac/FacilityTests + ... + [----------] 3 tests from TutorialFac/FacilityTests (44 ms total) + ... + +The goal of any good unit test is to define an initial state and expected final +state and then call a function and confirm that the observed final state matches +the expected final state. For the Storage facility, one such state transition is +as follows + +- **Initial State**: There is material in the ``input`` buffer +- **Function Call**: ``Tock()`` +- **Expected Final State**: The ``input`` buffer is empty and the inventory buffer + has increase by the same amount + +Begin by opening the file ``src/storage_tests.cc`` in your favorite text editor +and find the test for the ``Tock()`` function. It should look something like + +.. code-block:: c++ + + TEST_F(StorageTest, Tock) { + EXPECT_NO_THROW(facility->Tock()); + // Test Storage specific behaviors of the Tock function here + } + +You can set up the initial state by pushing a ``Material`` object to the +``input`` buffer. An easy way to make a ``Material`` object is to use the +``NewBlankMaterial()`` API. + +Add the following lines before the ``Tock()`` function call in the test + +.. code-block:: c++ + + double qty = 42; + facility->input.Push(cyclus::NewBlankMaterial(qty)); + +You can then test the test's initial condition + +.. code-block:: c++ + + EXPECT_DOUBLE_EQ(facility->input.quantity(), qty); + EXPECT_DOUBLE_EQ(facility->inventory.quantity(), 0); + +Then execute the Tock: + +.. code-block:: c++ + + EXPECT_NO_THROW(facility->Tock()); + +Next, add the test for the final state after the call to ``Tock()`` + +.. code-block:: c++ + + EXPECT_DOUBLE_EQ(facility->input.quantity(), 0); + EXPECT_DOUBLE_EQ(facility->inventory.quantity(), qty); + +Now your test should look like + +.. code-block:: c++ + + TEST_F(StorageTest, Tock) { + double qty = 42; + facility->input.Push(cyclus::NewBlankMaterial(qty)); + EXPECT_DOUBLE_EQ(facility->input.quantity(), qty); + EXPECT_DOUBLE_EQ(facility->inventory.quantity(), 0); + EXPECT_NO_THROW(facility->Tock()); + EXPECT_DOUBLE_EQ(facility->input.quantity(), 0); + EXPECT_DOUBLE_EQ(facility->inventory.quantity(), qty); + } + +Finally, build and test, same as it ever was + +.. code-block:: console + + $ ./install.py + $ Storage_unit_tests + +Exercise +--------- + +Can you come up with another unit test? + +.. note:: + + The ``Tock()`` test did not depend on any particular state. We always expect + the input-to-inventory transfer to take place, no matter what. Is that true + for your test? + + +Further Reading +---------------- + +After unit tests, the next step to take is testing your archetype in an actual +simulation. You can find more on the :ref:`testing` page. + +One of the best ways to learn is by example. The Cycamore repository has +`examples of running regression tests `_ +that include the full execution stack -- read an input file, +run a simulation, and test an output file. There are also `examples of integration tests +`_ +that utilize the new `MockSim +`_ +testing feature in Cyclus. diff --git a/_sources/arche/tutorial_cpp/toolkit.rst.txt b/_sources/arche/tutorial_cpp/toolkit.rst.txt new file mode 100755 index 000000000..b876e81d8 --- /dev/null +++ b/_sources/arche/tutorial_cpp/toolkit.rst.txt @@ -0,0 +1,732 @@ +Adding Buffers and Policies from the Toolkit +================================================= + +In this lesson, we will: + +1. Add ResBufs to track material inventories +2. Add Policies to manage the trading of material +3. Add inventory management logic +4. Change our log information to show the info about the inventories +5. Add a notion of total storage capacity + +Overview +-------------- + +Cyclus has a growing Toolkit of standard patterns that can be used by +archetype developers. There are many advantages to using the Toolkit patterns +rather than developing similar functionality yourself, typical of most code +reuse situations: + +* robustness - Toolkit patterns have been subjected to the Cyclus QA process +* time savings - It will take less time to learn how to use a Toolkit than it takes to develop your own +* improvements - You can benefit immediately from any improvements in the performance of the Toolkit pattern + +Code reuse is a critical best practice in all software development. + +One of the Toolkit patterns is a ``ResBuf``, providing a way to track an +inventory of ``Resource`` objects. There are also ``MatlBuyPolicy`` and +``MatlSellPolicy`` for managing the trading of ``Material`` objects. + +Add State Variables, Buffers, and Policies +------------------------------------------ + +All state variable additions should be included in ``src/storage.h`` below the +other state variables added previously. + + A ``ResBuf`` is available as a data type for another state variable, so we + simply have to add the following: + +.. code-block:: c++ + + /// this facility holds material in storage. + #pragma cyclus var {} + cyclus::toolkit::ResBuf inventory; + +This creates a state variable named ``inventory`` that is based on the +``cyclus::toolkit::ResBuf`` class. We'll explain how buffers and policies +work in just a moment. A ResBuf object has special handling by the +preprocessor, so it will not appear in the schema and therefore will not +appear in the Cycic UI either. + +Next, add two additional buffers + +.. code-block:: c++ + + /// a buffer for incoming material + #pragma cyclus var {} + cyclus::toolkit::ResBuf input; + + /// a buffer for outgoing material + #pragma cyclus var {} + cyclus::toolkit::ResBuf output; + +Now add the policies. Policies do not require any special handling, and +thus do not need a pragma + +.. code-block:: c++ + + /// a policy for requesting material + cyclus::toolkit::MatlBuyPolicy buy_policy; + + /// a policy for sending material + cyclus::toolkit::MatlSellPolicy sell_policy; + +There needs to be a mechansim for keeping track of when materials enter the +inventory. In order to utilize Cyclus' sophisticated restart capability, we must +choose a data structure that is compatible with the at least one of the Cyclus +output databases (see :ref:`dbtypes`). Given that requirement, an appropriate +data structure is a `list +`_. Accordingly, add the +following + +.. code-block:: c++ + + /// list for material entry times, providing a default lets this variable be + /// optional in an input file + #pragma cyclus var { \ + "default": [] \ + } + std::list entry_times; + +This requires another header file, so at the top of the storage.h file, after +``#include ``, add another include + +.. code-block:: c++ + + #include + +Finally, check that everything works by installing and testing + +.. code-block:: console + + $ ./install.py + $ Storage_unit_tests + +You can also confirm that everything still works with running the simulation: + +.. code-block:: console + + $ cyclus -v 3 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 + + +Add Implementation Logic +----------------------------- + +The goal of a storage facility is to ask for material up to some limit, store it +for an amount of time, and then send it on to any interested parties. This can +be implemented in Cyclus by utilizing the Toolkit objects stated above. The buy +and sell policies will automatically fill and empty the input and output +buffers, respectively. A concept of material flow through the facility is +shown below. + +.. figure:: storage_diagram.svg + :width: 75 % + :align: center + + **Figure:** Material flow through a Storage facility. Green arrows occur + **before** the DRE (during the Tick). Yellow arrows occur during the + DRE. Brown arrows occur **after** the DRE (during the Tock). + +Connect Buffers and Policies +++++++++++++++++++++++++++++++++ + +In order for policies to be utilized, they must be connected to their respective +buffers. The storage facility would like them always connected; accordingly, +that operation should happen at the time when the facility enters a +simulation. The kernel will let agents know that they are entering a simulation +via the ``EnterNotify()`` function. + +Add the following to ``src/storage.h`` before the ``Tick()`` function + +.. code-block:: c++ + + /// set up policies and buffers + virtual void EnterNotify(); + +And add the following to ``src/storage.cc`` before the ``Tick()`` function + +.. code-block:: c++ + + void Storage::EnterNotify() { + cyclus::Facility::EnterNotify(); // call base function first + buy_policy.Init(this, &input, std::string("input"), throughput).Set(incommod).Start(); + sell_policy.Init(this, &output, std::string("output"), throughput).Set(outcommod).Start(); + } + +Buffer Transfer Logic +++++++++++++++++++++++++++++++++ + +The job of the ``Storage`` archetype developer is to determine and implement +the logic related to transfering material between the input and output buffers +and the middle inventory buffer. Two rules govern buffer transfer logic +in this model: + +1. All material in the input buffer is transferred to the inventory buffer +2. Material in the inventory buffer that has been stored for long enough is + transferred to the output buffer + +Because the input buffer transfer should occur *after* the DRE, it must happen +in the ``Tock()`` method. Similarly, because the output buffer transfer should +occur *before* the DRE, it must happen in the ``Tick()`` method. For each +transfer, care must be taken to update the ``entry_times`` list appropriately. + +The input buffer transfer requires the following operation for each object in +the buffer: + +1. *Pop* the object from the input buffer +2. *Push* the object to the inventory buffer +3. *Push* the current time to the ``entry_times`` + +In order to implement this, replace the current ``Tock()`` implementation in +``src/storage.cc`` with + +.. code-block:: c++ + + void Storage::Tock() { + int t = context()->time(); + while (!input.empty()) { + inventory.Push(input.Pop()); + entry_times.push_back(t); + } + } + +The output buffer transfer requires the following operation so long as the +condition in 1. is met: + +1. Check whether enough time has passed since the time at the front of + ``entry_times`` *and* the inventory is not empty. If so: +2. *Pop* an object from the inventory buffer +3. *Push* that object to the output buffer +4. *Pop* a time from the ``entry_times`` + +In order to implement this, replace the current ``Tick()`` implementation in +``src/storage.cc`` with + +.. code-block:: c++ + + void Storage::Tick() { + int finished_storing = context()->time() - storage_time; + while (!inventory.empty() && entry_times.front() <= finished_storing) { + output.Push(inventory.Pop()); + entry_times.pop_front(); + } + } + + +Build and Test +++++++++++++++++++++++++++++++++ + +Same as it ever was + +.. code-block:: console + + $ ./install.py + $ Storage_unit_tests + +Add Some Logging +--------------------------------------------- + +Now that all of the required logic is there, it would be nice to know some +information about what is happening to a facility during a simulation. This is +accomplished in Cyclus through :ref:`logging`, which is implemented as a stream +operation. + +Information about the current inventory can be added by updating the ``Tock()`` +function (after any pushing/popping) with + +.. code-block:: c++ + + LOG(cyclus::LEV_INFO2, "Storage") << "The total inventory at time " + << t << " is " + << inventory.quantity() + output.quantity() + << " kg."; + +After updating the function should look something like + +.. code-block:: c++ + + void Storage::Tock() { + int t = context()->time(); + while (!input.empty()) { + inventory.Push(input.Pop()); + entry_times.push_back(t); + } + + LOG(cyclus::LEV_INFO2, "Storage") << "The total inventory at time " + << t << " is " + << inventory.quantity() + output.quantity() + << " kg."; + } + +Notice that this uses the built in ``quantity()`` method of a ResBuf +object and that both the ``inventory`` and ``output`` buffers are queried. While +the implementation logic requires multiple buffers, the model assumes the +facility acts as a single cohesive unit. + +You can also add information about the quantity of material that will be +requested and offered. Since this information is important to know *before* the +DRE, it goes in the ``Tick()`` + +.. code-block:: c++ + + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be requested: " << buy_policy.TotalQty() << " kg."; + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be offered: " << sell_policy.Limit() << " kg."; + +After updating the function should look something like + +.. code-block:: c++ + + void Storage::Tick() { + int finished_storing = context()->time() - storage_time; + while (!inventory.empty() && entry_times.front() <= finished_storing) { + output.Push(inventory.Pop()); + entry_times.pop_front(); + } + + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be requested: " << buy_policy.TotalQty() << " kg."; + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be offered: " << sell_policy.Limit() << " kg."; + } + + +To see the logging output, build and rerun the simulation + +.. note:: + + Increase the verbosity from ``2`` to ``3``. + +.. code-block:: console + + $ ./install.py + $ cyclus -v 3 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(core ):Current time: 0 + INFO2(core ): Beginning Tick for time: 0 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 0 + INFO2(core ): Beginning Tock for time: 0 + INFO2(Storag): The total inventory at time 0 is 0 kg of material. + INFO1(core ):Current time: 1 + INFO2(core ): Beginning Tick for time: 1 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 1 + INFO2(core ): Beginning Tock for time: 1 + INFO2(Storag): The total inventory at time 1 is 0 kg of material. + INFO1(core ):Current time: 2 + INFO2(core ): Beginning Tick for time: 2 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 2 + INFO2(core ): Beginning Tock for time: 2 + INFO2(Storag): The total inventory at time 2 is 0 kg of material. + INFO1(core ):Current time: 3 + INFO2(core ): Beginning Tick for time: 3 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 3 + INFO2(core ): Beginning Tock for time: 3 + INFO2(Storag): The total inventory at time 3 is 0 kg of material. + INFO1(core ):Current time: 4 + INFO2(core ): Beginning Tick for time: 4 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 4 + INFO2(core ): Beginning Tock for time: 4 + INFO2(Storag): The total inventory at time 4 is 0 kg of material. + INFO1(core ):Current time: 5 + INFO2(core ): Beginning Tick for time: 5 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 5 + INFO2(core ): Beginning Tock for time: 5 + INFO2(Storag): The total inventory at time 5 is 0 kg of material. + INFO1(core ):Current time: 6 + INFO2(core ): Beginning Tick for time: 6 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 6 + INFO2(core ): Beginning Tock for time: 6 + INFO2(Storag): The total inventory at time 6 is 0 kg of material. + INFO1(core ):Current time: 7 + INFO2(core ): Beginning Tick for time: 7 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 7 + INFO2(core ): Beginning Tock for time: 7 + INFO2(Storag): The total inventory at time 7 is 0 kg of material. + INFO1(core ):Current time: 8 + INFO2(core ): Beginning Tick for time: 8 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 8 + INFO2(core ): Beginning Tock for time: 8 + INFO2(Storag): The total inventory at time 8 is 0 kg of material. + INFO1(core ):Current time: 9 + INFO2(core ): Beginning Tick for time: 9 + INFO2(Storag): Quantity to be requested: 10 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 9 + INFO2(core ): Beginning Tock for time: 9 + INFO2(Storag): The total inventory at time 9 is 0 kg of material. + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 747f6c86-fce8-49be-8c57-8bb38e11761a + +Add a State Variable to Define Storage Capcity +------------------------------------------------------------- + +A natural extension for the current storage facility implementation is to have a +maximum storage capacity. To do so, first add a capacity state variable to +storage.h . If you still want the input file to work, you have to provide a +``default`` key in the pragma data structure. A sufficiently large value will +do. + +.. code-block:: c++ + + #pragma cyclus var { \ + 'doc': 'Maximum storage capacity (including all material in the facility)', \ + 'tooltip': 'Maximum storage capacity', \ + 'units': 'kg', \ + 'default': 1e200, \ + 'uilabel': 'Maximum Storage Capacity' \ + } + double capacity; + +The required implementation is nontrivial. The goal of adding a capacity +member is to guarantee that the amount of material in the facility never exceeds +a certain value. The only way for material to enter the facility is through the +``input`` ResBuff via the ``buy_policy``. The ``MatlBuyPolicy`` sets a maximum +buy amount based on both its ``throughput`` and the ``capacity`` of the +connected ``ResBuf``. Accordingly, you can update the ``input`` buffer's +capacity before the DRE occurs to achieve this behavior. + + +.. figure:: storage_capacity.svg + :align: center + + **Figure:** Storage buffers between two time steps. The total capacity is + represented by the area of all three boxes. The ``input`` buffer's capacity + must be updated to reflect how much material is in both the ``inventory`` + and ``output`` buffers. The colored arrows on the right match the material + flows in the previous figure. + + +To do so, add the following line to the end of the ``Tick()`` function (in the +implementation file), which updates capacity of the ``input`` through the +``ResBuf`` ``capacity()`` API + +.. code-block:: c++ + + // only allow requests up to the storage capacity + input.capacity(capacity - inventory.quantity() - output.quantity()); + +So the full ``Tick()`` function now looks like + +.. code-block:: c++ + + void Storage::Tick() { + int finished_storing = context()->time() - storage_time; + while (!inventory.empty() && entry_times.front() <= finished_storing) { + output.Push(inventory.Pop()); + entry_times.pop_front(); + } + + // only allow requests up to the storage capacity + input.capacity(capacity - inventory.quantity() - output.quantity()); + + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be requested: " << buy_policy.TotalQty() << " kg."; + LOG(cyclus::LEV_INFO2, "Storage") << "Quantity to be offered: " << sell_policy.Limit() << " kg."; + } + + +Build and Test +++++++++++++++++++++++++++++++++ + +Same as it ever was + +.. code-block:: console + + $ ./install.py + $ Storage_unit_tests + +Update Input File and Run +++++++++++++++++++++++++++++++++ + +You can test that your new capacity capability works by adding the following to +the end of the ``config`` block for ``Storage`` (before the close tag +) in ``input/storage.xml`` + +.. code-block:: xml + + 8 + +Note that this capacity is smaller than the throughput! What do you think you +will see in the output logs? + +Try it out (don't forget to delete the old sqlite file first): + +.. code-block:: console + + $ rm cyclus.sqlite + $ cyclus -v 3 input/storage.xml + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: MatlBuyPolicy is experimental and its API may be subject to change + Experimental Warning: MatlSellPolicy is experimental and its API may be subject to change + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(core ):Current time: 0 + INFO2(core ): Beginning Tick for time: 0 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 0 + INFO2(core ): Beginning Tock for time: 0 + INFO2(Storag): The total inventory at time 0 is 0 kg of material. + INFO1(core ):Current time: 1 + INFO2(core ): Beginning Tick for time: 1 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 1 + INFO2(core ): Beginning Tock for time: 1 + INFO2(Storag): The total inventory at time 1 is 0 kg of material. + INFO1(core ):Current time: 2 + INFO2(core ): Beginning Tick for time: 2 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 2 + INFO2(core ): Beginning Tock for time: 2 + INFO2(Storag): The total inventory at time 2 is 0 kg of material. + INFO1(core ):Current time: 3 + INFO2(core ): Beginning Tick for time: 3 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 3 + INFO2(core ): Beginning Tock for time: 3 + INFO2(Storag): The total inventory at time 3 is 0 kg of material. + INFO1(core ):Current time: 4 + INFO2(core ): Beginning Tick for time: 4 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 4 + INFO2(core ): Beginning Tock for time: 4 + INFO2(Storag): The total inventory at time 4 is 0 kg of material. + INFO1(core ):Current time: 5 + INFO2(core ): Beginning Tick for time: 5 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 5 + INFO2(core ): Beginning Tock for time: 5 + INFO2(Storag): The total inventory at time 5 is 0 kg of material. + INFO1(core ):Current time: 6 + INFO2(core ): Beginning Tick for time: 6 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 6 + INFO2(core ): Beginning Tock for time: 6 + INFO2(Storag): The total inventory at time 6 is 0 kg of material. + INFO1(core ):Current time: 7 + INFO2(core ): Beginning Tick for time: 7 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 7 + INFO2(core ): Beginning Tock for time: 7 + INFO2(Storag): The total inventory at time 7 is 0 kg of material. + INFO1(core ):Current time: 8 + INFO2(core ): Beginning Tick for time: 8 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 8 + INFO2(core ): Beginning Tock for time: 8 + INFO2(Storag): The total inventory at time 8 is 0 kg of material. + INFO1(core ):Current time: 9 + INFO2(core ): Beginning Tick for time: 9 + INFO2(Storag): Quantity to be requested: 8 kg. + INFO2(Storag): Quantity to be offered: 0 kg. + INFO2(core ): Beginning DRE for time: 9 + INFO2(core ): Beginning Tock for time: 9 + INFO2(Storag): The total inventory at time 9 is 0 kg of material. + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 1ce98e9b-bd89-402b-8bd6-c8266e293dba diff --git a/_sources/arche/tutorial_py/index.rst.txt b/_sources/arche/tutorial_py/index.rst.txt new file mode 100755 index 000000000..afd14b92a --- /dev/null +++ b/_sources/arche/tutorial_py/index.rst.txt @@ -0,0 +1,28 @@ +Archetype Development Tutorial [Python] +======================================= +In this tutorial, we will work through a number of steps for creating a +Facility archetype for Cyclus. This tutorial assumes that the learner is +already reasonably familiar with programming in Python and with the primary +vocabulary of Cyclus. We also assume that the learner has a Github account. + +Overview +--------- +Through this tutorial, we will develop +an open source Cyclus archetype module that includes an archetype to simulate +a very simple interim storage facility, named ``Storage``. Ultimately, this +facility will have the following characteristics, all definable by the user: + +* a fixed rate at which it can transfer material +* a minimum time that material stays in storage +* a fixed storage capacity + +This tutorial has the following steps: + +.. toctree:: + :maxdepth: 1 + + setup + state_var + toolkit + testing + input_files diff --git a/_sources/arche/tutorial_py/input_files.rst.txt b/_sources/arche/tutorial_py/input_files.rst.txt new file mode 100755 index 000000000..65081a574 --- /dev/null +++ b/_sources/arche/tutorial_py/input_files.rst.txt @@ -0,0 +1,5 @@ + +Making Input Files +=============================== +Cyclus uses XML, JSON, or Python as its input file format, and there is an extensive guide to +making input files on the `website `_. diff --git a/_sources/arche/tutorial_py/setup.rst.txt b/_sources/arche/tutorial_py/setup.rst.txt new file mode 100755 index 000000000..c175145a6 --- /dev/null +++ b/_sources/arche/tutorial_py/setup.rst.txt @@ -0,0 +1,170 @@ +Setup a New Project +============================================== +In this lesson, we will: + +1. Clean up the file system for the single storage facility +2. Install the storage facility +3. Run an input file that uses the new storage facility + +Make a New Project +------------------- +First let's start by making a tutorial example project with an ``agents.py`` file. + +.. code-block:: console + + ~ $ mkdir -p tutorial/tut + ~ $ cd tutorial/tut + ~/tuorial/tut $ touch __init__.py agents.py + + +Make a Storage Facility +------------------------------------------ +Next, make a new facility by editing the ``agents.py`` file to look like the following: + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + from cyclus.agents import Facility + + + class Storage(Facility): + """My storage facility.""" + + def tick(self): + print("Hello,") + print("World!") + + +Install and Test +---------------------------------- +To install the tutorial project, we'll need to have a ``setup.py`` file in the +root tutorial directory. Create one that looks like: + +**~/tutorial/setup.py:** + +.. code-block:: python + + #!/usr/bin/env python + from distutils.core import setup + + + VERSION = '0.0.1' + setup_kwargs = { + "version": VERSION, + "description": 'My Cyclus tutorial', + "author": 'Just Me', + } + + if __name__ == '__main__': + setup( + name='tut', + packages=['tut'], + scripts=['xo'], + **setup_kwargs + ) + + +Now we can install the tutorial project via, + +.. code-block:: console + + ~ $ cd tutorial + ~/tutorial $ python setup.py install --user + + +Let's now make an example input file in a special ``input`` directory: + +.. code-block:: console + + ~ $ cd tutorial + ~/tutorial $ mkdir -p input + ~/tutorial $ touch input/storage.py + +Now open up the ``input/storage.`` input file and edit it to look like: + +.. code-block:: python + + SIMULATION = { + 'simulation': { + 'archetypes': { + 'spec': [ + {'lib': 'tut.agents', 'name': 'Storage'}, + {'lib': 'agents', 'name': 'NullInst'}, + {'lib': 'agents', 'name': 'NullRegion'}, + ], + }, + 'control': {'duration': 10, 'startmonth': 1, 'startyear': 2000}, + 'facility': {'config': {'Storage': None}, 'name': 'OneFacility'}, + 'region': { + 'config': {'NullRegion': None}, + 'institution': { + 'config': {'NullInst': None}, + 'initialfacilitylist': {'entry': {'number': 1, 'prototype': 'OneFacility'},}, + 'name': 'OneInst', + }, + 'name': 'OneRegion', + }, + }, + } + + +Test the input file by running |Cyclus|: + +.. code-block:: console + + $ cyclus -v 2 input/storage.py + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 + diff --git a/_sources/arche/tutorial_py/state_var.rst.txt b/_sources/arche/tutorial_py/state_var.rst.txt new file mode 100755 index 000000000..2def677a4 --- /dev/null +++ b/_sources/arche/tutorial_py/state_var.rst.txt @@ -0,0 +1,228 @@ +Adding State Variables +======================= +In this lesson, we will: + +1. Add the necessary state variables to define the storage facility +3. Modify the sample input file to include these variables + +Add State Variables +---------------------------------------------- +The Cyclus Python interface preprocessor provides a ``typesystem`` module that help define +variables that are state variables for an archetype. These state vars also allow convenient +annotations. + +First, we'll add the maximum monthly transfer capacity, called ``throughput``. +Open the file ``tutorial/tut/agents.py`` in your text editor. +Immediately after the storage class name, add the following: + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + from cyclus.agents import Facility + import cyclus.typesystem as ts + + + class Storage(Facility): + """My storage facility.""" + + # this declares throughput to be of type double for purposes of storage + # and user input + throughput = ts.Double( + doc="Maximum amount of material that can be transferred in or " + "out each time step", + tooltip="Maximum amount of material that can be transferred in " + "or out each time step", + units="kg", + uilabel="Maximum Throughput", + ) + + def tick(self): + print("Hello, World!") + + +Now, we'll add variables for the minimum amount of time that material is +stored and the input/output commodity names. + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + storage_time = ts.Int( + doc="Minimum amount of time material must be stored", + tooltip="Minimum amount of time material must be stored", + units="months", + uilabel="Storage Time", + ) + incommod = ts.String( + tooltip="Storage input commodity", + doc="Input commodity on which Storage requests material.", + uilabel="Input Commodity", + uitype="incommodity", + ) + outcommod = ts.Int( + tooltip="Storage output commodity", + doc="Output commodity on which Storage offers material.", + uilabel="Output Commodity", + uitype="outcommodity", + ) + ... + +Re-innstall the Modified Module +--------------------------------------- +To reinstall this module, just issue the same ``setup.py`` command as before: + +.. code-block:: console + + ~/tutorial $ python setup.py install --user + + +Modify the Input File +------------------------- +If you try to run the same input file with your modified module, you will get +errors because the sample input file no longer includes the necessary pieces +to define your module. It is missing the new variables. Try it: + +.. code-block:: console + + ~/tutorial $ cyclus -v 2 input/storage.py + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Entity: line 17: element Storage: Relax-NG validity error : Expecting an element throughput, got nothing + Entity: line 17: element Storage: Relax-NG validity error : Invalid sequence in interleave + Entity: line 17: element Storage: Relax-NG validity error : Element Storage failed to validate content + ERROR(core ):Document failed schema validation + +The simulation now fails because it does not match the schema. You can view the schema with + +.. code-block:: console + + ~/tutorial $ cyclus --agent-schema :tut.agents:Storage + +Notice that you were able to take advantage of the input file validation simply by using +the special ``typesystem`` class attributes. + +Our failed cyclus simulation produced an output file that will need to be deleted. + +.. code-block:: console + + ~/tutorial $ rm cyclus.sqlite + +Now, we'll change that input file. Open the file ``input/storage.py`` in +your text editor, and find the prototype configuration for the single facility +named "OneFacility" that looks like this. + +**~/tutorial/input/storage.py:** + +.. code-block:: python + + { + # ... + 'facility': {'config': {'Storage': None}, 'name': 'OneFacility'} + # ... + } + +We need to replace the ```` element with this: + +**~/tutorial/input/storage.py:** + +.. code-block:: python + + { + # ... + 'facility': {'config': {'Storage': { + 'throughput': 10, + 'storage_time': 1, + 'incommod': 'fuel', + 'outcommod': 'stored_fuel', + }}, + 'name': 'OneFacility'} + # ... + } + +Now we can try it again: + +.. code-block:: console + + ~/tutorial $ cyclus -v 2 input/storage.py + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 diff --git a/_sources/arche/tutorial_py/testing.rst.txt b/_sources/arche/tutorial_py/testing.rst.txt new file mode 100755 index 000000000..688b997c1 --- /dev/null +++ b/_sources/arche/tutorial_py/testing.rst.txt @@ -0,0 +1,4 @@ +Adding a Test +================ +Feel free to use pytest, nosetests, or your favorite Python testing framework to test your +archetypes. \ No newline at end of file diff --git a/_sources/arche/tutorial_py/toolkit.rst.txt b/_sources/arche/tutorial_py/toolkit.rst.txt new file mode 100755 index 000000000..eb0b4eed9 --- /dev/null +++ b/_sources/arche/tutorial_py/toolkit.rst.txt @@ -0,0 +1,329 @@ +Adding Resource Buffers +================================================= +In this lesson, we will: + +1. Add ResBufs to track material inventories +2. Add a notion of total storage capacity + +Overview +-------------- +Cyclus has a collection of standard patterns that can be used by +archetype developers. There are many advantages to using the toolkit patterns +rather than developing similar functionality yourself, typical of most code +reuse situations: + +* robustness - toolkit patterns have been subjected to the Cyclus QA process +* time savings - It will take less time to learn how to use a toolkit than it takes to develop your own +* improvements - You can benefit immediately from any improvements in the performance of the toolkit pattern + +Code reuse is a critical best practice in all software development. + +One of the toolkit patterns is a ``ResBuf``, providing a way to track an +inventory of ``Resource`` objects. + +Add State Variables and Resource Buffers +------------------------------------------ +All state variable additions should be included in ``~/tutorial/tut/agents.py`` below the +other state variables added previously in this tutorial. + +A ``ResBuf`` is available as a data type in the ``typesystem``. However, to use it +as a state variable, so we instead have to use the ``ResBufMaterialInv`` or +``RefBufProductInv`` classes. These inventories should be added below the other state +variables we have already applied to the storage class. + + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + from cyclus.agents import Facility + import cyclus.typesystem as ts + + + class Storage(Facility): + """My storage facility.""" + ... + # this facility holds material in storage. + inventory = ts.ResBufMaterialInv() + + +This creates a state variable named ``inventory`` that is based on the +``ResBuf`` class. We'll explain how buffers +work in just a moment. A ResBuf object and its ``ts.Inventory`` state var has special +handling by the Python ``Agent`` class from which ``Facility`` inherits. It will not appear +in the schema. + +Next, add two additional buffers: + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + # this facility holds material in storage. + inventory = ts.ResBufMaterialInv() + # a buffer for incoming material + input = ts.ResBufMaterialInv() + # a buffer for outgoing material + output = ts.ResBufMaterialInv() + + +Finally, check that everything works by reinstalling like before. +You can also confirm that everything still works with running the simulation: + +.. code-block:: console + + ~/tutorial $ cyclus -v 3 input/storage.py + : + .CL:CC CC _Q _Q _Q_Q _Q _Q _Q + CC;CCCCCCCC:C; /_\) /_\)/_/\\) /_\) /_\) /_\) + CCCCCCCCCCCCCl __O|/O___O|/O_OO|/O__O|/O__O|/O____________O|/O__ + CCCCCCf iCCCLCC ///////////////////////////////////////////////// + iCCCt ;;;;;. CCCC + CCCC ;;;;;;;;;. CClL. c + CCCC ,;; ;;: CCCC ; : CCCCi + CCC ;; ;; CC ;;: CCC` `C; + lCCC ;; CCCC ;;;: :CC .;;. C; ; : ; :;; + CCCC ;. CCCC ;;;, CC ; ; Ci ; : ; : ; + iCC :; CC ;;;, ;C ; CC ; : ; . + CCCi ;; CCC ;;;. .C ; tf ; : ; ;. + CCC ;; CCC ;;;;;;; fC : lC ; : ; ;: + iCf ;; CC :;;: tC ; CC ; : ; ; + fCCC :; LCCf ;;;: LC :. ,: C ; ; ; ; ; + CCCC ;; CCCC ;;;: CCi `;;` CC. ;;;; :;.;. ; ,; + CCl ;; CC ;;;; CCC CCL + tCCC ;; ;; CCCL ;;; tCCCCC. + CCCC ;; :;; CCCCf ; ,L + lCCC ;;;;;; CCCL + CCCCCC :;; fCCCCC + . CCCC CCCC . + .CCCCCCCCCCCCCi + iCCCCCLCf + . C. , + : + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + Experimental Warning: ResBuf is experimental and its API may be subject to change + INFO1(core ):Simulation set to run from start=0 to end=10 + INFO1(core ):Beginning simulation + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + INFO1(tutori):Hello + INFO1(tutori):World! + + Status: Cyclus run successful! + Output location: cyclus.sqlite + Simulation ID: 9f15b93c-9ab2-49bb-a14f-fef872e64ce8 + + +Add Implementation Logic +----------------------------- +The goal of a storage facility is to ask for material up to some limit, store it +for an amount of time, and then send it on to any interested parties. This can +be implemented in Cyclus by utilizing the Toolkit objects stated above. The buy +and sell policies will automatically fill and empty the input and output +buffers, respectively. A concept of material flow through the facility is +shown below. + +.. figure:: storage_diagram.svg + :width: 75 % + :align: center + + **Figure:** Material flow through a Storage facility. Green arrows occur + **before** the DRE (during the Tick). Yellow arrows occur during the + DRE. Brown arrows occur **after** the DRE (during the Tock). + + +Buffer Transfer Logic +++++++++++++++++++++++++++++++++ +The job of the ``Storage`` archetype developer is to determine and implement +the logic related to transferring material between the input and output buffers +and the middle inventory buffer. Two rules govern buffer transfer logic +in this model: + +1. All material in the input buffer is transferred to the inventory buffer +2. Material in the inventory buffer that has been stored for long enough is + transferred to the output buffer + +Because the input buffer transfer should occur *after* the DRE, it must happen +in the ``tock()`` method. Similarly, because the output buffer transfer should +occur *before* the DRE, it must happen in the ``tick()`` method. For each +transfer, care must be taken to update the ``entry_times`` list appropriately. + +The input buffer transfer requires the following operation for each object in +the buffer: + +1. *Pop* the object from the input buffer +2. *Push* the object to the inventory buffer +3. *Push* the current time to the ``entry_times`` + +In order to implement this, add or replace the current ``tock()`` implementation in +``agents/py`` with: + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + def __init__(self, ctx): + """Agents that have an init method must accept a context and must call super + first thing! + """ + super().__init__(ctx) + self.entry_times = [] + + def tock(self): + t = self.context.time + while not self.input.empty(): + self.inventory.push(self.input.pop()) + entry_times.append(t) + +The output buffer transfer requires the following operation so long as the +condition in 1. is met: + +1. Check whether enough time has passed since the time at the front of + ``entry_times`` *and* the inventory is not empty. If so: +2. *pop()* an object from the inventory buffer +3. *push()* that object to the output buffer +4. *pop()* a time from the ``entry_times`` + +In order to implement this, replace the current ``tick()`` implementation in +``agents.py`` with + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + def tick(self): + finished_storing = self.context.time - self.storage_time + while (not self.inventory.empty()) and (self.entry_times[0] <= finished_storing): + self.output.push(self.inventory.pop()) + del self.entry_times[0] + + +At this point, please feel free to reinstall and rerun. + +Add a State Variable to Define Storage Capcity +------------------------------------------------------------- +A natural extension for the current storage facility implementation is to have a +maximum storage capacity. To do so, first add a capacity state variable to +storage.h . If you still want the input file to work, you have to provide a +``default`` key in the pragma data structure. A sufficiently large value will +do. + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + capacity = ts.Double( + doc='Maximum storage capacity (including all material in the facility)', + tooltip='Maximum storage capacity', + units='kg', + default=1e200, + uilabel='Maximum Storage Capacity', + ) + +The required implementation is nontrivial. The goal of adding a capacity +member is to guarantee that the amount of material in the facility never exceeds +a certain value. The only way for material to enter the facility is through the +``input`` ResBuff. + +.. figure:: storage_capacity.svg + :align: center + + **Figure:** Storage buffers between two time steps. The total capacity is + represented by the area of all three boxes. The ``input`` buffer's capacity + must be updated to reflect how much material is in both the ``inventory`` + and ``output`` buffers. The colored arrows on the right match the material + flows in the previous figure. + + +To do so, add the following line to the end of the ``tick()`` function (in the +implementation file), which updates capacity of the ``input`` through the +``ResBuf`` ``capacity`` API. + +**~/tutorial/tut/agents.py:** + +.. code-block:: python + + class Storage(Facility): + """My storage facility.""" + ... + def tick(self): + finished_storing = self.context.time - self.storage_time + while (not self.inventory.empty()) and (self.entry_times[0] <= finished_storing): + self.output.push(self.inventory.pop()) + del self.entry_times[0] + # only allow requests up to the storage capacity + self.input.capacity = self.capacity - self.inventory.quantity - self.output.quantity + + + +Update Input File and Run +++++++++++++++++++++++++++++++++ +You can test that your new capacity capability works by adding the following to +the end of the ``config`` block for ``Storage`` (before the close tag +) in ``input/storage.py`` + + +**~/tutorial/input/storage.py:** + +.. code-block:: python + + { + # ... + 'facility': {'config': {'Storage': { + 'throughput': 10, + 'storage_time': 1, + 'incommod': 'fuel', + 'outcommod': 'stored_fuel', + # capacity is optional since it has a default + 'capacity': 8, + }}, + 'name': 'OneFacility'} + # ... + } + + +Note that this capacity is smaller than the throughput! What do you think you +will see in the output logs? + +Try it out (don't forget to delete the old sqlite file first)! diff --git a/_sources/basics/acknowledgements.rst.txt b/_sources/basics/acknowledgements.rst.txt new file mode 100755 index 000000000..9ce133383 --- /dev/null +++ b/_sources/basics/acknowledgements.rst.txt @@ -0,0 +1,27 @@ +|Cyclus| Funding and Support +============================ + +The development of the |Cyclus| core infrastructure has been supported +by a number of programs and agencies. + +* U.S. Nuclear Regulatory Commission + + * Faculty Development Program + +* Department of Energy Nuclear Energy University Program (NEUP) + + * Fellowship program + * Research and Development program + +* University of Wisconsin-Madison Graduate School + + * Graduate School Research program + +* Argonne National Laboratory + + * Lab-grad program + +The |Cyclus| project benefits greatly from the computational resources of the +University of Wisconsin-Madison's `Center for High Throughput Computing +`_ and it's `BaTLab `_ build +and test facility. diff --git a/_sources/basics/concepts.rst.txt b/_sources/basics/concepts.rst.txt new file mode 100755 index 000000000..8dae3b4db --- /dev/null +++ b/_sources/basics/concepts.rst.txt @@ -0,0 +1,125 @@ +.. _basics-concepts: + +Fundamental Concepts in |Cyclus| +================================ + +Several fundamental concepts are deeply engrained in the |Cyclus| kernel, and +understanding them is important for users and developers of |Cyclus|. + +The following concepts are defined in more detail below: + +* |Cyclus| is an :ref:`agent-based simulation ` +* agents are either :ref:`regions, institutions, or facilities ` +* |Cyclus| tracks the :ref:`evolution of a system over time ` +* agents interact through a :ref:`dynamic resource exchange ` that is recomputed at each time step +* |Cyclus| catalogs the transactions of :ref:`discrete quanta of resources ` +* agents may :ref:`enter or leave the simulation ` over the lifetime of a simulation +* each agent is deployed as a :ref:`clone of a prototype ` +* each prototype is defined as a :ref:`configuration an archetype ` +* archetypes are :ref:`loaded dynamically at runtime ` and can be contributed by any user/developer + +.. _agent-based: + +Agent-Based Simulation +---------------------- + +A |Cyclus| simulation models a system of discrete agents that interact to +exchange resources. Most of the behavior of a |Cyclus| simulation is the +result of the interaction among a set of individual and nominally independent +agents. + +.. _rif: + +Region, Institution, Facility Hierarchy +--------------------------------------- + +The primary agent interaction is among Facility agents, each representing a +single discrete nuclear fuel cycle facility. + +Each Facility agent is owned/operated by an Institution agent, representing a +legal operating organization such as a utility, government, non-governmental +organization, etc. Institution agents are responsible for deploying and +decommissioning Facility agents. + +Each Institution operates in a Region agent, representing a geopolitical +region such as a nation-state, sub-national state, super-national region, etc. +Region agents are responsible for requesting the deployment of additional +Facilities through their Institutions. + +Institution and Region agents can alter the way that their Facility agents +interact with other Facility agents. + +.. _timesim: + +Tracking the Evolution of a System Over Time +--------------------------------------------- + +A |Cyclus| simulation marches through time with a fixed time step. At each +time step, the system itself may change and the dynamic resource exchange is +recomputed. + +.. _dre_concepts: + +Dynamic Resource Exchange +------------------------- + +Facility agents interact through the dynamic resource exchange by submitting +requests for resources and/or receiving bids to provide those resources. All +facilities that request resources can then establish their preferences across +the set of bids they receive and the global set of preferences is used to +resolve the exchange by maximizing the global preference. + +.. _discretemat: + +Discrete Resource Tracking +-------------------------- + +The outcome of the dynamic resource exchange is a set of transactions of +discrete resources, with specific quantities and identities, between specific +facility agents. These discrete resources can be tracked through their +life cycle by their identities. + +.. _deploy: + +Agent Deployment and Decommissioning +------------------------------------ + +Facility agents can be deployed or decommissioned at each time step, changing +the system that is being modeled through the dynamic resource exchange. The +decision of when to deploy new facility agents and which agents to deploy is +made by the institution agents based on user input. Agents may be +decommissioned either because they reach their lifetime or because a decision +to decommission is made by the institution that operates them. + +.. _prototype: + +Agent Prototypes +---------------- + +Each agent in the simulation is deployed as a clone of a prototype. A +prototype is formed by adding user-defined configuration details to an +archetype. + +.. _archetype: + +Agent Archetypes +---------------- + +Agent archetypes define the logic that governs the behavior of an agent. An +archetype may allow a user to define some parameters that influence that +behavior. Broadly speaking, the behavior of an agent can be divided into the +behavior that represents the physical models of the system and the behavior +that represents the interaction of the agent with other agents. + +.. _plugin: + +Run-time Discovery and Loading of Archetypes +-------------------------------------------- + +To maximize the flexibility of the |Cyclus| infrastructure, is has been +designed to allow the addition of new archetypes without having to make any +changes to the |Cyclus| kernel. Therefore, the kernel has no *a priori* +knowledge of archetypes or their behavior other than how they are +deployed/decommissioned and how they interact with the dynamic resource +exchange. For this reason, every |Cyclus| simulation must find and load the +archetypes requested by the user. diff --git a/_sources/basics/ecosystem.rst.txt b/_sources/basics/ecosystem.rst.txt new file mode 100755 index 000000000..2d3801ded --- /dev/null +++ b/_sources/basics/ecosystem.rst.txt @@ -0,0 +1,162 @@ +==================================== + The |Cyclus| Community & Ecosystem +==================================== + +**The Cyclus project is owned by its community of users & developers and welcomes code & contributions from everyone!** + +An important goal of the |cyclus| effort is to attract a community of +developers contributing to a vibrant ecosystem of models. Due to +sensitivities regarding the distribution of software for simulating nuclear +systems, this ecosystem requires careful considerations in its design and +implementation. + +Critical to the success of this community is the widespread availability of +the core infrastructure of the |Cyclus| simulation environment. Because this +environment is formulated using a variety of generic concepts not specific to +nuclear energy systems, this should mitigate concerns for the open source +distribution of this core infrastructure. + +Moreover, this infrastructure is also designed to allow for the addition of +runtime :term:`modules `, or :term:`plug-ins `, that can be developed and +distributed under any licensing scheme. Separate from the core +infrastructure, the distribution responsibility will rest with the developer +of each module. This system will insulate the core infrastructure from +accidental "pollution" by modules of a sensitive nature, and, similarly, limit +issues regarding the authorization for distribution to the author's +organization. Ideally, most module developers will be authorized for open +distribution of their modules. + +Finally, the community will be relied upon to provide review and curation of +available modules, establishing both quality assurance practices and +recommendations for best use cases for each contributed module. + +Below, a more detailed exposition of these characteristics is provided. + +Open Source Core Infrastructure +================================ + +The current portfolio of fuel cycle simulators has been characterized by +barriers to adoption by new users and developers including: + +* policies of limited/restricted distribution, + +* reliance on propriety software development infrastructures, and + +* deeply embedded nuclear technology assumptions arising from + development path. + +Because one of the principle purposes of |cyclus| is to create a fuel cycle +simulator system with a low barrier to adoption, a policy of open source +distribution of this core infrastructure is critical to its mission. +(|cyclus| is also committed to free and widely used software development +tools, such as GNU compilers, SQLite, Boost, etc.) The |cyclus| core is +currently available via its `GitHub repository +`_. Interested users and developers are +invited to make their own copy of this repository, review the list of open +issues, and participate in the developer's mailing list. Like all open source +projects, this distribution mode permits a thorough code review by interested +parties and the possibility of contributions in order to identify/resolve +defects or request/provide feature enhancements. + +The |cyclus| core infrastructure provides a generic environment for modeling +flows of materials through a collection of nuclear facilities. This +infrastructure could be used for modeling many different supply chain systems, +nuclear and non-nuclear alike, this infrastructure prioritizes nuclear systems +analysis. Addressing the barrier of deeply embedded nuclear technology +assumptions, this approach ensures that the core infrastructure has a very low +risk of containing sensitive information regarding the simulation of nuclear +systems. These capabilities are added by acquiring and invoking plug-ins +developed and distributed by the |cyclus| community. + +The open source approach can also allow the project to leverage the efforts a +larger pool of developers and improve the quality of the software product +[1]_. + +Decentralized Module Development & Distribution +=============================================== + +When a user/developer wishes to contribute a new module to the |cyclus| +ecosystem, they will be responsible for all aspects of that distribution. The +|cyclus| core development team will provide a catalog of available modules +(details are still under development), but this catalog will point to external +distribution sites that are consistent with each contributors personal and/or +institutional needs. For example, developers who are permitted to follow an +open source approach with their own contributions can have their own GitHub +account and share their modules through the same mechanism as - but a +different location from - the |cyclus| core. For some subset of open source +distribution mechanisms, the |cyclus| core will include tools to make it +easier for individual users to download and install contributed modules or +collections of modules. + +Decentralizing the development and distribution of runtime modules provides a +number of benefits. First, as is true for the core infrastructure, a larger +pool of developers can contribute to the |cyclus| ecosystem by providing +modules that represent their organization's specific interests. If a +particular user/developer would like to understand the impact of their own +technology on the greater fuel cycle, they are free to develop a module that +simulates this technology and contribute it to the broader community. + +More importantly, this will contribute to the maintenance of a "pristine" core +infrastructure, from the point of view of sensitive information. Any software +added to the source code repository leaves behind permanent artifacts - even +if removed at a later date. The inclusion of all newly developed plug-ins in a +centralized software repository could result in the entire repository being +declared sensitive. Decentralized distribution mitigates this risk. + +Finally, a centralized approach would require identifying a single +organization that would accept an ongoing burden of authorizing distribution, +assessing quality and assembling collections. A decentralized approach +removes the burden of authorizing distribution and reviewing contributions +from a central authority. Rather, the authors and community are responsible +for these tasks, as described in the following sections. + +Distribution Authorization by Owner +----------------------------------- + +Considering the concerns for copyright, intellectual property, and the risk +that sensitive information could be contained in a module, the burden of +acquiring and confirming distribution rights by a centralized organization +could become prohibitive. If instead the modules developed for the |cyclus| +ecosystem are documented in a catalog that refers to a variety distribution +sites as appropriate for each developer, the effort for ensuring the rights +for distribution are the responsibility of the developer and their +organization. The inclusion of a given module in the catalog requires little +oversight and the details of distribution remain between the provider and +consumer of each module. + +Peer-review QA and Rating +--------------------------- + +For most organizations, including a plug-in in a centralized software +distribution would be regarded as a tacit approval of the quality and utility +of the module. In most such cases, a substantial burden of quality assurance +and testing would be required by the organization preforming this centralized +distribution. In the decentralized approach of the |cyclus| ecosystem, +mechanisms will be provided for members of the community to provide +peer-review of the modules' quality and applicability to certain problems. + +For modules that are distributed with an open source policy, other users and +developers will be able to perform a direct source code review as well as +testing the functionality of the module in fuel cycle analyses. For other +distribution policies, more limited review will be possible. + +In all cases, practices and policies will emerge from the community to support +standardization of this process. For example, providing adequate +documentation and test suites will result in a better review from members of +the community and ultimately will become pre-requisites to a positive peer +review. + +Curation and Collections +------------------------- + +When the number of contributions is sufficiently large, there will be benefit +in developing collections of modules that are known to be useful for certain +types of simulations. A decentralized approach will allow individual members +of the |cyclus| community to create such collections, providing a curation +function to help both new and experienced users identify the modules that are +likely to give them the most benefit. + +Footnotes +^^^^^^^^^ + +.. [1] J.W. Paulson, *et al*, "An Empirical Study of Open-Source and Closed-Source Software Products", *IEEE Transactions on Software Engineering*, **30** (4), April 2004. http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=01274044 diff --git a/_sources/basics/fcs_background.rst.txt b/_sources/basics/fcs_background.rst.txt new file mode 100755 index 000000000..0122b242f --- /dev/null +++ b/_sources/basics/fcs_background.rst.txt @@ -0,0 +1,58 @@ +Nuclear Fuel Cycle Simulators +----------------------------- + +A nuclear :term:`fuel cycle simulator` is a tool used to explore the impacts of +alternative nuclear fuel cycle choices when considered as a full system at a +national or international level. Fundamentally, these simulators track the +flow of materials through the nuclear fuel cycle, accounting for processes +such as enrichment, transmutation, decay, and partition of isotopes. From the +material flows and information about the operation history of the associated +facilities, various metrics can be assessed for different nuclear fuel cycle +designs. As such, economic, environmental and security metrics resulting from +different fuel cycles can be compared to support decision making on research, +development and deployment decisions for future fuel cycle facilities. + +Fuel cycle simulators provide insights into important trends as nuclear fuel +cycles undergo technological transitions in an uncertain socio-political +environment. While it is important to achieve an overall conservation of +mass, there is typically a trade-off between the accuracy of specific isotopic +compositions and the speed of calculation. Given the inherent uncertainty of +making predictions in unknown socio-political futures, the physics models used +for each individual process in the fuel cycle are generally low-order +approximations based on a higher order analysis. + +Fuel cycle simulators are not designed to provide detailed simulations +of specific facilities: neither high-fidelity predictive simulation nor +virtual reality environments. + +History of Nuclear Fuel Cycle Simulators +++++++++++++++++++++++++++++++++++++++++ + +A variety of simulators have been developed to study nuclear fuel cycles in +two categories. One category models detailed facilities arranged in complex +coupling schemes that are validated with measurements from real systems. +While these tools offer a much more rigorous treatment of the physics, they +often require an experienced analyst to compute the results and may offer more +precision in the physics than is warranted given the socio-political +uncertainty. The other category of tools is typically derived from simplified +systems models, with physics detail and complexity added where necessary to +improve the fidelity of results, but preferring rapid computation to +precision. + +Regardless of the development path, these simulators have inherent +assumptions, limitations in their underlying software infrastructure, and +constraints on the variety of nuclear fuel cycle options that can be assessed. +Comparing the results from different tools, often in order to generate +confidence in them all, can be challenging and frequently requires +oversimplified problems that preclude the use of the advanced features of any +one tool. + +There are a number of tools currently used around the world to support systems +decisions on nuclear fuel cycle options: + +* VISION +* DANESS +* COSI +* NUWASTE +* CAFCA +* NFCSim diff --git a/_sources/basics/glossary.rst.txt b/_sources/basics/glossary.rst.txt new file mode 100755 index 000000000..a4b565f6c --- /dev/null +++ b/_sources/basics/glossary.rst.txt @@ -0,0 +1,155 @@ +.. summary Glossary of Cyclus Fuel Cycle Simulator Terms + +:version: Document v1.0 - 8/14/2012 + +Glossary of Cyclus Terms +======================== + +.. glossary:: + :sorted: + + context + + The queryable environment of a |cyclus| simulation. + + fuel cycle simulator + + A computational framework for modeling nuclear fuel cycles. + + commodity + + A name assigned to a class of resources. |cyclus| determines the flow of + resources during a time step based on the supply of and demand for + commodities based on :term:`agent's ` requests and bids for those + commodities. + + dynamic resource exchange + + the methodology that governs time step behavior in |cyclus| -- see + :doc:`Dynamic Resource Exchange <../arche/dre>` + + plug-in + + See :term:`module`. + + open development platform + + A code repository or server that is publicly viewable and downloadable, + though not necessarily modifiable. + + open development process + + A software development workflow, usually on an :term:`open development + platform`, that is transparent to the public. Hallmarks include public bug + reports, source code access, and code contribution. + + closed development platform + + A code repository or server that is kept private during development to + secure proprietary or sensitive work. + + closed development process + + A software development workflow, usually on a :term:`closed development + platform`, that is not transparent to the public as authorization is + required before development access to the codebase is granted. This is used + for secure proprietary or sensitive work. + + cyclus core + + The repository at github.com/cyclus/cyclus and primary focus of the core + developers of the cyclus project. + + cyclus kernel + + The simulation engine housed in :term:`cyclus core`. :term:`Archetypes + ` defined in :term:`modules ` are linked dynamically to the + kernel at the beginning of every simulation. + + archetype + + A collection of logic and behavior which can be configured into a + :term:`prototype` which can then be instantiated in simulation as a + :term:`agent`. Archetypes are represented as C++ classes that inherit from + the base ``cyclus::Agent`` class. + + prototype + + A configured :term:`archetype` with initial state and conditions. + :term:`Agents ` that do act in the simulation are cloned (copied) from + prototypes. + + agent + + An entity that acts in a |cyclus| simulation. Agents enter the simulation + after having been cloned from a :term:`prototype`. An agent's internal logic + and behavior is determined by its :term:`archetype`. + + module + + A shared-object library that houses implementations of :term:`archetypes + ` and related tools that is dynamically linked to the :term:`cyclus + kernel` at runtime if one of its :term:`archetype` is used in a simulation. + + core developer + + An advanced developer tasked with developing and maintaining the + :term:`cyclus kernel` and related code. + + archetype developer + + An individual from science, academia, government, or the general public + interested in contributing to the ecosystem of :term:`archetypes ` + available for use with the simulator. + + user + + A member of the public, government, or academia who use |cyclus| to run + simulations. + + nuclear fuel cycle + + The progression of nuclear fuel through the collection of facilities and + process stages from mining to disposal that are necessary to generate + nuclear power as well as to prepare, manage, recycle, and store nuclear + fuel. + + parent agent + + An :term:`agent` that manages (is in charge of) some number of child agents. + + kernel phase + + A phase during a simulation time step that is managed by the :term:`cyclus + kernel`. + + agent phase + + A phase during a simulation time step in which :term:`agents ` are + allowed to query the simulation environment and perform general actions. + + tick + + An :term:`agent phase` that occurs before the :term:`dynamic resource + exchange` every time step + + tock + + An :term:`agent phase` that occurs after the :term:`dynamic resource + exchange` every time step + + composition + + A list of nuclides and their relative quantity. + + material + + A particular kind of resource that combines a :term:`composition` and a + mass to be exchanged + + entity + + The kind of the archetype. Usually this is either region, institution, + or facility. For agents that are not specifically one of these kinds + still inherit from the ``Agent`` class the term archetype is used. + Otherwise the entity is unknown. diff --git a/_sources/basics/index.rst.txt b/_sources/basics/index.rst.txt new file mode 100755 index 000000000..acb1bd323 --- /dev/null +++ b/_sources/basics/index.rst.txt @@ -0,0 +1,81 @@ +|Cyclus| Introduction +===================== + +|cyclus| is a nuclear fuel cycle simulation platform whose genesis was driven +by a variety of gaps seen in previous fuel cycle simulation efforts, which +attempted to address three major design and development philosophies: + + #. A desire for usability, thus developing a tool which begins with a + simple model in a visual development environment that aims to provide an + intuitive user interface (e.g. DYMOND, DANESS, VISION) + #. A desire for rapid prototyping, thus developing a tool which begins + with simple models in a scripting language that allows for quick answers to + early problems (e.g. CAFCA, GENIUS v1) + #. A desire for detail/fidelity, thus developing a tool with an ad-hoc + combination of existing complex analysis tools (e.g. COSI) + +Each of these philosophies can hinder the simulation of some classes of +interesting problems due to complexity limits. In most cases this complexity +constrains first the usability of the tool followed by its extensibility due +to increasingly convoluted dependencies. The final victim is performance, as +the ability to quickly solve simple problems is lost to the desire to solve +more complex ones. + +In addition to these technical challenges there is also an institutional one. +A combination of closed development platforms and processes has made it +difficult for an individual researcher to incorporate their ideas into fuel +cycle systems analysis studies or frameworks. The ability to combine existing +systems simulation tools with data about new facilities or fuel cycle concepts +is so challenging that many researchers either choose to avoid systems +analysis altogether or to write their own simplified tool. These custom fuel +cycle simulation tools involve a duplication of effort. + +Each of these approaches lacks a design basis in computational science and +software development that can deliver the desired attributes of the final +software product: + + * **usability:** accommodating a wide range of user sophistication, + + * **performance:** solving simple problems in interactive time scales, and + + * **fidelity:** accommodating many levels of detail & fidelity, + commensurate with a range of user sophistication. + +While these attributes could be achieved across a set of different tools, by +providing a common physics and resource exchange infrastructure that can meet +a broad range of needs, |Cyclus| facilitates meaningful comparisons among +different use cases that has been challenging when comparing different tools. + +A complete nuclear fuel cycle simulator requires modeling efforts in a wide +variety of physical and social science domains. This places a premium on a +software development process that will facilitate fluid collaboration among a +large group of geographically dispersed developers. With this constraint in +mind, a number of software development practices can be identified as highly +valuable for this effort: + + * **openness:** the process should have low institutional & technical + obstacles to collaboration, + + * **modularity:** a particular approach to modularity should be pursued to + allow the core infrastructure to be independent of proprietary or + sensitive data and models, and + + * **extensibility:** attention to both robustness and flexibility allows + for myriad potential developer extensions. + +Sections +---------- + +.. toctree:: + :maxdepth: 1 + + concepts + sw_dev + fcs_background + ecosystem + projects + optsens + acknowledgements + glossary + + diff --git a/_sources/basics/optsens.rst.txt b/_sources/basics/optsens.rst.txt new file mode 100755 index 000000000..d4607b5d8 --- /dev/null +++ b/_sources/basics/optsens.rst.txt @@ -0,0 +1,13 @@ + + +Optimization and Sensitivity +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +There is an initial desire to minimize the direct simulation of institutional +decision making to seek optimal solutions. Because institutional decision +making tends to seek an optimal solution only for the actor making that +decision (local optimization), it may not lead to an outcome that optimizes +for the largest population of stakeholders. Instead, the fundamental approach +is to drive a single simulation with a large multi-dimensional data set and +then allow modern optimization technology to seek globally optimal solutions +based on global objective functions. diff --git a/_sources/basics/projects.rst.txt b/_sources/basics/projects.rst.txt new file mode 100755 index 000000000..9741fd9ac --- /dev/null +++ b/_sources/basics/projects.rst.txt @@ -0,0 +1,19 @@ +Projects Using |Cyclus| +========================= + +A variety of projects are using, or have used, |Cyclus| for both analysis and +method developments purposes. + + +Consortium for Verification Technology +-------------------------------------- + +.. figure:: ../astatic/CVT-logo-250pix1.png + :align: right + :width: 100 + +As part of the `Consortium for Verification Technology (CVT) +`_, |Cyclus| is being used to study issues in +nuclear security and non-proliferation. Research areas include the +incorporation of social-behavioral models to agent interactions, nuclear +material tracking and forensics, and detector sensitivity estimation. diff --git a/_sources/basics/sw_dev.rst.txt b/_sources/basics/sw_dev.rst.txt new file mode 100755 index 000000000..cd4aaf532 --- /dev/null +++ b/_sources/basics/sw_dev.rst.txt @@ -0,0 +1,61 @@ +Software Process & Architecture +================================ + +The software architecture and accompanying development process are critical to +a simultaneously robust and flexible analysis platform. + +Open Source Development Process +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The |cyclus| development framework employs a modern, open source philosophy +that ensures transparency, attracts contributions from a varied community of +collaborators, and guarantees institution-independent access to all potential +:term:`users `. (`BSD 3-Clause License `_) +In this development path, a public source code repository provides +unhindered access to the `fundamental simulation framework +`_ and `additional agent archetypes +`_ volunteered by developers. Granting +unfettered access only to the |cyclus| engine allows for compartmentalization +of the code and its input data. Thus, secure and proprietary :term:`archetype +developers ` can be similarly encouraged to utilize the |cyclus| framework. +This modern development model passively distributes specialized content to +interested research groups, and facilitates parallel archetype development +efforts by institutions with complimentary goals. The transparency inherent +in this type of :term:`open development process` also facilitates code review by +exposing available content to verification and validation by collaborators +with diverse areas of specialization and levels of expertise. + +Another aspect of this development process is a preference for open source +third party libraries where additional functionality is necessary and +available from such libraries. This includes basic infrastructure such as +file input/output, as well as archetype-specific capabilities like +integer programming for network flow optimization. + +Dynamically Loadable Modules +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Dynamically loadable modules are the primary mechanism for extending |cyclus| +with new underlying :term:`archetypes `. The primary benefit of this +approach is encapsulation: the :term:`cyclus kernel` is completely independent +of the individual archetypes and all customization and extension is +implemented only in the loadable module. A secondary benefit of this +encapsulation is the ability for contributors to choose different distribution +and licensing strategies. Finally, this strategy allows individual developers +to explore different levels of complexity within their archetypes, +including wrapping other simulation tools as loadable modules for |cyclus|. + +Use Cases & Visualization +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Because of the wide array of use cases for |cyclus|, flexibility in the user +interface is important to provide users with their desired functionality. +This is true for input generation as well as output visualization. A +graphical user interface has been designed and will be implemented in parallel +with the development of the underlying modules. The graphical interface is +extensible by loadable modules in the same way as the core code to provide +developers the same flexibility in managing their input as they have in +implementing their archetypes. Output visualization is also +important - the discrete facility/discrete material paradigm generates a +large volume of small data that needs to be aggregated in various ways to +provide context to a variety of users. + diff --git a/_sources/cep/cep0.rst.txt b/_sources/cep/cep0.rst.txt new file mode 100755 index 000000000..dbceb4de3 --- /dev/null +++ b/_sources/cep/cep0.rst.txt @@ -0,0 +1,83 @@ +|Cyclus| Enhancement Proposals +============================== + +.. raw:: html + + + +
+ +:CEP: 0 +:Title: Index of |Cyclus| Enhancement Proposals (CEPs) +:Version: N/A +:Last-Modified: 2013-11-01 +:Author: Anthony Scopatz +:Status: Active +:Type: Informational +:Created: 2013-07-03 + +.. raw:: html + + + +.. image:: ../astatic/bicyclelady.jpg + :align: center + +.. raw:: html + +
+ +Introduction +------------ +This CEP contains the index of all |Cyclus| Enhancement Proposals, +known as CEPs. CEP numbers are assigned by the CEP editors, and +once assigned are never changed. The git history of +the CEP texts here represent their historical record. + +Index +----- + +*Meta-CEPs (CEPs about CEPs or Processes)* + +.. toctree:: + :maxdepth: 1 + + PA - 1 - CEP Purpose and Guidelines - Scopatz + PA - 2 - Separation of Concerns in the Cyclus Ecosystem - Scopatz + PA - 3 - Release Procedure - Scopatz + PD - 4 - Attribution of Code Products in the |Cyclus| Ecosystem - Huff + PL - 5 - Archetype Development Best Practices - Gidden + PD - 6 - Cyclus Pull Request Style Guide - Gidden + PD - 80 - Cycamore Archetype API/Warning Requirements - Gidden + +*Standard CEPs* + +.. toctree:: + :maxdepth: 1 + + SA - 17 - Resource Tracking and Interfaces Re-Re-Redo - Carlsen + SA - 18 - Dynamic Resource Exchange Procedure - Gidden + SW - 19 - Cyclus Input Procedure Updates - Flanagan + SA - 20 - Time Step Execution Stack - Gidden + SA - 21 - Agent Identification and Discovery - Carlsen + SL - 22 - Logging Methodology and Implementation - Gidden + SA - 23 - Defining Time Step Length, High Noon for Blue Moon - Scopatz + SA - 24 - Default Preferences - Gidden + SA - 25 - Preference Adjustment Process - Gidden + SD - 26 - Generalize the DRE to Optimize Multiple Metrics - Flanagan, Scopatz + SA - 27 - Toolkit Capabilities Injection into an Archetype - Mouginot + +Key +--- +- S - Standards Track CEP +- I - Informational CEP +- P - Process CEP + +- A - Accepted proposal +- R - Rejected proposal +- W - Withdrawn proposal +- L - Deferred proposal +- F - Final proposal +- C - Active proposal +- D - Draft proposal +- U - Superseded proposal diff --git a/_sources/cep/cep1.rst.txt b/_sources/cep/cep1.rst.txt new file mode 100755 index 000000000..1f8b27fb8 --- /dev/null +++ b/_sources/cep/cep1.rst.txt @@ -0,0 +1,487 @@ +CEP 1 - CEP Purpose and Guidelines +********************************** + +:CEP: 1 +:Title: CEP Purpose and Guidelines +:Last-Modified: 2013-07-03 +:Author: Anthony Scopatz +:Status: Active +:Type: Process +:Created: 2013-07-03 + +What is a CEP? +============== + +CEP stands for |Cyclus| Enhancement Proposal. A CEP is a design +document providing information to the |cyclus| community, or describing +a new feature or process for |Cyclus| and related projects in its ecosystem. +The CEP should provide a concise technical specification of the feature and a +rationale for the feature. + +We intend CEPs to be the primary mechanisms for proposing major new +features, for collecting community input on an issue, and for +documenting the design decisions that have gone into the |Cyclus| ecosystem. +The CEP author is responsible for building consensus within the community and +documenting dissenting opinions. + +Because the CEPs are maintained as text files in a versioned +repository, their revision history is the historical record of the +feature proposal [1]_. + + +CEP Types +========= + +There are three kinds of CEP: + +1. A **Standards Track** CEP describes a new feature or implementation + for |cyclus|. It may also describe an interoperability standard that will + be supported outside of |cyclus| core. + +2. An **Informational** CEP describes a |cyclus| design issue, or + provides general guidelines or information to the |cyclus| community, + but does not propose a new feature. Informational CEPs do not + necessarily represent a |cyclus| community consensus or + recommendation, so users and implementers are free to ignore + Informational CEPs or follow their advice. + +3. A **Process** CEP describes a process surrounding |cyclus|, or + proposes a change to (or an event in) a process. Process CEPs are + like Standards Track CEPs but apply to areas other than the |cyclus| + code development. They may propose an implementation, but not to + |cyclus|'s codebase; they often require community consensus; unlike + Informational CEPs, they are more than recommendations, and users + are typically not free to ignore them. Examples include + procedures, guidelines, changes to the decision-making process, and + changes to the tools or environment used in |cyclus| development. + Any meta-CEP is also considered a Process CEP. + + +CEP Workflow +============ + + +|cyclus|'s BDFP +--------------- + +There are several reference in this CEP to the "BDFP". This acronym stands +for "Benevolent Dictator for the Proposal." In most cases, it is fairly clear +who this person is (Paul Wilson or Anthony Scopatz). It is this persons +responsibility to consider the entire |cyclus| ecosystem when deciding whether +or not to accept a proposal. Weighted with this burden, their decision +must be adhered to (dictator status), though they will try to do the right +thing (benevolent). + + +CEP Editors +----------- + +The CEP editors are individuals responsible for managing the administrative +and editorial aspects of the CEP workflow (e.g. assigning CEP numbers and +changing their status). See `CEP Editor Responsibilities & Workflow`_ for +details. The current editors are: + +* Paul Wilson +* Anthony Scopatz +* Katy Huff + +CEP editorship is by invitation of the current editors. + + +Submitting a CEP +---------------- + +The CEP process begins with a new idea for |cyclus|. It is highly +recommended that a single CEP contain a single key proposal or new +idea. Small enhancements or patches often don't need +a CEP and can be injected into the |cyclus| development workflow with a +patch submission to the |cyclus| `issue tracker`_. The more focused the +CEP, the more successful it tends to be. The CEP editors reserve the +right to reject CEP proposals if they appear too unfocused or too +broad. If in doubt, split your CEP into several well-focused ones. + +Each CEP must have a champion -- someone who writes the CEP using the +style and format described below, shepherds the discussions in the +appropriate forums, and attempts to build community consensus around +the idea. The CEP champion (a.k.a. Author) should first attempt to +ascertain whether the idea is CEP-able. Posting to the `cyclus-dev`_ +mailing list is the best way to go about this. + +Vetting an idea publicly before going as far as writing a CEP is meant +to save the potential author time. Many ideas have been brought +forward for changing |cyclus| that have been rejected for various +reasons. Asking the |cyclus| community first if an idea is original +helps prevent too much time being spent on something that is +guaranteed to be rejected based on prior discussions (searching +the internet does not always do the trick). It also helps to make sure +the idea is applicable to the entire community and not just the author. +Just because an idea sounds good to the author does not +mean it will work for most people in most areas where |cyclus| is used. + +Once the champion has asked the |cyclus| community as to whether an +idea has any chance of acceptance, a draft CEP should be presented to +mailing list. This gives the author a chance to flesh out the draft +CEP to make properly formatted, of high quality, and to address +initial concerns about the proposal. + +Following a discussion on the mailing list, the proposal should be sent as a +draft CEP to the one of the CEP editors. The draft must be written +in CEP style as described below, else it will be sent back without further +regard until proper formatting rules are followed (although minor errors +will be corrected by the editors). + +If the CEP editors approve, they will assign the CEP a number, label it +as Standards Track, Informational, or Process, give it status "Draft", +and create and check-in the initial draft of the CEP. The CEP editors +will not unreasonably deny a CEP. Reasons for denying CEP status +include duplication of effort, being technically unsound, not +providing proper motivation or addressing backwards compatibility, or +not in keeping with the |cyclus| philosophy. The BDFP can be consulted +during the approval phase, and is the final arbiter of the draft's +CEP-ability. + +Developers with git push privileges for the `CEP repository`_ may claim +CEP numbers directly by creating and committing a new CEP. When doing so, +the developer must handle the tasks that would normally be taken care of by +the CEP editors (see `CEP Editor Responsibilities & Workflow`_). This +includes ensuring the initial version meets the expected standards for +submitting a CEP. Alternately, even developers may choose to submit CEPs +through the CEP editors. When doing so, let the CEP editors know you have +git push privileges and they can guide you through the process of updating +the CEP repository directly. + +As updates are necessary, the CEP author can check in new versions if they +(or a collaborating developer) have git push privileges, or else they can +email new CEP versions to the CEP editors for publication. + +After a CEP number has been assigned, a draft CEP may be discussed further on +mailing list (getting a CEP number assigned early can be useful for ease of +reference, especially when multiple draft CEPs are being considered at the +same time). + +Standards Track CEPs consist of two parts, a design document and a +reference implementation. It is generally recommended that at least a +prototype implementation be co-developed with the CEP, as ideas that sound +good in principle sometimes turn out to be impractical when subjected to the +test of implementation. + +CEP authors are responsible for collecting community feedback on a CEP +before submitting it for review. CEP authors should use their discretion here. + + +CEP Review & Resolution +----------------------- + +Once the authors have completed a CEP, they may request a review for +style and consistency from the CEP editors. However, the content and +final acceptance of the CEP must be requested of the BDFP, usually via +an email to the development mailing list. CEPs are reviewed by the +BDFP and their chosen consultants, who may accept or reject a CEP or +send it back to the author(s) for revision. For a CEP that is +predetermined to be acceptable (e.g., it is an obvious win as-is +and/or its implementation has already been checked in) the BDFP may +also initiate a CEP review, first notifying the CEP author(s) and +giving them a chance to make revisions. + +The final authority for CEP approval is the BDFP. However, whenever a new +CEP is put forward, any core developer that believes they are suitably +experienced to make the final decision on that CEP may offer to serve as +the BDFP's delegate (or "CEP czar") for that CEP. If their self-nomination +is accepted by the other core developers and the BDFP, then they will have +the authority to approve (or reject) that CEP. This process happens most +frequently with CEPs where the BDFP has granted in principle approval for +*something* to be done, but there are details that need to be worked out +before the CEP can be accepted. + +If the final decision on a CEP is to be made by a delegate rather than +directly by the normal BDFP, this will be recorded by including the +"BDFP" header in the CEP. + +For a CEP to be accepted it must meet certain minimum criteria. It +must be a clear and complete description of the proposed enhancement. +The enhancement must represent a net improvement. The proposed +implementation, if applicable, must be solid and must not complicate +the infrastructure unduly. Finally, a proposed enhancement must be +follow |cyclus| best practices in order to be accepted by the BDFP. + +Once a CEP has been accepted, the reference implementation must be +completed. When the reference implementation is complete and incorporated +into the main source code repository, the status will be changed to "Final". + +A CEP can also be assigned status "Deferred". The CEP author or an +editor can assign the CEP this status when no progress is being made +on the CEP. Once a CEP is deferred, a CEP editor can re-assign it +to draft status. + +A CEP can also be "Rejected". Perhaps after all is said and done it +was not a good idea. It is still important to have a record of this +fact. The "Withdrawn" status is similar - it means that the CEP author +themselves has decided that the CEP is actually a bad idea, or has +accepted that a competing proposal is a better alternative. + +When a CEP is Accepted, Rejected or Withdrawn, the CEP should be updated +accordingly. In addition to updating the status field, at the very least +the Resolution header should be added with a link to the relevant post +in the `cyclus-dev`_ mailing list archives. + +CEPs can also be superseded by a different CEP, rendering the original +obsolete. This is intended for Informational CEPs, where version 2 of +an API can replace version 1. + +The possible paths of the status of CEPs are as follows: + +.. image:: cep-0001-1.png + +Some Informational and Process CEPs may also have a status of "Active" +if they are never meant to be completed. E.g. CEP 1 (this CEP). + +**Lazy Consensus:** After 1 month of no objections to the wording of a CEP, +it may be marked as "Accepted" by lazy consensus. The author, BDFP, and +the Cyclus community manager are jointly responsible for sending out weekly +reminders of an unapproved CEP without active discussion. + + +CEP Maintenance +--------------- + +In general, Standards track CEPs are no longer modified after they have +reached the Final state. Once a CEP has been completed, the Language and +Standard Library References become the formal documentation of the expected +behavior. + +Informational and Process CEPs may be updated over time to reflect changes +to development practices and other details. The precise process followed in +these cases will depend on the nature and purpose of the CEP being updated. + + + +What belongs in a successful CEP? +================================= + +Each CEP should have the following parts: + +1. Preamble -- headers containing meta-data about the + CEP, including the CEP number, a short descriptive title, the names, + and optionally the contact info for each author, etc. + +2. Abstract -- a short (~200 word) description of the technical issue + being addressed. + +3. Copyright/public domain -- Each CEP must either be explicitly + labeled as placed in the public domain (see this CEP as an + example) or licensed under the `Open Publication License`_. + +4. Specification -- The technical specification should describe the + syntax and semantics of any new feature. + +5. Motivation -- The motivation is critical for CEPs that want to + change the |cyclus| ecosystem. It should clearly explain why the + existing language specification is inadequate to address the + problem that the CEP solves. CEP submissions without sufficient + motivation may be rejected outright. + +6. Rationale -- The rationale fleshes out the specification by + describing what motivated the design and why particular design + decisions were made. It should describe alternate designs that + were considered and related work, e.g. how the feature is supported + in other languages. + + The rationale should provide evidence of consensus within the + community and discuss important objections or concerns raised + during discussion. + +7. Backwards Compatibility -- All CEPs that introduce major backwards + incompatibilities must include a section describing these + incompatibilities and their severity. The CEP must explain how the + author proposes to deal with these incompatibilities. CEP + submissions without a sufficient backwards compatibility treatise + may be rejected outright. + +8. Reference Implementation -- The reference implementation must be + completed before any CEP is given status "Final", but it need not + be completed before the CEP is accepted. While there is merit + to the approach of reaching consensus on the specification and + rationale before writing code, the principle of "rough consensus + and running code" is still useful when it comes to resolving many + discussions of API details. + + The final implementation must include test code and documentation + appropriate for |cyclus|. + + +CEP Header Preamble +=================== + +Each CEP must begin with a header preamble. The headers +must appear in the following order. Headers marked with "*" are +optional and are described below. All other headers are required. :: + + CEP: + Title: + Version: + Last-Modified: + Author: + * BDFP: + Status: + Type: + * Requires: + Created: + * Cyclus-Version: + * Replaces: + * Superseded-By: + * Resolution: + +The Author header lists the names, and optionally the email addresses +of all the authors/owners of the CEP. The format of the Author header +value must be + + Random J. User + +if the email address is included, and just + + Random J. User + +The BDFP field is used to record cases where the final decision to +approve or reject a CEP rests with someone other than the normal BDFP. + +The Type header specifies the type of CEP: Standards Track, +Informational, or Process. + +The Created header records the date that the CEP was assigned a +number, while Post-History is used to record the dates of when new +versions of the CEP are posted to |cyclus| mailing list. Both +headers should be in yyyy-mm-dd format, e.g. 2001-08-14. + +Standards Track CEPs will typically have a |cyclus|-Version header which +indicates the version of |cyclus| that the feature will be released with. +Standards Track CEPs without a |cyclus|-Version header indicate +interoperability standards that will initially be supported through +external libraries and tools, and then supplemented by a later CEP to +add support to the standard library. Informational and Process CEPs do +not need a |cyclus|-Version header. + +CEPs may have a Requires header, indicating the CEP numbers that this +CEP depends on. + +CEPs may also have a Superseded-By header indicating that a CEP has +been rendered obsolete by a later document; the value is the number of +the CEP that replaces the current document. The newer CEP must have a +Replaces header containing the number of the CEP that it rendered +obsolete. + + +Auxiliary Files +=============== + +CEPs may include auxiliary files such as diagrams. Such files must be +named ``cep-XXXX-Y.ext``, where "XXXX" is the CEP number, "Y" is a +serial number (starting at 1), and "ext" is replaced by the actual +file extension (e.g. "png"). + + +Reporting CEP Bugs, or Submitting CEP Updates +============================================= + +How you report a bug, or submit a CEP update depends on several +factors, such as the maturity of the CEP, the preferences of the CEP +author, and the nature of your comments. For the early draft stages +of the CEP, it's probably best to send your comments and changes +directly to the CEP author. For more mature, or finished CEPs you may +want to submit corrections to the |cyclus| `issue tracker`_ so that your +changes don't get lost. If the CEP author is a |cyclus| developer, assign the +bug/patch to them, otherwise assign it to a CEP editor. + +When in doubt about where to send your changes, please check first +with the CEP author and/or a CEP editor. + +CEP authors with git push privileges for the CEP repository can update the +CEPs themselves by using "git push" to submit their changes. + + +Transferring CEP Ownership +========================== + +It occasionally becomes necessary to transfer ownership of CEPs to a +new champion. In general, it is preferable to retain the original author as +a co-author of the transferred CEP, but that's really up to the +original author. A good reason to transfer ownership is because the +original author no longer has the time or interest in updating it or +following through with the CEP process, or has fallen off the face of +the earth (i.e. is unreachable or not responding to email). A bad +reason to transfer ownership is because the author doesn't agree with the +direction of the CEP. One aim of the CEP process is to try to build +consensus around a CEP, but if that's not possible, an author can always +submit a competing CEP. + +If you are interested in assuming ownership of a CEP, send a message +asking to take over, addressed to both the original author and the |cyclus| +mailing list. If the original author doesn't respond to +email in a timely manner, the CEP editors will make a unilateral +decision (it's not like such decisions can't be reversed :). + + +CEP Editor Responsibilities & Workflow +====================================== + +A CEP editor must subscribe to the |cyclus| development mailing list. +For each new CEP that comes in an editor does the following: + +* Read the CEP to check if it is ready: sound and complete. The ideas + must make technical sense, even if they don't seem likely to be + accepted. + +* The title should accurately describe the content. + +* Edit the CEP for language (spelling, grammar, sentence structure, etc.). + +If the CEP isn't ready, an editor will send it back to the author for +revision, with specific instructions. + +Once the CEP is ready for the repository, a CEP editor will: + +* Assign a CEP number (almost always just the next available number, + but sometimes it's a special/joke number, like 666 or 3141). + +* Add the CEP to the CEP repository. + +* Commit and push the new (or updated) CEP + +* Monitor cyclus.github.com to make sure the CEP gets added to the site + properly. + +* Send email back to the CEP author with next steps (post to the + |cyclus| development mailing list). + +Many CEPs are written and maintained by developers with write access +to the |cyclus| codebase. The CEP editors monitor the various repositories +for CEP changes, and correct any structure, grammar, spelling, or +markup mistakes they see. + +CEP editors don't pass judgment on CEPs. They merely do the +administrative & editorial part (which is generally a low volume task). + +Document History +================ +This document was forked and modified from the `Python Enhancement Proposals +`_ + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. [1] This historical record is available by the normal git commands + for retrieving older revisions, and can also be browsed via HTTP here: + https://github.com/cyclus/cyclus.github.com/tree/source/source/cep + +.. _issue tracker: + https://github.com/cyclus/cyclus + +.. _Open Publication License: http://www.opencontent.org/openpub/ + +.. _reStructuredText: http://docutils.sourceforge.net/rst.html + +.. _CEP repository: https://github.com/cyclus/cyclus.github.com/tree/source/source/cep + +.. _cyclus-dev: https://groups.google.com/forum/#!forum/cyclus-dev diff --git a/_sources/cep/cep17.rst.txt b/_sources/cep/cep17.rst.txt new file mode 100755 index 000000000..04b905cd5 --- /dev/null +++ b/_sources/cep/cep17.rst.txt @@ -0,0 +1,670 @@ +CEP 17 - Resource Tracking and Interfaces Re-Re-Redo +*********************************************************** + +:CEP: 17 +:Title: Resource Tracking and Interfaces Re-Re-Redo +:Last-Modified: 2013-09-03 +:Author: Robert Carlsen +:Status: Accepted +:Type: Standards Track +:Created: Robert Carlsen + +Abstract +=========== + +This proposal serves to address two related issues: + +1. **Resource tracking:** + + Several types of analysis are made difficult to impossible by the + incomplete resource history currently recorded by |Cyclus| simulations. Such + analyses include agent time-dependent isotopic inventories and + proliferation-resistance material handling. It is proposed that all + resource state and state transitions will be tracked (as opposed to just + recording state at inter-agent transactions). In addition to required + internal additions/changes to resource classes, explicit ``transmute`` + functionality will be added to the Material class to accommodate + mass-conserving state changes that occur in agents such as Reactors. + +2. **Resource interface complexity:** + + Creating, querying, and manipulating resources is too complex and is spread + across too many classes. The resource class (and friends) will have their + interfaces minimized and all extra functionality will be provided by one or + more wrapper classes. + +Motivation and Rationale +========================== + +This proposal serves to address two related issues: resource tracking and +resource interface complexity. Because changes to resource tracking will be +intrusive to the current resource interfaces, performing these changes +together is desirable. + +**Resouce Tracking:** + +Currently |Cyclus| only tracks the state of resources when they are transacted. +This limited tracking is problematic for certain kinds of output +analysis. Examples: + +1. The meaning of "inventory" for agents that transmute materials is + ill-defined. To calculate the inventory of a reactor faciltiy, an + analysis of present data would show fresh fuel coming in, and spent fuel + coming out. The aggregation of transactions to a specific point in time + would not be the reactor's current inventory. Rather it would be the + reactor's inventory plus the difference between fresh and spent fuel + processed until that point in time. The same problem exists with decay. + +2. We cannot determine if a resource was ever handled inappropriately (e.g. + non-proliferation analysis) internally within an agent. + +3. We are unable to determine "source" agents that create material and what + they created. + +4. There is no mass-conservation-safe way to transmute a material (i.e. + change its nuclide composition) outside of destroying and simultaneously + creating new material objects (which isn't mass-conservations-safe). + +5. When resources are split and combined, there is no way to recall this + heritage. Tracing paths of certain material objects is not possible. + Analyzing the contribution of agent X to the flow of isotope Y through + agent Z is not possible. + +The above deficiencies are used as drivers for designing/implementing a more +thorough resource tracking infrastructure. + +Additionally, some materials will exist in the simulation that are not +"part" of the simulation and should not be recorded in the ouptut. Some of +these materials will be objects representing what agents are +offering/requesting. A new implementation must accomodate this +requirement. + +**Resource Interface Complexity:** + +The interface(s) for creating, manipulating, and using resources is too +confusing and complex. There are methods for accessing material state +variables spread across three classes (Material, IsoVector, CompMap). The +current trio will be reduced to a duo (Material and Composition classes). +All query convenience related methods will be moved to one (or more) +wrapper classes for interrogating and manipulating material compositions. +*Functionality provided by these wrapper classes can grow organically as +needs arise without affecting the core resource classes.* + +Part of the problem has been that some questions belong to the Material +class, some belong to the composition class. And some can only be answered +by using information from both. Another reason to use wrapper classes is +that sometimes a user/dev might want to manipulate compositions, and other +times they will want to manipulate materials - and many of those +queries/operations have significant overlap that we don't want duplicated +on both classes' implementations nor interfaces. Another reason is to help +the classes be more modular/maintainable for the core developers. Some +basic material/composition query/manipulation wrapper(s) can be made +setting the stage for the further development of a "toolkit" for dealing +with materials and compositions. External developers can easily create +toolkits for others to use that don't even need to be a part of the |Cyclus| +core. This makes it easier to ensure that material/composition inner +workings remain pure and correct despite rapid or significant changes to +the kitchen-sink API that will likely evolve. + +Specification +=============== + +A reference implementation exists for both the |cyclus| core and cycamore. +These reside at https://github.com/rwcarlsen/cyclus ("res" branch) and +https://github.com/rwcarlsen/cycamore ("res" branch) respectively. Further +implementation details can be found there. + +Data Tracking ++++++++++++++++++++++++ + +In addition to tracking the transfer of resources between agents (and +corresponding state), we track: + +* Creation of a resource. Parentless resources are implicitly defined as + "newly created" + +* Transmutation of a material resource within an agent (Resource, + ResourceHeritage, Compositions, GenericResource tables). The transmuted + resource has the prev resource as its only parent. This helps address + problem #1 and #4 from Motivation section. + +* Decay of a material resource (Resource, ResourceHeritage, Compositions + tables): This is a special, common case of transmutation. + +* All splitting/combining of materials. Tracked by recording the parent(s) + of each Resource object. Resources with no parent were newly created. + Helps address problem #2, #3 and #5. + +This also simplifies rules for acceptable resource handling. Namely, it is +never okay for a resource to be destructed or thrown-away unless it is +being stored permanently. The new changes should make it more obvious to +agent developers how enforce correct, measurable mass-conservation. + +This proposed tracking provides orthogonality between resource +handling/operations and resource ownership. Resource operations don't +know/care about who is splitting/combining/transmuting/creating them. This +orthogonality, I believe, is a good feature because: it simplifies the +resource APIs, decouples transaction and resource manipulation and data +recording code, and it decouples output data elegantly. Resource tracking +becomes entirely independent of facility operations, transactions, and +simulation time-stepping. If problem #1 as described in the Motivation +section is a fundamentally necessary analysis for basically every +simulation we want to run, then we either need (minimally) the tracking +proposed in this CEP or we need to break the orthogonality that I just +described. Eliminating even one of the things tracked as described above +will break the ability to unambiguously determine agent inventories. + +Output Schema ++++++++++++++++++++++++ + +All recorded data will stay the same except for the tables listed below: + +* [TableName] ([new/modified/removed]): [field1], [field2], ... + +- Resource (modified): ID, Time, Type, Quantity, StateID, Parent1, Parent2 +- Compositions (new): ID, Isotope, Quantity +- TransactedResources (modified): TransactionID, Position, ResourceID +- GenericResources (modified): ID, Quality, Units +- IsotopicStates (removed) + + +*Note that unlike GenericResources, there is no units field for +compositions because we can record all material composition amounts in a +canonical unit (i.e. kg). GenericResources, however, are +expected/anticipated to have different unit types along with their +differing "quality" field values.* + +Resources/Material API ++++++++++++++++++++++++ + +The Material and Composition classes will be designed to provide only the +minimal interface to support basic manipulation and tracking required by the +|cyclus| core. All more complex operations will be implemented in helper +classes (like MatQuery). A summary of each of these classes' new role and +its public interfaces are described below. + +Resource class +~~~~~~~~~~~~~~~ + +Resource class provides an abstract interface allowing different types of +resources to be transacted in a simulation. + +.. code-block:: c++ + + namespace cyclus { + + typedef std::string ResourceType; + + class Resource { + public: + typedef boost::shared_ptr Ptr; + + virtual ~Resource() { }; + + /// returns the unique id corresponding to this resource and its current + /// state. + const int id() const; + + /// assigns a new, unique id to this resource and its state. + void BumpId(); + + /// returns an id representing the specific resource implementation's + /// internal state. Any change to the state_id should be accompanied by a + /// call to BumpId. + virtual int state_id() const = 0; + + virtual const ResourceType type() const = 0; + + /// returns an untracked (not part of the simulation) copy of the resource. + virtual Ptr Clone() const = 0; + // the clone method implementations should set tracked_ = false. + + /// records the resource's state to the output database. This method should + /// generally / NOT record data accessible via the Resource class public + /// methods (e.g. / state_id, units, type, quantity) + virtual void Record() const = 0; + + /// Returns the units this resource is based in. + virtual std::string units() const = 0; + + /// returns the quantity of this resource with dimensions as specified by + /// units(). + virtual double quantity() const = 0; + + /// splits the resource and returns the extracted portion as a new resource + /// object. Allows for things like ResourceBuff and market matching to + /// split offers/requests of arbitrary resource implementation type. + virtual Ptr ExtractRes(double quantity) = 0; + + }; + + } // namespace cyclus + +Material class +~~~~~~~~~~~~~~~ + +The material class is primarily responsible for enabling basic material +manipulation while helping enforce mass conservation. It also provides the +ability to easily decay a material up to the current simulation time; it +does not perform any decay related logic itself. + +There are four basic operations that can be performed on materials: create, +transmute (change material composition - e.g. fission by reactor), absorb +(combine materials), extract (split a material). All material +handling/manipulation will be performed using these operations - and all +operations performed will be recorded. Usage examples: + +* A mining facility that "creates" new material + +.. code-block:: c++ + + Composition::Ptr nat_u = ... + double qty = 10.0; + + Material::Ptr m = Material::Create(qty, nat_u); + +* A conversion facility mixing uranium and flourine: + +.. code-block:: c++ + + Material::Ptr uf6 = uranium_buf.PopOne(); + Material::Ptr f = flourine_buf.PopOne(); + + uf6.Absorb(f); + +* A reactor transmuting fuel: + +.. code-block:: c++ + + Composition::Ptr burned_comp = ... // fancy code to calculate burned isotopics + Material::Ptr assembly = core_fuel.PopOne(); + + assembly.Transmute(burned_comp); + +* A separations plant extracting stuff from spent fuel: + +.. code-block:: c++ + + Composition::Ptr comp = ... // fancy code to calculate extraction isotopics + Material::Ptr bucket = spent_fuel.PopOne(); + double qty = 3.0; + + Material::Ptr mox = bucket.ExtractComp(qty, comp); + + +Proposed material class interface: + +.. code-block:: c++ + + class Material: public Resource { + public: + typedef boost::shared_ptr Ptr; + static const ResourceType kType; + + virtual ~Material(); + + static Ptr Create(double quantity, Composition::Ptr c); + static Ptr CreateUntracked(double quantity, Composition::Ptr c); + + virtual int state_id() const; + + virtual const ResourceType type() const; + + virtual Resource::Ptr Clone() const; + + virtual void Record() const; + + /// returns "kg" + virtual std::string units() const; + + /// returns the mass of this material in kg. + virtual double quantity() const; + + virtual Resource::Ptr ExtractRes(double qty); + + Ptr ExtractQty(double qty); + + Ptr ExtractComp(double qty, Composition::Ptr c, double threshold = eps_rsrc()); + + void Absorb(Ptr mat); + + void Transmute(Composition::Ptr c); + + void Decay(int curr_time); + + static void DecayAll(int curr_time); + + Composition::Ptr comp() const; + }; + + } // namespace cyclus + +GenericResource class +~~~~~~~~~~~~~~~~~~~~~~ + +Implements the Resource class interface in a simple way usable for things +like: bananas, man-hours, water, buying power, etc. + +.. code-block:: c++ + + class GenericResource : public Resource { + public: + typedef boost::shared_ptr Ptr; + static const ResourceType kType; + + static Ptr Create(double quantity, std::string quality, std::string units); + static Ptr CreateUntracked(double quantity, std::string quality, + std::string units); + + /// not needed/no meaning for generic resources + virtual int state_id() const { + return 0; + }; + + /// Returns the concrete type of this resource + virtual const ResourceType type() const { + return kType; + }; + + /// Returns a reference to a newly allocated copy of this resource + virtual Resource::Ptr Clone() const; + + virtual void Record() const { }; + + /// Returns the total quantity of this resource in its base unit + virtual std::string units() const { + return units_; + }; + + /// Returns the total quantity of this resource in its base unit + virtual double quantity() const { + return quantity_; + }; + + virtual const std::string& quality() const { + return quality_; + }; + + virtual Resource::Ptr ExtractRes(double quantity); + + /// Extracts the specified mass from this resource and returns it as a + /// new generic resource object with the same quality/type. + + /// @throws CycGenResourceOverExtract + GenericResource::Ptr Extract(double quantity); + + /// Absorbs the contents of the given 'other' resource into this + /// resource + /// @throws CycGenResourceIncompatible 'other' resource is of a + void Absorb(GenericResource::Ptr other); + }; + + } // namespace cyclus + +Composition class +~~~~~~~~~~~~~~~~~~~~~~ + +An immutable object responsible for tracking decay lineages (to prevent +duplicate calculations and output recording) and able to record its +composition data to output when told. Each composition will keep a pointer +to references to every other composition that is a result of decaying this +or a previously decayed-from composition. + +Note that previously, composition creation/modification involved a notion +of equivalence via threshold comparison to facilitate reduced +memory/storage burdens. This proposal discards this idea in favor of +defining equivalence trivially as "the same object in memory" or pointer +equality. Some discussion regarding this can be found in comments here: +https://github.com/cyclus/cyclus/issues/484. Of particular concern w.r.t. +the previous equivalence notion is this:: + + Also - another potential issue I thought of: Repeatedly calling multiple + consecutive small differences negligible could result in compositions + staying the same that would have otherwise been appreciably different if + each small change were allowed to propogate as a new composition. + +While there are definitely uses for material/composition equivalence, they +should/will not be used by the core (for now) and best belong in MatQuery +or other places. + +.. code-block:: c++ + + + namespace cyclus { + + typedef int Iso; + typedef std::map CompMap; + + // Represents an immutable nuclear material composition + class Composition { + public: + typedef boost::shared_ptr Ptr; + + static Ptr CreateAtom(CompMap v); + static Ptr CreateMass(CompMap v); + + int id(); + const CompMap& atom_vect(); + const CompMap& mass_vect(); + + Ptr Decay(int delta); + + /// record in output database (if not done previously). + void Record(); + }; + + } // namespace cyclus + +compmath namespace +~~~~~~~~~~~~~~~~~~~~~~ + +The excellent floating point calculation handling and thresholding +functionality introduced by @katyhuff will be preserved. The current +(pre-proposal) Material::Diff and Material::ApplyThreshold methods will become +public functions that operate on CompMap types. Other common +composition manipulation functions will live here. They will operate on +CompMap's because Composition's themselves are immutable. Resource +and Composition classes will use these methods where appropriate instead of +their own, internal versions. This namespace is intended to grow organically as +needed. + +.. code-block:: c++ + + namespace cyclus { + namespace compmath { + + CompMap Add(const CompMap& v1, double qty1, + const CompMap& v2, double qty2); + + /// previously Material::Diff + CompMap Sub(const CompMap& v1, double qty1, + const CompMap& v2, double qty2); + + void ApplyThreshold(CompMap* v, double threshold); + + void Normalize(cyclus::CompMap* v, double val); + + bool ValidIsos(const CompMap& v); + + bool AllPositive(const CompMap& v); + + bool AlmostEq(const CompMap& v1, + const CompMap& v2, + double threshold); + + } // namespace compmath + } // namespace cyclus + + +MatQuery class +~~~~~~~~~~~~~~~~~~~~~~ + +(This interface will probably need extension) + +This is intended to allow user-developers to *easily* retrieve any kind of +information about a material they could ever reasonably need. The interface is +designed to grow organically as needed. + +.. code-block:: c++ + + class MatQuery { + public: + MatQuery(Material::Ptr m); + + /// Convenience constructor that auto-casts a Resource::Ptr to a + /// Material::Ptr. + MatQuery(Resource::Ptr m); + + double mass(Iso iso); + + double moles(Iso iso); + + double mass_frac(Iso iso); + + double atom_frac(Iso iso); + + double qty(); + + bool AlmostEqual(Material::Ptr other, double threshold=cyclus.eps()); + }; + +Other Changes +++++++++++++++ + +The RecipeLibrary's role of composition decay management has been shifted into +the Composition class. *The decay lineage tracking functionality introduced by +Matt Gidden has been effectively preserved.* RecipeLibrary now is only +responsible for loading recipes from xml input and serving them up simulation +wide. Agents are also allowed to register their own compositions manually. +RecipeLibrary interface becomes: + +.. code-block:: c++ + + class RecipeLibrary { + public: + /** + Gives all simulation objects global access to the RecipeLibrary by + returning a pointer to it. + Like the Highlander, there can be only one. + + @return a pointer to the RecipeLibrary + */ + static RecipeLibrary* Instance(); + + /** + loads the recipes from the input file + */ + void LoadRecipes(QueryEngine* qe); + + /** + loads a specific recipe + */ + void LoadRecipe(QueryEngine* qe); + + /** + records a new recipe in the simulation + - records the recipe in the BookKeeper + + @param recipe the recipe to be recorded, a CompMapPtr + */ + void AddRecipe(std::string name, Composition::Ptr c); + + /** + This returns a CompMapPtr to the named recipe in the recipes_ map + + @param name the name of the parent recipe, a key in the recipes_ map + */ + Composition::Ptr GetRecipe(std::string name); + }; + +Backwards Compatibility +======================== + +Most backwards incompatible changes are unambiguously described by the +reference implementation at https://github.com/rwcarlsen/cycamore ("res" +branch). Existing modules will need to be updated to use the new API's. These +changes are fairly straight forward and include: + +* Material queries will have to be modified to use MatQuery class. + +* CompMap/IsoVector creation will need to change to use new Composition + factory methods. + +* Material creation will need to change to use new Material factory + methods. + +* Agents (esp. reactors) must be modified to transmute rather than + throw-away/create material. + +Other Notes +============ + +Current implementation bugs +++++++++++++++++++++++++++++ + +* The current (before this CEP) |Cyclus| core does not correctly record + decayed compositions in the output database. This makes comparing + simulation output size and performance with that of this CEP's proposed + changes not exactly "fair". + +Backends and Performance ++++++++++++++++++++++++++ + +Preliminary investigation on my part indicates that this extra tracking +will cause significant slowdown using an Sqlite backend database *when +material decay is frequent*. This slowdown prompted the development of a +faster HDF5 alternative (currently merged into develop branch). + +Basic performance stats were collected by running a full |cyclus| +inpro_low.xml simulation ``time cyclus [path/to/]inpro_low.xml``. For +reference: + +* ~50,000 material objects total +* 1100 months +* 2200 decay calculations +* ~28,000,000 resource object state changes recorded (with CEP implemented) + +|Cyclus| was built with CMake's "RELEASE" mode. Results reported are +approximate and specific to my office computer. + +Without proposed changes (decayed compositions are not recorded - current bug): + +===================== ========= =============== +* Backend +--------------------- ------------------------- +Decay Sqlite Hdf5 +===================== ========= =============== +Every 2nd timestep 40 sec. 15 sec. +None 40 sec. 15 sec. +===================== ========= =============== + +With proposed changes: + +===================== ========= =============== +* Backend +--------------------- ------------------------- +Decay Sqlite Hdf5 +===================== ========= =============== +Every 2nd timestep 16 min. 55 sec. +None 54 sec. 15 sec. +===================== ========= =============== + +With proposed changes running inpro_low.xml with decay on and hdf5 backend: + +* Event and EventManager code takes ~20% of +* Hdf5Back code takes ~20% of runtime. +* ticking, tocking, and daily-tasking take about ~45% of runtime. +* Decay calculations take ~10% of runtime. + +Decay Initiation +++++++++++++++++++ + +There has been some debate regarding the best way(s) to handle decaying +material objects in the simulation. Options include: manually by agents, +automatically and periodic, automatically at transaction time, and others. +While this involves the resource+material classes and can have a large +impact on simulation speed and output size, it has no direct impact on nor +directly impacts this proposal. Further discussion on this can be found +here https://github.com/cyclus/cyclus/issues/466 and to lesser degree +https://github.com/cyclus/cyclus/issues/204. + diff --git a/_sources/cep/cep18.rst.txt b/_sources/cep/cep18.rst.txt new file mode 100755 index 000000000..b90fef19b --- /dev/null +++ b/_sources/cep/cep18.rst.txt @@ -0,0 +1,530 @@ +CEP 18 - Dynamic Resource Exchange Procedure +******************************************** + +:CEP: 18 +:Title: Dynamic Resource Exchange Procedure +:Last-Modified: 2013-11-04 +:Author: Matthew Gidden +:Status: Accepted +:Type: Standards Track +:Created: 2013-09-02 + +Abstract +======== + +An updated procedure for determining dynamic resource exchanges is presented. It +occurs nominally in four phases: a request for bids, a response to the request +for bids, preference assignment, and resolution. The first three phases +encompass an information gathering procedure, providing generic information to +any market exchange solution procedure. The final phase is modular in that any +algorithm can be used to solve the exchange. This modular phase takes the place +of the current implementation of MarketModels. The procedure is informed by +agent-based supply chain modeling literature :cite:`julka_agent-based_2002` with +modifications as required for our nuclear-engineering domain specific +information. + +Motivation +========== + +The current implementation of Markets in |Cyclus| includes a base MarketModel +class which is intended to be derived from by concrete, dynamically loaded, +user-defined classes. Markets are assigned specific commodities, i.e., there is +no communication across demand for multiple commodities. Markets act in the +simulation during the **resolve** step, which occurs after the **tick** and +before the **tock** for each timestep. + +Markets are communicated with through Messages. Communication to Markets utilize +the Transaction class to define whether the communication is an **offer** or +**request** for the Market's commodity. Communication is initialized by +Facilities, but there is no |Cyclus| core support for this operation. Individual +derived Facilities (e.g., the Sink and Source in Cycamore) +define this functionality during their **HandleTick** functions. This +interaction is invoked during the tick phase in the current facility invocations +purely by practice. There is no requirement for such behavior; for example, one +could send an offer or request during the tock phase, which would be ignored +until the proceeding resolve step. In general lookups for specific markets and +dynamic casts to communicate with those markets are required. + +The MarketModel class defines a pure virtual function, **Resolve**, which is +used by derived classes to determine the specific algorithm by which the market +is to be resolved. Markets receive proposed Transactions through their +Communicator class interface, which requires the **ReceieveMessage** function to +be defined by the market. The Resolve function then invokes the derived-class +algorithm to determine matches for the given set of offers and requests. + +This class structure and interaction has worked well for a proof-of-prototype +use of |Cyclus| to model simple, once-through fuel cycles. However, an extension +or refactor is necessary to model more complicated fuel cycles for a number of +reasons. First, there is no support for facilities that can offer or request +resources across multiple commodities if a capacity is included. The current +implementation of the market system can only provide this notion by ordering the +markets in some arbitrary manner. Second, and perhaps least important of these +reasons, is that the Transaction class is ambiguous with respect to proposed +offers, requests, and matched offers and requests. This ambiguity can be +addressed during a refactor to provide clarity to future developers. Third, +there is no defined structure to the market-facility interaction. This +interaction is the core purpose of |Cyclus|' Dynamic Resource Exchange concern, +but users and developers are required to define their own interactions (e.g., +sending offers during the tick phase). The original conception of the tick-tock +paradigm was to define a notion of time before the resource exchange (i.e., a +pre-step) and after the resource exchange (i.e., a post-step). The current +implementation includes the resource exchange concern during both of these +phases, complicating the process and mixing concerns. Finally, there is no +response mechanism for facilities to delineate between resources of a given +commodity. The current implementation places this concern upon the market's +resolution algorithm, rather than on the facility via some communication +mechanism, again muddying the concerns associated with the resource exchange. + +Rationale +========= + +The proposed refactor addresses each of the issues provided in the previous +section. The notion of market models is redefined, separating the collection of +supply-demand information from the algorithm used to match suppliers with +consumers. The information gathering framework is structured and handled by the +|Cyclus| core (i.e., not adjustable by model developers). It is top-down in the +sense that it queries facilities for their supply and demand rather than +requiring facility-based notifications. Accordingly, concerns are appropriately +separated: the information is gathered by the core at the beginning of the +resolve step, allowing facilities to inform a given market algorithm; market +algorithms determine the set of offers and requests to be matched; and the core +sends out resolved transactions. Message passing to and from markets is +addressed by the framework, providing facilities, institutions, and regions each +with specific, defined agency. + +Supply-Demand Framework +----------------------- + +Supply-demand determination at any given time step occurs in nominally three +steps, or **phases**, and the associated terminology is taken from previous +supply chain agent-based modeling work +:cite:`julka_agent-based_2002`. Importantly, this information-gathering step is +agnostic as to the actual matching algorithm used, it is concerned only with +querying the current status of supply and demand and facility preference thereof +in the simulation. + +The first phase allows consumers of commodities to denote both the quantity of a +commodity they need to consume as well as the target isotopics, or quality, by +**posting** their demand to the market exchange. This posting informs producers +of commodities what is needed by consumers, and is termed the **Request for +Bids** (RFB) phase. Consumers are allowed to over-post, i.e., request more +quantity than they can actually consume, as long as a corresponding capacity +constraint accompanies this posting. Further, consumers are allowed to post +demand for multiple commodities that may serve to meet the same combine +capacity. For example, consider an LWR that can be filled with MOX or UOX. It +can post a demand for both, but must define a preference over the set of +possible commodities it can consume. Another example is that of an advanced fuel +fabrication facility, i.e., one that fabricates fuel partially from separated +material that has already passed through a reactor. Such a facility can choose +to fill the remaining space in a certain assembly with various types of fertile +material, including depleted uranium from enrichment or reprocessed uranium from +separations. Accordingly, it could demand both commodities as long as it +provides a corresponding constraint with respect to total consumption. + +At the completion of the RFB phase, the market exchange will have a set of +consumption portfolios, :math:`P`, for each requester in the exchange, shown as +the orange box in Figure 1. Each portfolio consists of a set of requests, +:math:`R`, a cardinal preferential ordering over the requests, :math:`\alpha_R`, +and possibly a set of constraints over the requests, :math:`c_R`. A constraint +can be associated with more than one request. Take the previous example of MOX +and UOX for an LWR. Each is a separate request, but a constraint may be +concerned with the combination of the two. Another example is a repository that +may request many commodities, but has a radiotoxicity constraint over any +commodities it receives for a given time step. + +A request consists of a quantity, :math:`q_r`, and a target isotopic vector, +:math:`I_r`. Consumers are allowed to offer the null set of isotopics as their +profile, effectively providing no information. In general, a requester may have +more than one request (nodes in Figure 1) per commodity. A prime example is a +reactor that chooses to requests fuel assemblies, of which they request many. + +.. image:: cep-0018-3.png + :align: center + :scale: 50 % + +**Figure 1:** A Requester during the RFB Phase, where a collection of requests +(as nodes) is shown. + +The second phase allows suppliers to **respond** to the set of consumption +portfolios, and is termed the **Response to Request for Bids** (RRFB) phase +(analogous to Julka's Reply to Request for Quote phase). Each consumption +portfolio is comprised of requests for some set of commodities, and suppliers of +those commodities are allowed to respond to demand. Suppliers, like consumers, +are allowed to offer the null set of isotopics. + +A supplier may have its production constrained by more than one parameter. For +example, a processing facility may have both a throughput constraint (i.e., it +can only process material at a certain rate) and an inventory constraint (i.e., +it can only hold some total material). Further, the facility could have a +constraint on the quality of material to be processed, e.g., it may be able to +handle a maximum radiotoxicity for any given time step which is a function of +both the quantity of material in processes and the isotopic content of that +material. + +At the completion of the RRFB phase, the market exchange will have a set of +supplier responses for each request. The supplier responses define the possible +connections between supplier and producer facilities, i.e., the arcs in a graph +of a matching problem. A response is comprised of a proposed isotopic profile +the supplier is able to provide. Furthermore, constraints can be associated with +the set of responses to be applied by the market matching algorithm. A +constraint must identify the requests that it is associated with, define a +capacity, and define a translation function. The translation function takes a +request as an argument and returns a value in the units of the constraint. A +prime example is an enrichment facility, which may be able to enrich many +orders, but is constrained by the total SWUs it can provide. + +.. image:: cep-0018-4.png + :align: center + :scale: 50 % + +**Figure 2:** A Supplier during the RRFB Phase, where a collection of commodity +supplies (as nodes) is shown. + +The final phase of the information gathering procedure allows consumer +facilities to adjust their set of preferences and for managers of consumer +facilities to affect the consumer's set of preferences, as described in the +remaining sections. Accordingly, the last phase is termed the **Preference +Adjustment** (PA) phase. Preference adjustments can occur in response to the set +of responses provided by producer facilities. Consider the example of a reactor +facility that requests two fuel types, MOX and UOX. It may get two responses to +its request for MOX, each with different isotopic profiles of the MOX that can +be provided. It can then assign preference values over this set of potential MOX +providers. Another prime example is in the case of repositories. A repository +may have a defined preference of material to accept based upon its heat load or +radiotoxicity, both of which are functions of the quality, or isotopics, of a +material. In certain simulators, limits on fuel entering a repository are +imposed based upon the amount of time that has elapsed since the fuel has exited +a reactor, which can be assessed during this phase. The time constraint is, in +actuality, a constraint on heat load or radiotoxicity (one must let enough of +the fission products decay). A repository could analyze possible input fuel +isotopics and set the arc preference of any that violate a given rule to 0, +effectively eliminating that arc. + +It should be noted that these preferences are requester based. This choice is +based on the current simulation design notion of requesters having a preference +over possible inputs. It is possible that in the future, one would like to model +the notion of supplier preference (i.e., more so than the implicit nature +currently provided by allowing suppliers to set the transaction quality and +whether to respond to the transaction at all). One suggestion may be to allow +suppliers to also have a supply preference, and to use the average of them in +the objective function, but this gets into even murkier modeling/simulation +ground. Another would be to move the paradigm more towards economics and have +the suppliers set the cost of a transaction, which they could tailor to the +requester. However, this draws in a whole other field of bidding that requires +much more rigor and thought as to its validity and implementation. + +.. image:: cep-0018-5.png + :align: center + :scale: 50 % + +**Figure 3:** A supplier-consumer pair with request isotopics, response +isotopics, and an associated preference. + +Institutions and Regions in |Cyclus| are provided in order to add granularity to +the levels of relational modeling available to a user or developer. Both types +of agents or models in |Cyclus| can possibly be allowed to affect preferences +during the PA phase. A slightly longer discussion is included below. + +Facility Agency ++++++++++++++++ + +Facilities in |Cyclus| are abstracted to either consumers or suppliers of +commodities, and some may be both. Supplier agents are provided agency by being +able to communicate to the market-resolution mechanism a variety of production +capacity constraints in second phase of the information gathering +methodology. Consumer agents are provided agency by being able to assign +preferences among possible suppliers based on the supplier's quality of +product. Because this agency is encapsulated for each agent, it is possible to +define strategies that can be attached or detached to the agents at +run-time. Such strategies are an example of the Strategy design pattern +:cite:`vlissides_design_1995`. + +Institutional Agency +++++++++++++++++++++ + +Institutions in |Cyclus| manage a set of facilities. Facility management is +nominally split into two main categories: the commissioning and decommissioning +of facilities and supply-demand association. The goal of including a notion of +institutions is to allow an increased level of detail when investigating +regional-specific scenarios. For example, there exist multi-national +enterprises, such as AREVA, that operate fuel cycle facilities in a variety of +countries, or regions. Furthermore, there are international governmental +organizations, such as the IAEA, have proposed managing large fuel cycle +facilities that service many countries in a given global region. A fuel bank is +an example of such a facility. + +Accordingly, institutions in this proposal are able to augment the preferences +of supplier-consumer pairs that have been established in order to simulate a +mutual preference to trade material within an institution. Of course, situations +arise in real life where an institution has the capability to service its own +facilities, but choose to use an outside provider because of either cost or time +constraints. Such a situation is allowed in this framework as well. It is not +clear how such a relationship should be instantiated and to what degree +institutions should be allowed to affect their managed facilities' +preferences. This issue lies squarely in the realm of simulation design +decisions, part of the **art** of simulation. Accordingly, the strategy of +affecting preferences is encapsulated within the full preference allocation +phase in order to allow for further modularity of relational options between +agents. + +Regional Agency ++++++++++++++++ + +Regions are provided agency by their ability to affect preferences between +supplier-consumer facility pairs in the PA phase, much like institutions. The +ability to perturb arc preferences between a given supplier and a given consumer +allows fuel cycle simulation developers to model relatively complex interactions +at a regional level, such as tariffs and sanctions. Constraints to cross-border +trading can also be applied. For example, a region could place constraints on +the total amount of a given commodity type that is able to flow into it or out +of it into a different region. Such constraints could be applied not only to +bulk quantities of a commodity, but also to the quality of each commodity. Such +a mechanism could be used to model interdiction of highly-enriched uranium +transport, for example. + +.. image:: cep-0018-2.svg + :align: center + +**Figure 4:** Information Gathering Phase Order. + +.. blockdiag code below + + http://interactive.blockdiag.com/?compression=deflate&src=eJztVd1qwyAYvd9TfLjrQVihpJQMmsKgd2n6AMUuX9KAqDMKKyHvXqNbfrbsCexBQY-KcvQc2yeAAktqmD5XShh5_hBMKEiAC45bCBETSZorlWjFsMrwAouL-Nr2w7aQo0F1gxw_DTYaVUPg5e2HPRkpWT2QwyTIFJaW9Ju46kSH1rWB0QuyhOTvGVk-F4C7noQ8R1GcxunStLDgRFm4jKDRi9L9fmEPOIxGs74m-T9eCw2zbEnjeB2Fmi3TQBlzfHDUt5umcZ3tyEy-zWb1ut97Tqgauaa6Ftw-NymUVrTWfo8_30L_Vxx4o6f9HKt-rWf8Kbo7GUM8HQ + + blockdiag { + default_group_color = none; + default_shape = roundedbox; + + "Query Requesters" -> "Query Suppliers" -> "Requester Prefs" + + group { + label = "RFB" + color="#008B8B" + "Query Requesters" + } + + group { + label = "RRFB" + color="#B8860B" + "Query Suppliers" + } + + group { + label = "PA" + color="#9932CC" + orientation = portrait + + "Requester Prefs" -> "Inst Prefs" -> "Region Prefs" + } + } + +Market Resolution +----------------- + +Upon completion of the information gathering step, all information regarding the +exchange is known. Importantly, proposed resource qualities, constraining values +based on the resource quality, and other data such as preferences and/or costs +are known. Given these static values, the exchange can be translated to a graph +with supplier/consumer nodes, arcs defined by bids, supplier and consumer +constraints on those arcs, and consumer-based preferences for those arcs. + +The exchange is responsible for translating its gathered information into such a +graph formulation, and various solvers can solve the material flow along the +arcs of that graph. The solutions are then provided to the exchange for +back-translation into resource-specific request-bid pairs. Given such pairings, +the exchange executes the trades. + +It is important to note that a generic solver interface is defined and its +constructor is provided a resource exchange graph. Different subclasses can +define solution algorithms given the graph. + +Specification \& Implementation +=============================== + +Each major phase method and associated classes are treated. Method inputs and +outputs are described as well as known issues dealing with their +implementation. The members and methods of proposed classes are also +described. Because the phases utilize new classes and containers, those are +described first. + +Constituent Classes and Containers +---------------------------------- + +The major new data structures required for this proposal are: + +* Bids +* BidPortfolios +* CapacityConstraints +* Requests +* RequestPortfolios + +Reference implementation (in /src) and tests (in /tests) for each can be found +in the `CEP18 branch`_. + +A template approach has been taken, delineating, for instance, a material +request, ``Request``, from a GenericResource request, +``Request``. The current behavior (i.e., only using parent +classes and dynamic casting to derived classes) can be invoked by templating on +the ``Resource`` type, i.e., ``Request``. See the `capacity constraint +tests`_ for an example of this range of behavior. + +Resource Exchange +----------------- + +The resource exchange is implemented through coordination of two classes, the +ResourceExchange and the ExchangeContext, both of which are implemented with +tests in the `CEP18 branch`_. + +The ExchangeContext retains the current state of the exchange, including +information regarding the players (i.e., requesters and suppliers) as well as +information regarding requests and bids. The ResourceExchange initiates the +various phases and updates the context state. As currently envisioned, an +exchange and context's lifetime is the single resolution of the exchange at a +given time. The exchange is populated with traders as known by the wider +simulation context. Both the ExchangeContext and ResourceExchange are templated +on the Resource being exchanged, as was the case above. An overview of the +exchange implementation follows, noting the state updates of the context at each +phase. + +RFB Phase ++++++++++ + +Note that the ExchangeContext has no state at the beginning of the phases. + +ResourceExchange operations: + +* Queries each Trader registered with the simulation Context, asking for + RequestPortfolios + +ExchangeContext state at end of phase: + +* Requesters +* Requests +* RequestPortfolio + +RRFB Phase +++++++++++ + +ResourceExchange operations: + +* Queries each Trader registered with the simulation Context, asking for + BidPorftolios +* The ExchangeContext is given to each trader in order to determine all Requests + for a specific commodity + +ExchangeContext state at end of phase: + +* Bidders +* BidPortfolios +* Default preferences for each Bid-Request pair (provided in the original Request) + +PA Procedure +++++++++++++ + +ResourceExchange operations: + +* For each Requester and each parent in the Model child-parent tree of that + Requester, preferences are allowed to be perturbed, which looks nominally like: + +.. code-block:: c++ + + /// @brief allows a trader and its parents to adjust any preferences in the + /// system + void DoAdjustment(Trader* t) { + typename PrefMap::type& prefs = ex_ctx_.Prefs(t); + Model* m = dynamic_cast(t); + while (m != NULL) { + cyclus::AdjustPrefs(m, prefs); + m = m->parent(); + } + }; + +For full implementation details, please see the `CEP18 branch`_. + +ExchangeContext state at end of phase: + +* Possibly perturbed preferences for each Bid-Request pair + +ExchangeGraph +------------- + +An ExchangeGraph is a graph representation of a resource exchange. It provides a +resource-free representation of the exchange, i.e., the quality-specific +constraint and preference values are "baked in". By the nature of the +supplier/requester setup, the graph is bipartite, thus there is a notion of U +(left) and V (right) nodes, and arcs strictly connect a U node to a V +node. Constraints are defined along arcs, where each u-v node pair is associated +with a constraining value. Preferences are also defined along arcs. + +ExchangeTranslator +------------------ + +The ExchangeTranslator is an object responsible for translating a given +ExchangeContext into an ExchangeGraph, and has a pretty simple interface: + +.. code-block:: c++ + + template + struct ExchangePair { + Request::Ptr r; // request + Bid::Ptr b; // bid + double p; // percent of bid to give + } + + template + class ExchangeTranslator { + public: + ExchangeGraph ToGraph(const ExchangeContext& ec) { + /* do translation */ + }; + + std::set< ExchangePair > + FromGraph(const ExchangeGraph& eg) { + /* do back-translation */ + }; + }; + +ExchangeSolver +-------------- + +The ExchangeSolver is a virtual interface for solvers of a resource exchange. A +constrained ExchangeGraph is provided as input, and a solution ExchangeGraph is +provided as output, which satisfies the provided constraints. It too, has a +pretty simple interface + +.. code-block:: c++ + + class ExchangeSolver { + public: + virtual void Solve(const ExchangeGraph& g) = 0; + }; + +Backwards Compatibility +======================= + +This CEP proposes a number of backwards incompatibilities. + +- The MarketModel is replaced by an information gathering procedure and a + modular MarketAlgorithm + +- Transactions are reduced to accepted offers, rather than proposed offers and + requests + +- The Message and Communicator classes are no longer needed + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. rubric:: References + +.. bibliography:: cep-0018-1.bib + :cited: + +.. _CEP18 branch: https://github.com/gidden/cyclus/tree/cep18 + +.. _capacity constraint tests: https://github.com/gidden/cyclus/blob/cep18/tests/capacity_constraint_tests.cc diff --git a/_sources/cep/cep19.rst.txt b/_sources/cep/cep19.rst.txt new file mode 100755 index 000000000..9182e07bb --- /dev/null +++ b/_sources/cep/cep19.rst.txt @@ -0,0 +1,602 @@ +CEP 19 - |Cyclus| Input Procedure Updates +******************************************** + +:CEP: 19 +:Title: |Cyclus| Input Procedure Updates +:Last-Modified: 2013-10-16 +:Author: Dr. Tony Scopes & Robby Flanny +:Status: Withdrawn +:Type: Standards Track +:Created: 2013-10-16 + +Introduction +============ + +This CEP proposes to update the |cyclus| input paradigm and the module schemas such that +they enable a wider variety of tools. This CEP was written with two types of tools in mind: +graphical user interfaces and large scale parameter investigations. The goal of this +CEP is to give the input scheme the descriptive power it needs to provide users and module +developers with an elegent and clear method of building |cyclus| input files. + + +The first major change is to develop a suite of patterns for use by |cyclus| module schema. +These patterns are meant to richly representing module input fields. These patterns will be a +collection of elements that provide sufficient metadata needed by the two use cases listed +above. For instance, one such additional element is 'tooltip'. + +The second change is the addition of an interface to modules. This interface will be used in +conjuction with the current 'schema()' member function. This function will be called 'default_inputs()' +and return an xml input file snippit for the facility with default values in all input fields. + +Motivation +========== +CycIC (and other less useful interfaces) requires this new suite of patterns to provide users with +a better experience. For example integrated module documentation is part of this proposal. In addition, +many elements of the pattern will also be useful for parametric sweeps. + +Specification \& Implementation +=============================== +The following patterns are proposed to be added to the master |Cyclus| schema. + + +Tooltip ++++++++ +Tooltip elements is a short string of text that the developer can add to an input field that will +show when a user scrolls over this field in the graphical user interface. This is an optional field. + +.. code-block:: xml + + + + + + + + +Help +++++ +Help elements will provide a more thorough explaination of the input field, it can be accessed through the +graphical user interface. This is an optional field. + +.. code-block:: xml + + + + + + + + +Units ++++++ +Units elements apply information to an input field that indicate to the user what units are attached to the +value in this field. + +.. code-block:: xml + + + + + + + + +User Level +++++++++++ +User level elements allow developers to set the user level of a specific input field. This value ranges +from 0 to 10 with 0 being simple inputs and 10 being very advanced inputs. This is an optional field +and if left blank the value will be set to zero by the graphical user interface. + +.. code-block:: xml + + + + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + + + + + +Vary +++++ +The 'vary' element is a special boolean element that allows a |cyclus| user to set wether the input +field it is attached to can be varied for a parametric study. This flag is optional and can take +the values "true", "false", "1", "0". + +.. code-block:: xml + + + + + + + + +Sampling Function ++++++++++++++++++ +Sampling function is an element that goes with the vary element. If the vary element is set to true +a sampling function is required to provide the sampling behavior for the element. This is a string +input that represents the mathematical expression of the sampling function. This is an optional flag. + +.. code-block:: xml + + + + + + + + +Field Types ++++++++++++ + +The field types used for input fields are listed below. In general they are associated with a +specific data type. In addition there are several field types that are categorical. This +implies that the field has discrete values for which it can take. + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Cycic Specific Tags +=================== +In order to facilitate loading |cyclus| scenarios that were previously built with CycIC +some additional fields are proposed to be added to the xml grammar. These fields will +hold information on how to display the graphical parts of the simulation. + +This portion of the xml file will not be read by |cyclus|, and should have no impact on +the |cyclus| core code. + +Top level Information ++++++++++++++++++++++ +Here the name of the CycIC simulation, a description, and some comments about it +can be saved. + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Facility Circles +++++++++++++++++ +Here the initital proposal is to save the x and y locations of the facilities so that +they may be loaded in the proper place. + +.. code-block:: xml + + + + + + + + + + + + + + + + +Market Circles ++++++++++++++++ +Here the initital proposal is to save the x and y locations of the markets so that +they may be loaded in the proper place. + +.. code-block:: xml + + + + + + + + + + + + + + + + +Region Shapes ++++++++++++++++ +Here the initital proposal is to save the x and y locations of the region nodes so that +they may be loaded in the proper place. + +.. code-block:: xml + + + + + + + + + + + + + + + + +Institution Shapes +++++++++++++++++++++ +Here the initital proposal is to save the x and y locations of the institution +nodes so that they may be loaded in the proper place. + +.. code-block:: xml + + + + + + + + + + + + + + + + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. rubric:: References + diff --git a/_sources/cep/cep2.rst.txt b/_sources/cep/cep2.rst.txt new file mode 100755 index 000000000..1ed627b16 --- /dev/null +++ b/_sources/cep/cep2.rst.txt @@ -0,0 +1,316 @@ +CEP 2 - Separation of Concerns in the |cyclus| Ecosystem +******************************************************** + +:CEP: 2 +:Title: Separation of Concerns in the |cyclus| Ecosystem, or Where Do I Put My Code? +:Last-Modified: 2017-09-01 +:Author: Anthony Scopatz, Matthew Gidden +:Status: Accepted +:Type: Process +:Created: 2013-08-05 + +Abstract +======== +The purpose of this CEP is to clearly delineate the purpose -- technical and +cultural -- of the various projects which make up the |cyclus| ecosystem. +Projects, for purposes here, are unique entities which have independent lifetimes +and central concerns. Many projects may try to tackle the same concern but no +single project may tackle more than one concern. Concerns, like projects, may +be dependent upon one another. + +The central concerns in the |cyclus| ecosystem are +**dynamic resource exchange simulation** (DRES), **domain models** (DM), +**analysis & visualization** (A&V), and **simulation orchestration** (ORC). + +Concerns +======== +A rich fuel cycle simulator solution has four primary organizational pieces that +must have robust implementations. These pieces are a mechanism for solving for +resource exchange in the fuel cycle, relevant and interesting models for the +domains of interest (physics, economics, policy, etc.), a +programmatic method for parsing, slicing, aggregating, and displaying +simulation results, and a mechanism for executing and collecting many simulations. +As an effectively designed suite of software, these concerns +should be completely separated from one another +and interact only through well-defined interfaces [1]_. This +independence allows both users and developers to reason about each concern +without needing to consider upstream effects. Coupled with a stable interface +or API, this independence also allows users and developers to ignore downstream +effects in most cases. + +The domain model concern is dependent only on the resource exchange concern. +However, the analysis & visualization concern is directly dependent on both the +resource exchange and the domain model concerns. These relationships may be seen +in Figure 1. + +.. figure:: cep-0002-1.svg + :align: center + + **Figure 1:** Dependencies Between Concerns + +.. blockdiag code below + + http://interactive.blockdiag.com/?compression=deflate&src=eJxlkM9qwzAMxu95CtHDbnuC0MFgO47BBr0so7i21ghsKfjPSFv27jOJkyyZb5J-nz_pAwC4QQXDM_ilko3Hs5fUHbVY8bAHFsZ6Q4RWdZhnGWSD5iR9XRXEY8Bew4dVJ7T73dOFlSMNbxgkeY0NP_e6VXxGeCeXrIokvPucDcQ5MYtanCKGFzFow0Iptt90nalHVvYSKMBdwwcKSVm6bv4N5MQvWy3WDb963WKIviiqteL-oVy08c79kajXd-f-SMyBDGnCrVQA4gk5Dm45wU58tqZYz_NJPtVjJFP9889uPS8B_lljVP0CxFWTeA + + { + default_group_color = none; + default_shape = roundedbox; + + resexc [label="Dynamic Resource\nExchange Simulation"]; + dommod [label="Domain Models"]; + anlviz [label="Analysis &\nVisualization"]; + simorc [label="Simulation\nOrchestration"] + + simorc -> resexc; + anlviz -> simorc; + resexc -> anlviz; + + group { + orientation = portrait; + anlviz; + dommod; + } + resexc -> dommod; + dommod -> anlviz; + } + + +Dynamic Resource Exchange Simulation +------------------------------------ +The dynamic resource exchange simulation concern is the basis for all other fuel +cycle concerns. This dictates and manages how resources flow through a system and +the time paradigm used to model the system. A number of possible representations of +system elements exist. Two main options stand out: 1) *individual-based* models in +which every actor receives its own instance, and 2) *fleet-based* models where +like actors are grouped together and act identically. Resource exchange may be +implemented using a strict *agent-based* modeling [2]_ approach or strict +*system dynamics* methods [3]_. However, these two paradigms are not restrictive +and implementations may pull from a variety of algorithms as needed. + +Furthermore, the choice of how to represent time evolution may fall into one +of the following categories: + +* **Equilibrium** - initial transients are ignored or discarded in favor of a steady + state solution. +* **Quasi-static** - initial transients are computed but natural time (sec, min, etc) + are replaced with an easier to compute number of passes through a given + actor. +* **Discrete time** - natural time is implemented but discretized to some minimum + and constant dt. +* **Adaptive time** - natural time is implemented and discretized, but the value of + dt may change from time step to time step, allowing for finer resolution only + when needed. +* **Continuous time** - natural time is implemented as a continuous variable. + +It is important to note that this concern is a solely mathematical endeavor and +should not implement any domain-specific calculations. However, the +implementation may be *domain-aware* in that it may know about certain sub-type +specializations. For example, materials and U.S. Dollars are both sub-types of +resources. Still, the dynamic resource exchange simulation concern is not +allowed to discriminate between any of these specializations nor perform +domain-specific computations (such as transmuting a material or pricing a +derivative). + +This concern is responsible for housing general archetypes that allow for +general, dynamic simulation of supply chain networks in a resource-neutral +manner. Supply chain network models require, at minimum, three types of entities +(i.e., nodes) :cite:`bazaraa2011linear`: + +* Sources (supply nodes) +* Storage (transshipment nodes) +* Sinks (demand nodes) + +In addition to enabling such basic simulations, the dynamic resource exchange +simulation concern is also responsible for all optimizations of the fuel cycle. +This includes optimizing resource exchange between multiple actors as well as +finding the initial conditions which optimize a value function subject to some +constraints. + +Domain Models +------------- +The purpose of the domain models concern is to provide interesting, accurate, and +relevant models of various aspects of the fuel cycle. These aspects are often the +technical meat of the fuel cycle analysis. However, they may be mathematically +separated from resource exchange. This concern ensures that those mathematical +separations remain distinct in the software. There are a number of domain models +which are pertinent to fuel cycle calculations: + +* Physics +* Chemistry +* Health Physics +* Economics +* Public Policy +* and more! + +The implementation of specific domain computations should rely on the system dynamics +for all systematic flow and timing needs. The implementation of the domain +calculations should be completely separated from the system dynamics concern. +This establishes a clean interface between these two concerns. + +For example, take an enrichment facility which is asked to compute product and tails +enrichments. In the initialization of this calculation, the dynamic resource +exchange simulation concern hands off the simulation time (t), the time delta (dt), +and the initial feed material to the underlying physics model. The physics model +then computes the desired outputs without further interaction with the resource +exchange model. Lastly, the outputs are returned to the DRES model. + +Analysis & Visualization +------------------------ +The purpose of the analysis & visualization concern is to supply aggregation and +introspection into the simulation outputs. The analysis may take place at both +high and low levels, common aggregations should be easy to perform, and static +and interactive visualization should be provided as a mechanism for easy human +consumption. All post-processing of simulation data falls under this concern. + +The analysis & visualization concern is dependent directly on both the dynamic +resource exchange simulation concern and the domain models concern. This is because +meaningful inspection of simulation data requires parameters from both concerns. +Note that these dependencies are independent. The analysis & visualization tools +must handle the case where only DRES models are used. However, if domain models +are used and the analysis & visualization is aware of these domain models, +all DRES parameters are guaranteed to also be present. + +Simulation Orchestration +------------------------ +Simulation campaigns often involve executing multiple instances of the DRE and +associated analysis and visualization. This may be with the purpose of, + +* performing a sensitivity study, +* running a parameter sweep, +* sampling from a large option space, or +* creating a training set for machine learning models. + +This execution and analysis is either managed manually or automatically, but it +is always managed. Running, analyzing, visualizing, and generating many |cyclus| +input files is termed here "orchestration." This includes provisioning compute +resources where these tasks are executed. Data management also falls under the +purview of simulation orchestration. + +Simulation orchestration provides a feedback loop for the |cyclus| ecosystem. +It both drives the DRE simulator and incorporates the results of previous +simulations. + + +The |Cyclus| Ecosystem +====================== +While many fuel cycle simulators may choose to implement all of the above concerns +in a single project, each concern in the |cyclus| ecosystem is implemented in +its own project. Many projects may satisfy the needs of a concern. However, no +project may try to address multiple concerns. This provides a clear guideline +for which projects should accept which kinds of code. + +If for some reason ambiguities exist, first attempt to refactor the code at hand +with these concerns in mind. If this fails because of a fundamental ambiguity +or mixing of multiple concerns, place the code with the most dependent concern. +For example, if it is not clear if a class belongs with domain models or with the +resource exchange put it with the domain models to be safe. + +The |cyclus| development team currently supports projects for these concerns: + +* `Cyclus`_ - Dynamic Resource Exchange Simulation (individual actors, discrete + time, canonical supply chain entities) +* `Cycamore`_ - Domain Models +* `Cymetric`_ - Analysis & Visualization +* `Cyclist`_ - Analysis & Visualization (historical) +* `Rickshaw`_ - Simulation orchestration + +The dependency graph for these projects is similar to the graph of the concerns. +Figure 2 displays this graph along with other projects which implement these concerns. + +.. figure:: cep-0002-2.svg + :align: center + + **Figure 2:** Dependencies Between Projects is |Cyclus| Ecosystem. + +.. blockdiag code below + + http://interactive.blockdiag.com/?compression=deflate&src=eJyFUstqwzAQvOcrFgV6M_QYY1JI1fZQKIUUeiklyNLGFpW1QZLbJCX_XsV52HESqtNKM7MzWhYA4HcAzVE4F7UJs8JRvZhJMuRgDJYsZj2GL8UCIxaJVqHKaZkN9pRGDA49LuWxMwA5jTaIoMlG3YJccEKH7IgbkaMZsyl6qp1EeFzKUtgCWUvhK2lq3943p5aKqopUx3Lf8oEqoS28kELjO-0O_2PDp1s-GaUd6L-wMYmoyCEkSawVum3B7p0uypAYHZA1D3yVkyvY1cTCmm-9Pk88scKsvPZwA-_a18LodZOlH37MhpyPUs7PhvT8tosmtbzqTk6eW786WaKP373k1wwrzeMOqA401fIr7sPPBaNdGEjujhPLLiG7wC20ndoJ9DEnE9fss6PWcsvoex_urbqn3fwBgOfNqA + + { + default_group_color = none; + default_shape = roundedbox; + + group resexc { + orientation = portrait; + label="Resource Exchange"; + Cyclus; + } + + group dommod { + label="Domain Models"; + color = "#F0CA89"; + orientation = portrait; + Cycamore -- Cyder -- "Bright-lite" -- "Cyborg"; + } + + group anlviz { + label="Analysis & Visualization"; + color="#CC89CC"; + CyclusJS -- Cycic; + } + + group orc { + label="Orchestration"; + color = "#9befad"; + Rickshaw; + } + + Cyclus -> Cycamore; + Cyclus -> CyclusJS ; + Cyborg -> CyclusJS [folded]; + Cycic -> Rickshaw; + Rickshaw -> Cyclus [folded]; + } + +Toolkits +-------- +In any real system, there is glue code which holds the projects together in a +cohesive manner. A collection of such utilities is called a *toolkit*. While +toolkits are critically important to well functioning software their components +are united only in that "should be useful." There need not be underlying concept +tying them together. For this reason, toolkits are not a top-level concern on +par with resource exchange, domain models, and analysis & visualization. + +Instead, each project may have its own toolkit which contains utilities that +corresponds most closely with its concern. The toolkit provides a layer on top of +the concern implementation. Thus the toolkit will be aware of other parts of the +project but the concern implementation should not call into elements from the toolkit. + +For example, resources are part of the primary concern of |cyclus|. Thus +a ResourceBuffer class would be part of the |cyclus| toolkit. This is because +resource exchange can be implemented without a ResourceBuffer but such a class +is useful to provide to domain model developers. Furthermore, the buffer +applies to all resources is not specific to any domain. Thus this class should be +included next to the resource exchange implementation. + +Summary +======= +Many other ecosystems and projects model the fuel cycle and make their own choices +about how to separate -- or not -- the concerns of resource exchange, domain models, +and analysis and visualization. The |cyclus| ecosystem places all concerns in +separate projects. This allows a high degree of modularity between software and +developers. Such an ecosystem enables experts to contribute their specific +knowledge base in a way that is independent from other parts of the ecosystem +while simultaneously integrating well with the rest of the ecosystem. Finally, +this document provides instructions on where to implement tasks based on the task's +primary concern. + +Document History +================ +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. [1] http://en.wikipedia.org/wiki/Separation_of_concerns +.. [2] http://en.wikipedia.org/wiki/Agent-based_model +.. [3] http://en.wikipedia.org/wiki/System_dynamics + +.. _Cyclus: https://github.com/cyclus/cyclus +.. _Cycamore: https://github.com/cyclus/cycamore +.. _Cymetric: https://github.com/cyclus/cymetric +.. _Cyclist: https://github.com/cyclus/cyclist2 +.. _Rickshaw: https://github.com/ergs/rickshaw + +.. bibliography:: cep-0002-1.bib + :cited: diff --git a/_sources/cep/cep20.rst.txt b/_sources/cep/cep20.rst.txt new file mode 100755 index 000000000..610247c1a --- /dev/null +++ b/_sources/cep/cep20.rst.txt @@ -0,0 +1,203 @@ +CEP 20 - Time Step Execution Stack +********************************** + +:CEP: 20 +:Title: Time Step Execution Stack +:Last-Modified: 2014-02-24 +:Author: Matthew Gidden +:Status: Accepted +:Type: Standards Track +:Created: 2014-02-19 + +Abstract +======== + +An update to the time step execution stack is proposed. A timestep will now +progress through phases, including a building phase, a tick phase, a resource +exchange phase, a tock phase, and a decommissioning phase. Phases are grouped in +two categories: kernel phases and agent phases. Kernel phases have required or +guaranteed actions that occur during them, and include the build, exchange, and +decommission phases. Agent phases include the Tick, Tock, and Decision phases, and allow +agents to inspect simulation state and update their own state. + +Motivation +========== + +The current time step in |cyclus| consists of the following stack: + +* Tick +* Resource Exchange +* Tock + +Until very recently, only Regions received ticks/tocks from the Timer +class. They were then expected to pass the Tick/Tock "message" to their +children, and so on, until all Models received a Tick or Tock. It was pointed +out recently that this behavior, when mixed with entity entry and exit into/from +the simulation could produce unexpected behavior, e.g., an entity could +enter/exit in the middle of a time step. Furthermore, modules were developed +specifically taking advantage of this behavior (i.e., the ordering of +ticks/tocks) in order to guarantee that entities that were constructed during +the Tick phase also received a Tick in that phase. Furthermore, this imposed a +requirement on Regions and Institutions that they pass Ticks and Tocks along to +their children in a trickle-down-like manner. + +Accordingly, there is a need to standardize what can/should be expected to occur +in each phase of a given time step. Guarantees should be given to module +developers that if an entity enters a simulation, that it will experience the +entire time step on the time step it enters, and if an entity leaves a +simulation, that it will experience an entire time step on the time it leaves. + +Tick and Tock serve as phases for agents to perform actions. As an action can +occur in either phase, no one specific phase serves as a good time to make +decisions based on the state of the simulation. Therefore a user phase specifically +for decision must occur after the tock phase. Note, this phase exists only for +agents to make decisions based on that time step. Other actions should +occur in the Tick and Tock phases. + +Rationale +========= + +By Law's definition :cite:`Law:1999:SMA:554952`, a |cyclus| simulation is, +broadly, a dynamic, discrete-event simulation that uses a fixed-increment time +advance mechanism. In general, fixed-increment time advance scenarios assume a +time step (dt), and assume that all events that would happen during a time occur +simultaneously at the end of the time step. This situation can be thought of as +an event-based time advance mechanism, i.e., one that steps from event to event, +that executes all events simultaneously that were supposed to have occurred in +the time step. + +Two key types of events happen in a |cyclus| simulation (at present): + +* the exchange of resources +* agent entry into and exit from the simulation + +Simulation entities can have arbitrarily complex state which is dependent on the +results of the exchange and the present status of agents in the +simulation. Accordingly, methods that allow entities to update state must occur +in response to these events and to schedule agent entry and exit. + +Because there is a key event that defines agent interaction in a given time +step, it is necessary to involve all agents in that interaction. Accordingly it +is necessary that there be an ordering between these two key types of events, +deviating slightly from Law's description of fixed-increment time +advance. Specifically, we want to preserve the following invariant: *any agent +that exists in a given time step should be included in the resource exchange, +or, equivalently, experience the entire time step execution stack*. + +This leads to the following ordering, or *phases*, of time step execution: + +* agents enter simulation (Building Phase) +* agents respond to current simulation state (Tick Phase) +* resource exchange execution (Exchange Phase) +* agents respond to current simulation state (Tock Phase) +* agents react to simulation (Decision Phase) +* agents leave simulation (Decommissioning Phase) + +The Building, Exchange, and Decommissioning phases each include critical, +core-based events, and will be called *Kernel* phases. The Tick, Tock, and Decision +phases do not include core-based events, and instead let agents react to previous +core-based events and inspect core simulation state. Furthermore, they are +periods in which agents can update their own state and are accordingly +considered *Agent* phases. In general, Agent phases *must* bracket *critical* +Kernel phases, of which only the Exchange Phase exists for now. If another +critical core phase is added in the future it must provide a similar invariant, +i.e., that it is bracketed by Agent phases. For example, if a new phase is added +before Exchange, then the time execution stack would follow as: Building, Tick, +*New Kernel Phase*, *New Agent Phase*, Exchange, Tock, Decommission. + +Technically, whether agent entry occurs simultaneously with agent exit or not +does not matter from a simulation-mechanics point of view, because the two +phases have a direct ordering. It will, however, from the point of view of +module development. It is simpler cognitively to think of an agent entering the +simulation and acting in that time step, rather than entering a simulation at a +given time and taking its first action in the subsequent time step. + +In the spirit of Law's definition of a fixed-increment time advance mechanism, +there is a final important invariant: *there is no guaranteed agent ordering of +within-phase execution*. This invariant allows for: + +* a more cognitively simple process +* paralellization + +Any future addition of phases in the timestep execution stack neccessarily +guarantee the three invariants described above. + +Specification \& Implementation +=============================== + +Two primary concerns exist for changing the current state of |cyclus| to +incorporate this CEP: + +* how to implement agent entry/exit as described +* what name to give to the response phases + +Currently, the response phases are called Tick and Tock. These names have been +criticized for not being specific/informative about the expected actions agents +will/should take during the phases. I propose we instead use *PreExchange* and +*PostExchange*. Wordsmithing and/or other suggestions are welcome. + +The agent entry/exit question is a bit more involved because of the parent-child +(or manager-managed) relationship agents have in |cyclus|. Specifically, the +entry and exit of agents should be managed by the agent's manager. The following +provides one possible specification. + +.. code-block:: python + + /// @brief execute time step stack + def Step(context): + time = context.time() + + for each builder, prototype in build_list[time]: + builder.build(prototype) + + for each agent in agent_list: + agent.PreExchange() + + for each manager in resource_exchange_managers: + manager.Execute() + + for each agent in agent_list: + agent.PostExchange() + + for each agent in decomm_list[time]: + agent.parent->decommission(agent) + +The primary change here is the notion of a build_list and decomm_list. Managers +of agents, nominally their parent, can add agents to each list as required +during the Pre- and PostExchange phases. At some future time, the building and +decommissioning lists can be made queryable in order to determine future overall +or sub-simulation state (e.g., the power level at a future point in +time). Accordingly, prototypes (which know their initial state) are used in the +build_list and to-be decommissioned agents in the decomm_list. + +As described above, the notion of build and decommission lists can change in a +time step. When combined with the invariant that the order of agent execution +within a phase is unordered, future simulation predictions would be unreliable +*if* both lists could be changed in within a phase. Therefore, these lists must +be immutable *during* phases. This issue can be remedied by using staging data +structures and merging the staging data structures into the lists after the +completion of a phase. + +Backwards Compatibility +======================= + +The overall |cyclus| implementation/framework will remain largely unchanged, +with the exception of the core's handling of agent entry/exit +registration. *Cycamore* modules that deal with agent entry/exit will have to be +redesigned to incorporate the new execution stack. + + + +Document History +================ +1. Adding Decision Phase (April 2018) - Author: Robert Flanagan + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. rubric:: References + +.. bibliography:: cep-0020-1.bib + :cited: diff --git a/_sources/cep/cep21.rst.txt b/_sources/cep/cep21.rst.txt new file mode 100755 index 000000000..e5f719755 --- /dev/null +++ b/_sources/cep/cep21.rst.txt @@ -0,0 +1,94 @@ +CEP 21 - Agent Identification and Discovery +*********************************************************** + +:CEP: 21 +:Title: Agent Identification and Distribution +:Last-Modified: 2014-05-05 +:Author: Robert Carlsen +:Status: Accepted +:Type: Standards Track +:Created: Robert Carlsen + +Abstract +======== + +|Cyclus| is designed to have plugin modules that can be easily distributed and +installed. A "module" is a shared library containing one or more compiled +|Cyclus| agents. Agents within mouldes must be uniquely identifiable and +discoverable by both users managing their |Cyclus| installation and by the +|Cyclus| kernel itself. A user wishing to use certain modules must install them +in a desired location and then identify specific agents in them to |Cyclus|. +This CEP explains where modules can/should be installed and how |Cyclus| finds +and identifies agents in them. + +.. _agent-spec-docs: + +Agent Spec +=========== + +Agents will be uniquely identified by 3 components together referred to as an +"agent spec": + +1. path: e.g. ``my/module/path`` + + A slash-delimited, valid filesystem path relative to CYCLUS_PATH (see + Module Discovery below). + +2. library: e.g. ``MyModule`` + + Name of the compiled shared object library file without the "lib" prefix + and without the file extension. If empty, is expanded to the agent class. + The example above would correspond to a library file named "libMyModule.so" + (linux), "libMyModule.dylib" (darwin), etc. + +3. agent class: e.g. ``MyAgent`` + + The name of the agent's c++ class as compiled into the shared library file. + +An agent spec also has a single-string form composed of the three components +separated by colons:: + + [path]:[library]:[agent-class] + + e.g. "my/module/path:MyModule:MyAgent" + +Example linux agent specs with corresponding filepath expansions:: + + my/path:MyModule:MyAgent -> my/path/libMyModule.so + my/path::MyAgent -> my/path/libMyAgent.so + :MyModule:MyAgent -> libMyModule.so + ::MyAgent -> libMyAgent.so + +Module Discovery +================ + +When running a simulation, |Cyclus| will search the following candidate +directories (in order) for each given agent spec: + +1. Each colon-separated directory in the CYCLUS_PATH environment variable. + +2. The default |cyclus| module install directory: ``[install-dir]/lib/cyclus``. + +|Cyclus| will check for the library by building consecutive paths with the +following composition:: + + [candidate-dir]/[path]/lib[library][extension] + +|Cyclus| uses the first matching shared library file found and assumes the +specified agent class exists inside it. + +Conventions +============ + +The path should consist of only alpha-numeric characters, slashes, +underscores, and dashes. **No** spaces. If there are resource files that must +be installed with the shared library file, the library and resources should be +placed in their own directory. + +The shared library name should consist of only alpha-numeric characters, +slashes, underscores. **No** spaces. If the shared library only has a +single agent in it, the library should be the same as the agent class. For +example, if my agent was named ``MyAgent``, then the library file should be +named ``libMyAgent.so`` on a linux system. This allows the defaults to +prevent stuttering in the agent's module spec. + diff --git a/_sources/cep/cep22.rst.txt b/_sources/cep/cep22.rst.txt new file mode 100755 index 000000000..a58441b86 --- /dev/null +++ b/_sources/cep/cep22.rst.txt @@ -0,0 +1,28 @@ +CEP 22 - Logging Methodology and Implementation +************************************************************** + +:CEP: 22 +:Title: Logging Methodology and Implementation +:Last-Modified: 2014-06-29 +:Author: Matthew Gidden +:Status: Deferred +:Type: Standards Track +:Created: 2014-06-29 + +.. note:: + + This CEP is looking for a champion. + +Overview +======== + +The current state of logging in |cyclus|, i.e., reporting results to `stdout` +and `stderr`, has been identified as non-ideal. A non-deferred version of this +CEP will provide a new logging methodology, an implementation thereof, and a +discussion a series of examples of how logging should occur at both the kernel +and archetype development level (if neccessary). + +Document History +================ +This document is released under the CC-BY 3.0 license. + diff --git a/_sources/cep/cep23.rst.txt b/_sources/cep/cep23.rst.txt new file mode 100755 index 000000000..3d04bc031 --- /dev/null +++ b/_sources/cep/cep23.rst.txt @@ -0,0 +1,139 @@ +CEP 23 - Defining Time Step Length, High Noon for Blue Moon +************************************************************** + +:CEP: 23 +:Title: Defining Time Step Length, High Noon for Blue Moon +:Last-Modified: 2014-12-01 +:Author: Anthony Scopatz +:BDFP: Paul P. H. Wilson +:Status: Draft +:Type: Standards Track +:Created: 2014-12-01 + +Motivation +========== +Cyclus is a discrete time simulator whose assumed default time step is +months. Months are the worst unit ever. This proposal adds precision and +flexibility to what we mean by :math:`\delta t`. Namely, this CEP moves from +months to seconds and allows the user to set the time step length, preserving +a default length of a Julian month. + +Discussion +========== +Cyclus lacks a canonical time system. This CEP seeks to unambiguously define +the seconds as the default time unit. This allows agents to unambiguously +communicate with each other and to determine their own time scales internally. +This CEP also adds the capability for users to specify a time step length +(:math:`\delta t`) of their choosing. The default time step, if unspecified, +will be a well-defined month, improving on the historically nebulous month. + +This CEP is motivated by our past woes with months. +Months are an awful time step because there is no single definition for what a +month *is* and all definitions lack a physical basis. Days and years map nicely +(enough) onto a solar cycle. A lunar cycle is 29.53059 days with 7.4 days per phase. +This does not map on well to any solar equivalent. In fact, a 12 month lunar year +is only 354.36708 days, which is a far cry from a solar year. This is why many +lunar calendars are, in fact, lunisolar. Various strategies +for dealing with this time defect are either to add an extra months occasionally +or to have non-month days between years. + +As physically impossible as it is to perfectly sync the sun and the moon, +it is an even worse idea to implement a full Gregorian calendar. Like with +time zones, the opportunities for failure are nearly endless. Furthermore, +going with a real calendar breaks with the current notion that all time steps +have an equal :math:`\delta t`. + +Specification +============================== +This CEP defines the default time step as the average length of a Julian +month as measured in seconds, the proper unit for time: + +.. math:: + + \delta t = \frac{365.25 [d]}{12} = \frac{31557600 [s]}{12} = 2629800 [s/m] + +Furthermore, this actual time step should be able to be set by the user in the +input file. The following changes to the master schema(s) are thus needed: + +.. code-block:: xml + + + + + . . . + + + + + + + + + +This information would be added to the context with the following members: + +.. code-block:: c++ + + class Context { + public: + // Returns the time step in seconds + inline uint64_t dt() { return dt_; }; + + // Returns the time step in [units], given as string + uint64_t dt(std::string units); + + // Returns the time step in [units], given as TimeUnits enum + uint64_t dt(TimeUnits units); + + private: + uint64_t dt_; // the length of the time step, in seconds. + } + +All archetypes and toolkit code should then ask the context what the time step +size is whenever they actually need the current. As per `CEP20 `_, +the time step length is fixed for the entire simulation and may not change. + +Furthermore, ``TimeUnits`` will be a fixed set of time increments that will +not be able to be set by the users. An initial set of time units are: +s, min, hr, d, month (as defined above), y, ky, My, Gy. + +Best Practices +-------------- +Along with this CEP comes the best practice that +archetypes which model time-dependent behavior should not +assume a nominal time step. Archetypes should always get the time step length +from the context. Since the time step is fixed, this need only be done once +per prototype. + +From here, we also define two broad archetype classifications: those which care +about actual real physical time and those which simply function per +simulation time step. + +When an archetype uses real time, due to physics calculations or other needs, +the archetype should now check that :math:`\delta t` is within a valid range +that they define. This is because users will now be able to set the time step. +This validation check maybe performed in any of the archetype's member functions. +If a static range is known ahead of time, then this check is most appropriate in +the constructor. If the time step length is outside of the valid range of the agent, +then an exception should be raised. We recommend something along the lines of: + +.. code-block:: c++ + + if (context().dt() > max_dt) + throw cyclus::ValidationError("time step exceeds valid range!"); + +On the other hand, if the archtype only models per time step behavior, then +state variables should be expressible by default in terms of number of time steps, +not in terms of seconds. If other time values are desirable, the user +should explicitly give the time units. For any time-based variable, the default +associated units should be provided by the metadata. + +Implementation +============== +The implementation of this code should be fairly straight forward. Unlike time +itself, there is no funny business here. + +Document History +================ +This document is released under the CC-BY 4.0 license. + diff --git a/_sources/cep/cep24.rst.txt b/_sources/cep/cep24.rst.txt new file mode 100755 index 000000000..b2cc25aa6 --- /dev/null +++ b/_sources/cep/cep24.rst.txt @@ -0,0 +1,67 @@ +CEP 24 - Default Preferences +***************************************************** + +:CEP: 24 +:Title: Default Preferences +:Last-Modified: 2015-07-29 +:Author: Matthew Gidden +:Status: Accepted +:Type: Standards Track +:Created: 2015-04-09 + + +Abstract +======== + +This CEP describes agreed-upon default preference values within the DRE. + +Motivation +========== + +The current default preference is zero. Preferences of zero are problematic +because they are invariant under multiplication and do not behave well under +monotonic transformations (e.g., the inversion operator). + +Rationale +========= + +The default preference will change from zero to unity. Default preferences will +then be stable under both additive and multiplicative operations. Currently, +negative preferences denote potential trades to be removed from resource +exchanges before the solution phase. This will change from negative to +non-positive preferences (see `Backwards Compatibility`_). + +Specification \& Implementation +=============================== + +See [1]_ and [2]_ for the implementation of unity default preferences. + +Backwards Compatibility +======================= + +API backwards compatability is not broken with this CEP. However, trade logic +backwards compatability will be broken if any previous model was dependent on a +default preference value of `0`. Developers will have to update models given the +new default preference value of `1`. + +For a simulator, however, this is still backwards incompatability -- simulation +behavior for valid input files can (and will) change if explicit use of 0-valued +preferences is engaged. Accordingly, to make this deprecation loud and explicit, +an error will be thrown for the remainder of this minor release cycle (currently +release 1.3.1 to 1.3.2). At the end of this cycle, arcs with 0-valued +preferences will be "quietly" removed (i.e., as quietly as negative-preference +arcs are currently). An issue will be made to perform this update. + +For updating archetype code, look primarily to the `AddRequest` and +`Adjust*Pref` APIs. + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. [1] https://github.com/cyclus/cyclus/pull/1121 +.. [2] https://github.com/cyclus/cycamore/pull/381 diff --git a/_sources/cep/cep25.rst.txt b/_sources/cep/cep25.rst.txt new file mode 100755 index 000000000..13b82fbdc --- /dev/null +++ b/_sources/cep/cep25.rst.txt @@ -0,0 +1,102 @@ +CEP 25 - Preference Adjustment Process +***************************************************** + +:CEP: 25 +:Title: Preference Adjustment Process +:Last-Modified: 2015-08-25 +:Author: Matthew Gidden +:Status: Accepted +:Type: Standards Track +:Created: 2015-07-07 + + +Abstract +======== + +This CEP describes the process of adjusting preferences in the DRE, e.g., with +regard to implementing international trade instruments. It generalizes +methodology of the preference adjustment phase. + +Motivation +========== + +The current preference adjustment phase only includes the requesting facility +and its managers (i.e. institution and region). Only allowing requesting +managers to adjust preferences is problematic because it prohibits, for +example, the complete modeling of intra-regional instruments such as tariffs. + +Specification \& Implementation +=============================== + +In order for managers of bidding regions to apply tariffs, or any other +inter-entity instruments, they must be involved in preference +adjustment. Previously, only managers of the requesting entities were allowed to +affect preference values. This CEP will allow bidders and managers of bidding +entities to affect preferences as well. + +There is not a clear reason or motivation as-of-yet to allow requesting managers +to adjust preferences before bidding managers (and vice-versa). Accordingly, a +general approach is taken for the preference *adjustment ordering* +methodology. The entities involved in any trade preference adjustment are the +two traders, and each of their associated managers. In a common Cyclus use case, +this involves two ``Trader`` entities whose immediate "manager" is the +``Facility`` entity of whom they are a member. Further, each ``Facility`` is +managed by an ``Institution`` which is managed by a ``Region``. + +For the purpose of this CEP, a default ordering is defined: the requester and +its managers are queried in order followed by the managers of the bidder. The +bidder is not involved, because it is assumed that suppliers are motivated to +reduce inventory. Bidder's managers are involved in order to generally model +international instruments, such as tariffs. As different orderings are desired +in the future, they may be implemented. The only requirement of a given ordering +implementation is that it must maintain a preference adjustment history. That +is, a data structure comprising and ordered list of entity-preference pairs that +records the history of the adjusted preference for each trade. + +An important caveat includes the adjustment of preferences to a "no trade" +value. Archetype developers are allowed to denote a trade as "impossible" by +setting the preference value to a non-positive number. If at any point during +the adjustment phase such a state is found, the phase is considered over for +that trade and the trade is removed from the exchange. Consider the following +situation: a trade is initially set to the default preference of unity; the +first manager queried has a rule that negates the trade (sending its value to +negative unity) while the next manager queried has a rule that increases all +trades by a magnitude of two units. Rather than setting the final trade +preference at unity based on input from both managers, the trade is removed from +the exchange after its preference is adjusted by the first manager. + +The determination of the final preference value given the adjustment history, +i.e., *the preference aggregation rule*, is also tuneable. One could imagine +many different negotiation models, or negotiation rules, by which to determine a +final value given a collection of entities' input. Again, this CEP provides a +default rule, which is to take the final preference value, unperturbed, through +the adjustment process. However, any rule that takes as an argument the +adjustment history data structure and provides a final preference value is valid +in this methodology. Of course, different rules may be implemented as they are +required. + +This CEP does not explicitly provide an user-facing interface for adjusting +either the adjustment ordering or aggregation. The provided methodology is a +novel first step in fuel cycle simulation, and it is not at all clear that full +user control over the adjustment process is necessary for the current set of +modeled scenarios. If that capability is identified as critical path in the +future, a user-facing interface can be implemented that allows adjustment of +both the preference adjustment ordering and preference aggregation +determination. + +See [1]_ for implementation of Agent-based preference adjustment. + +Backwards Compatibility +======================= + +No backwards incompatibilities are introduced with this CEP. + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. [1] https://github.com/cyclus/cyclus/pull/1122 diff --git a/_sources/cep/cep26.rst.txt b/_sources/cep/cep26.rst.txt new file mode 100755 index 000000000..1b44c3d6e --- /dev/null +++ b/_sources/cep/cep26.rst.txt @@ -0,0 +1,190 @@ +CEP 26 - Generalize the DRE to Optimize Multiple Metrics +******************************************************** + +:CEP: 26 +:Title: Generalize the DRE to Optimize Multiple Metrics +:Last-Modified: 2016-10-19 +:Author: Robert Flanagan \& Anthony Scopatz +:Status: Draft +:Type: Standards Track +:Created: 2016-10-19 + + +Abstract +======== +This CEP proposes to enable broader user customization of the DRE by opening +up the Cyclus resource exchange interface to many metrics of interest. The DRE will +no longer solely +attempt to minimize quantity divided by preference, but rather be capable of +minimizng or maximizing many metrics jointly. Different DRE solvers may +choose which metrics to include. Along with this new interface will come a +new implementation of the Greedy solver that makes use of all metrics. + +Motivation +========== +There are several fundamental issues with preferences as an optimization variable: + +1. Global optimization of Request-Bid arcs is not possible because the meaning and + scale of preferences are independent between requesters. +2. There is no standard conversion from preference to cost, only the convention that + cost = quantity / preference. +3. The limits of preference are :math:`(0, \infty)`, which implies that there is + no possible way to reject a bid once it has been made and there is no way to + represent negative costs (subsidies). +4. The preference adjustment phase cannot guarantee validity of adjustments because + there is not a uniform preference scaling between requesters. +5. Preferences do not support a consistent way for other metrics to be resolved into + request preferences. Thus to-date, other metrics have been avoided and discouraged. + +The failure of preferences as an optimization variable can be shown with the following +simple system. Consider an exchange graph with two requesters and one bidder for a single +commodity. The requesters both have infinite capacity, while the bidder may only offer +a constrained quantity. The bidder may trade 2 units of qualitatively unique resources +(of the same commodity, e.g. UOX and MOX). Requester 1 has an equal preference (say 5) +for both resources, even though they are qualitatively different. Requester 2, on the +other hand, has a high preference (say 15) for one resource and a low preference (say 1) +for the other resource. Currently in Cyclus, these preferences would be assigned during +the preference adjustment phase. + +The DRE, and the greedy solver in particular, would give both units of the resource to +Requester 2. This is because the greedy solver sorts by requester, giving precedence to the +requester with the highest average preference. Requester 1's average preference is 5 +and Requester 2's average preference is 8. Since, both requesters have infinite (or +greater than or equal to 2 units) of capacity, all bids go to Requester 2. + +This situation remains true even as the low preference of Requester 2 tends towards zero +(i.e. 1e-100). There is no way for Requester 2 to reject a bid and thus Requester 1 will +never receive a resource. This can be seen in Figure 1 below. + +.. figure:: cep-0026-1.png + :align: center + :scale: 50 % + + Figure 1: Simple transaction with weighted preferences. + +The above situation can arise in real world fuel cycle scenarios. One example is the +case of partitioning used fuel storage based on decay heat into wet and dry storage. +A used fuel commodity may have instances that are either high or low heat, and storage +requesters must be able to reject material whose decay heats are above its thermal limit. +An additional use case is a system where a reactor may choose to be agnostic to UOX or MOX +in their core while other reactors in the system reject MOX in favor of a strong preference +for UOX. Cyclus would currently give MOX to the reactor that effectively rejected it anyway, +leaving the agnostic reactor unfueled. + +As a concept, the current formulation of preferences seems poorly defined and therefore +difficult to explain or intuit. As shown above, this can lead to incorrect and unanticipated +results. From here, an attempt can either be made to patch the preference system with +further constraints or it can be replaced with a more customizable, and thus more intuitive and +directly relevant, concept. + +We propose a system that will allow the computation of many potential metrics, will sort +all of the arcs by minimizing or maximizing each each metric in order of a user given +precedence, and then will finally perform a single greedy solve on the sorted arcs. + +The set of standard available metrics will include the quantity, preference, and +unit cost. The benefit of providing the unit costs is that they are directly +and linearly comparable to one another. Moreover they more commonly used to make +quantitative comparisons than preferences. +Additionally, costs provide a mechanism for resolving +request objectives (price limit or maximum cost) and bid objectives (offer price). +If an offer price is less than or equal to the request price limit, the request-bid +can be created. Otherwise the request-bid arc will be rejected. + + +Specification \& Implementation +=============================== +To accomplish the methodology proposed here will require changes to the API within +the dynamic resource exchange and the cyclus core code. At a minimum, + +1. Bids will need to be able to hold a unit cost. The API will need to support + developers accessing and setting this cost. +2. Update Requests to contain a max-unit-cost, as well as a preference. +3. The current greedy solver will need to be updated or replaced to accomodate the + change from preference to a multivariate solver. +4. Updating all of the existing archetypes within the Cyclus core and Cycamore to + support this change. + +The first change will be to add the ability for bids to hold a unit cost value. The +implementation of this may be simple as it will mirror the implementation of the +current preference attribute of requests. Going forward the request max cost will still be +the default cost for a request-bid arc. However, this may also be accomplished in a +more generic fashion by allowing arbitrary metrics, of which unit cost is only one. + +The addition of the unit cost on the request may also be simple. +The majority of the +work required will be updating all ressource exchange calls currently in use +throughout the many archetypes and Cyclus core code. Similarly, this could be +extended to a framework for arbitrary metrics, of which unit cost is only one. + +Once Bids and Requests have their own unit costs, updating the default solver for +Cyclus will be done to perform a global optimization of the entire trade system each +time step. This can be done by collecting all of the possible Request-Bid arcs. +These arcs will be constructed by determining if the bid in the arc has a +unit cost associated with it. If this is the case that unit cost will be used +for the pair. If there is no bid unit cost however, the max-unit-cost of the +request will be used. Again, if a metric framework approach is taken, resolution will +take place via a generic interface, of which cost is only one metric. + +Once the arcs have been created, the DRE solver can sort the value of all unit costs +from smallest to largest, quantities from either lowest-to-highest (current behavior) +or highest-to-lowest, and prefences from highest to lowest. +This will therefore minimizing the total cost of the whole system, maximize or +minimize flow, and maximize preference. + +As a motivating feature, these changes also increase the flexibility of the +greedy solver interface. Namely, it will grant users the ability to specify +the way the system is optimized. The above mechanism for primarily +minimizing cost is only one method for global optimization. This proposal +identifies three primary, orthoganal metrics that the greedy solver will jointly +solve: + +* unit cost (min) +* quantity (min) +* preference (max) + +Each of these can also be used in conjuction with each other or without the +others. For example, if two +request-bid arcs have the same unit cost, these two arcs can be sorted by mass or +preference. It will also be possible to choose maximization and minimization for +each of the discussed metrics (unit cost, quantity, preference). + +However, the above precedence need not be static. We propose that the user be allowed +to set the ordering of these metrics in the input file. Furthermore, they will +also be allowed to modify the flag for whether to maximize or minimize each +metric. Such a change would enable a much broader set of use cases to be simulated +according to the users needs. It will also allow the exploration of a vareity +of DRE effects based on precedence changes. +This will be setup through the cyclus input file, but the default ordering will be +``unit cost (min), quantity (min), preference (max)``. + +Furthermore, in a framework setting, additional metrics can be registered with the +dynamic resource exchange and then used in the same way as the standard metrics +above. + +This change represents a fundamental modification to the behavior of the cyclus +simulator. As mentioned there will be several alterations to the cyclus core code. +We will aimed to update all of these locations with the new code +as well as documentation to help developers update their software and to support +future developers using Cyclus. + +Backwards Compatibility +======================= +It is our goal to ensure that the Cyclus core and the Cycamore archetypes will be +updated to be in line with this CEP. Unfortunately any third party archetypes will +need to be updated by those parties. + +It is our aim that this change functions as a staging point for a Cyclus 2.0 release. + +The current behaviour of the greedy solver will be recoverable by the user if they set +the sorting metrics to be ``average requester pref (max), quantity over preference (min)``. +These two metrics will be added for backwards compatability. + +Document History +================ + +This document is released under the CC-BY 4.0 license. + +References and Footnotes +======================== + +.. .. [1] https://github.com/cyclus/cyclus/pull/1293 diff --git a/_sources/cep/cep27.rst.txt b/_sources/cep/cep27.rst.txt new file mode 100755 index 000000000..153d4a21d --- /dev/null +++ b/_sources/cep/cep27.rst.txt @@ -0,0 +1,187 @@ +CEP 27 - Toolkit Capabilities Injection into an Archetype +********************************************************* + +:CEP: 27 +:Title: Agent Toolkit Capabilities +:Last-Modified: 2019-10-28 +:Author: Baptiste Mouginot +:Status: Active +:Type: Standards Track +:Created: Baptiste Mouginot + + +Abstract +======== + +The |Cyclus| toolkit is designed to easily implement specific capabilities in +newly developed archetypes, such as a trading policy, commodity producers, etc. +To add characteristics to archetypes such as `Position` or `Metadata`, the +actual implementation method is very verbose. It relies on adding the new +specification in the archetype header, assigning it and use it in the cpp +file. The developers have to manually ensure the consistency in variable naming and +implementation across multiple archetypes/files. +This CEP explains introduces the concept of snippets to simplify and maintain consistency +in the implementation and the usage, across multiple archetypes. + + +Toolkit Implementation +====================== + +Each |Cyclus| toolkit component will contain 3 different files: +- 2 for the definition of the feature C++ class (``cpp`` and header) that allows + the use of the capabilities, and optionally to register its values in the + output database, +- a snippet definition file used to simplify the implementation and ensure + consistency accross its integration in the different archetypes. + +The snippet definition file will be included in the ``private`` section of the +archetype header as: ``#include toolkit/my_feature_snippet.cycpp.h``. (The use of the +``cycpp.h`` has been chosen to allow syntax highlighting and inform developers +that this is not a standard C++ header.) + +The snippet file, will contain the declaration of all the variables required +to use the capabilities class: + +- the definition of the capability class as a member variable. + +- initialization of the added variables. + +- (optional) if the capability requires/allows variable input from users, + standard |Cyclus| member variable declaration with variable ``#pragma`` is + required. In addition, to the standard variable declaration and the + ``#pragma`` the method also require a ``std::vector + cycpp_shape_myvariable`` to be declared for each of the decorated variable + that are in the `toolkit/my_feature_snippet.cycpp.h` file. (``cycpp preprocessor`` is + not able at the time to add them automatically for included files.) + + +The main purpose of this include method would be to ensure consistency across +archetypes using the same toolkit capability requiring user input, avoiding 1 +set of input syntax per archetypes for the same capability. + +If the toolkit features needs the capabilities to write in the output database a +``RecordSnippet(Agent* agent)`` method will be implemented in the toolkit class to avoid +multiplication of implementation in the each archetype using the feature. + + +Archetypes Integration +====================== + +When the capability is integrated in an Archetype the following implementations +have to be done: + +1. Include toolkit class header in in the class header: + ``#include 'toolkit/my_feature.h'``. + +2. Include the snippet in the class header core: + ``#include toolkit/my_feature_snippet.cycpp,h``. + +3. (optional) In the ``Archetype::EnterNotify()``, initialise the toolkit class member + variables with variables. + +4. (optional) If required, call the ``RecordSnippet()`` method when necessary during the + Archetype operation. + + +Class member vs Inheritance +=========================== + +With inheritance of the capability class, one will need to also modify the +archetype class declaration in addition to simply including the snippet at the +right place. +This may also lead to confusion, as one can believe that the user input value +for variable are passed in the constructor of the class and might lead the +develop to skip the assignation of the value in the inherited class in the +``EnterNotify``... + +Otherwise behavior would be very similar. + +Example: +======== + + +Without Inheritance: +-------------------- +``toolkit/my_feature_snippet.cycpp.h``: +.. highlight:: c + cyclus::toolkit::Position coordinates(0,0); + + #pragma cyclus var { \ + "default": 0.0, \ + "uilabel": "Geographical latitude in degrees as a double", \ + "doc": "Latitude of the agent's geographical position. The value should " \ + "be expressed in degrees as a double." } + double latitude = 0; + // required for compilation but not added by the cycpp preprocessor... + std::vector cycpp_shape_latitude; + + #pragma cyclus var { \ + "default": 0.0, \ + "uilabel": "Geographical longitude in degrees as a double", \ + "doc": "Longitude of the agent's geographical position. The value should" \ + "be expressed in degrees as a double." } + double longitude = 0; + // required for compilation but not added by the cycpp preprocessor... + std::vector cycpp_shape_longitude; + +``my_archetype_example.h``: +.. highlight:: c + #include 'toolkit/Position.h' + + class fun_archetype : public cyclus::facility{ + public: + [...] + private: + [...] + #include "toolkit/my_feature_snippet.cycpp.h" + } + +``my_archetype_example.cpp``: +.. highlight:: c + void fun_archetype::EnterNotify() { + coordinates.set_position(latitude, longitude); + coordinates.RecordPosition(this); + [...] + } + +With Inheritance: +----------------- +``toolkit/my_feature_snippet.cycpp.h``: +.. highlight:: c + #pragma cyclus var { \ + "default": 0.0, \ + "uilabel": "Geographical latitude in degrees as a double", \ + "doc": "Latitude of the agent's geographical position. The value should " \ + "be expressed in degrees as a double." } + double latitude = 0; + // required for compilation but not added by the cycpp preprocessor... + std::vector cycpp_shape_latitude; + + #pragma cyclus var { \ + "default": 0.0, \ + "uilabel": "Geographical longitude in degrees as a double", \ + "doc": "Longitude of the agent's geographical position. The value should" \ + "be expressed in degrees as a double." } + double longitude = 0; + // required for compilation but not added by the cycpp preprocessor... + std::vector cycpp_shape_longitude; + +``my_archetype_example.h``: +.. highlight:: c + #include 'toolkit/Position.h' + + class fun_archetype : public cyclus::facility, public Position { + public: + [...] + private: + [...] + #include "toolkit/my_feature_snippet.cycpp.h" + } + +``my_archetype_example.cpp``: +.. highlight:: c + void fun_archetype::EnterNotify() { + this.set_position(latitude, longitude); + this.RecordPosition(this); + [...] + } diff --git a/_sources/cep/cep3.rst.txt b/_sources/cep/cep3.rst.txt new file mode 100755 index 000000000..882993db2 --- /dev/null +++ b/_sources/cep/cep3.rst.txt @@ -0,0 +1,406 @@ +CEP 3 - |Cyclus| Release Procedure +******************************************************** + +:CEP: 3 +:Title: |Cyclus| Release Procedure +:Last-Modified: 2017-11-06 +:Author: Anthony Scopatz and Matthew Gidden and Baptiste Mouginot +:Status: Accepted +:Type: Process +:Created: 2013-10-25 + +Abstract +======== +The purpose of this document is to act as a guideline and checklist for how +to release the |cyclus| core code base and the supported projects in the ecosystem. + +The |Cyclus| Ecosystem +====================== +The very first thing to do when preparing for an upcoming release is to elect +a release manager. This person has the special responsibility of making sure +all of the following tasks are implemented. Therefore, their judgment for the +placement of issues and code stability must be adhered to. + +The |cyclus| ecosystem has a few projects which are all released together. +(This may change in the future a development diverges and the core becomes more +stable.) The projects that are under the release manager's purview are: + +* `Cyclus`_ +* `Cycamore`_ +* `Cymetric`_ + +The projects which are not yet under the release managers purview are: + +* `Rickshaw`_ +* `CyclusJS`_ + + +.. note:: + + The following full release process only applies to MAJOR and MINOR + release number changes. MICRO or PATCH releases may be performed + with a version bump and a git tag alone. This is to enable fast turn + arounds for bug fixes and binary package creation (ie deb or conda). + Therefore versions with a non-zero MICRO number should be considered + relatively unstable. + + +Release Candidates (Tags & Branches) +==================================== +At the beginning of a release, a special branch for *each* project should be +made off of ``master`` named ``vX.X.X-release``. Note the *v* at the beginning. Each +project should have the initial version of of it's release branch *tagged* as +``X.X.X-rc1``, the first release candidate. + +.. note:: + + To distingush them, branch names have a ``v`` prefix (``vX.X.X-release``) + while tag names lack this prefix (``X.X.X-rcX``). + +Release candidates serve as an official proving ground for the release. Upon +creation, an announcement should be made to the developer's list, and users of +the project should be encouraged to test them out in order to bugs/other issues. + +Any required changes must be pull requested from a topical branch into the +*release* branch. After this has been accepted, the topical branch must be +merged with ``master`` as well. The release branch is there so that development +can continue on the ``master`` branch while the release candidates (rc) are out +and under review. This is because otherwise any new developments would have to +wait until post-release to be merged into ``master`` to prevent them from +accidentally getting released early. + +Everything that is in the release branch must also be part of ``master``. +Graphically, + +.. figure:: cep-0003-1.svg + :align: center + + **Figure 1:** Branch hierarchy under release. + +.. note:: + + Any commits merged into the release branch must *also* be merged into + ``master``. It is common practice for the release manager to request the + reviewer pull requests to merge the topical branch into ``master`` + as well. However, it is the ultimate release manager's responsibility to + make sure ``master`` is kept up to date with the ``release`` branch. + +If changes are made to the release branch, a new candidate must be issued after +*2 - 5 days*. Every time a new release candidate comes out the ``vX.X.X-release`` +must be tagged with the name ``X.X.X-rcX``. A developer's list annoucement must +accompany any new candidate. + +The release branch must be quiet and untouched for *2 - 5 days prior* to the +full release. When the full and final release happens, the ``vX.X.X-release`` +branch is deleted. All commits in the ``vX.X.X-release`` branch must have also +been merged into the ``master`` branch as they were accepted. + +Project Checklist +================= + +.. note:: + + Utility scripts for this process can be found in the `release`_ repository + +Releasing a |cyclus| project is comprised of the following operations. Each +operation should be enacted in order. + +Release Candidate Process +------------------------- + +#. Review **ALL** issues and pull requests, reassigning or closing them as needed. + +#. Ensure that all issues/PRs in this release's milestone have been closed. + Moving them to the next release's milestone is a perfectly valid strategy for + completing this milestone. + +#. Initiate the release candidate process (see above) + +#. Review the current state of documentation and make approriate updates. + +#. Finish the release candidate process + + - make sure all commits in the ``release`` branch also are in ``master`` + +Release Process +--------------- + +#. Make sure every local |cyclus| project repository is up to date with its + ``master``, and ``vX.X.X-release`` branches on ``upstream``. + +#. Bump the version in ``cyclus/src/version.h.in`` and ``cyclus/cyclus/__init__.py``, + ``cycamore/src/cycamore_version.h.in``, and + ``cymetric/setup.py``; commit the changes + +#. Perform maintenance tasks for all projects. The maintenance depends on `PyNE + `_ and Doxygen. Maintenance files can be + found `here + `_. + + - they are described in detail below, *but* the ``maintenance.sh`` utility + in ``release/utils`` will do this automatically for you + + - make sure to have your ``rs.cred`` file (see ``maintenance.sh``'s help) + + .. code-block:: bash + + $ cd /path/to/release/utils + $ export CYCLUS_DIR=/path/to/cyclus + $ export CYCAMORE_DIR=/path/to/cycamore + $ ./maintenance.sh -r -v X.X.X # X.X.X is *this* version + + .. note:: + + If maintenance script fails because of an ABI failure that is caused by + a compiler update (or other similar change caused by reasons other + than code changes), you might want to accept them and procceed with the + release with those. To do so you need to generate the new symbols and + commit them: + + #. First make sure those changes can be ignored by emailing for + discussion/approval the dev-list + + #. if the dev-list agrees to those changes, update the symbols and + commit the new one: + + .. code-block:: bash + + $ cd $CYCLUS_DIR/release + $ ./smbchk.py --update -t X.X.X # X.X.X is *this* version + $ git add symbols.json + $ git commit -m "Describe here all the change on the ABI" + + +#. Commit all changes for all projects. + + .. code-block:: bash + + $ cd /path/to/project + $ git checkout vX.X.X-release + $ git commit -am "final release commit after maintenence" + +#. Update all master branches. + + .. code-block:: bash + + $ cd /path/to/project + $ git checkout master + $ git merge --no-ff vX.X.X-release + $ git push upstream master + +#. *Locally* tag the repository for *each* of the projects. + + .. code-block:: bash + + $ cd /path/to/project + $ git checkout master + $ git merge --no-ff vX.X.X-release + $ git tag -a -m "Cyclus project release X.X.X, see http://fuelcycle.org/previous/vX.X.X.html for release notes" X.X.X + +#. Draft release notes. + + - the ``make_release_notes.sh`` utility in ``release/utils`` will help + provide a template + + .. code-block:: bash + + $ cd /path/to/release/utils + $ export CYCLUS_DIR=/path/to/cyclus + $ export CYCAMORE_DIR=/path/to/cycamore + $ export CYMETRIC_DIR=/path/to/cymetric + $ ./make_release_notes.sh W.W.W X.X.X # W.W.W is the previous version, X.X.X is *this* version + + - add the release notes as ``cyclus.github.com/source/previous/vX.X.X.rst`` + with appropriate updates to ``index.rst`` in that directory + +#. Update the API docs. + + - the ``api_docs.sh`` utility in ``release/utils`` will do this + automatically for you + + .. code-block:: bash + + $ cd /path/to/release/utils + $ export CYCLUS_DIR=/path/to/cyclus + $ export CYCAMORE_DIR=/path/to/cycamore + $ ./api_docs.sh X.X.X # X.X.X is *this* version + +#. Update the ``master`` branch of all projects and clean up. + + .. code-block:: bash + + $ cd /path/to/project + $ git push upstream X.X.X master + $ git push upstream --delete vX.X.X-release + +#. Manually visit the github.com page for each project and draft/publish a new release. + + - See instructions `here + `_ + + +#. Update Conda-forge + + - For each project, find the corresponding feedstock repository in the + conda-forge organization on github. For example, cyclus' feedstock is at + https://github.com/conda-forge/cyclus-feedstock + + - In each project's feedstok, open up a PR which updates the + `recipe/meta.yaml` file with the new version number and the new SHA-256 + value of the new version's tarball. See conda-forge documentation for more + or ask the feedstock maintainers for help. + + - Note that each feedstock must be accepted and the package uploaded to + anaconda.org (automatic) prior to accepting updates for the next feedstock + dependency. For example, cyclus must be fully updated before cycamore. + + +#. Create a DOI. See :doc:`CEP4 <./cep4>` for details. + + - This can be updated one day to use the Figshare `API + `_ + +#. Update website release information. + + - on the front page (``source/index.rst``) + - DOIs (``source/cite/index.rst``) + - release notes (``source/previous/index.rst``), remember both the release + notes and the zip/tar URLs! + - layout template (``source/atemplates/layout.html``) of the website + - install from tarball instruction + (``source/user/install_from_tarball.rst``) + + +#. Commit all changes to ``cyclus.github.com`` and ``make gh-publish`` + +#. Send out an email to ``cyclus-dev`` and ``cyclus-users`` to announce the release! + + +.. This part has been commented, as it is required for the website, but the + person in charge of the release might not have the proper access to update the + Dory worker. This should be automated when a merge is done on the master branch + a CI-hook should update the dory cloudlus server and relaunch the worker. + Moreover the cloudlus server is not directly related to Cyclus and depend on + the UW-Madison community but the website relies on it to host the + online cyclus calculation... (see + https://github.com/cyclus/cyclus.github.com/pull/227#pullrequestreview-21589660 + discussion for more details.) + +.. #. Update ``Dory``'s ``Cyclus``/``Cycamore`` version and relaunch ``Dory`` worker. + To do this you need a acces to the ``Dory`` server (if you don't please + contact an administrator), the ``go`` toolchain as well as ``cde`` installed + on your computer. Also, the release version of ``Cyclus`` and ``Cycamore`` + have to be compiled on you system and both executable and lib have to be on + the default paths. Please refer to the :doc:`source installation + <../user/install_from_git>` if you need. +.. .. code-block:: bash + $ git clone https://github.com/rwcarlsen/cloudlus.git + $ cd cloudlus + $ go install ./cmd/cloudlus + $ cd misc/fuelcycle.org + $ make + $ ssh dory.fuelcycle.org 'mv cyc-cde.tar.gz cyc-cde.tar.gz_bkp' + $ scp cyc-cde.tar.gz dory:fuelcycle.org:./ + $ ssh dory.fuelcycle.org + $ ps -fe | grep cloudlus | grep work | grep ':80' | cut -d" " -f6 | xargs kill -9 + $ rm -rf worker-* + $ ./launch.sh 2 + + + +Maintainence Tasks +================== + +.. note:: + + There is now the ``maintenence.sh`` utility in ``release/utils`` that + will automate this for you. The section remains here for posterity. + +Each project may have associate maintenance tasks which may need to be performed +at least as often as every micro release. + +|Cyclus| +-------- + +**Update PyNE:** PyNE source code is included and shipped as part of |cyclus|. As pyne +evolves, we'll want to have our version evolve as well. Here are the steps to do so. +These assume that in your HOME dir there are both the pyne and |cyclus| repos. Remember +to check in the changes afterwards. + +.. code-block:: bash + + $ cd ~/pyne + $ ./amalgamate.py -s pyne.cc -i pyne.h + $ cp pyne.* ~/cyclus/src + +**Update Nuclear Data:** PyNE also provides a nuclear data library generator which we use for +our source data. Occassionally, this needs to be updated as updates to pyne itself come out. +The command for generating |cyclus| specific nuclear data is as follows: + +.. code-block:: bash + + $ cd ~/pyne + $ nuc_data_make -o cyclus_nuc_data.h5 \ + -m atomic_mass,scattering_lengths,decay,simple_xs,materials,eaf,wimsd_fpy,nds_fpy + +Once the file is generated it must be put onto rackspace. + +**Update Gtest:** We include a copy of the fused Gtest source code within our +source tree located in the ``tests/GoogleTest`` directory. To keep up with +Gtest's natural evolution cycle, please download the latest release of Google Tests +and follow `the fused source directions here`_. If we go too long without doing this, +it could be very painful to update. + +**Verify & Update API Stability:** Since |Cyclus| v1.0 we promise API +stability. Luckily, we have a tool for keeping track of this mostly +automatically. In order to check this correctly, you must have a **RELEASE** +build of Cyclus compiled/installed. Every release please run the following +command to verify that the release branch is stable: + +.. code-block:: bash + + $ cd cyclus/release + $ ./smbchk.py --update -t HEAD --no-save --check + +If |cyclus| only has API additions, it is considered stable and the command will +tell you so. If |cyclus| also has API deletions, then |cyclus| is considered +unstable and a diff of the symbols will be printed. +**You cannot release |cyclus| if it is unstable!** Please post the diff to +either the mailing list or the issue tracker and work to resolve the removed +symbols until it this command declares that |cyclus| is stable. It is +probably best to do this prior to any release candidates if possible. + +Once stable and there are no more code changes to be made, add the symbols +in this release to the database with the following command (again - make sure +you are working on a RELEASE build of Cyclus): + +.. code-block:: bash + + $ cd cyclus/release + $ ./smbchk.py --update -t X.X.X + +where ``X.X.X`` is the version tag. This should alter the ``symbols.json`` +file. Commit this and add it to the repo. + +Cycamore +-------- + +No maintenence required. + +Cymetric +-------- + +No maintenance required. + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +.. _Cyclus: https://github.com/cyclus/cyclus +.. _Cycamore: https://github.com/cyclus/cycamore +.. _Cymetric: https://github.com/cyclus/cymetric +.. _Rickshaw: https://github.com/ergs/rickshaw +.. _CyclusJS: https://github.com/cyclus/cyclist2 +.. _release: https://github.com/cyclus/release +.. _the fused source directions here: https://code.google.com/p/googletest/wiki/V1_6_AdvancedGuide#Fusing_Google_Test_Source_Files diff --git a/_sources/cep/cep4.rst.txt b/_sources/cep/cep4.rst.txt new file mode 100755 index 000000000..e2abf4dec --- /dev/null +++ b/_sources/cep/cep4.rst.txt @@ -0,0 +1,127 @@ +CEP 4 - Attribution of Code Products in the |cyclus| Ecosystem +************************************************************** + +:CEP: 4 +:Title: Attribution of Code Products in the |cyclus| Ecosystem +:Last-Modified: 2014-06-27 +:Author: Kathryn Huff +:Status: Accepted +:Type: Process +:Created: 2014-06-01 + +Abstract +======== + +The purpose of this CEP is to define the method for attribution of code +products within the |cyclus| ecosystem. In particular, along with any software +release a unique, publicly citable object should be created which +appropriately attributes its authors. This CEP therefore introduces a method +for creating a `Digital Object Identifier`_ for each code release, with alphabetically ordered +authorship, and encapsulating all of and only the authors responsible for that +effort. + +Concerns +======== + +The concerns driving this CEP are threefold : + +* **Unambiguous Citation** +* **Author Identification** +* **Contribution Equality** + +First, public and unambiguous citation of scientific and code products like +those in the |cyclus| ecosystem is of paramount importance to scientific +reproducibility. Due to the algorithmic and authorship differences between +versions of the codebase, a unique identifier is required for accurate citation +of that version. Therefore, to enable reproducibility in the use of the +|cyclus| ecosystem, each version must be unambiguously citable with a distinct +DOI. + +Second, to provide an appropriately transparent public link between the +identities and efforts of the authors, the true names of the authors should be +listed. As with other forms of scientific publication, public attribution of +authorship is of importance for appropriately enabling direct praise and blame +related to that scientific work :cite:`shamoo_responsible_2003`. This feature +of scientific publication holds the scientist accountable for their work and +enables them to establish a record of their scientific pursuits. It is for this +reason that clear attribution of true names is superior to other options, such +as using a pseudonym for the group (Cyclus developers). + +Finally, since ordering of authorship has conventional meaning and value in the +scientific community, the ordering of authorship for code products in the +|cyclus| ecosystem should similarly reflect the community consensus concerning +relative contribution importance. Specifically, due to the inherently +apples-and-oranges nature of code contributions, no metric for code importance +was deemed suitable for comparing contribution importance within the |cyclus| +ecosystem. That is, a lack of hierarchy was preferred. Thus, alphabetical +ordering, which is perceived by convention as non-hierarchical, shall be used. + +What releases should have a DOI? +------------------------------------ + +Cyclus versions are indicated by numbers of the form : vMAJ.MIN.MICRO-patch. At the +very least, major, and minor versions should have associated DOIs. For micro +versions, which do not undergo a release process, a DOI is optional. + +How should a DOI be created? +------------------------------------ + +Creation of a DOI should be conducted or delegated by the code release +manager. Accordingly, :doc:`CEP3<./cep3>` has been updated to reflect this responsibility. +That person is responsible for identifying the code contributors since the last +release at that level. + +Among online services that have the capability of creating a DOI for a code +product, `figshare`_ is preferred. It was initially chosen due to both its +nascent adoption by the scientific computing community and its native +ability to capture github-hosted codebases. + +Once the DOI is created, it should be recorded on the cyclus website and should +be shared with the development team. + + +Who is an author? +------------------------------------ + +An author has contributed code contributing to the release. +For a **major release**, all authors that contributed code between version +m.0.0 and version n.0.0 should be listed in the n.0.0 code release DOI. + +In the same way, for a **minor release**, all authors that contributed code between 1.m.0 and +1.n.0 should be listed in the 1.n.0 code release DOI. Note that additional authors +should not be included if they have not contributed to this minor release. For +example, if someone has contributed to version 1.0.0, but not since then, that +person should not be listed as an author on the DOI for version 1.1.0. + +How are authors listed? +------------------------------------ + +All authors should be listed in (english) alphabetical order. This serves both +to (1) convey a lack of hierarchy in code contribution importance and to (2) reflect the +true identities of the authors. + +Summary +======= + +In the absence of a rigid convention in the scientific computing community concerning +contribuion metrics, author attribution, and code citation, this CEP proposes +that uniquely and publicly citable DOIs as well as comprehensive but flat +authorship reflect the needs and desires of the |cyclus| development community. +Finally, this document provides resources for implementing the requirements +it introduces. + +Document History +================ +This document is released under the CC-BY 3.0 license. + +References and Footnotes +======================== + +.. _figshare: http://figshare.com/ +.. _Digital Object Identifier: http://en.wikipedia.org/wiki/Digital_object_identifier + +.. rubric:: References + +.. bibliography:: cep-0004-1.bib + :cited: + diff --git a/_sources/cep/cep5.rst.txt b/_sources/cep/cep5.rst.txt new file mode 100755 index 000000000..3f16dfc9e --- /dev/null +++ b/_sources/cep/cep5.rst.txt @@ -0,0 +1,54 @@ +CEP 5 - Archetype Development Best Practices +************************************************************** + +:CEP: 5 +:Title: Archetype Development Best Practices +:Last-Modified: 2014-06-29 +:Author: Matthew Gidden +:Status: Deferred +:Type: Process +:Created: 2014-06-29 + +.. note:: + + This CEP is looking for a champion. + +Overview +======== + +As the archetype ecosystem begins to develop, an initial set of archetype +development best practices need to be identified that both achieve the aims of +fuel cycle simulation and analysis and encourage the continued proliferation of +the ecosystem. This set of best practices should have general consensus among +both kernel and archetype developers, it should be documented, and the best +practices should be used in code examples. This CEP could be a living document +for some amount of time that is updated as additional best practices are +identified. + +A primary example of such a concern is archetype interaction implementation. One +of the aims of Cyclus as a fuel cycle simulator is to provide a plug-and-play, +modular platform. Accordingly, there is a desire for archetypes to actually *be* +plug-and-playable. However, in an initial use case, archetype developers found +the easiest archetype implementation to include explicit type identification. + +Three interaction models have been identified: + +* *Black Box* - do not dynamically type check, requiring all interfaces be known + at compile time (note that not even Cyclus currently is completely "black box" + in this manner -- the institution class type checks its children to access the + facility's ``Decommission`` API). +* *Grey Box* - dynamic type check can be performed only for |cyclus| and |cyclus| + toolkit interfaces. To date this has been implemented using toolkit mixins + with Cycamore agents. +* *White Box* - dynamic type checking can be performed for any interface, + specifically allowing special interactions between two archetype + implementations. + +A non-deferred version of this CEP will identify these interaction models and +provide guidance for which models the use of which are considered a best +practice. + +Document History +================ +This document is released under the CC-BY 3.0 license. + diff --git a/_sources/cep/cep6.rst.txt b/_sources/cep/cep6.rst.txt new file mode 100755 index 000000000..5a17cdfe5 --- /dev/null +++ b/_sources/cep/cep6.rst.txt @@ -0,0 +1,109 @@ +CEP 6 - |Cyclus| Pull Request Style Guide +************************************************************** + +:CEP: 6 +:Title: |Cyclus| Pull Request Style Guide +:Last-Modified: 2015-05-08 +:Author: Matthew Gidden +:Status: Draft +:Type: Process +:Created: 2015-05-04 + +Abstract +======== + +There is a strong motivation for summarizing and enumerating feature additions, +bug fixes, and other changes to the code base. Through use of an agreed-upon +format and style, tools for aggregating and categorizing changes can be +developed. While this strategy may be applied to issues, this CEP is related to +pull requests (PRs) only. + +A canoncial class of top-level labels is proposed. The purpose of these labels +is to broadly categorize additions to the code base. Then, a minimum style guide +is proposed to provide a known, queryable structure to the body of each pull +request. + +Labels +======= + +Every PR must be assigned at least one label from the following set: + +- Feature - Release Notes +- Feature +- Bug Fix +- Maintenance +- Other + +While a PR may have any number of other descriptive labels, it is considered +blocked if it does not have (at minimum) one of the above labels. + +A PR may be labeled as `Feature - Release Notes` by either the author or +reviewer. If there is a disagreement between the two parties, deference is given +to the party who prefers the `Feature - Release Notes` tag. A PR with this label +is provided candidacy for inclusion in the release notes (highlighting the +feature addition) but does not guaranteed inclusion in the release notes. The +release manager is provided deference in making the decision of what features to +highlight in the release notes, per `CEP 3 `_. + +Layout +======= + +Any PR must have, at minimum, a succinct summary of its associated changes. This +summary must be present at the top of the PR body and must be followed by a new +line. A PR is considered blocked if it does comply with this structure. + +Any additional structure, while clarifying, is optional. + +Example +------- + +The following provides an example of the raw markdown associated with an +existing `PR `_:: + + Added simple buy and sell inventory policies + + Detail + ====== + Inventory policies were added that automate simplistic interactions with the + DRE. Each policy is assigned to a `ResBuf` instance and implements the `Trader` + interface. They can be initialized with information regarding the commodities to + be bought or sold as well as a maximum per-timestep throughput. Purchasing + inventory policies also support `(S, s)` behavior, noted in supply chain literature. [1] + + [1] Zheng, Yu-Sheng. "A simple proof for optimality of (s, S) policies in + infinite-horizon inventory systems." Journal of Applied Probability + (1991): 802-810. + + Related Issues + ============== + * closes #1047 + * related to cyclus/cycamore#318 + +Automation +========== + +Using the Github `API `_ either directly or +through a module like `github3.py +`_ in conjunction with a standard +style can allow for the automation of otherwise repetitive and time consuming +tasks. A chief use case is the generation of release notes. Specifically, if +every PR that enables a major and minor feature can be identified and +a summary statement extracted, then the task of writing release notes becomes +much simpler. This proposal enables such tools to be constructed and utilized. + +Backwards Compatibility +======================= + +Closed PRs are archival documents whereas a codebase is a living +"document". Accordingly, while one would expect a code style guide to be +applicable upon acceptance to the entire code base, this style guide to only be +applicable to open PRs. Closed PR text cannot be edited such that it no longer +complies with the document structure listed in the Layout section. Additional +comments on closed PRs encouraged as they are needed. + +Document History +================ + +This document is released under the CC-BY 3.0 license. + +.. _syntax: https://help.github.com/articles/github-flavored-markdown/ \ No newline at end of file diff --git a/_sources/cep/cep80.rst.txt b/_sources/cep/cep80.rst.txt new file mode 100755 index 000000000..7cebba2f4 --- /dev/null +++ b/_sources/cep/cep80.rst.txt @@ -0,0 +1,51 @@ +CEP 80 - Cycamore Archetype API/Warning Requirements +************************************************************** + +:CEP: 80 +:Title: Cycamore Archetype API/Warning Requirements +:Last-Modified: 2015-05-21 +:Author: Matthew Gidden +:Status: Draft +:Type: Process +:Created: 2015-05-21 + +Abstract +========== + +History has shown that initial designs for archetypes can be quickly found to be +insufficient after usage by others. With timely user response, these designs can +be updated to be more robust in a short period of time, thereby satisfying a +broader range of use cases. This CEP proposes a standard workflow requiring +warnings in any new archetype for at least one release cycle. + +Proposal +=========== + +Reasoning +----------- + +An archetype developer can design a general archetype that satisfies her set of +use cases. After sufficient review, valid and useful archetypes should be merged +into Cycamore. A number of use cases have shown that small additions, however, +can be made to otherwise useful archetypes that greatly expand their set of use +cases. This process is healthy, should be expected, and the ecosystem sanctioned +workflow should take account of it. + +Requirements +--------------------------- + +Any *new* archetype proposed to be merged into Cycamore *must* have an +``ExperimentalWarning`` in its constructor and its user-facing API (i.e., input +file format) is considered unstable. This warning and expected instability must +remain until at least the next microrelease. + +Backwards Compatibility +======================= + +Any archetypes in Cycamore at the present time that did not exist at the last +microrelease must be updated to conform to this CEP. + +Document History +================ + +This document is released under the CC-BY 3.0 license. diff --git a/_sources/cite/index.rst.txt b/_sources/cite/index.rst.txt new file mode 100755 index 000000000..50e62994c --- /dev/null +++ b/_sources/cite/index.rst.txt @@ -0,0 +1,51 @@ +|Cyclus| Publications & Meetings +================================= + +.. image:: ../astatic/flying_gears.jpg + :align: center + :scale: 50 + +|Cyclus| in the Literature +-------------------------- + +The following are notable publications regarding |cyclus|: + +.. bibliography:: pubs.bib + :all: + :list: enumerated + :enumtype: upperroman + +|Cyclus| Presentations +----------------------- + +The following are presentations given about |cyclus|: + +* `Cyclus: Next Generation Fuel Cycle Simulator `_, presented at the Fuel Cycle Options Campaign meeting, 12/16/14, Las Vegas, NV +* `Market-Based and System-Wide Fuel Cycle Optimization `_, presented at the Fuel Cycle Options Campaign meeting, 12/16/14, Las Vegas, NV + + + +|Cyclus| Meetings and Tutorials +------------------------------- + +The |Cyclus| community will occasionally hold meetings and tutorials, with documents shared here: + +.. toctree:: + :maxdepth: 1 + :glob: + + meetings/* + tutorials/* + + + +Citing |Cyclus| +--------------- + +Here are entries for citing |cyclus| and Cycamore in your publications: + +.. bibliography:: citecyc.bib + :all: + :list: bullet + +.. _here: citecyc.bib diff --git a/_sources/cite/meetings/2014.10.23.ANL.rst.txt b/_sources/cite/meetings/2014.10.23.ANL.rst.txt new file mode 100755 index 000000000..2dc873739 --- /dev/null +++ b/_sources/cite/meetings/2014.10.23.ANL.rst.txt @@ -0,0 +1,79 @@ +Review of Cyclus Code and Associated Modules/Tools Development - Argonne National Lab (10/23/14) +================================================================================================ + +Agenda +------ + ++---------+------------------------------------------------------------------+------------------------+ +| 8:00 | Welcomes - Fuel Cycle Options Campaign & Cyclus Development Team | B.P. Singh (DOE) | +| | | R. Wigeland (INL) | +| | | T. Taiwo (ANL) | +| | | P. Wilson (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ +| 8:20 | Introductory Comments by DOE Technical | B. Dixon (INL) | +| | Point of Conctact for Cyclus Related-Activities | | ++---------+------------------------------------------------------------------+------------------------+ +| 8:30 | |830_wilson|_ | P. Wilson (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ +| 9:30 | |930_scopatz|_ | Scopatz (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ +| 10:00 | |1000_brossard|_ | Brossard (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ +| 10:30 | Break | | ++---------+------------------------------------------------------------------+------------------------+ +| 10:45 | Building Cyclus Scenarios with Cycic (Live Demo) | Flanagan (U. Texas) | ++---------+------------------------------------------------------------------+------------------------+ +| 11:15 | |1115_livnat|_ | Livnat (U. Utah) | ++---------+------------------------------------------------------------------+------------------------+ +| 11:45 | |1145_huff|_ | Huff (UC- Berkeley) | ++---------+------------------------------------------------------------------+------------------------+ +| 12:15 | Lunch | | ++---------+------------------------------------------------------------------+------------------------+ +| 13:30 | Insights on Fuel Cycle Simulators | Price (Consultant) | ++---------+------------------------------------------------------------------+------------------------+ +| 14:00 | |1400_schneider|_ | Schneider (U. Texas) | ++---------+------------------------------------------------------------------+------------------------+ +| 14:30 | |1430_skutnik|_ | Skutnik (U. Tennessee) | ++---------+------------------------------------------------------------------+------------------------+ +| 15:00 | Break | | ++---------+------------------------------------------------------------------+------------------------+ +| 15:15 | |1515_carlsen|_ | Carlsen (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ +| 15:45 | |1545_scopatz|_ | Scopatz (U. Wisc) | ++---------+------------------------------------------------------------------+------------------------+ + +.. |830_wilson| replace:: Cyclus Development: History, Strategy, Contributors, Funding, Future Developmental Needs, and Potential Users + +.. _830_wilson: http://dx.doi.org/10.6084/m9.figshare.1285435 + +.. |930_scopatz| replace:: Cyclus v1.1 Status and Capabilities + +.. _930_scopatz: http://dx.doi.org/10.6084/m9.figshare.1289050 + +.. |1000_brossard| replace:: Thrust 1: Stakeholder, Parameter & Metric Identification + +.. _1000_brossard: http://dx.doi.org/10.6084/m9.figshare.1285755 + +.. |1115_livnat| replace:: Exploring Cyclus Results with Cyclist + +.. _1115_livnat: http://dx.doi.org/10.6084/m9.figshare.1291039 + +.. |1145_huff| replace:: Module development for FCO analysis + +.. _1145_huff: http://dx.doi.org/10.6084/m9.figshare.1287476 + +.. |1400_schneider| replace:: Reactor Modules for Cyclus based on Bright-lite + +.. _1400_schneider: http://dx.doi.org/10.6084/m9.figshare.1291036 + +.. |1430_skutnik| replace:: Facility Modules for Cyclus based on Origen + +.. _1430_skutnik: http://dx.doi.org/10.6084/m9.figshare.1291144 + +.. |1545_scopatz| replace:: A Cyclus Roadmap + +.. _1545_scopatz: http://dx.doi.org/10.6084/m9.figshare.1289053 + +.. |1515_carlsen| replace:: Cyclus Optimization Strategies + +.. _1515_carlsen: http://dx.doi.org/10.6084/m9.figshare.1289349 diff --git a/_sources/cite/tutorials/2015-ans-archdev.rst.txt b/_sources/cite/tutorials/2015-ans-archdev.rst.txt new file mode 100755 index 000000000..c3ca0a3c6 --- /dev/null +++ b/_sources/cite/tutorials/2015-ans-archdev.rst.txt @@ -0,0 +1,29 @@ +|cyclus| Archetype Developer's Tutorial at the 2015 ANS Annual Meeting +---------------------------------------------------------------------- + +| **Where:** `ANS Annual Meeting `_ (Lone Star A) +| **When:** Wednesday, June 10, 1:00-4:00 PM +| **Who:** `Matt Gidden `_ & `The Cyclus Development team `_ +| **Why:** Learn how to develop your own plugin module for the Cyclus Fuel Cycle Simulator + +Cyclus is an advanced and flexible fuel cycle simulator capable of modeling +the long-term impacts of different nuclear fuel cycle options. The tutorial +will demonstrate how developers can integrate their archetype with the +graphical user interface for both scenario definition and output exploration +and describe how to distribute new archetypes as part of the Cyclus +community. Cyclus, its graphical user interfaces, and its development tools +are all freely available for users and developers. Participants should bring a +laptop computer for the installation of Cyclus. Participants are also advised +to attend the :doc:`Users Tutorial<2015-ans-users>` earlier that day. + +All participants should + +- start by installing |Cyclus| via instructions on the `Readme + `_ + +- try out the `Hello Cyclus! `_ + example + +- then we can move on to the `tutorial content + `_ + diff --git a/_sources/cite/tutorials/2015-ans-users.rst.txt b/_sources/cite/tutorials/2015-ans-users.rst.txt new file mode 100755 index 000000000..a86109ff5 --- /dev/null +++ b/_sources/cite/tutorials/2015-ans-users.rst.txt @@ -0,0 +1,18 @@ +|cyclus| User's Tutorial at the 2015 ANS Annual Meeting +--------------------------------------------------------- + +| **Where:** `ANS Annual Meeting `_ (Room TBD) +| **When:** Wednesday, June 10, 8:30-11:30 AM +| **Who:** `Matt Gidden `_ & `The Cyclus Development team `_ +| **Why:** Learn how to use the Cyclus Fuel Cycle Simulator + +Cyclus is an advanced and flexible fuel cycle simulator capable of modeling +the long-term impacts of different nuclear fuel cycle options. Cyclus allows +users to arrange models of individual fuel cycle facilities into innovative +fuel cycle configurations. Cyclus and its graphical interfaces are freely +available. This tutorial will explore the fundamental concepts of Cyclus and +guide participants through the process of designing and analyzing a typical +nuclear fuel cycle. Participants should bring a laptop computer for the +installation of Cyclus. + +You can begin our tutorial :doc:`here <../../user/tutorial/index>`. diff --git a/_sources/index.rst.txt b/_sources/index.rst.txt new file mode 100755 index 000000000..8c14178d1 --- /dev/null +++ b/_sources/index.rst.txt @@ -0,0 +1,160 @@ +|Cyclus| +========== + +.. raw:: html + +


+ +.. image:: logos/logo2_bike.gif + :align: center + :alt: Cyclus + +.. raw:: html + +
+ + +|cyclus| is the next-generation agent-based nuclear :doc:`fuel cycle simulator +`, providing flexibility to users and developers +through a :term:`dynamic resource exchange` solver and :term:`plug-in`, +user-developed :term:`agent` framework. + +The goal of |cyclus| is to enable a broad spectrum of :term:`fuel cycle +simulation ` while providing a low barrier to entry for +new users and agent developers. |Cyclus| engages with potential module +developers and encourages them to join a vibrant community in an +:doc:`expanding ecosystem `. Users and developers are +always welcome and encouraged to use or contribute to the |cyclus| project. + +The |Cyclus| project repository is located at http://github.com/cyclus/cyclus + +Quick Start +----------- +:doc:`Get started with Cyclus ` + +News +---- + +**June 1st, 2018:** :doc:`Cyclus Newsletter Spring 2018! ` + +**October 6th, 2017:** :doc:`Cyclus Newsletter Fall 2017! ` + +**December 13, 2016:** :doc:`Cyclus v1.5.0 is released ` + +**July 6-8, 2016:** Technical workshop on Dynamic Fuel Cycle in Paris, France + +**August 13, 2015:** :doc:`Cyclus included in FY2016 workscopes for the NEUP program ` + +**July 21-24, 2015:** Joint workshop with CLASS_ project held in Madison, WI + +**June 10, 2015:** First Cyclus :doc:`user tutorial ` and :doc:`developer tutorial ` are held at the 2015 ANS Annual Meeting in San Antonio, TX + +**June 7, 2015:** :doc:`Cyclus v1.3.1 is released ` + +.. toctree:: + :maxdepth: 1 + + news/fy16neup + newsletters/oct2017 + + +Learn More +---------- + +.. toctree:: + :maxdepth: 1 + + basics/index + user/index + arche/index + kernel/index + python/index + cep/cep0 + previous/index + cite/index + +.. _try-it: + +Try It -- Out-of-Service +------------------------ + +The web-based capability to run Cyclus is out of service. Please check out our :doc:`user start guide ` to get other ways to try Cyclus. +Feel free to reach out using our `Users' mailing list and forum `_ if you need help. + + + +Contact Us +---------- + +* `Users' mailing list and forum `_ + +* `Developers' mailing list and forum `_ + +* `Developer Call times `_: Fridays at 3:00PM EST + +Contributors +------------ + +* Robert Carlsen + +* Denia Djokic + +* Royal Elmore + +* Robert Flanagan + +* `Matthew Gidden `_ + +* Ryan Hodge + +* `Kathryn (Katy) Huff `_ + +* Jenny Littell + +* `Meghan McGarry `_ + +* `Baptiste Mouginot `_ + +* `Arrielle Opotowsky `_ + +* Olzhas Rakhimov + +* `Anthony Scopatz `_ + +* Steve Skutnik + +* Zach Welch + +* `Paul Wilson `_ + +* John Xia + +* Teddy Bae + +Acknowledgments +---------------- + +Support for this research has included funding received from: + +.. container:: image_band + + .. image :: astatic/neup_logo_large.png + :height: 100 px + + .. image :: astatic/AnlLogo.png + :height: 100 px + + .. image :: astatic/USNRC.png + :height: 100 px + + .. image :: astatic/nsf_logo.png + :height: 100 px + + .. image :: astatic/crest.png + :height: 100 px + + .. image :: astatic/nnsa.png + :height: 100 px + + +.. _CLASS: https://forge.in2p3.fr/projects/classforge diff --git a/_sources/kernel/build_from_source.rst.txt b/_sources/kernel/build_from_source.rst.txt new file mode 100755 index 000000000..cb3128f7f --- /dev/null +++ b/_sources/kernel/build_from_source.rst.txt @@ -0,0 +1,87 @@ +Getting and Building |Cyclus| From Source +========================================= + +.. warning:: + + In the cyclus ecosystem, only versions whose micro or patch number + (the third and last number) are zero are considered **stable**. + Other releases where the version number is greater than zero are + bugfix and maintainence releases and are considered **unstable**. + For example, a release number of ``1.42.0`` is stable, while + ``1.42.3`` is unstable. + + +The |Cyclus| Library Suite +-------------------------- +The |cyclus| ecosystem is composed of two projects: + + * |Cyclus| Core, comprising core kernel functionality + * Cycamore, a physics and other domain module repository + +Installation information is provided in the README of each repository, and the +core must be installed before Cycamore. Accordingly, installation steps are as +follows: + + #. Visit the `Cyclus repo `_ and follow the + installation instructions on the main page (README.rst) + #. Visit the `Cycamore readme `_ and + follow the installation instructions on the main page (README.rst) + +Supported Systems +~~~~~~~~~~~~~~~~~ + +Currently, two specific systems are supported: + + * Linux 64-bit (Ubuntu 12+ recommended) + * MacOSX 8 64-bit + +Unfamiliar with git and Github? +------------------------------- + +For the git uninitiated, one must perform the following steps to acquire |cyclus|: + + #. `Set Up git`_ shows one how to set up SSH keys and git user info + #. Fork the |cyclus| repository, as shown in `Fork A Repo`_ + +Note that each |cyclus| repository has **two** branches: + + * master -- the latest stable release of the library + * develop -- the latest working copy that passes all tests + +The above branches are synchronized with each other, and should be used in tandem +(i.e., use master (|Cyclus|) with master (Cycamore) or develop with develop only). + +.. _`Set Up git`: http://help.github.com/linux-set-up-git/ + +.. _`Fork A Repo`: http://help.github.com/fork-a-repo/ + +Help with git and GitHub +~~~~~~~~~~~~~~~~~~~~~~~~ + +If you are unfamiliar with git, here are some resources: + + * http://progit.org/book/ - this is a fantastic guide, from beginner to expert + * http://book.git-scm.com/ + * http://gitimmersion.com/ - A very hands-on tutorial. + * http://www-cs-students.stanford.edu/~blynn/gitmagic/ + +If you are unfamiliar with GitHub, here are some resources: + + * `Github Help`_ + + * To have your changes integrated into the cyclus/cyclus project, you must + submit a GitHub *Pull Request*. Visit `Send pull requests`_ to learn more. + +.. _`Github Help`: http://help.github.com + +.. _`Send pull requests`: http://help.github.com/send-pull-requests/ + +Contact Us +---------- + +If you have further comments or questions about the build process, please don't +hesitate to email or join the |Cyclus| users list, which will allow you to contact +the community of users and developers of |Cyclus|. + +* Email the Users' list: cyclus-users@groups.google.com +* Join the Users' list: https://groups.google.com/forum/?fromgroups#!forum/cyclus-users diff --git a/_sources/kernel/build_with_conda.rst.txt b/_sources/kernel/build_with_conda.rst.txt new file mode 100755 index 000000000..a42e33280 --- /dev/null +++ b/_sources/kernel/build_with_conda.rst.txt @@ -0,0 +1,70 @@ +Building |Cyclus| With Conda +---------------------------------------------------------------- + +.. warning:: + + In the cyclus ecosystem, only versions whose micro or patch number + (the third and last number) are zero are considered **stable**. + Other releases where the version number is greater than zero are + bugfix and maintainence releases and are considered **unstable**. + For example, a release number of ``1.42.0`` is stable, while + ``1.42.3`` is unstable. + +The process of building Conda packages involves a system called +`Conda Recipes `_ . A Conda Recipe +is a directory containing at least two files, meta.yaml and build.sh. +Version information, build and run dependencies, the location of the source +code, and other information about the package are stored in meta.yaml, while +build.sh contains a script to build from source. Packages are built from +recipes using the ``conda build `` command. Necessary dependency +packages will be automatically downloaded and installed before the build.sh +script is run and installed. The final output is a tar.bz2 file which is a +Conda package containing the necessary binaries, libraries, etc. This package +can then be installed or can be uploaded to `Binstar `_, +which is a service provided to store and distribute Conda packages. Notice +that Conda requires all dependencies explicitly listed in meta.yaml must have +an available Conda package to install. + + +All associated Conda recipes can be found in the +`Ciclus Repo `_. As part of installing and +maintaining |Cyclus| with Conda, recipes for a number of dependencies have +also been created. All lowercase directories in this repo (except fetch) are +Conda recipes. Additionally, this repo contains a stock ``.condarc`` file +which automatically points to the +|Cyclus| `Binstar Account `_. + + +------------------------------------------------------------------ +How to work with Conda +------------------------------------------------------------------ +There are many ways to customize the files in Ciclus repo. + +1) Push a package to Binstar Once you have successfully built a Conda recipe, +it can be uploaded to Binstar with the command :: + + binstar upload -u cyclus anaconda/conda-bld/linux-64/cyclus-.tar.bz2 + +So, for instance, uploading version 1.0 of |Cyclus| would be :: + + binstar upload -u cyclus anaconda/conda-bld/linux-64/cyclus-1.0.tar.bz2 + + +2) **Change the repository to build:** Say you want to test your fork of |Cyclus| +before making a pull request. To customize what repos |Cyclus| and Cycamore +are pulled from, look in ``cyclus/meta.yaml`` and ``cycamore/meta.yaml`` +respectively. In these files you can change the ``git_url`` field to point to +the repo of your choice. + +3) **Change the branch to build:** In ``cyclus/meta.yaml`` (or Cycamore), alter the +``git_tag`` field to the branch or tag you want to use. + +4) **Test a new build process for Cyclus and Cycamore:** To alter |Cyclus| or +Cycamore's build process, look at ``build.sh`` in |Cyclus| or Cycamore +respectively. + +5) **Create/upload a new version of a dependency:** Alter the dependency's +``meta.yaml`` file to point to the correct version of dependency source code. +Build the package, follow instructions in 1 to upload to Binstar. + +.. _`Cyclus Homepage`: http://cyclus.github.com diff --git a/_sources/kernel/contributing_to_cyclus.rst.txt b/_sources/kernel/contributing_to_cyclus.rst.txt new file mode 100755 index 000000000..ed9b1fb59 --- /dev/null +++ b/_sources/kernel/contributing_to_cyclus.rst.txt @@ -0,0 +1,187 @@ +.. summary Contributing to |Cyclus| + +Guide for Contributing to |Cyclus| +================================== + +|cyclus| has a number of projects under its umbrella. The core |cyclus| +project repository is located at http://github.com/cyclus/cyclus. Additional +projects found at http://github.com/cyclus include : + +- Cycamore, the |cyclus| additional module repository +- Cymetric, the |cyclus| metrics calculator +- Rickshaw, the automated |cyclus| driver +- and more to come. + +Although you do not have to register with GitHub to download and edit the +code, if you desire your work to be integrated into the |cyclus| mainline of +development *you must fork the cyclus core repository into your own GitHub +account and submit 'Pull Requests'*. :doc:`Here is a tutorial on getting and +building cyclus.` + +Working on a Topic +--------------------- +*Note that "upstream" repository refers to the primary `cyclus/cyclus` repository.* + +You may find or create an issue report in a |cyclus| repository that you would +like to solve. + +You'll first need to fork your repository and create a branch for the topic +you'd like you solve. As you do your development, push only to your own fork. +Make a pull request to the upstream repository (usually the "develop" branch) +only after: + +* You have pulled the latest changes from the upstream repository. +* You have completed a logical set of changes. +* |Cyclus| compiles with no errors. +* All tests pass. +* |Cyclus| input files run as expected. +* Your code has been reviewed by another developer. + +Code from the "develop" branch generally must pass even more rigorous checks +before being integrated into the "master" branch. Hotfixes would be a +possible exception to this. + +Keeping Your Fork Up To Date +----------------------------- +* Use a branching workflow similar to the one described at + http://progit.org/book/ch3-4.html. + +* The "develop" branch is how |cyclus| developers will share (generally + compilable) progress when we are not yet ready for the code to become + 'production'. + +* Keep your own "master" and "develop" branches in sync with the upstream + repository's "master" and "develop" branches. The master branch should + always be the 'stable' or 'production' release of |cyclus|. + + - Pull the most recent history from the upstream repository "master" + and/or "develop" branches before you merge changes into your + corresponding local branch. Consider doing a rebase pull instead of + a regular pull or 'fetch and merge'. For example:: + + git checkout develop + git pull --rebase upstream develop + +* As you do development on topic branches in your own fork, consider + rebasing the topic branch onto the "master" and/or "develop" branches + after *pulls* from the upstream repository rather than merging the pulled + changes into your branch. This will help maintain a more linear (and clean) + history. *Please see caution about rebasing below*. For example:: + + git checkout [your topic branch] + git rebase develop + +Passing Tests +------------- +To check that your branch passes the tests, you must build and install your topic +branch and then run the tests built during that process. + +For the |cyclus| core, the tests are run using the CyclusUnitTestDriver (at +the moment, ```make test``` is insufficient). For example:: + + mkdir build + mkdir install + cd build + cmake ../src -DCMAKE_INSTALL_PREFIX=../install + make + make install + ../install/cyclus/bin/CyclusUnitTestDriver + +In Cycamore, the additional module repository, the tests are run in an exactly +analogous way, but using the CycamoreUnitTestDriver. For example :: + + mkdir build + mkdir install + cd build + cmake ../src -DCMAKE_INSTALL_PREFIX=../install + make + make install + ../install/cycamore/bin/CycamoreUnitTestDriver + +In addition to the CycamoreUnitTestDriver, a suite of input files can be run and +tested using the run_inputs.py script that is configured, built, and installed +with Cycamore. It relies on the input files that are part of your Cycamore +repository, and only succeeds for input files that are correct (some may have +known issues. See the issue list in Cycamore for details.) To run the example +input files, :: + + python ../install/cycamore/bin/run_inputs.py + +Making a Pull Request +---------------------- + +When you are ready to move changes from one of your topic branches into the +"develop" branch, it must be reviewed and accepted by another developer. + + - You may want to review this `tutorial + `_ before you make + a pull request to the develop branch. + +Sometimes, your pull request will be closed by the reviewer until further +changes are made to appease the reviewer's concerns. This may be frustrating, +but please act rationally, discuss the issues on the GitHub space made for +your pull request, consult the `style guide `, email the +developer listhost for further advice, and make changes to your topic branch +accordingly. The pull request will be updated with those changes when you push +them to your fork. When you think your request is ready for another review, +you can reopen the review yourself with the button made available to you. + + +Changelog +--------- +Pull requests will often have CHANGELOG entries associated with. However, +to avoid excessive merge conflicts, please follow the following procedure: + +1. Go into the ``news/`` directory, +2. Copy the ``TEMPLATE.rst`` file to another file in the ``news/`` directory. + We suggest using the branchname:: + + $ cp TEMPLATE.rst branch.rst + +3. Add your entries as a bullet pointed lists in your ``branch.rst`` file in + the appropriate category. It is OK to leave the ``None`` entries for later + use. +4. Commit your ``branch.rst``. + +Feel free to update this file whenever you want! Please don't use someone +else's file name. All of the files in this ``news/`` directory will be merged +automatically at release time. The ``None`` entries will be automatically +filtered out too! + + +Reviewing a Pull Request +---------------------------- + + - Build, install, and test it. If you have added the remote repository as + a remote you can check it out and merge it with the current develop + branch thusly, :: + + git checkout -b remote_name/branch_name + git merge develop + + - Look over the code. The `next page ` details what to look for while reviewing.) + + - Check that it meets :doc:`our style guidelines `. + + - Make inline review comments concerning improvements. + + - Accept the Pull Request + + - In general, **every commit** (notice this is not 'every push') to the + "develop" and "master" branches should compile and pass tests. This + is guaranteed by using a NON-fast-forward merge during the pull request + acceptance process. + + - The green "Merge Pull Request" button does a non-fast-forward merge by + default. However, if that button is unavailable, you've made minor + local changes to the pulled branch, or you just want to do it from the + command line, make sure your merge is a non-fast-forward merge. For example:: + + git checkout develop + git merge --no-ff remote_name/branch_name -m "A message"" + + +See also +-------- +A good description of a git workflow with good graphics is available at +http://nvie.com/posts/a-successful-git-branching-model/ diff --git a/_sources/kernel/cycpp.rst.txt b/_sources/kernel/cycpp.rst.txt new file mode 100755 index 000000000..60d20c39f --- /dev/null +++ b/_sources/kernel/cycpp.rst.txt @@ -0,0 +1,6 @@ +cycpp +===== + +.. automodule:: cycpp + :members: + :member-order: bysource \ No newline at end of file diff --git a/_sources/kernel/index.rst.txt b/_sources/kernel/index.rst.txt new file mode 100755 index 000000000..06be5422c --- /dev/null +++ b/_sources/kernel/index.rst.txt @@ -0,0 +1,71 @@ +|Cyclus| Kernel Developer Guide +=============================== + +The |cyclus| project repository is located at +http://github.com/cyclus/cyclus. + +Although you do not have to register with GitHub to download and edit the +code, if you desire your work to be integrated into the |cyclus| mainline of +development *you must fork the cyclus core repository into your own github +account and submit 'Pull Requests'*. + + +.. toctree:: + :maxdepth: 1 + + build_from_source + cycpp + +Software Development Aids +-------------------------- +.. toctree:: + :maxdepth: 1 + + contributing_to_cyclus + pr_review + build_with_conda + style_guide +.. make-models/main + +Diversions +---------- + +A video history of our development (video created using gource): + + * `Award winning + `_ + snippet + + .. raw:: html + +
+ +| + + * The original full video + + .. raw:: html + +
+ +| + + * We also have a `prior `_ version + representing development from March 3, 2010 to July 25, 2012 + +The |Cyclus| core developer team circa 1.0 release, 2014-05-30: + +.. image:: /astatic/core-team-2014-05-30.jpg + :width: 750px + :align: center + + +Relevant xkcd comics: + + * `Standards `_ + * `The General Solution `_ + diff --git a/_sources/kernel/pr_review.rst.txt b/_sources/kernel/pr_review.rst.txt new file mode 100755 index 000000000..0102f8849 --- /dev/null +++ b/_sources/kernel/pr_review.rst.txt @@ -0,0 +1,156 @@ + +.. summary reviewing pull requests + +Guide for Reviewing Pull Requests +================================== + +|cyclus| depends on a community of contributors. Bug fixes and new features +(and archetypes!) are added by submitting a pull request on github. The new +code is then reviewed by other |cyclus| developers to confirm that the code +meets all requirements for style and stability before being added to the code +base. You do not need to be an expert |cyclus| developer to contribute by +reviewing pull requests! In fact, reviewing other people's code is a great way +to learn the code base! Below we offer a rough guide to how to review a pull +request. + +Maintaining a Collegial Atmosphere +----------------------------------- + +A collegial (as opposed to an adversarial) atmosphere is critical to the success +of an open-source software project. Imagine how it will feel for a new +person to appear out of the blue wanting to contribute to Cyclus. Let’s not +drive them away! + +* Contributing is ideally all rainbows and butterflies (only positive + interactions) +* Thank people for contributing +* Timely feedback engenders enthusiasm and future contributions +* There is no need for adversarial comments, even (especially) when there is + disagreement +* We never know who may be lurking and thinking about contributing in the future +* To understand what makes good and bad communities, follow or contribute to + other open-source projects + + +Should I Review This Pull Request (PR)? +--------------------------------------- +Am I ready to do a review on my own? + +* It’s ok for multiple people to review PRs, so don’t feel like you can’t + review if someone else already is +* Take responsibility for your reviewing - do not expect that someone else + will re-review YOUR review +* If you are not 100% comfortable, then complete your review and say “I have + completed my review and will merge this in 2 days if there are no further + comments.” This gives more experienced reviewers the opportunity to look at + it if they choose to +* A good exercise for learning your way around the code base is to start from + cyclus.cc and follow the trail of code execution as a simulation is + initialized and executed - to get a rough sort of callgraph in your head + +How do I feel about the purpose of this PR? + +* I like it/am interested: Do the review +* Don’t care: Still do the review +* I dislike it/disagree with it: Initiate a broader discussion about whether + the PR is appropriate + + +Start Reviews by Looking for Hard Stops +--------------------------------------- + +Start a review with the obvious stuff, so that if there are major problems then +the coder can fix them before you do the detailed review: + +* Does it pass + `continuous integration `_ tests (CI)? +* Does it build and pass tests on my machine? (ie. nosetests, cyclus_unit_tests) +* Have new unit tests been added to confirm the functionality of the proposed + change? +* Does it adhere to the style guide? +* Is there documentation explaining the new features? (Sometimes documentation + will need to be added to both the code itself and the cyclus website, + especially in the case of new tools for developers to use. Then you should + expect to see two pull requests) +* Can I understand what is being changed right away by looking at the + documentation and the API, or from just the new tests? + + +Do I understand why this PR is being added? + +* Do not merge code you do not understand; instead, use the API to figure out + what the code is doing +* Never assume the person who opened the PR knew what they were doing +* If you still can’t figure it out - put inline comment to ask why it is done + this way +* Fixing bugs should always take precedence over adding features +* Feature PRs should have a much higher standard to be merged + + + +Getting Into The Details +------------------------ +Does the general use case for this PR match its API and implementation? + +* Imagine there are two approaches to solving the problem: if option A was + chosen, what was option B and why is A the preferred option. The chosen + option should balance performance with the use-case most likely to come up +* For example, bitwise operations are very confusing (but are very fast). If + you don’t need it for performance, readability and clarity are more important +* The majority of the Cyclus code base should be easier to read/maintain rather + than faster in the absence of concrete need for speed + +Is there sufficient test coverage (more than just "are there tests")? + +* Start with tests - if there are insufficient tests then you should not do the + code review until the tests are added +* If there are enough tests then they can show the reviewer what the goal of + the PR is +* In most cases, every line of code should be tested (except for test code, + which would be infinitely recursive), but not necessarily every code pathway + (not every combination must be tested) +* If there is a conditional code, there should be tests for both outcomes of + the conditional +* If there are very obscure corner-case tests that are missing, do not close + the pull request + +Is there a reasonable use case that would fail given this implementation? + +* Make sure you can’t think of a way to make the code fail. If you can, there + needs to be a test for this, and there likely needs to be a code modification +* This is most likely to occur in a PR with very few tests (writing the tests + naturally help the coder to identify many of these cases) + +Is the code implemented cleanly? + +* Are there "easy" optimizations (e.g. variable allocation outside of a well- + used loop)? +* Are the data structures you’re using the right ones? (ie. sets have unique + elements while vectors have ordered elements) +* For loops vs while loops +* Premature optimization is not always good (you don’t know *a priori* where + the sticking points will be, and optimization often reduces maintainability) + + + +More Best Practices +------------------- +Cover the full gamut of `Software Carpentry `_ +best practices. And remember: + +* Is there sufficient documentation? +* Style Guide adherence is not a personal critique. It is designed to keep + code maintainable. Don’t be offended. Everyone hates something in the style + guide, but a common standard is necessary +* Google C++ style guide says Never Abbreviate. Cyclus has historical reasons + for some abbreviations, but new abbreviations are strongly discouraged absent + justification +* Communally agreed upon departures from the existing style guide should be + documented + + +Remember, if there is *anything* in the pull request that you don't understand, +don't merge it! Educate yourself using the API docs, ask questions, or request +an explanation from the coder. + + diff --git a/_sources/kernel/style_guide.rst.txt b/_sources/kernel/style_guide.rst.txt new file mode 100755 index 000000000..c6bc6b1dd --- /dev/null +++ b/_sources/kernel/style_guide.rst.txt @@ -0,0 +1,34 @@ +Style Guidelines for Developers +=============================== + +|cyclus| uses the `Google C++ Style Guide`_ and `Google Python Style Guide`_. +In order to ensure compliance with these styles, we recommend the `Artistic +Style`_ tool with the following `settings`_ located in |cyclus| repo. However, +be wary of applying this tool blindly because it has some `limits and bugs`_. +`Cpplint`_ and `Pylint`_ are other helpful tools to check your code for style +and syntax errors. Unfortunately, these tools may also suffer false positives +and false negatives. + +Doxygen Code Documentation +=============================== +The definitive documentation of any software is the source code itself. +|cyclus| will relies on Doxygen for automation of rich documentation from +appropriately formatted comments in the source code. Current Doxygen +documentation can be found online for both `cyclus +`_ and `cycamore +`_. These pages will be updated nightly. + +Documentation is a make target in the CMake build system. Documentation +will automatically be built when you `make all`. You can build only the +documentation by running `make cyclusdoc` instead of `make all` or `make`. + + +.. _`Google C++ Style Guide`: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml +.. _`Google Python Style Guide`: http://google-styleguide.googlecode.com/svn/trunk/pyguide.html +.. _`Artistic Style` : http://astyle.sourceforge.net +.. _`settings` : http://github.com/cyclus/cyclus/blob/master/misc/.astylerc +.. _`limits and bugs` : https://sourceforge.net/p/astyle/bugs/ +.. _`Cpplint` : http://google-styleguide.googlecode.com/svn/trunk/cpplint/ +.. _`Pylint` : http://www.pylint.org/ + + diff --git a/_sources/news/fy16neup.rst.txt b/_sources/news/fy16neup.rst.txt new file mode 100755 index 000000000..f71dd1ac1 --- /dev/null +++ b/_sources/news/fy16neup.rst.txt @@ -0,0 +1,32 @@ +FY2016 NEUP Funding Opportunity with |Cyclus| +================================================ + +Date: August 13, 2015 + +The NEUP_ program has released the workscope definitions for the `FY2016 +Consolidated Innovative Nuclear Research +`_ +program. These workscopes include specific activities in support of the +|Cyclus| ecosystem. Interested parties are encouraged to `contact the Cyclus +team `_ to learn more about the project +and how the |Cyclus| team can best support your research interests. + +FC-5.1b: Maintaining and advancing Fuel Cycle Simulation Capability +--------------------------------------------------------------------- + +The current nuclear fuel cycle is a well-established and well-understood system. Fuel cycle analysis is important for understanding how a transition to an alternative fuel cycle will impact that system. |Cyclus| (www.fuelcycle.org) is an open-source nuclear fuel cycle simulator that is designed to enable collaborative enhancements and improvements that accommodate different fuel cycle analysis questions and use cases. Projects which can maintain and advance this capability developed in part due to past NEUP_ support are invited. For example: + +* Develop modules that support specific types of fuel cycles or fuel cycle technologies +* Develop capability for sensitivity analysis and/or optimization +* Interfacing with tools designed to model broader energy & climate futures (e.g., MARKAL_, GCAM_, etc.) +* Developing capability for economic and financial modeling +* Incorporation of time and geospatial considerations for the transportation of material +* Maintaining and enhancing Cycamore, the basic module library for Cyclus and providing the Cyclus community facilitator role and a resource for developers of archetype modules and analysis tools. + + +.. _NEUP: http://www.neup.gov + +.. _MARKAL: http://www.iea-etsap.org/web/Markal.asp + +.. _GCAM: http://www.globalchange.umd.edu/models/gcam/ + diff --git a/_sources/newsletters/may2018.rst.txt b/_sources/newsletters/may2018.rst.txt new file mode 100755 index 000000000..7759aec6b --- /dev/null +++ b/_sources/newsletters/may2018.rst.txt @@ -0,0 +1,51 @@ +============================== +Cyclus Newsletter May 2018 +============================== + +.. raw:: html + +


+ +.. image:: ../logos/logo2_bike.gif + :align: center + :alt: Cyclus + +.. raw:: html + +
+ + +Greetings! Warm weather is upon us and the Cyclus development team is looking forward to a productive summer. This past fall and spring have been busy for us! Accordingly, we still have some wonderful things to share. + +Developments +============ +Cyclus has been undergoing a number of changes recently. These changes have not been released in a full version as of yet. However, as they are forthcoming the following is a list of changes coming with the next release. + +- New Decision Phase: This phase occurs at the end of a time step and allows agents to make decisions about the operations that occured during the time step. +- TimeSeriesRecord Updates: This update allows agents to see the TimeSeriesRecord calls from other agents if they desire. + +Third Party Modules +=================== +D3ploy +------ +This package is designed to manage the deployment of facilities automatically based on a increasing demand. It uses autoregressive time series methods to predict future demand and supply from historical data. + +Information on this can be obtained at the github page. https://github.com/ergs/d3ploy + +Peddler +------- +This agent aims to simulate trucks that transport materials between facilities. It is currently under development. If you're interested in this agent for use or development please contact Robert Flanagan at flanagrr@mailbox.sc.edu. + +News +====== +Gyu Tae Park received an undergrad research award for his geopositioning work with Cyclus. Information about the award can be found here. http://arfc.github.io/jekyll/update/2018/04/20/park-ugrad-award/ + +Dr. Paul Whitney from Pacific Northwest National Laboratory visited `CNERG `_ at the University of Wisconsin-Madison as a `Consortium for Verification Technology `_ Lab Fellow to discuss the use of Cyclus as part of an ongoing effort to simulate misuse and diversion in nuclear fuel cycles. This use case is similar to the work funded by the CVT project at UW-Madison and Dr. Whitney bring valuable experience with applying machine learning and decision analysis methodologies to this problem. + +Publications +============ + +.. bibliography:: pubsmay2018.bib + :all: + :list: bullet + :enumtype: upperroman diff --git a/_sources/newsletters/oct2017.rst.txt b/_sources/newsletters/oct2017.rst.txt new file mode 100755 index 000000000..c640d8605 --- /dev/null +++ b/_sources/newsletters/oct2017.rst.txt @@ -0,0 +1,114 @@ +============================== +Cyclus Newsletter October 2017 +============================== + +.. raw:: html + +


+ +.. image:: ../logos/logo2_bike.gif + :align: center + :alt: Cyclus + +.. raw:: html + +
+ + +Greetings! As the fall weather approaches the Cyclus development team wants to give you an update +on the work being done and updates one things currently in development. + +Developments +============ +Geolocation +----------- +Cyclus modules now have the capability to utilize real values for latitude and +longitude. This allows developers and users to plot the facilities that Cyclus +builds at coordinates on mapping tools, such as google maps. This utility is also +useful for instituions or regions that might be interested in determining where +facilities should be placed using GIS information. + + +Third Party Modules +=================== +CyBorg +------ +CyBorg has been given an offical release. + +Cyborg uses effective one-group cross-sections for different fuel assembly +types, initial compositions, and problem-specific burnups +are automatically interpolated from pre-existing Origen +reactor data libraries + +New reactor libraries can easily be created using SCALE + +CyBORG can be built using SCALE shared libraries +(in principle, can be built without requiring the SCALE source code) + +CyBORG v1.0 has been publicly released: http://www.github.com/sskutnik/cyborg + +Bright-lite +----------- +Bright-lite has been updated to work with the new build system for cyclus. Bright-lite has also been +mitraged to the BriXsuite organization on github. Development on the module is still continuing +if you'd like to contribute to the software please contact Robert Flanagan at flanagrr@mailbox.sc.edu. + +CyCLASS +------- +A `cyclus module under development `_ that leverages the work of the CLASS methodology. More +information on CLASS can be found `here `_ (registration required). + +MBMore +------ + +A collection of archetypes that support Cyclus work at the University of +Wisconsin in the Consortium for Verification Technology. One of these +archetypes is `CascadeEnrich` that incorporates modeling equations for +individual centrifuge machines to enable the deployment of an enrichment +facility that designs an optimal cascade from a given number of centrifuges +and target enrichment. The `InteractRegion` and `StateInst` archetypes are +designed to track the interaction between different nation states to estimate +a probability that any given state will pursue nuclear weapons, based on +analysis of historical factors that contribute to such a decision. + + +Events +====== + +TWoFCS +------ +July 19th through the 21st, the ERGS group at the University of South Carolina hosted a +Technical Workshop on Fuel Cycle Simulation. Several members of the Cyclus community +were in attendance and presented cyclus related work. Talks involving Cyclus included: + +- CyCLASS +- CyBorg +- Rickshaw + +Additionally, Dr. Yarden Livnat was present at the meeting to talk about visualization +and how it can be used to support simulation. Dr. Livnat supports Cyclus primarily +though a NEUP, but was available to get feedback from the attendees. + +Cyclus Developer Meeting +------------------------ +Following the Technical Workshop on Fuel Cycle Simulation (TWoFCS), several members of the +cyclus development team met to discuss the current state, and future of Cyclus. Over the +course of the meeting a list of current use cases and issues were brought up to set a basis +for where future efforts should be focused. From this base, a list of improvements and +changes were built. + +- Publish a Python Notebook with demonstration of Cymetric usage +- Update the database to make the analysis of results easier to accomplish. +- Split Cycamore - create a new repository for more advanced modules. +- Add python notebook section to website. +- Create a database for real existing reactors +- Package in with cyclus a list of recipes common fuel forms +- Update cyclus tutorial + +Publications +============ + +.. bibliography:: pubsoct2017.bib + :all: + :list: bullet + :enumtype: upperroman diff --git a/_sources/previous/index.rst.txt b/_sources/previous/index.rst.txt new file mode 100755 index 000000000..3462e8ea2 --- /dev/null +++ b/_sources/previous/index.rst.txt @@ -0,0 +1,135 @@ +|Cyclus| Previous Versions +========================== + +.. image:: ../astatic/sp_sketch.jpg + :align: center + :scale: 50 + +The following are release notes for and links to previously released versions of +|cyclus|: + +.. toctree:: + :maxdepth: 1 + + v1.5.5 + v1.5 + v1.3 + v1.2 + v1.1 + v1.0 + v0.4 + v0.3 + v0.2 + +Note: As official 1.4.0 release has been skipped, all the release notes of 1.4.0 +have been included in the 1.5.0. + +.. rst-class:: centered + +========= ========== ================ ============== +Version Date Zip Tar +========= ========== ================ ============== +1.5.5 2019-01-14 `zip 1.5.5`_ `tar 1.5.5`_ +1.5.0 2016-12-13 `zip 1.5.0`_ `tar 1.5.0`_ +1.5.0 2016-12-13 `zip 1.5.0-rc1`_ `tar 1.5.0-rc1`_ +1.4.1 2016-11-01 `zip 1.4.1`_ `tar 1.4.1`_ +1.4.0 2016-10-31 `zip 1.4.0`_ `tar 1.4.0`_ +1.4.0-rc3 2016-09-14 `zip 1.4.0-rc3`_ `tar 1.4.0-rc3`_ +1.4.0-rc2 2016-08-29 `zip 1.4.0-rc2`_ `tar 1.4.0-rc2`_ +1.4.0-rc1 2016-05-26 `zip 1.4.0-rc1`_ `tar 1.4.0-rc1`_ +1.3.0 2015-05-27 `zip 1.3.0`_ `tar 1.3.0`_ +1.3.0-rc6 2015-04-27 `zip 1.3.0-rc6`_ `tar 1.3.0-rc6`_ +1.3.0-rc5 2015-04-27 `zip 1.3.0-rc5`_ `tar 1.3.0-rc5`_ +1.3.0-rc4 2015-04-27 `zip 1.3.0-rc4`_ `tar 1.3.0-rc4`_ +1.3.0-rc3 2015-04-27 `zip 1.3.0-rc3`_ `tar 1.3.0-rc3`_ +1.3.0-rc2 2015-04-27 `zip 1.3.0-rc2`_ `tar 1.3.0-rc2`_ +1.3.0-rc1 2015-04-27 `zip 1.3.0-rc1`_ `tar 1.3.0-rc1`_ +1.2.0 2014-12-02 `zip 1.2.0`_ `tar 1.2.0`_ +1.2.0-rc1 2014-11-25 `zip 1.2.0-rc1`_ `tar 1.2.0-rc1`_ +1.1.0 2014-09-19 `zip 1.1.0`_ `tar 1.1.0`_ +1.1.0-rc1 2014-09-16 `zip 1.1.0-rc1`_ `tar 1.1.0-rc1`_ +1.0.0 2014-05-30 `zip 1.0.0`_ `tar 1.0.0`_ +1.0.0-rc4 2014-05-30 `zip 1.0.0-rc4`_ `tar 1.0.0-rc4`_ +1.0.0-rc3 2014-05-27 `zip 1.0.0-rc3`_ `tar 1.0.0-rc3`_ +1.0.0-rc2 2014-05-26 `zip 1.0.0-rc2`_ `tar 1.0.0-rc2`_ +1.0.0-rc1 2014-05-24 `zip 1.0.0-rc1`_ `tar 1.0.0-rc1`_ +0.4.4 2014-05-01 `zip 0.4.4`_ `tar 0.4.4`_ +0.4.2 2014-03-06 `zip 0.4.2`_ `tar 0.4.2`_ +0.4.1 2014-02-27 `zip 0.4.1`_ `tar 0.4.1`_ +0.4 2014-02-13 `zip 0.4`_ `tar 0.4`_ +0.4-rc1 2014-02-09 `zip 0.4-rc1`_ `tar 0.4-rc1`_ +0.3 2013-10-28 `zip 0.3`_ `tar 0.3`_ +0.3-rc1 2013-10-25 `zip 0.3-rc1`_ `tar 0.3-rc1`_ +0.2 2013-07-17 `zip 0.2`_ `tar 0.2`_ +0.2-rc1 2013-07-12 `zip 0.2-rc1`_ `tar 0.2-rc1`_ +0.1 2012-03-27 `zip 0.1`_ `tar 0.1`_ +========= ========== ================ ============== + +.. _zip 1.5.5: https://github.com/cyclus/cyclus/archive/1.5.5.zip +.. _tar 1.5.5: https://github.com/cyclus/cyclus/arcive/1.5.5.tar.gz +.. _zip 1.5.0: https://github.com/cyclus/cyclus/archive/1.5.0.zip +.. _tar 1.5.0: https://github.com/cyclus/cyclus/archive/1.5.0.tar.gz +.. _zip 1.5.0-rc1: https://github.com/cyclus/cyclus/archive/1.5.0-rc1.zip +.. _tar 1.5.0-rc1: https://github.com/cyclus/cyclus/archive/1.5.0-rc1.tar.gz +.. _zip 1.4.1: https://github.com/cyclus/cyclus/archive/1.4.1.zip +.. _tar 1.4.1: https://github.com/cyclus/cyclus/archive/1.4.1.tar.gz +.. _zip 1.4.0: https://github.com/cyclus/cyclus/archive/1.4.0.zip +.. _tar 1.4.0: https://github.com/cyclus/cyclus/archive/1.4.0.tar.gz +.. _zip 1.4.0-rc3: https://github.com/cyclus/cyclus/archive/1.4.0-rc3.zip +.. _tar 1.4.0-rc3: https://github.com/cyclus/cyclus/archive/1.4.0-rc3.tar.gz +.. _zip 1.4.0-rc2: https://github.com/cyclus/cyclus/archive/1.4.0-rc2.zip +.. _tar 1.4.0-rc2: https://github.com/cyclus/cyclus/archive/1.4.0-rc2.tar.gz +.. _zip 1.4.0-rc1: https://github.com/cyclus/cyclus/archive/1.4.0-rc1.zip +.. _tar 1.4.0-rc1: https://github.com/cyclus/cyclus/archive/1.4.0-rc1.tar.gz +.. _zip 1.3.0: https://github.com/cyclus/cyclus/archive/1.3.0.zip +.. _tar 1.3.0: https://github.com/cyclus/cyclus/archive/1.3.0.tar.gz +.. _zip 1.3.0-rc6: https://github.com/cyclus/cyclus/archive/1.3.0-rc6.zip +.. _tar 1.3.0-rc6: https://github.com/cyclus/cyclus/archive/1.3.0-rc6.tar.gz +.. _zip 1.3.0-rc5: https://github.com/cyclus/cyclus/archive/1.3.0-rc5.zip +.. _tar 1.3.0-rc5: https://github.com/cyclus/cyclus/archive/1.3.0-rc5.tar.gz +.. _zip 1.3.0-rc4: https://github.com/cyclus/cyclus/archive/1.3.0-rc4.zip +.. _tar 1.3.0-rc4: https://github.com/cyclus/cyclus/archive/1.3.0-rc4.tar.gz +.. _zip 1.3.0-rc3: https://github.com/cyclus/cyclus/archive/1.3.0-rc3.zip +.. _tar 1.3.0-rc3: https://github.com/cyclus/cyclus/archive/1.3.0-rc3.tar.gz +.. _zip 1.3.0-rc2: https://github.com/cyclus/cyclus/archive/1.3.0-rc2.zip +.. _tar 1.3.0-rc2: https://github.com/cyclus/cyclus/archive/1.3.0-rc2.tar.gz +.. _zip 1.3.0-rc1: https://github.com/cyclus/cyclus/archive/1.3.0-rc1.zip +.. _tar 1.3.0-rc1: https://github.com/cyclus/cyclus/archive/1.3.0-rc1.tar.gz +.. _zip 1.2.0: https://github.com/cyclus/cyclus/archive/1.2.0.zip +.. _tar 1.2.0: https://github.com/cyclus/cyclus/archive/1.2.0.tar.gz +.. _zip 1.2.0-rc1: https://github.com/cyclus/cyclus/archive/1.2.0-rc1.zip +.. _tar 1.2.0-rc1: https://github.com/cyclus/cyclus/archive/1.2.0-rc1.tar.gz +.. _zip 1.1.0: https://github.com/cyclus/cyclus/archive/1.1.0.zip +.. _tar 1.1.0: https://github.com/cyclus/cyclus/archive/1.1.0.tar.gz +.. _zip 1.1.0-rc1: https://github.com/cyclus/cyclus/archive/1.1.0-rc1.zip +.. _tar 1.1.0-rc1: https://github.com/cyclus/cyclus/archive/1.1.0-rc1.tar.gz +.. _zip 1.0.0: https://github.com/cyclus/cyclus/archive/1.0.0.zip +.. _tar 1.0.0: https://github.com/cyclus/cyclus/archive/1.0.0.tar.gz +.. _zip 1.0.0-rc4: https://github.com/cyclus/cyclus/archive/1.0.0-rc4.zip +.. _tar 1.0.0-rc4: https://github.com/cyclus/cyclus/archive/1.0.0-rc4.tar.gz +.. _zip 1.0.0-rc3: https://github.com/cyclus/cyclus/archive/1.0.0-rc3.zip +.. _tar 1.0.0-rc3: https://github.com/cyclus/cyclus/archive/1.0.0-rc3.tar.gz +.. _zip 1.0.0-rc2: https://github.com/cyclus/cyclus/archive/1.0.0-rc2.zip +.. _tar 1.0.0-rc2: https://github.com/cyclus/cyclus/archive/1.0.0-rc2.tar.gz +.. _zip 1.0.0-rc1: https://github.com/cyclus/cyclus/archive/1.0.0-rc1.zip +.. _tar 1.0.0-rc1: https://github.com/cyclus/cyclus/archive/1.0.0-rc1.tar.gz +.. _zip 0.4.4: https://github.com/cyclus/cyclus/archive/0.4.4.zip +.. _tar 0.4.4: https://github.com/cyclus/cyclus/archive/0.4.4.tar.gz +.. _zip 0.4.2: https://github.com/cyclus/cyclus/archive/0.4.2.zip +.. _tar 0.4.2: https://github.com/cyclus/cyclus/archive/0.4.2.tar.gz +.. _zip 0.4.1: https://github.com/cyclus/cyclus/archive/0.4.1.zip +.. _tar 0.4.1: https://github.com/cyclus/cyclus/archive/0.4.1.tar.gz +.. _zip 0.4: https://github.com/cyclus/cyclus/archive/0.4.zip +.. _tar 0.4: https://github.com/cyclus/cyclus/archive/0.4.tar.gz +.. _zip 0.4-rc1: https://github.com/cyclus/cyclus/archive/0.4-rc1.zip +.. _tar 0.4-rc1: https://github.com/cyclus/cyclus/archive/0.4-rc1.tar.gz +.. _zip 0.3: https://github.com/cyclus/cyclus/archive/0.3.zip +.. _tar 0.3: https://github.com/cyclus/cyclus/archive/0.3.tar.gz +.. _zip 0.3-rc1: https://github.com/cyclus/cyclus/archive/0.3-rc1.zip +.. _tar 0.3-rc1: https://github.com/cyclus/cyclus/archive/0.3-rc1.tar.gz +.. _zip 0.2: https://github.com/cyclus/cyclus/archive/0.2.zip +.. _tar 0.2: https://github.com/cyclus/cyclus/archive/0.2.tar.gz +.. _zip 0.2-rc1: https://github.com/cyclus/cyclus/archive/0.2-rc1.zip +.. _tar 0.2-rc1: https://github.com/cyclus/cyclus/archive/0.2-rc1.tar.gz +.. _zip 0.1: https://github.com/cyclus/cyclus/archive/v0.1.zip +.. _tar 0.1: https://github.com/cyclus/cyclus/archive/v0.1.tar.gz diff --git a/_sources/previous/release_notes.rst.txt b/_sources/previous/release_notes.rst.txt new file mode 100755 index 000000000..d5e51d60e --- /dev/null +++ b/_sources/previous/release_notes.rst.txt @@ -0,0 +1,84 @@ +.. _1.5.5: + +================================== +Cyclus 1.5.5 Release +================================== +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version of the +cyclus ecosystem! + +Major features +============== + +No major features added. + +`Cyclus `_ +--------------------------------------------- + +**Added:** + +* Added a test example of Cyclus sensitivity analysis studies conducted using Dakota. +* Script and CI implementation ensuring at least 1 news file have been recreated. +* Added capability to register unit when reporting values in a time series. +* Added `map>` typesystem. This can be used with C++ archetypes. But not python archetypes. + + +**Changed:** + +* git and open-ssh added to the dockerfile (removed from CI). +* MACOS only: link against PYTHON lib in the binary building process. It should not be required when building the Python package as python knows about itself. For some reason, this is only true (and working) on MACOS, and was an issue when using Conda to install Python and other Cyclus deps. +* Updated the Cyclus quick installation instructions to reflect our use of conda to install dependencies. + + +**Removed:** + +* git and open-ssh from CI (added to the dockerfile). +* Reference to `develop` branch tests in the readme file. + + +**Fixed:** + +* News now checks diff against cyclus/master not origin/master. +* News check now triggers on PRs only. +* Allows build against Python => 3.7. +* Change cyclus-deps Docekrfile accordingly. (changing cython version to 0.28.5). + +`Cycamore `_ +-------------------------------------------------- + +**Changed:** + +* A reactor will now decommission itself if it is retired and the decommission requirement is met. + +`Cymetric `_ +-------------------------------------------------- + +**Added:** + +* Monthly electricity generated metric. One for returning electricity by one agent and another for all agents. +* Added units parameter. + +Summary +======= + +Since v1.5.4, + +* Cyclus: 159 commits resulting in 67 files changed, 1444 insertions(+), 977 deletions(-) + +* Cycamore: 19 commits resulting in 29 files changed, 270 insertions(+), 235 deletions(-) + +* Cymetric: 13 commits resulting in 7 files changed, 104 insertions(+), 4 deletions(-) + +Contributors +============ +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Anna Caldwell-Overdier * +* Baptiste Mouginot +* Gwendolyn Chee +* Jordan Stomps * +* Paul Wilson diff --git a/_sources/previous/v0.2.rst.txt b/_sources/previous/v0.2.rst.txt new file mode 100755 index 000000000..af52ed61d --- /dev/null +++ b/_sources/previous/v0.2.rst.txt @@ -0,0 +1,112 @@ +======================== +Cyclus 0.2 Release Notes +======================== + +:Author: Cyclus Developers +:Website: http://cyclus.github.io/ +:Contact: cyclus-dev@googlegroups.com + +The Cyclus core team is excited to announce the second stable version +after over a year of development! This includes nearly 1300 commits by +6 developers. Major features include, + +- A module separation effort. This required major changes to the building + and testing system. See Cycamore [1]. + +- Added tests and basic convenience features to various classes, mostly with + respect to the critical material class. + +- Substantive performance improvements (~50x for some simulations). + +- Input code revamp. + +- Output recording code rewrite. + +Changes from 0.1 to 0.2 +======================= + +New features +------------ + +- Added data type specification capability to rng system. +- Made various ResourceBuffer, Material Class, and agent memory management + improvements and tests. +- Made the relaxng schema system modular. +- Made significant build system and installation changes to allow separating + the modules into Cycamore and creating CycStub. +- Moved modules into their own repository (Cycamore). +- Improved or added material convenience functions for developers such as + subtraction, un-normalization, and more. +- Added significant testing in Material, CompMap, and related classes. +- Added additional exception throwing for exceptional absorption and extraction + cases (extracted too much, absorbed negative). +- Made fixes to the build system to better address the needs of Mac OSX users. +- Added libxml++ as a dependency. +- Added features to the command line interface to allow output file + specification. +- Updated code base in accordance with Google Style Guide (0's to NULL when NULL + is intended, prepended iterators, moved curly braces, etc.) +- Expanded extraction by mass to allow various input units. +- Added functions and tests for almost equality and thresholding in the + material class. +- Created the CycArithmetic class which holds tools for more sophisticated + floating point arithmetic. +- Fixed absorption method bug (#493, https://github.com/cyclus/cyclus/issues/493). +- Substantive performance improvements (~50x for some simulations). +- Easier to create/record custom data to output. Modular, drop-in support for + different output formats. +- Top-level simulation flow broken into clear module loading, simulation + initialization/construction, simulation running, and module unloading steps. +- Added ability to invoke daily actions (technically this reduces the timestep to + a single day for modules that need to take advantage of the smaller granularity). +- IsoVector's compmap encapsulated in a separate class. +- IsoVector and material interfaces updated accordingly. +- Added an enrichment toolkit to assist with SWU/NatlU calculations. +- Added SWU/Natural uranium calculation methods. +- Added a facility-building and management interface kit, allowing for + intelligent facility build decision making. +- Added a commodity supply/demand toolkit, providing an interface for + supply/demand inquiry and supplier/demander registration with a manager. +- Added a commodity production toolkit, providing an interface to query agents + ability to produce commodities. +- Added a toolkit for agenting general symbolic functions and factory methods + to produce them. +- Added derived classes to agent linear, exponential, and piecewise functions. +- Added a robust dynamic loading interface for dynamic libraries for easy opening, + access, and closing. +- Separated unix and windows-specific helper functions for dynamic loading. +- Added a generic interface for input querying. +- Added a specific interface for loading, parsing, and querying xml files, + including rng schema verification. +- Added interleaves to cyclus.rng's institution and region sections. +- Added capacity members to cyclus.rng. + +Deprecations +------------ + +- Deprecated converter facilities. + +Known bugs +---------- + +- Known Bug (#514): decayed compositions are not recorded in output database. + + +Contributors +============ + +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Matthew Gidden +* Katy Huff +* Anthony Scopatz* +* Zach Welch* +* Paul Wilson + + +References +========== + +[1] Cycamore: https://github.com/cyclus/cycamore diff --git a/_sources/previous/v0.3.rst.txt b/_sources/previous/v0.3.rst.txt new file mode 100755 index 000000000..8cc245431 --- /dev/null +++ b/_sources/previous/v0.3.rst.txt @@ -0,0 +1,325 @@ +======================== +Cyclus 0.3 Release Notes +======================== + +:Author: Cyclus Developers +:Website: http://cyclus.github.io/ +:Contact: cyclus-dev@googlegroups.com + +The Cyclus core team is excited to announce the latest stable version +after over a year of development! This includes nearly 340 commits by +6 developers. Major features include, + +- Implementation of the Cyclus Enhancment Proposal (CEP) system. + +- Merged Cyclopts into cyclus, CEP2 + +- Resource Tracking and Interfaces Re-Re-Redo, CEP17. + +- Google C++ Style Guide compliance. + +Since v0.2, 477 files have changed encompassing 52028 line insertions(+) and +51749 deletions(-). + +Changes from 0.2 to 0.3 +======================= + +New features +------------ + +- removed supply_demand and action_building namespace. closes #248. +- record agent that creates each resource in output db +- changed resource creation to take this ptr instead of context ptr. Removed context arg from Material::CreateUntracked. Made untracked resources have an id of zero instead of an id of garbage. fixed mat doc comments to use new res_buf method names. +- cleaned up resource buf interface. Added some basic templating to eliminate need for separate mat_buff +- added timestamp to resource table. +- sorted lists of files/includes alphabetically +- added header_impl file +- fixed logger macro issue from namespace removal and added a test to catch it at compile time in the future +- alphabetized cyclus.h +- moved all symfunctionptr to symfunction::ptr +- solverptr to solver::ptr +- moved function type pointers to function::ptr +- moved VariablePtr to Variable::Ptr +- removed additional cyclus:: prepends from implementation files +- removed extraneous cyclus namespace from fac_agent impl +- removed extraneous cyclus namespace from comp_math impl +- removed extraneous cyclus namespace from hdf_back impl +- moved solver interface impl under cyclus namespace +- removed extraneous cyclus namespace from commodity_producer impl +- put solver impl under cyclus namespace +- put cbc solver impl in cyclus namespace +- put variable implementation file in cyclus namespace +- removed explicit namespace usage in implementation files for function and building manager +- removed cyclus:: prefix from optim header files +- removed cylus:: prefix from non-optim files +- removed cyclus:: from building manager +- Update copyright years in license +- removed reference to include.h +- move symbolic functions into a different class name +- moved all files out of optim dirs into their respective top levels +- renamed cyclopts to optim +- change module install dir to not be split into separate fac, reg, inst subdirs. Still need to fix schema building and env class and dynamic_loading class correspondingly. made Env::ListModules more robust and include CYCLUS_MODULE_PATH env var dirs in search. Made BuildMasterSchema not care about agent type namespacing subdirs. +- fixed some gcsg issues and a typo +- made timer init method not reset previous timer config (e.g. listeners) - this caused confusion and debugging for me in the past +- made timer ticker registering more robust. Search env var dirs before install dirs for dyn modules. change default dyn module install dir to lib/cyclus instead of lib/Agents +- added hard coded version and more robust --tags flag to git describe for version. +- this should make CI pass... not sure if its what we want, though. +- updated install script with new structure +- made agent test files install to share dir, fixes #559 +- docs now in the top level directory, and a little clean up. fixes #602 +- docs currently build +- removed cyclus namespace from stubs +- moved stub directory to top level, made stubs a separate library, incorporated stub tests into cyclus unit tests +- a little cleaning before stubbing +- enabled testing in new build environment. simplified test module directory structure and building. +- gtest library builds +- added cli to at the top of the directory structure +- actually adds top level cmake file.. +- currently builds cycluscore from top-level directory +- encapsulated stubs namespace in cyclus namespace per gcsg +- redisabled facility tests as that 's a larger issue than this PR +- added include guards +- added stub market +- added stub inst and region. updated stub facility. +- removed any stubs that aren't facs, regions, insts, or agents +- updated namespace name to reflect directory name +- made mock fac/inst/region/market classes to be used with testing. added the stub facility in a new stub namespace and related tests. +- added initial stub directory and adjusted cmake files to include their tests. +- moved all dynamic loading into xml_file_loader. Added a method for listing installed/discoverable dynamic modules to env class. added rng schema methods to test agents and removed rng files from them. removed rng installation from cmake module macro. added master and module schema dumping to cyclus binary. added schema agent test (that schema parses). moved heavy stuff out of xml-file-loader constructor. renamed LoadAll to LoadSim. +- i think moving loglevel and the macros into the same namespace encapsulation is more promising... still unable to confirm. +- finishes remaining doxygen warnings +- I believe that this will fix the warning stemming from logger.h, but I do not see the warning on my machine, so I can't be sure +- fixed begincode error +- removed verbose linking flag +- fixes build error for macs, moves mac linker flag to top of cmake file to set the flag for all compiled libraries in the build +- added cli flag for printing cyclus include dir +- down-selected includes in cyclus.h. Removed remaining vestiges of converter agents +- create cyclus.h. added missing header install +- as @gonuke suggested, adding a preprocessor directive was the right way to go. tested with coin-2.3 on insam +- removed coin include prefix which causes problems on utk's darwin system +- removed unnecessary Config dir. Deleted duplicate (and outdated) LICENSE and README files. +- moved Core source files into base src/ directory. +- moved Testing dir to tests dir. Moved test modules into tests dir. Moved app.cc into new cli dir +- removed disabled tests from being found by the find test script. closes #591. +- removed pesky cout +- removed extraneous string var +- adjusted env var setting to append the current var if it was set +- added robustness in the environmental tests by resetting the environment variable and the dynamic loading tests by making sure to delete and close opened library modules. +- test driver now adds the build directory to the cyclus module path. fixes #592. note that this overwrites the global module variable only for the test driver's environment. +- Remove indirect dependencies +- main now returns 0 +- updated readline to use the decode method. the script is now python2/3 compliant. note that I tested with python3.3. +- renamed id, parentid member vars and accessors +- initfrom to CapCase +- made clone methods CapCase +- added from future import +- made print function python3-compliant +- fixed remaining coin and init issues +- doc improvement +- added python as a dependency +- adds a script to generate test names and adjust build system to add those tests to the make test target appropriately. fixes #176. +- improved clone and initfrom doc comments +- fixed resource table name +- have a working version of a ctest fix. need to clean it up and add python as a dependency before sending a PR +- fixed inst agent tests and fixed duplicate id bug in agent class if implicit copy-constructor is used +- constructor initializer list +- removed cruft from agent class. fixed to not record on undeployed decommission. improved var/accessor names +- removed unnecessary externed Destruct funcs +- fixed inst class tests +- fixed dynamic loading tests - removed redundant test with env class tests. Simplified dynamicModule further. Trying to fix inst class tests - still broken. +- updated test agents. 2 tests still failing +- updated tests to compile with new cloning and deploy semantics +- move clone method into agent class. Killed Clone[stuff] methods into single virtual clonefrom method. Change EnterSimulation[bla] methods into a single, virtual, Deploy method. Moved DynamicModule Init method into constructor. Removed redundant info from facility class (build date, etc.). +- Combiined cyclopts dependency list into cyclus dependency list. +- added file and cli flag for retrieving cyclus core and dependency versions. Fixes #578. +- Simplifying names and correcting some rst grammar. +- Add links to get sample input files. Updated dependency list. +- Update README.rst with additional information about dependencies and correct call of installation. +- removed singleton references in documentation +- undisabled building manager bug +- removed build dead code and mistakenly commited cyclus.rng file +- fixed seg fault due to double delete in tear down +- added tests for the optional query interface +- added cyclus namespace qualifier to new function usage +- moved the optional element query into its own nonmember, nonfriend templated function for easier, one-line usage. +- added tests for null queries +- removed try/catch blocks for fac agent query engine usage +- updated market agent tests for context usage +- added clarification to recipe add/get usage, closes #568 +- added clarification to recipe add/get usage +- style guide names +- style guide name changes. +- renamed externed construct/destruct functions to be CapCase +- updated facility tests to take the context constructor argument +- made a separate test context for easier testing and updated appropriate agent test files +- updated facility agent tests and fixed agent tests +- updated agent tests +- removed unncessary agent registration from context - because markets will soon be superseded by CEP18 anyway. +- updated prototype registration and agent creation to use context. recipe library become so small I moved it into xml_file_loader. renamed xml_file_loader methods according to GCSG and added a LoadAll method. +- moved control param xml parsing into xml_file_loader out of timer. Added timer init method to context. +- removed EM macro and simplified recipe library and changed it to recipe namespace +- fixed segfault issue. fiddled with includes and forward declarations +- everything compiles, but tests segfault +- more work converting core to use context - still doesn't compile +- started outline for a simulation context +- Moving include files to include/cyclus +- changes for making debian packages +- moved setup.py to install.py +- fixed var name style +- unadded redundant neg comp element check. Added test to check for exception throwing +- added missing neg quantity check +- adds comments about composition decay chaining. Remove leftover recipe_lib constructor from debugging +- fixed gcsg names in decay_handler and renamed class to decayer. fixed filename comments in product and improved a couple of guards +- fixes var names and comments to not refer/suggest anything 'vector' ish w.r.t. CompMap code. Change nextId to next_id +- re-disabled test... need more time to investigate +- added disabled building manager test +- readded disabled tests, which now pass +- removed variable bound introspection from the cbc solver. CI should build without issue now. +- moved variable bound introspection based on a VariablePtr into non member non friend functions in variable.h/cc. +- added some more simple tests for the cbc solver. two have been intentionally disabled because the maximization direction for the objective function does not appear to be working. I have double checked that the optimization direction for maximization is correct (it's 1.0) from the coin documentation. I'll investigate further. +- removed bounded 2 variable test, starting simple with 1 variable +- added a 1 variable test that should pass and a test that uses variable bounds. changed test names to better reflect the testing taxonomy +- made implicit cast a static cast +- changed Composition::Vect to CompMap +- added mat_query tests and polished mat_query doc comments +- made mat_query a proper implementation file. Removed contains for now and added almostEq to it. +- polished doc comments for compmath namespace +- fixed var name mistake in res_tracker +- polished doc comments on product, material, res_tracker, and composition classes. Added more complete error check to Product::Absorb +- polished resource class doc comments +- moved resource table all to res_tracker +- finished converting compmath tests +- doc fix +- moves resource-specific param recording into resource class and resource implementations now only record their special state. +- fixed comp_math add and sub funcs. material tests all pass +- moved unique id and bumping implementation into resource class +- fixed absorb and extract errors in material class +- finished remaining compile errors - now to fixing failed tests +- fixed material and matquery tests +- added tests and tried to consolidate iso_vector, comp_map, and material test content into material, composition and comp_math tests. +- everything compiles except tests +- literal 0 -> 0.0 for fp compares +- abs() -> fabs(), types they are a-changing. +- fixes doc errors, should clear up @gonuke's cron job errors +- fixes master schema building +- updated test files so cycamore can build +- ran all files in Core dir through astyle for style guide formatting +- updated enrichment function names +- fixed implementation issues +- fixed all compile errors +- fixed compile error and more sed replaces for typedef names +- fixed many typedefs to be CapCase +- updated macros to install in correct place +- flattened all directories, removed extraneous file, renamed all files and updated files regarding name changes +- renamed most funcs to CapCase +- finished variable-related tests, updated related api, and updated documentation. this last commit closes all code-related issues in cyclus/cyclopts#37. +- changed namespace names, closes #531 +- added tests for objective and constraint functions, updated documentation +- made constraint iterator access const as it should have been +- added tests for the function base class, updated documentation, and made slight API changes based on documentation +- prepended cyclopts to test name for easy regexp selection +- updated solver interface documentation +- made addconstituent public, removing need for friend class +- made variable tests less namespace verbose +- renamed integration tests to properly reflect that they are in fact testing the cbc solver. updates cbc solver documentation. +- added overarching but simple integration test for cyclopts +- resolve rebase compile errors +- renamed Error class files and formatted them according to style guide +- removed exception silencing from sqliteback +- fixed remaining build/run issues +- eliminated super-specific crazy exceptions. Created a few basic exception types to be used throughout cyclus core. Shortened exception class names +- added a test +- hotfix. Anthony's namespace merging wiped out my schema building invocation in XMLLoader. +- fixed header file guards in cyclopts +- fixed line lengths in header files in cyclopts +- fixed line lengths of cyclopts implementation files +- removed using namespace std from cyclopts files +- updated line lengths for header files in cyclopts +- fixed line length for Utility files touched in this PR +- added cyclus namespace on top of cyclopts namespace +- fixes a few things anthony missed +- test update. tag: move and squash +- removed find cyclopts +- updated findcyclopts +- Fixed some merge conflict +- cyclopts testing now exists is subdirectory of Testing +- ns updates finished now to mereg +- removed blas link, unnecessary. +- cyclopts headers now install in cyclopts directory +- added blas and lapack dependency for coin. tag: squash +- removed cyclus_tools in favor of explicit includes of variable and function. made cyclopts_limits limits. +- made cyclopts a subproject whose headers are now called by cyclopts/header.h +- updated readme and setup script +- cyclopts now builds as part of cyclus +- moved cyclopts files into Core directory with history +- Many testing fixes +- reverted some documentation overwrites and added some compliance +- make cyclus up to date with cyclopts google style compliance +- made input file recorded after schema validation +- added include guards as per style guide +- fixes include order, switch indentation, and adds missing map includes to csvback +- updated primary files used in this branch/PR to use google styleguide for indent/naming +- More namespace updates +- fixed Blob.hpp and other formatting. Added tests for each backend for the new blob type. +- Added cyclus::Blob type as a supported backend type for all backends. Removed unnecessary streaming operators in any.hpp. +- fixed query engine errors +- updates cyclus core to reflect cyclopts/cyclopts#33 +- fixed more error, everything is broken +- 'public, protected, private indent one space' +- fixes indent errors in DynamicModule.h described in #530. +- added ns to roesources. +- first cyclus ns changes. +- made buildSchema private. Used Agent class module type list instead of custom one. +- removed cyclus.rng.in generation - now done dynamically in cyclus core +- modified XML loading to dynamically build the master schema by searching for installed modules +- created csv backend. +- fixed name erro +- updated setup with localdir as default for some params +- added uninstall target. closes #268. +- made ~/.local the default install directory in the setup.py +- Actually have them all and they all work. +- I think that I got them all.. +- added hdf5 dep to readme instructions. fixes #520. +- fixed enum element style +- made eventmanager handle insertion of uuids into all events. backends now need to check for and handle boost::uuids::uuid value type +- wrote custom pool allocator new and delete for Event class. Created a producer/consumer type memory reuse vector in EventManager to prevent new/delete calls +- changed c cast to static_cast +- Added modified warning to any.hpp. added comment about event vals vector reserve +- added shortcut to void* in any.hpp. Simplified hdf5 backend fillBuff +- speed up event class by reserving capacity for event vals +- switched event class to use a tweaked boost::spirit::hold_any allowing non-explicit construction instead of boost::any. 30% performance boost of total inpro_low runtime. +- found out that boost has a installed called bjam. bjam has an option --layout which can take the form tagged. tagged adds -mt and - to a library. if multithreading is on (which it is by default), it must find a library with the -mt tag. I was able to turn off multi threading for it to find the boost libraries installed in filespace/groups/cnerg/cyclus_dependencies. I'd like to leave the comment there for posterity. this set of commits closes #521. +- added a message to determine which libraries were being used +- updated readme's boost version +- fixed null-padding on strings issue. changed set to group so Anthony is happy. +- changed hdf5 ext to .h5. Hdf5Back constructor takes std::string +- adds better doc comment to hdf5back class. Uncomments the db file deleting line. +- added hdf5back test +- added custom backend specification to App.cp via output file extension +- rewrote hdf5 backend to use C API. Made Sqlite destructor virtual +- refactored hdf5 back by splitting large code into smaller functions. +- created hdf5 backend - seems to be working. Probably could use some performance tweaking. + +Deprecations +------------ +N/A + +Known bugs +---------- +N/A + +Contributors +============ + +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Royal Elmore +* Matthew Gidden +* Katy Huff +* Olzhas Rakhimov* +* Anthony Scopatz +* Zach Welch +* Paul Wilson + diff --git a/_sources/previous/v0.4.rst.txt b/_sources/previous/v0.4.rst.txt new file mode 100755 index 000000000..208c49d17 --- /dev/null +++ b/_sources/previous/v0.4.rst.txt @@ -0,0 +1,97 @@ +======================== +Cyclus 0.4 Release Notes +======================== + +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version +of the cyclus ecosystem! This includes over 415 commits by +6 developers. Major features include, + +- Brand new Dynamic Resource Exchange Procedure, removed the previous notion + of markets, CEP18 + +- Continuous integration for all pull requests now occurs via BaTLab though + polyphemus. + +- Cleaned up API for agent instantiation and deallocation. Users no longer should + worry about memory management of their agents. + +- Added regression tests to the test suite. + +- Many bug and testing issues were fixed. + +Since v0.3, 207 files have changed encompassing a net 9173 line insertions(+) and +5043 deletions(-). + +Changes from 0.3 to 0.4 +======================= + +New features +------------ + +- added more detail about context agent ownership and stack agents are bad. (7682c6c) +- changed clone methods to use context-arg constructor (eaede68) +- changed xml Init[Core/Module]Member fan methods to be InitFrom chain. + Gave agent class a default val for *spec_* to facilitate testing of xml init + methods. (3efb2b6) +- renamed InitCoreMembers to InitFrom (f6e0add) +- fixed deploy self as parent bug in xmlfileloader. Agent class removes 'this' + from context *agent_list_* in destructor to prevent some segfaults when + agents are allocated on the stack causing a double delete (one by runtime and + one by context). Put guard on context::DelAgent to only delete if the agent is + in the *agent_list_* (53ec514) +- made context agent management more universal. Made *agent_list_* a std::set. + added doc comment about context agent management. minor tweaks (45efa47) +- removed agent_list getters from context class. agent list is now entirely + context-private (4b18f0d) +- updated exclusivity adjustment. this bug wasn't evident (or testable) because + capacity-constraints will cause tomatch < remain which then will by definition + be tomatch < excl_val of arc. all tests pass and alls well. (0ee97f2) +- made greedy algorithm a little simpler for exclusive arcs (deb90a0) +- added a namespace specifically for solver testing (9eaa900) +- exclusive bids now supported and tested (a098999) +- smaller hdf5 table chunk size and turn compression on (a3c4e98) +- trimmed fat from cyclus.rng.in and finished rng cleanup. (e1928dd) +- added authorship file (f021d01) +- moved test objects off the heap, fixes the building manager tests (d6d60e9) +- renamed timeagent ta vars to timelistener tl vars (3728fa0) +- removed boost date stuff from timer (60df1c9) +- renamed timeagent to timelistener and methods to just tick/tock. + removed daily tasks (4b07b64) +- renamed EventManager to Recorder and renamed Event to Datum and EventBackend to + RecBackend (8d2b9a6) +- initialized more members of the exchange node struct (3193d72) +- updated the initfrom interface to be easier to use/more intuitive (b2ba4e1) +- made context more resource generic (ed39a0d) +- buffers default to having a capacity (8497bf5) +- added a context helper for a facility with many input and output recipes and + commodities (13cffc7) +- added a hook for the context to register a facility (136d13a) +- added a resource exchange class (4a810d9) +- added request portfolios and associated tests. required notion of equality of + capacity constraints and requests and required notion of ordering of capacity + constraints for use as a map key, so I added an id member and associated < operator. + (f464cb8) +- added request class and associated tests for materials (202048c) + +Known bugs +---------- +N/A + +Contributors +============ + +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Royal Elmore +* Matthew Gidden +* Katy Huff +* Olzhas Rakhimov +* Anthony Scopatz +* Zach Welch +* Paul Wilson diff --git a/_sources/previous/v1.0.rst.txt b/_sources/previous/v1.0.rst.txt new file mode 100755 index 000000000..3d760acab --- /dev/null +++ b/_sources/previous/v1.0.rst.txt @@ -0,0 +1,98 @@ +======================== +Cyclus 1.0 Release Notes +======================== + +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version +of the cyclus ecosystem! This includes over 5000 commits by +8 developers. + +Major features +============== + +- Cyclus Enhancement Proposal (CEP) system for large changes + +- Testing suite + + * unit tests + * integration tests (continuous through BaTLab and Polyphemus) + * regression tests + +- Resource tracking functionality and resource interface simplicity (CEP 17) + +- Complicated fuel cycles enabled via dynamic resource exchange (CEP 18) + +- Advanced time step execution for consistent agent behavior (CEP 20) + +- Basic modules in Cyclus core, advanced modules in Cycamore + + * relatedly, agent identification (CEP 21) + +- Pre-processing + + * auto-generate input/output archetype code for supported datatypes + +- Simulation initialization and restart + +- Now using PyNE for nuclear data (http://pyne.io) + +- Basic Lodtka-Volterra predator/prey-like simulation behavior demonstrated + +- Updated build system + + * kernel in ``$PREFIX/lib/`` as ``cyclus`` (i.e., ``libcyclus.so`` or + ``libcyclus.dylib``) + + * cyclus agents in ``$PREFIX/lib/cyclus`` as ``agents`` + + * cyclus generic agent archetype unit tests in ``$PREFIX/lib/cyclus`` as + ``baseagentunittests`` + + * cycamore agents in ``$PREFIX/lib/cyclus`` as ``cycamore`` + + * cyclus unit tests in ``$PREFIX/bin`` as ``cyclus_unit_tests`` + + * cycamore unit tests in ``$PREFIX/bin`` as ``cycamore_unit_tests`` + + * support for easy build/install of modules with single agent archetype and + associated tests + + * support for easy build/install of modules of group of agent archetypes and + associated tests + +- Toolkit + + * separation of additional "helper" classes and interfaces out of kernel + source directory and namespace + +- Significantly updated database schema, utilized for both canonical input and + output + + * supports variable length datatypes for both sqlite and hdf5 + +Since v0.4 + +* Cyclus: 1,125 commits resulted in 262 changed files encompassing a net 33,825 + line insertions(+) and 9,676 deletions(-). + +* Cycamore: 270 commits resulted in 133 changed files encompassing a net 2,243 + line insertions(+) and 95,294 deletions(-). + +Contributors +============ + +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Matthew Gidden +* Katy Huff +* Arrielle Opotowsky +* Olzhas Rakhimov +* Anthony Scopatz +* Zach Welch +* Paul Wilson + diff --git a/_sources/previous/v1.1.rst.txt b/_sources/previous/v1.1.rst.txt new file mode 100755 index 000000000..b37218c1e --- /dev/null +++ b/_sources/previous/v1.1.rst.txt @@ -0,0 +1,58 @@ +======================== +Cyclus 1.1 Release Notes +======================== +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version +of the cyclus ecosystem! This includes nearly 300 commits by +8 developers. + +Major features +============== +- Ability to force decay calculations off everywhere in the simulation. +- A menagerie of new datatypes: + + * ``std::vector`` + * ``std::vector`` + * ``std::set`` + * ``std::list`` + * ``std::pair`` + * ``std::map`` + * ``std::map`` + * ``std::map`` + * ``std::map`` + * ``std::map`` + +- Human-readable nuclide names may now be uses in input files. +- Memory leak bug fix. +- New 'schematype' state variable annotation allows archetype developers to + explicitly set the XML datatype in the schema for a given state variable, + rather than relying on defaults. +- Quantity-based constraints added to DRE. +- Automatic archetype discovery with '-l' and '-a' command line arguments. +- Better error handling in cycpp. +- Optional allocation optimization using tcmalloc. + +Since v1.0, + +* Cyclus: 243 commits resulted in 274 changed files encompassing a net 24,441 + line insertions(+) and 5,222 deletions(-). + +* Cycamore: 38 commits resulted in 69 changed files encompassing a net 1,948 + line insertions(+) and 1,855 deletions(-). + +Contributors +============ +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Matthew Gidden +* Katy Huff +* Arrielle Opotowsky +* Olzhas Rakhimov +* Anthony Scopatz +* Zach Welch +* Paul Wilson diff --git a/_sources/previous/v1.2.rst.txt b/_sources/previous/v1.2.rst.txt new file mode 100755 index 000000000..ba5372de3 --- /dev/null +++ b/_sources/previous/v1.2.rst.txt @@ -0,0 +1,50 @@ +======================== +Cyclus 1.2 Release Notes +======================== +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version +of the cyclus ecosystem! This includes over 125 commits by 5 developers. + +Major features +============== +- Added 'entity' key to the archetype annotations. This may take on one of the + following values: region, institution, facility, archetype, or unknown. +- Added further reflection to archetypes by including 'parents' and 'all_parents' + lists to the metadata. +- Added archetype name to metadata annotations. +- Nicer looking JSON strings. +- Fixed dynamic loading error that was triggered in weird cases on linux. +- The command ``cyclus -m`` now returns all metadata. +- Added Squash() functions to MatQuery class. +- Added 'nuclide' to availible 'uitypes'. +- Added Extra debugging info via ``CYCLUS_DEBUG_DRE`` environment variable. +- Added new experimental ResBuf class for resource buffering. +- Added optional tails buffer to enrichment class. +- Many bug fixes. + +Since v1.1, + +* Cyclus: 95 commits resulted in 644 changed files encompassing a net 2347 + line insertions(+) and 397 deletions(-). + +* Cycamore: 33 commits resulted in 15 changed files encompassing a net 93 line + insertions(+) and 91 deletions(-). + +Contributors +============ +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Robert Flanagan* +* Matthew Gidden +* Katy Huff +* Arrielle Opotowsky +* Olzhas Rakhimov +* Anthony Scopatz +* Zach Welch +* Paul Wilson +* John Xia* diff --git a/_sources/previous/v1.3.rst.txt b/_sources/previous/v1.3.rst.txt new file mode 100755 index 000000000..70b04dc2c --- /dev/null +++ b/_sources/previous/v1.3.rst.txt @@ -0,0 +1,91 @@ +.. _1.3: + +================================== +Cyclus 1.3 Release Notes +================================== +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version of the +cyclus ecosystem! + +Major features +============== + + +`Cyclus `_ +--------------------------------------------- + +- ~3x speedups for recipe-based simulations +- Basic inventory policies added +- Support for recursive containers in archetypes +- Many new recursive containers added to sqlite backend +- Regression tests run on macs! +- A MockSim interface for full simulation testing without input files +- Added customizeable TimeSeries output for recording archetype-specific time + series +- Added json-to-xml conversion capability +- Added new ResMap container +- Decay added (via Pyne)! An input file flag can be set to + - never: never decay + - manual: archetypes must call the decay API manually + - lazy: materials are decayed as needed when their Material::comp function is + called + +`Cycamore `_ +-------------------------------------------------- + +- New facility archetypes added + - Reactor + - FuelFab + - Separations + - Enrichment +- Other facility archetypes removed + - BatchReactor + - EnrichmentFacility +- Some experimental archetype APIs updated + - GrowthRegion +- Much better end-of-life fuel handling in reactors +- Regression tests run on macs! + +`Cymetric `_ +-------------------------------------------------- + +- First release for a new analysis and visualization tool for Cyclus simulation output +- Command line tool and Python interface +- Calculates metrics of user interest from a Cyclus database + - Writes metrics back to database + - Simple for users to extend the suite of metrics + - Designed so calculations can be based on dependencies (other metrics or root metrics) + - Uses pandas data types + - Uses PyNE for nuclear data +- Visualization available from the command line via matplotlib + +Summary +======= + +Since v1.2.0, + +* Cyclus: 409 commits resulting in 113 files changed, 8466 insertions(+), 1760 deletions(-) + +* Cycamore: 353 commits resulting in 79 files changed, 7466 insertions(+), 6830 deletions(-) + +* Cymetric: 366 commits resulting in 49 files changed, 5978 insertions(+), 266 deletions(-) + +Contributors +============ +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Denia Djokic* +* Robert Flanagan +* Matthew Gidden +* Katy Huff +* Meghan McGarry* +* Arrielle Opotowsky +* Olzhas Rakhimov +* Anthony Scopatz +* Paul Wilson +* John Xia diff --git a/_sources/previous/v1.5.rst.txt b/_sources/previous/v1.5.rst.txt new file mode 100755 index 000000000..8af0eb79c --- /dev/null +++ b/_sources/previous/v1.5.rst.txt @@ -0,0 +1,143 @@ +.. _1.5.0: + +================================== +Cyclus 1.5.0 Release +================================== +:Author: Cyclus Developers +:Website: http://fuelcycle.org/ +:Contact: https://groups.google.com/forum/#!forum/cyclus-dev + +The Cyclus core team is excited to announce the latest stable version of the +Cyclus ecosystem! + +Major Features +============== + +Compatibility: + +* C++ 11 support is now required to compile Cyclus and Cycamore. + +* Resource exchange preferences now default to 1.0 instead of zero. + + +`Cyclus `_ +--------------------------------------------- + +Features: + +* Resource exchange now supports COIN linear and mixed integer linear solvers. + This can be specified in the input file. + +* Added new optional :ref:`ExplicitInventory ` and + :ref:`ExplicitInventoryCompact ` tables to the + database that can be enabled via input file. + +* Implemented custom time step duration that can be set in the input + file (i.e. CEP 23). + +* Agents/archetypes now can provide their own versions that are recorded in + the :ref:`AgentVersion ` table in the database for + provenance/reproducibility. + +* Support for new datatypes added to the sqlite backend: + + - ``std::list >`` + - ``std::map > >`` + - ``std::vector, std:map > > >`` + + +* ``cycpp`` now supports the ``internal`` annotation for state variables + allowing them to be persisted in the database, but not visible in the input + file or GUI. + +* Adding 2 new variables to allow adjustments to the caculation tolerance: + ``tolerance`` and ``tolerance_generic``. + +* Building stubs archetypes now requires C++11. + +* More effective hdf5 backend generation by using an AST setup with various + nodes and blocks of nodes + +* Generate lastest version in dbtypes.json upon install + +* Now generate a Python library allowing Cymetric to be full Python + +Bug fixes: + +* Fixed floating-point comparison bugs in DRE causing incorrectly failed + resource trades. + +* Determinism/reproducibility improved by calling agents' resource exchange + related functions in consistent order. + +* Fixed invalid memory access bugs affecting newer and mac compilers. + +* xinclude substitutions in input files are now processed for the input file + stored in output databases - rather than storing the incomplete, partial + input file. + +* Archetype compilation now correctly fails early if the ``cycpp`` + preprocessor fails. + +* Fix late silent failures on <= 0.0 quantity bids to early loud failures. + +* ``cyclus::toolkit::ResBuf`` is no longer experimental. + +* Fix bad types in ``dbtypes.json`` + + +`Cycamore `_ +-------------------------------------------------- + +* Added Storage archetype. This Facility is intended to hold materials for a + user specified amount of time in order to model a storage facility with a + certain residence time or holdup time. + +* Added Mixer archetype. This facility Mixer mixes N streams with fixed, + static, user-specified ratios into a single output stream. The Mixer has N + input inventories: one for each streams to be mixed, and one output stream. + The supplying of mixed material is constrained by available inventory of mixed + material quantities. + +* All Cycamore archetypes now uses the ``tolerance_resource`` for all the buffer ``Pop``. + + +`Cymetric `_ +-------------------------------------------------- + +* Added new metrics: full list `here `_ +* Added a new directory with cymetric usage examples +* Separated out all archetype-specific metrics from the main metrics +* Is now full Python + + +Summary +======= + +Since v1.3.0, + +* Cyclus: 865 commits resulting in 213 files changed, 23823 insertions(+), 6436 deletions(-) + +* Cycamore: 177 commits resulting in 71 files changed, 4389 insertions(+), 2077 deletions(-) + +* Cymetric: 65 commits resulting in 58 files changed, 1490 insertions(+), 4220 deletions(-) + + +Contributors +============ +The following people contributed to this release of Cyclus. A "*" by their +name indicates a first time contributor. Names follow alphabetically, + +* Robert Carlsen +* Robert Flanagan +* Matthew Gidden +* Ryan Hodge* +* Katy Huff +* Jenny Littell* +* Meghan McGarry +* Baptiste Mouginot* +* Arrielle Opotowsky +* Anthony Scopatz +* Steve Skutnik* +* Paul Wilson + diff --git a/_sources/python/actions.rst.txt b/_sources/python/actions.rst.txt new file mode 100755 index 000000000..d92baa5ac --- /dev/null +++ b/_sources/python/actions.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_actions: + +******************************************************************************** +Asynchronous Actions (``cyclus.actions``) +******************************************************************************** + +.. automodule:: cyclus.actions + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/agents.rst.txt b/_sources/python/agents.rst.txt new file mode 100755 index 000000000..9b7bfc371 --- /dev/null +++ b/_sources/python/agents.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_agents: + +******************************************************************************** +Agent Interface - Region, Institution, and Facility (``cyclus.agents``) +******************************************************************************** + +.. automodule:: cyclus.agents + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/cycpp.rst.txt b/_sources/python/cycpp.rst.txt new file mode 100755 index 000000000..1bf5766f5 --- /dev/null +++ b/_sources/python/cycpp.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_cycpp: + +******************************************************************************** +Cyclus Preprocessor (``cyclus.cycpp``) +******************************************************************************** + +.. automodule:: cyclus.cycpp + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/events.rst.txt b/_sources/python/events.rst.txt new file mode 100755 index 000000000..51425b003 --- /dev/null +++ b/_sources/python/events.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_events: + +******************************************************************************** +Event Loop (``cyclus.events``) +******************************************************************************** + +.. automodule:: cyclus.events + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/gentypesystem.rst.txt b/_sources/python/gentypesystem.rst.txt new file mode 100755 index 000000000..60232786f --- /dev/null +++ b/_sources/python/gentypesystem.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_gentypesystem: + +******************************************************************************** +Type System Code Generator (``cyclus.gentypesystem``) +******************************************************************************** + +.. automodule:: cyclus.gentypesystem + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/index.rst.txt b/_sources/python/index.rst.txt new file mode 100755 index 000000000..76fb2e3c4 --- /dev/null +++ b/_sources/python/index.rst.txt @@ -0,0 +1,63 @@ +.. summary Python Documentation for |Cyclus| + +|Cyclus| Python Interface +========================= +This covers the Python bindings for |Cyclus| and related utilities. + +High-level Python Interface +--------------------------- + +.. toctree:: + :maxdepth: 1 + + agents + simstate + pyagents + + +Low-level Python Wrappers +------------------------- + +.. toctree:: + :maxdepth: 1 + + typesystem + lib + main + nucname + + +Cyclus Server Interface +----------------------- + +.. toctree:: + :maxdepth: 1 + + server + actions + webapp + + +Python & C++ Interop Modules +---------------------------- + +.. toctree:: + :glob: + :maxdepth: 1 + + events + memback + + +Helpers & Utilities +---------------------------- + +.. toctree:: + :glob: + :maxdepth: 1 + + cycpp + gentypesystem + jsoncpp + lazyasd + system diff --git a/_sources/python/jsoncpp.rst.txt b/_sources/python/jsoncpp.rst.txt new file mode 100755 index 000000000..a66bd3b47 --- /dev/null +++ b/_sources/python/jsoncpp.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_jsoncpp: + +******************************************************************************** +JSON C++ (``cyclus.jsoncpp``) +******************************************************************************** + +.. automodule:: cyclus.jsoncpp + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/lazyasd.rst.txt b/_sources/python/lazyasd.rst.txt new file mode 100755 index 000000000..99e2ae40d --- /dev/null +++ b/_sources/python/lazyasd.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_lazyasd: + +******************************************************************************** +Lazy and Self-destructive Python Tools (``cyclus.lazyasd``) +******************************************************************************** + +.. automodule:: cyclus.lazyasd + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/lib.rst.txt b/_sources/python/lib.rst.txt new file mode 100755 index 000000000..1f5f68f07 --- /dev/null +++ b/_sources/python/lib.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_lib: + +******************************************************************************** +Cyclus Library Bindings (``cyclus.lib``) +******************************************************************************** + +.. automodule:: cyclus.lib + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/main.rst.txt b/_sources/python/main.rst.txt new file mode 100755 index 000000000..6a61300c3 --- /dev/null +++ b/_sources/python/main.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_main: + +******************************************************************************** +Main Command Line Interface (``cyclus.main``) +******************************************************************************** + +.. automodule:: cyclus.main + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/memback.rst.txt b/_sources/python/memback.rst.txt new file mode 100755 index 000000000..76f065ff0 --- /dev/null +++ b/_sources/python/memback.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_memback: + +******************************************************************************** +In-memory Backend (``cyclus.memback``) +******************************************************************************** + +.. automodule:: cyclus.memback + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/nucname.rst.txt b/_sources/python/nucname.rst.txt new file mode 100755 index 000000000..279e22fa9 --- /dev/null +++ b/_sources/python/nucname.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_nucname: + +******************************************************************************** +Nuclide Naming Functions (``cyclus.nucname``) +******************************************************************************** + +.. automodule:: cyclus.nucname + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/pyagents.rst.txt b/_sources/python/pyagents.rst.txt new file mode 100755 index 000000000..c01236507 --- /dev/null +++ b/_sources/python/pyagents.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_pyagents: + +******************************************************************************** +Agent Archetypes implemented in Python (``cyclus.pyagents``) +******************************************************************************** + +.. automodule:: cyclus.pyagents + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/server.rst.txt b/_sources/python/server.rst.txt new file mode 100755 index 000000000..f8bf89345 --- /dev/null +++ b/_sources/python/server.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_server: + +******************************************************************************** +Cyclus Server (``cyclus.server``) +******************************************************************************** + +.. automodule:: cyclus.server + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/simstate.rst.txt b/_sources/python/simstate.rst.txt new file mode 100755 index 000000000..7b753e83f --- /dev/null +++ b/_sources/python/simstate.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_simstate: + +******************************************************************************** +Simulation State (``cyclus.simstate``) +******************************************************************************** + +.. automodule:: cyclus.simstate + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/system.rst.txt b/_sources/python/system.rst.txt new file mode 100755 index 000000000..546ecb041 --- /dev/null +++ b/_sources/python/system.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_system: + +******************************************************************************** +System and Platform Specific Tools (``cyclus.system``) +******************************************************************************** + +.. automodule:: cyclus.system + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/typesystem.rst.txt b/_sources/python/typesystem.rst.txt new file mode 100755 index 000000000..be920376a --- /dev/null +++ b/_sources/python/typesystem.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_typesystem: + +******************************************************************************** +Cyclus Type System (``cyclus.typesystem``) +******************************************************************************** + +.. automodule:: cyclus.typesystem + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/python/webapp.rst.txt b/_sources/python/webapp.rst.txt new file mode 100755 index 000000000..55fdd396d --- /dev/null +++ b/_sources/python/webapp.rst.txt @@ -0,0 +1,11 @@ +.. _cyclus_pyapi_webapp: + +******************************************************************************** +Client Web Application (``cyclus.webapp``) +******************************************************************************** + +.. automodule:: cyclus.webapp + :members: + :undoc-members: + :inherited-members: + diff --git a/_sources/user/CYCAMORE_DEPS.rst.txt b/_sources/user/CYCAMORE_DEPS.rst.txt new file mode 100755 index 000000000..a66baaa1c --- /dev/null +++ b/_sources/user/CYCAMORE_DEPS.rst.txt @@ -0,0 +1,133 @@ +############################################## +Installing Cycamore Dependencies from Binaries +############################################## + +To see user and developer documentation for this code, please visit +the `Cyclus Homepage`_. + +This method describes two methods for installing Cycamore's only dependency, +the Cyclus Core, from binary distributions. If you would like to install it +from source code, please see the `Cyclus Core repository +`_. + +.. contents:: Table of Contents + :depth: 2 + +************ +Dependencies +************ + +==================== ================== +Package Minimum Version +==================== ================== +`Cyclus` 1.4 +==================== ================== + + +*********************** +Installing Dependencies +*********************** + +The Cyclus Core supports two binary installation options: + +.. website_include_binary_start + +#. `Conda`_ (Linux and Mac OSX) +#. `Debian package manager`_ (Linux only) + + +**Conda** is a cross-platform, user-space package manager aimed at simplifying +the installation of open source software. The Cyclus project uses Conda to +distribute pre-built Cyclus and Cycamore binaries. + +The **Debian package manager** simplifies the installation of open-source +software. It contains all of the files required to use specific software, as +well as variety of relevant information: maintainer, description, version, +dependencies (other software or libraries required to use it). The Cyclus +team provides pre-built Cyclus and Cycamore Debian packages to simplify +installation for the user. These packages are available for LTS Ubuntu version +14.04 and 16.04 (though they may also work on other Linux systems). + +.. website_include_binary_end + +.. website_include_conda_start + +~~~~~~~~~~~~~~~~~~~~~ +Conda +~~~~~~~~~~~~~~~~~~~~~ + + +1. If you don't have Conda, start by installing the Python 3.x version of + Anaconda_ (or miniconda_ for a more lightweight choice) to prepare it for + Cyclus. + +.. website_include_conda_end + +2. Once you have Conda installed, installing Cyclus straightforward. + + .. code-block:: bash + + $ conda install -c conda-forge cyclus + + +.. website_include_deb_start + +~~~~~~~~~~~~~~~~~~~~~~ +Debian Package Manager +~~~~~~~~~~~~~~~~~~~~~~ + + +This installation procedure assumes that you are using Ubuntu (LTS) 14.04 or +16.04. This method has only been tested on those Ubuntu versions. This +installation procedure also assumes that you have root access to you computer. + +#. Install Cyclus dependencies: + + .. code-block:: bash + + $ sudo apt-get install libtcmalloc-minimal4 libboost-filesystem-dev libboost-program-options-dev libboost-serialization-dev libhdf5-dev libxml++2.6-dev coinor-libcbc-dev + + WARNING: This dependency list is ONLY correct for the debian binary + installation, additional dependencies are required to install from source. + If you need/want more information about dependency installation please read the + `dependency installation documentation`_. + +#. Download the lastest version Cyclus Core Debian installation package: + + .. list-table:: + + * - Ubuntu 14.04 + - `without Python + `_ + - `with Python 2.7 + `_ + - + + * - Ubuntu 16.04 + - `without Python + `_ + - `with Python 2.7 + `_ + - `with Python 3.5 + `_ + + You can download previous/different version `here + `_. + + + +#. Install the package by running: + + .. code-block:: bash + + $ sudo dpkg -i cyclus_latest.deb + +.. website_include_deb_end + +.. _`Cyclus Homepage`: http://fuelcycle.org/ +.. _`Cyclus User Guide`: http://fuelcycle.org/user/index.html +.. _`Cyclus repo`: https://github.com/cyclus/cyclus +.. _`Cycamore Repo`: https://github.com/cyclus/cycamore +.. _Anaconda: https://www.continuum.io/downloads +.. _miniconda: http://conda.pydata.org/miniconda.html +.. _`dependency installation documentation`: https://github.com/cyclus/cyclus/blob/develop/DEPENDENCIES.rst diff --git a/_sources/user/CYCAMORE_INSTALL.rst.txt b/_sources/user/CYCAMORE_INSTALL.rst.txt new file mode 100755 index 000000000..21538fe62 --- /dev/null +++ b/_sources/user/CYCAMORE_INSTALL.rst.txt @@ -0,0 +1,196 @@ +########################### +Cycamore Installation Guide +########################### + +Cycamore uses the CMake cross-platform build-generator. To +simplify the usage of cmake to build Cycamore from source, a python script is +provided with the source. + +.. contents:: Table of Contents + +************ +Dependencies +************ + +Cycamore's only dependency is the Cyclus Core. + +==================== ================== +Package Minimum Version +==================== ================== +`Cyclus` 1.4 +==================== ================== + +There are a number of ways to install the Cyclus core: + +- To install from source code, see the `Cyclus Core repository + `_ + +- To install from a binary distribution, see the instructions for + `Installing Cyclus from Binaries `_ + + +****************************** +Installation +****************************** +.. website_include_start + +Before going further with the installation procedure, be sure you have installed +`Cyclus `_. + + +Default Installation +------------------------ + +Run the install script: + +.. code-block:: bash + + python install.py + + +If you successfully followed the instructions above, then the Cycamore library +has been generated and placed in ``.local/`` in your home directory. + +.. website_include_end + +.. website_custom_start + +Custom Cycamore Installation +---------------------------- + +The installation using the install script can be customized using the following +flag: + +.. list-table:: + + * - `-h`, `--help` + - show this help message and exit + + * - `--build_dir BUILD_DIR` + - where to place the build directory + + * - `--uninstall` + - uninstall + + * - `--no-update` + - do not update the hash in version.cc + + * - `--clean-build` + - attempt to remove the build directory before building + + * - `-j THREADS`, `--threads THREADS` + - the number of threads to use in the make step + + * - `--prefix PREFIX` + - the relative path to the installation directory + + * - `--config-only` + - only configure the package, do not build or install + + * - `--build-only` + - only build the package, do not install + + * - `--test` + - run tests after building + + * - `--allow-milps` + - Allows mixed integer linear programs by default + + * - `--dont-allow-milps` + - Don't Allows mixed integer linear programs by default + + * - `--deps-root DEPS_ROOT`, `--deps_root DEPS_ROOT` + - the path to the directory containing all dependencies + + * - `--coin-root COIN_ROOT`, `--coin_root COIN_ROOT` + - the relative path to the Coin-OR libraries directory + + * - `--boost_root BOOST_ROOT` + - the relative path to the Boost libraries directory + + * - `--hdf5_root HDF5_ROOT` + - the path to the HDF5 libraries directory + + * - `--cyclus-root CYCLUS_ROOT`, `--cyclus_root CYCLUS_ROOT` + - the relative path to Cyclus installation directory + + * - `--cmake_prefix_path CMAKE_PREFIX_PATH` + - the cmake prefix path for use with FIND_PACKAGE, FIND_PATH, FIND_PROGRAM, or FIND_LIBRARY macros + + * - `--build-type BUILD_TYPE`, `--build_type BUILD_TYPE` + - the CMAKE_BUILD_TYPE + + * - `-D VAR` + - Set enviornment variable(s). + + +For example, if you have installed coin-Cbc from source or otherwise have it +installed in a non-standard location, you should make use of the coinRoot +installation flag. The otherwise identical process would look like: + +.. code-block:: bash + + .../cycamore$ python install.py --coin_root=path/to/coin + + +CMake Cycamore Installation +--------------------------- + +If you are ``CMake`` aficionado you can also install Cycamore without using the +install.py python script and use ``cmake`` directly, which should look like: + + +.. code-block:: bash + + mkdir bld + cd build + cmake .. -DCMAKE_INSTALL_PREFIX=~/.local/ + make + make install + +You can customize your cmake installation using the proper cmake flag. All +cmake variables can be listed using: ``cmake -LAH``. The main variables used are: + +.. list-table:: + + * - ``COIN_ROOT_DIR`` + - set Coin-OT library directory + + * - ``BOOST_ROOT`` + - set Boost liraries directory + + * - ``HDF5_ROOT`` + - set HDF5 root directory + + * - ``HDF5_LIBRARIES`` + - set HDF5 libraries path + + * - ``HDF5_LIBRARY_DIRS`` + - set HDF5 library directory + + * - ``HDF5_INCLUDE_DIRS`` + - set HDF5 include directory + +All variables can be set using ``-DMY_VARIABLE=MY_VARIABLES_VALUE``. + +.. website_custom_end + +****************************** +Running Tests +****************************** + +Installing Cycamore will also install a test driver (i.e., an executable of all of +our tests). We strongly recommend after a fresh install of Cycamore, or after +any modification on the source code, to rerun those tests in order to insure the +proper functioning of Cycamore. You can run the tests yourself via: + +.. code-block:: bash + + $ cycamore_unit_tests + + +.. _`Cyclus Homepage`: http://fuelcycle.org/ +.. _`Cyclus User Guide`: http://fuelcycle.org/user/index.html +.. _`Cyclus repo`: https://github.com/cyclus/cyclus +.. _`Cycamore Repo`: https://github.com/cyclus/cycamore + diff --git a/_sources/user/CYCLUS_INSTALL.rst.txt b/_sources/user/CYCLUS_INSTALL.rst.txt new file mode 100755 index 000000000..99a51e3f0 --- /dev/null +++ b/_sources/user/CYCLUS_INSTALL.rst.txt @@ -0,0 +1,211 @@ +######################### +Cyclus Installation Guide +######################### + +Cyclus uses the ``CMake`` cross-platform build-generator. To +simplify the usage of cmake to build Cyclus from source, a python script is +provided with the source. + +.. contents:: Table of Contents + +************ +Dependencies +************ + +A full list of the Cyclus package dependencies is shown below: + +==================== ================== +Package Minimum Version +==================== ================== +``CMake`` 2.8 +``boost`` 1.46.1 +``libxml2`` 2 +``libxml++`` 2.36 +``python`` 2.7 or 3.3+ +``sqlite3`` 3.7.10 +``HDF5`` 1.8.4 +``Coin-Cbc`` 2.5 +==================== ================== + +************ +Installation +************ +.. website_include_start + +Before going further with the installation procedure be sure you have installed +all the required dependencies listed above. We have provided detailed +instructions for :doc:`installing dependencies `.for the major supported +systems. + + +Default Installation +-------------------- + +Run the install script: + +.. code-block:: bash + + python install.py + +If you successfully followed the instruction above, the cyclus binary has been +generated and placed in the ``~/.local/`` in your home directory. +You need to add ``~/.local/bin`` to the front of your ``$PATH``: + +.. code-block:: bash + + echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc + source ~/.bashrc + +On MacOSX you also need to add ~/.local/lib/pythonX.Y/site-packages to your +``$PYTHONPATH``: + +.. code-block:: bash + + echo "export PYTHONPATH=\"\$HOME/.local/lib/python`python -c 'import sys; \ + print(".".join(map(str, sys.version_info[:2])))'`/site-packages:\$PYTHONPATH\"" >> ~/.bashrc + source ~/.bashrc + +.. website_include_end + +.. website_custom_start + +Custom Cyclus Installation +-------------------------- + +The installation using the install script can be customized using the following +flags: + +.. list-table:: + + * - ``-h, --help`` + - show the help message and exit + + * - ``--build_dir BUILD_DIR`` + - where to place the build directory + + * - ``--uninstall`` + - uninstall + + * - ``--no-update`` + - do not update the hash in version.cc + + * - ``--clean-build`` + - attempt to remove the build directory before building + + * - ``-j THREADS, --threads`` + - THREADS the number of threads to use in the make step + + * - ``--prefix PREFIX`` + - the relative path to the installation directory + + * - ``--config-only`` + - only configure the package, do not build or install + + * - ``--build-only`` + - only build the package, do not install + + * - ``--test`` + - run tests after building + + * - ``--coin_root COIN_ROOT`` + - the relative path to the Coin-OR libraries directory + + * - ``--boost_root BOOST_ROOT`` + - the relative path to the Boost libraries directory + + * - ``--hdf5_root HDF5_ROOT`` + - the path to the HDF5 libraries directory + + * - ``--cmake_prefix_path CMAKE_PREFIX_PATH`` + - the cmake prefix path for use with FIND_PACKAGE, FIND_PATH, FIND_PROGRAM, or FIND_LIBRARY macros + + * - ``--build_type BUILD_TYPE`` + - change the CMAKE_BUILD_TYPE + + * - ``-D VAR`` + - set environment variable(s). + + +For example, if you have installed coin-Cbc from source or otherwise have it +installed in a non-standard location, you should make use of the ``coin_root`` +installation flag. The otherwise identical process would look like: + +.. code-block:: bash + + .../cyclus$ python install.py --coin_root=path/to/coin + + +CMake Cyclus Installation +------------------------- + +If you are ``CMake`` aficionado you can also install Cyclus without using the +``install.py`` python script and use ``cmake`` directly, which should look like: + + +.. code-block:: bash + + mkdir build + cd build + cmake .. -DCMAKE_INSTALL_PREFIX=~/.local/ + make + make install + +As usual you can customize your cmake installation using the proper cmake flag. +All cmake variables can be listed using: ``cmake -LAH``. +The main variables used are: + +.. list-table:: + + * - ``COIN_ROOT_DIR`` + - set Coin-OT library directory + + * - ``BOOST_ROOT`` + - set Boost libraries directory + + * - ``HDF5_ROOT`` + - set HDF5 root directory + + * - ``HDF5_LIBRARIES`` + - set HDF5 libraries path + + * - ``HDF5_LIBRARY_DIRS`` + - set HDF5 library directory + + * - ``HDF5_INCLUDE_DIRS`` + - set HDF5 include directory + +All variables can be set using ``-DMY_VARIABLE=MY_VARIABLES_VALUE``. + +.. website_custom_end + +Note on Building Cyclus with Conda +---------------------------------- + +If your python libraries are installed using Conda, install cyclus +dependencies through conda-forge. + +.. code-block:: bash + + conda config --add channels conda-forge + conda install cyclus-build-deps + + +************* +Running Tests +************* + +Installing Cyclus will also install a test driver (i.e., an executable of all of +our tests). We strongly recommend after a fresh install of Cyclus, or after +any modification on the source code, to rerun those tests in order to insure the +proper functioning of Cyclus. You can run the tests yourself via: + +.. code-block:: bash + + $ cyclus_unit_tests + + +.. _`Cyclus Homepage`: http://fuelcycle.org/ +.. _`Cyclus User Guide`: http://fuelcycle.org/user/index.html +.. _`Cyclus repo`: https://github.com/cyclus/cyclus +.. _`Cycamore Repo`: https://github.com/cyclus/cycamore +.. _`for installing those dependencies for the major supported systems`: DEPENDENCIES.rst diff --git a/_sources/user/DEPENDENCIES.rst.txt b/_sources/user/DEPENDENCIES.rst.txt new file mode 100755 index 000000000..c50ab64c3 --- /dev/null +++ b/_sources/user/DEPENDENCIES.rst.txt @@ -0,0 +1,298 @@ +########### +Cyclus Core +########### + +The core of the Cyclus nuclear fuel cycle simulator from the +University of Wisconsin - Madison is intended to be a simulation +framework upon which to develop innovative fuel cycle simulations. + +To see user and developer documentation for this code, please visit +the `Cyclus Homepage`_. + +.. contents:: Table of Contents + :depth: 2 + +************ +Dependencies +************ + +.. website_include_start + +In order to facilitate future compatibility with multiple platforms, +Cyclus is built using ``CMake``. A full list of the Cyclus package +dependencies is shown below: + +==================== ================== +Package Minimum Version +==================== ================== +``CMake`` 2.8 +``boost`` 1.46.1 +``libxml2`` 2 +``libxml++`` 2.36 +``python`` 2.7 or 3.3+ +``sqlite3`` 3.7.10 +``HDF5`` 1.8.4 +``Coin-Cbc`` 2.5 +==================== ================== + +.. website_include_end + +On some platforms, such as Ubuntu 16.04, the following are also necessary: + +==================== ================== +Package Minimum Version +==================== ================== +``g++`` 4.8.2 +``libblas-dev`` 1.2 +``liblapack-dev`` 3.5.0 +==================== ================== + + +And a few optional dependencies: + +==================== ================== +Package Minimum Version +==================== ================== +doxygen (for docs) 1.7.6.1 +tcmalloc (for speed) any +Cython >=0.25 and <0.27 +Python (dev version) 2.7 or 3.3+ +Jinja2 any +NumPy 1.9+ +Pandas any +==================== ================== + +*Note that the Debian/Ubuntu package ``libtcmalloc`` is NOT discovered correctly +by our build system. Instead use ``libgoogle-perftools-dev``.* + +*Also note that the development version of Python, Jinja2, NumPy, and Pandas are +only needed if Cython is installed.* + +*********************** +Installing Dependencies +*********************** + +Cyclus dependencies can either be installed manually or using an operating system's package +manager. + +Installing Dependencies (Linux and Unix) +---------------------------------------- + +This guide assumes that the user has root access (to issue ``sudo`` commands) and +access to a package manager or has some other suitable method of automatically +installing established libraries. This process was tested using a fresh install +of Ubuntu versions 16.04, using ``apt-get`` as the package +manager (scroll down further for Mac OSX instructions). + +The command to install a dependency takes the form of: + +.. code-block:: bash + + sudo apt-get install package + +where "package" is replaced by the correct package name. The minimal list of +required library package names is: + +#. make +#. cmake +#. libboost-all-dev (see note below) +#. libxml2-dev +#. libxml++2.6-dev +#. libsqlite3-dev +#. libhdf5-serial-dev +#. libbz2-dev +#. coinor-libcbc-dev +#. coinor-libcoinutils-dev +#. coinor-libosi-dev +#. coinor-libclp-dev +#. coinor-libcgl-dev + +and (optionally): + +#. doxygen +#. g++ +#. libblas-dev +#. liblapack-dev +#. libgoogle-perftools-dev +#. python-dev or python3-dev +#. python-tables or python3-tables +#. python-pandas or python3-pandas +#. python-numpy or python3-numpy +#. python-nose or python3-nose +#. python-jinja2 or python3-jinja2 +#. cython or cython3 (see note below) + +For example, in order to install libxml++ (and libxml2) on your system, type: + +.. code-block:: bash + + sudo apt-get install libxml++2.6-dev + +If you'd prefer to copy/paste, the following line will install all **required** +*Cyclus* dependencies: + +.. code-block:: bash + + sudo apt-get install -y cmake make libboost-all-dev libxml2-dev libxml++2.6-dev \ + libsqlite3-dev libhdf5-serial-dev libbz2-dev coinor-libcbc-dev coinor-libcoinutils-dev \ + coinor-libosi-dev coinor-libclp-dev coinor-libcgl-dev + +And to install all *Cyclus* dependencies (**required and optional**): + +- if using python 2.x: + +.. code-block:: bash + + sudo apt-get install -y cmake make libboost-all-dev libxml2-dev libxml++2.6-dev \ + libsqlite3-dev libhdf5-serial-dev libbz2-dev coinor-libcbc-dev coinor-libcoinutils-dev \ + coinor-libosi-dev coinor-libclp-dev coinor-libcgl-dev libblas-dev liblapack-dev g++ \ + libgoogle-perftools-dev python-dev python-tables python-pandas python-numpy python-nose \ + python-jinja2 cython + +- if using python 3.x: + +.. code-block:: bash + + sudo apt-get install -y cmake make libboost-all-dev libxml2-dev libxml++2.6-dev \ + libsqlite3-dev libhdf5-serial-dev libbz2-dev coinor-libcbc-dev coinor-libcoinutils-dev \ + coinor-libosi-dev coinor-libclp-dev coinor-libcgl-dev libblas-dev liblapack-dev g++ \ + libgoogle-perftools-dev python3-dev python3-tables python3-pandas python3-numpy python3-nose \ + python3-jinja2 cython3 + +To determine which version of Python is already installed on your computer, run: + +.. code-block:: bash + + python -V + + +Despite having installed python3, Ubuntu installations may still point at python2.7 by default. So Python -V can return a version of python that is not preferred. In that case the python version can be changed system-wide with the update-alternatives command. + +First, you can list alternatives with the following command: + + .. code-block:: bash + + update-alternatives --list python + +Ubuntu may not list any alternatives. To make Ubuntu aware of python 2.7 and python 3.5, use: + + .. code-block:: bash + + sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1 + sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 2 + +From now on, to switch between different versions, use: + + .. code-block:: bash + + sudo update-alternatives --config python + +Even if you only have a single python installation, you may have to use update-alternatives to point python at the correct version to avoid build errors. + +Check your current python version with the following command: + + .. code-block:: bash + + python --version + +Then make Ubuntu aware of your current python version. Run the following command, using the python version you just checked. The following command uses version python3.8 as an example and will fail if you do not replace 3.8 with your own version number. + + .. code-block:: bash + + sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 2 + + +Cython Note +^^^^^^^^^^^ +If you get an error related to an old Cython version, then this may be +because the Debian stable version of Cython is 0.23.4. However, +Cyclus requires 0.25.0+. To install the latest cython version, please +visit the `Cython Documentation`_. + +Boost Note +^^^^^^^^^^ + +The ``libboost-all-dev`` used above will install the entire Boost library, which +is not strictly needed. We currently depend on a small subset of the Boost +libraries: + +#. libboost-program-options-dev +#. libboost-system-dev +#. libboost-filesystem-dev + +However, it is possible (likely) that additional Boost libraries will be used +because they are an industry standard. Accordingly, we suggest simply installing +``libboost-all-dev`` to limit any headaches due to possible dependency additions +in the future. + +Installing Dependencies (Mac OSX) +--------------------------------- + +Cyclus archetype development is not fully supported on Mac. Nonetheless, +because there are some use cases which require installation from source, we have +compiled a list of instructions that should be successful. Use a Mac platform +at your own risk; we strongly recommend Linux as a primary development environment. + +This guide assumes that the user has root access (to issue ``sudo`` commands) and +access to a package manager or has some other suitable method of automatically +installing established libraries. This process was tested using a fresh install +of 10.11.6 (El Capitan) using ``macports`` as the package +manager. Macports installs packages in ``/opt/local``. If installing to a +different location, (i.e. ``/usr/local``) change paths in the following +instructions accordingly. If you use ``homebrew``, try the following instructions +with brew commands in place of the port commands. + +The command to install a dependency takes the form of: + +.. code-block:: bash + + sudo port install package + +where "package" is replaced by the correct package name. The minimal list of +required library package names is: + +#. cmake +#. boost +#. hdf5 +#. libxml2 +#. libxmlxx2 +#. sqlite3 +#. doxygen +#. glibmm + +Then install Coin-Cbc from source. They can be downloaded to any directory on +your computer: + +**Coin-Cbc**: Download and build using the svn command in the terminal: + +.. code-block:: bash + + svn co https://projects.coin-or.org/svn/Cbc/stable/2.8 Coin-Cbc + cd Coin-Cbc/ + mkdir build + cd build/ + ../configure --prefix=/opt/local + make + sudo make install + + +Finally, update your path and the following environment variables in your +``~/.profile`` (or ``~/.bashrc`` ) file: + +.. code-block:: bash + + export DYLD_FALLBACK_LIBRARY_PATH=/opt/local/lib:/opt/local:$DYLD_FALLBACK_LIBRARY_PATH + + export CMAKE_MODULE_PATH=/opt/local/include:$CMAKE_MODULE_PATH + export CMAKE_PREFIX_PATH=/opt/local:$CMAKE_PREFIX_PATH + + # add to PATH: + export PATH=${HDF5_DIR}:/opt/local/bin:${HOME}/.local/bin:$PATH + + +.. _`Cython Documentation`: http://cython.readthedocs.io/en/latest/src/quickstart/install.html +.. _`Cyclus Homepage`: http://fuelcycle.org/ +.. _`Cyclus User Guide`: http://fuelcycle.org/user/index.html +.. _`Cyclus repo`: https://github.com/cyclus/cyclus +.. _`Cycamore Repo`: https://github.com/cyclus/cycamore + diff --git a/_sources/user/analysis_usecases.rst.txt b/_sources/user/analysis_usecases.rst.txt new file mode 100755 index 000000000..ad523ae5a --- /dev/null +++ b/_sources/user/analysis_usecases.rst.txt @@ -0,0 +1,217 @@ +.. summary Discussing Standard Usage of |Cyclus| Output Transaction Data + +Use Cases for |Cyclus| Data Analysis +==================================== + +This section will attempt to document a number of primary data exploration use +cases. For an overview of the information recorded in a +|cyclus| simulation database, check out :doc:`dbdoc`. The two most common +modes are explorations of the material flows and the facility histories. + +Material flow explorations +-------------------------- + +Many material flow explorations would begin by visualizing the +time-dependent material flow between a set of sending facilities and a +set of receiving facilities. The minimum information needed to +generate such a visualization is the population of the two sets of +facilities, and detailed discussion on how to populate these sets is +given below. Once these sets are defined, the material flow +information can be summed over all the possible transaction pathways +at each time step to generate a single time series of data. The +following discussion will identify ways to restrict/limit the +quantity of data represented in such a time series visualization based +primarily on filtering operations for different dimensions of the +material flow data. + +It is important to note that single visualizations may contain +multiple time series of data, with a variety of alternative +representations depending on the user's interests. The following +discussion will consider, in this order: + + 1. the resolution of the time domain, + 2. filtering operations to restrict the data included in a single time series, + 3. application of post-processing functions for alternative engineering responses, and + 4. comparative visualization of multiple time series. + +Time Domain Resolution and Representation +''''''''''''''''''''''''''''''''''''''''' + +Most simulations are expected to proceed with monthly time steps (this +is user-configurable), probably too fine for meaningful visualization. +The default resolution for such a visualization should be annual flows +of material, requiring a summation operation across non-overlapping +regions of the time domain. It is likely that a user may want to +interactively change the time domain resolution, possibly interested +in the aggregated solution over time frames that are even coarser than +annual. + +It is also likely that users may want to switch between visualizations +of the instantaneous material flow rate within a given step of the +time resolution, and a cumulative material flow, integrating from the +beginning of the simulation to the current step of the time +resolution. + +In a related and common time series interaction, users may want to +zoom in and out of regions of the time domain to explore detailed +features. + +Filtering the Sets of Participating Facilities +'''''''''''''''''''''''''''''''''''''''''''''' + +Filtering operations will be always be necessary to define the set of +facilities that participate in a given material flow visualization. +The simplest form of such a filter is the selection of an entire +market, thereby selecting all the facilities that participate in that +market. Beyond that, some other obvious ways to create sets of +facilities for either the source or receiving set are: + + * choosing individual facilities from a list of existing facilities + * choosing individual institutions and therefore including all + facilities owned by that institution + * choosing individual regions and therefore including all facilities + operating in that region + * choosing a particular facility prototype and therefore including + all facilities based on that prototype + * choosing a particular facility module and therefore including all + facilities based on that module + +The ideal user interface will allow subsets of facilities to be added +and deleted from the ultimate set of facilities using the notions of +intersection, union, and negation. + +The ideal user interface will also allow a single time series to be +separated into multiple time series (possibly displayed in a +comparative fashion), by selecting a characteristic that defines +subsets of facilities. + +Filtering the Set of Nuclides +''''''''''''''''''''''''''''' + +It will also be important to restrict the material flow time series +data by filtering on the set of nuclides that are included in the +material flow data. There are a small number of standard ways to +define sets of nuclides: + +* include all nuclides +* choose individual chemical elements (e.g. uranium) and thereby + including all the nuclides of that element +* choose individual nuclides (e.g. U-235) +* choose from predefined meaningful sets of nuclides + (e.g. fission products, actinides, transuranics, fissile nuclides) + +As with the facility filtering capability, an ideal user interface +will allow subsets of nuclides to be added and deleted from the data +set using the notions of intersection, union, and negation. + +One example of a graph that shows the cumulative makeup of material in a +facility with respect to nuclide can be found in figure 5.11 of Kyle Oliver's +masters thesis, GeniusV2: Software Design and Mathematical Formulations For +Multi-Region Discrete Nuclear Fuel Cycle Simulation And Analysis. + +.. image:: cumulative_iso_dist.png + :width: 500pt + +Post-processing for Alternative Engineering Responses +''''''''''''''''''''''''''''''''''''''''''''''''''''' + +While the fundamental material flows are defined as the raw quantity +of each nuclide that is being transacted, there will be a growing set +of transformations that convert these number densities into other +interesting metrics/quantities including: + +* radiotoxicity +* decay heat +* waste volume +* others to-be-determined + +Users will want to apply these transformations, either changing the +metric shown in the primary visualization or cloning the primary +visualization but showing the other metric. + +Workflows for Comparitive Time Series Exploration +''''''''''''''''''''''''''''''''''''''''''''''''' + +Once a number of single time series are defined, it will be common to +visualize them on adjacent axes or within the same set of axes. One +possible workflow is as follows: + + 1. A user selects a market and is immediately shown the + instantaneous material flow through that market over the entire + simulation time domain, with a default time resolution. + 2. A user selects the originating region as a characteristic that + splits the single material flow time series into multiple time + series, each one now defined with a set of source facilities + from a different region. These time series are shown on the + same axes as a stacked area chart. The envelope of these now + differentiated time series is identical to the envelope of the + original time series. + 3. The user is then interested in a certain subset of the nuclides, + say the fissile nuclides, and requests that this same material + flow data be filtered to only include those nuclides. Each of + the material flow time series may (or may not) be reduced as the + set of nuclides it includes is altered. (Note that while it is + theoretically possible to differentiate by nuclide, it may + become difficult to visualize the many different time series + formed by differentiating by facility characteristic and nuclide + at the same time. In some cases, especially where a small + number of nuclide subsets are identified, this may be + practical.) + 4. At this point the user may seek a detailed isotopic breakdown of + one of the material flows, either as a time series shown on a + different axis pair, or as a single time step snapshot. In the + latter case, a variety of options are available to visualize + this, including bar charts, pie charts, tables of data, and + other more advanced representations. When examining a snapshot, + the linked visualization tool may update constantly as a user + swipes a bar across the time series visualization. + +At this point, an ideal user interface may allow users to "tear-off" +individual time series from the collection of time series into +different axes for further exploration/differentiation in modes +similar to above. + +(Quasi-)Spatial Representation of Material Flows +''''''''''''''''''''''''''''''''''''''''''''''''' + +Another interesting visualization of this time series data is as an +animated graph representation. Graph nodes would represent source and +receiving facilities with the connecting arcs somehow indicating the +magnitude of material flow (e.g. line thickness). The time domain +would be represented by animation. + +In some cases, the graphs of two different markets may be shown +together, indicating the connectedness of these graphs through +facilities that participate in both. Different commodities could be +represented by different colors, for example. + +Such a representation could also be coordinated with the more +traditional time series visualization, in which the graph serves as a +way to select which facilities will be included in the sets for +defining the material flow time series, either by selecting specific +nodes or by selecting specific arcs. + +At such a time that geospatial data (or an approximation/surrogate to +this data) is available, this graph visualization could be arranged to +represent the real geospatial locations of facilities. + +Commodity Capacity and Supply/Demand Exploration +------------------------------------------------- + +Another primary visualization is time series data for installed +capacity of a set of facilities. Most of the operations discussed +above will be of interest including: + +* time domain resolution and representation +* filtering across different dimensions (although not across a nuclide dimension) +* applying transformations +* comparative visualization + +By combining the information about the theoretical capacity with the +information about material transactions, the relationship between +supply and demand can be explored. (Note that the standardization of +input and output resource buffers within facilities means that +instantaneous transaction flow rates are not always representative of +instantaneous utilization of the available processing capacity. +Access to this information will require additional output records.) + diff --git a/_sources/user/cycamoreagents.rst.txt b/_sources/user/cycamoreagents.rst.txt new file mode 100755 index 000000000..e8105b073 --- /dev/null +++ b/_sources/user/cycamoreagents.rst.txt @@ -0,0 +1,30 @@ +.. _cycamore_archetypes: + +Cycamore Archetypes +==================== + +This is a collection of archetypes found in the ``cycamore`` module that comes with +cycamore itself. + +.. cyclus-agent:: :cycamore:Source + +.. cyclus-agent:: :cycamore:Sink + +.. cyclus-agent:: :cycamore:Enrichment + +.. cyclus-agent:: :cycamore:Reactor + +.. cyclus-agent:: :cycamore:Separations + +.. cyclus-agent:: :cycamore:FuelFab + +.. cyclus-agent:: :cycamore:Storage + +.. cyclus-agent:: :cycamore:Mixer + +.. cyclus-agent:: :cycamore:DeployInst + +.. cyclus-agent:: :cycamore:ManagerInst + +.. cyclus-agent:: :cycamore:GrowthRegion + :no-sep: diff --git a/_sources/user/cyclusagents.rst.txt b/_sources/user/cyclusagents.rst.txt new file mode 100755 index 000000000..71a8cb0b2 --- /dev/null +++ b/_sources/user/cyclusagents.rst.txt @@ -0,0 +1,22 @@ +.. _cyclus_archetypes: + +Cyclus Archetypes +=================== + +This is a collection of archetypes found in the ``agents`` module that comes with +|cyclus| itself. + +.. cyclus-agent:: :agents:Source + +.. cyclus-agent:: :agents:Sink + +.. cyclus-agent:: :agents:NullRegion + +.. cyclus-agent:: :agents:NullInst + +.. cyclus-agent:: :agents:KFacility + +.. cyclus-agent:: :agents:Predator + +.. cyclus-agent:: :agents:Prey + :no-sep: diff --git a/_sources/user/cymetric/api/brightlite_root_metrics.rst.txt b/_sources/user/cymetric/api/brightlite_root_metrics.rst.txt new file mode 100755 index 000000000..c7dc1a366 --- /dev/null +++ b/_sources/user/cymetric/api/brightlite_root_metrics.rst.txt @@ -0,0 +1,8 @@ +.. _cym_brightlite_root_metrics: + +==================================================================== +:mod:`cymetric.brightlite_root_metrics` - Bright-lite Root Metrics +==================================================================== + +.. automodule:: cymetric.brightlite_root_metrics + :members: diff --git a/_sources/user/cymetric/api/cycamore_root_metrics.rst.txt b/_sources/user/cymetric/api/cycamore_root_metrics.rst.txt new file mode 100755 index 000000000..51ca53b7d --- /dev/null +++ b/_sources/user/cymetric/api/cycamore_root_metrics.rst.txt @@ -0,0 +1,8 @@ +.. _cym_cycamore_root_metrics: + +============================================================= +:mod:`cymetric.cycamore_root_metrics` - Cycamore Root Metrics +============================================================= + +.. automodule:: cymetric.cycamore_root_metrics + :members: diff --git a/_sources/user/cymetric/api/evaluator.rst.txt b/_sources/user/cymetric/api/evaluator.rst.txt new file mode 100755 index 000000000..f9f30a5fc --- /dev/null +++ b/_sources/user/cymetric/api/evaluator.rst.txt @@ -0,0 +1,8 @@ +.. _cym_evaluator: + +=============================================== +:mod:`cymetric.evaluator` - Evaluators +=============================================== + +.. automodule:: cymetric.evaluator + :members: diff --git a/_sources/user/cymetric/api/execution.rst.txt b/_sources/user/cymetric/api/execution.rst.txt new file mode 100755 index 000000000..42042faf6 --- /dev/null +++ b/_sources/user/cymetric/api/execution.rst.txt @@ -0,0 +1,8 @@ +.. _cym_execution: + +=============================================== +:mod:`cymetric.execution` - Execution +=============================================== + +.. automodule:: cymetric.execution + :members: diff --git a/_sources/user/cymetric/api/fco_metrics.rst.txt b/_sources/user/cymetric/api/fco_metrics.rst.txt new file mode 100755 index 000000000..9ee3ad536 --- /dev/null +++ b/_sources/user/cymetric/api/fco_metrics.rst.txt @@ -0,0 +1,8 @@ +.. _cym_fco_metrics: + +======================================================= +:mod:`cymetric.fco_metrics` - Fuel Cycle Option Metrics +======================================================= + +.. automodule:: cymetric.fco_metrics + :members: diff --git a/_sources/user/cymetric/api/filters.rst.txt b/_sources/user/cymetric/api/filters.rst.txt new file mode 100755 index 000000000..1862b332b --- /dev/null +++ b/_sources/user/cymetric/api/filters.rst.txt @@ -0,0 +1,8 @@ +.. _cym_filters: + +=============================================== +:mod:`cymetric.filters` - Filters +=============================================== + +.. automodule:: cymetric.filters + :members: diff --git a/_sources/user/cymetric/api/graphs.rst.txt b/_sources/user/cymetric/api/graphs.rst.txt new file mode 100755 index 000000000..b3895d798 --- /dev/null +++ b/_sources/user/cymetric/api/graphs.rst.txt @@ -0,0 +1,8 @@ +.. _cym_graphs: + +=============================================== +:mod:`cymetric.graphs` - Graphs +=============================================== + +.. automodule:: cymetric.graphs + :members: diff --git a/_sources/user/cymetric/api/index.rst.txt b/_sources/user/cymetric/api/index.rst.txt new file mode 100755 index 000000000..e6bb62ee6 --- /dev/null +++ b/_sources/user/cymetric/api/index.rst.txt @@ -0,0 +1,43 @@ +Cymetric API +============ +The following modules make up the cymetric package. Note that most of the +important stuff you can get directly from ``cymetric`` without needing to import +the module. For example: + +.. code-block:: python + + from cymetric import metric + + +**Interface Modules:** + +.. toctree:: + :maxdepth: 1 + + schemas + evaluator + execution + filters + graphs + + +**Metrics Modules:** + +.. toctree:: + :maxdepth: 1 + + metrics + root_metrics + cycamore_root_metrics + brightlite_root_metrics + fco_metrics + + +**Helper Modules:** + +.. toctree:: + :maxdepth: 1 + + main + tools + timeseries diff --git a/_sources/user/cymetric/api/main.rst.txt b/_sources/user/cymetric/api/main.rst.txt new file mode 100755 index 000000000..4a1142b5a --- /dev/null +++ b/_sources/user/cymetric/api/main.rst.txt @@ -0,0 +1,8 @@ +.. _cym_main: + +=============================================== +:mod:`cymetric.main` - Command Line Interface +=============================================== + +.. automodule:: cymetric.main + :members: diff --git a/_sources/user/cymetric/api/metrics.rst.txt b/_sources/user/cymetric/api/metrics.rst.txt new file mode 100755 index 000000000..3237c0146 --- /dev/null +++ b/_sources/user/cymetric/api/metrics.rst.txt @@ -0,0 +1,8 @@ +.. _cym_metrics: + +=============================================== +:mod:`cymetric.metrics` - Metrics +=============================================== + +.. automodule:: cymetric.metrics + :members: diff --git a/_sources/user/cymetric/api/root_metrics.rst.txt b/_sources/user/cymetric/api/root_metrics.rst.txt new file mode 100755 index 000000000..2a4d7de91 --- /dev/null +++ b/_sources/user/cymetric/api/root_metrics.rst.txt @@ -0,0 +1,8 @@ +.. _cym_root_metrics: + +=============================================== +:mod:`cymetric.root_metrics` - Root Metrics +=============================================== + +.. automodule:: cymetric.root_metrics + :members: diff --git a/_sources/user/cymetric/api/schemas.rst.txt b/_sources/user/cymetric/api/schemas.rst.txt new file mode 100755 index 000000000..67bbfcd5f --- /dev/null +++ b/_sources/user/cymetric/api/schemas.rst.txt @@ -0,0 +1,8 @@ +.. _cym_schemas: + +=============================================== +:mod:`cymetric.schemas` - Schemas +=============================================== + +.. automodule:: cymetric.schemas + :members: diff --git a/_sources/user/cymetric/api/timeseries.rst.txt b/_sources/user/cymetric/api/timeseries.rst.txt new file mode 100755 index 000000000..333281257 --- /dev/null +++ b/_sources/user/cymetric/api/timeseries.rst.txt @@ -0,0 +1,8 @@ +.. _cym_timeseries: + +=============================================== +:mod:`cymetric.timeseries` - Timeseries +=============================================== + +.. automodule:: cymetric.timeseries + :members: diff --git a/_sources/user/cymetric/api/tools.rst.txt b/_sources/user/cymetric/api/tools.rst.txt new file mode 100755 index 000000000..216012e96 --- /dev/null +++ b/_sources/user/cymetric/api/tools.rst.txt @@ -0,0 +1,8 @@ +.. _cym_tools: + +=============================================== +:mod:`cymetric.tools` - Tools +=============================================== + +.. automodule:: cymetric.tools + :members: diff --git a/_sources/user/cymetric/index.rst.txt b/_sources/user/cymetric/index.rst.txt new file mode 100755 index 000000000..ca11f5902 --- /dev/null +++ b/_sources/user/cymetric/index.rst.txt @@ -0,0 +1,18 @@ +Cymetric +========== +Cymetric (pronounced *symmetric*) is a general analysis library and tool for +interacting with Cyclus data. Its primary purpose is to compute and display +fuel cycle metrics while making those metrics easy to write. + +The cymetric project repository is located at http://github.com/cyclus/cymetric. + +Learn More +---------- + +.. toctree:: + :maxdepth: 1 + + tutorial_cli + tutorial_py + tutorial_metrics + api/index diff --git a/_sources/user/cymetric/tutorial_cli.rst.txt b/_sources/user/cymetric/tutorial_cli.rst.txt new file mode 100755 index 000000000..725ec1e9a --- /dev/null +++ b/_sources/user/cymetric/tutorial_cli.rst.txt @@ -0,0 +1,224 @@ +.. _cym_tutorial_cli: + +Cymetric Command Line Tutorial +============================== +This tutorial describes how to use cymetric from the command line. + +Cymetric is an extension of |cyclus|, so it is assumed that |cyclus| is already +installed on your system. (If not, please visit `Getting and Building Cyclus +from Source `_.) Cymetric +installation instructions are available on `GitHub +`_. + +Cymetric operates by reading data from a |cyclus| database, computing metrics, +and writing those metrics back to the database. This way, previously seen +metrics are stored for later retrieval. The dependencies between metrics are +automatically computed and evaluated. + +Without further ado, let's dive in! + +Command Line Usage +------------------ +Cymetric ships with a command line utility, just called ``cymetric``. +The command line tool is useful for quick feedback. It can show a list of +tables in a database or execute some code using a database, e.g., evaluating +a metric or quickly checking a plot. + +Since cymetric is wholly dependent on |cyclus| databases, you must supply a +database as an argument on the command line. This will look something like the +following: + +.. code-block:: bash + + $ cymetric database -flags + +We'll be using ``test.h5`` and ``test.sqlite`` as our example databases here. +The sections below explain the flags for use on the command line. + +.. warning:: + + Please note that cymetric may not work on the command line within its own directory. + +Table Listing: ``-l`` +~~~~~~~~~~~~~~~~~~~~~ +The first switch here, lowercase-L ``-l``, simply lists the tables in the +database. Note that this may list more tables in the database than are +strictly part of the |cyclus| interface, because of the need for |cyclus| to +store metadata. Don't be alarmed. Listing the current tables is easy: + +.. code-block:: bash + + $ cymetric test.h5 -l + AgentEntry + AgentStateAgent + AgentStateInventories + AgentState_agents_NullRegionInfo + ... + BlobKeys + BlobVals + BuildSchedule + Compositions + DecayMode + Finish + Info + InputFiles + MaterialInfo + NextIds + Prototypes + Recipes + ResCreators + Resources + Snapshots + StringKeys + StringVals + Transactions + XMLPPInfo + +Metrics that are generated will show up in this listing after they have been +computed. All of the core |cyclus| tables are denoted as root metrics, and they +are listed here too. To understand the core tables included in a |cyclus| +database, please review the page `Understanding the Database +`_. + +Code Execution: ``-e`` +~~~~~~~~~~~~~~~~~~~~~~~ +Cymetric allows you to execute arbitrary code on metrics from the command line +with the ``-e`` flag. The code that you pass in is pure Python. Every metric +and root |cyclus| table are assigned automatically to variable names that you +can use. Indexing the table variables will return the metric as a `pandas +`_ DataFrame. For example, to print the +``AgentEntry`` table, we would write ``AgentEntry[:]`` to get the table and +``print(AgentEntry[:])`` to display it after the ``-e`` flag: + +.. code-block:: bash + + $ cymetric test.h5 -e "print(AgentEntry[:])" + SimId AgentId Kind Spec Prototype ParentId Lifetime EnterTime + 0 db805939-c565-404a-9483-adfb3da8b6d2 11 Region :agents:NullRegion SingleRegion -1 -1 0 + 1 db805939-c565-404a-9483-adfb3da8b6d2 12 Inst :cycamore:DeployInst SingleInstitution 11 -1 0 + 2 db805939-c565-404a-9483-adfb3da8b6d2 13 Facility :cycamore:Source UOX_Source 12 -1 1 + 3 db805939-c565-404a-9483-adfb3da8b6d2 14 Facility :cycamore:Source MOX_Source 12 -1 1 + 4 db805939-c565-404a-9483-adfb3da8b6d2 15 Facility :cycamore:BatchReactor Reactor1 12 -1 1 + 5 db805939-c565-404a-9483-adfb3da8b6d2 16 Facility :cycamore:BatchReactor Reactor2 12 -1 2 + 6 db805939-c565-404a-9483-adfb3da8b6d2 17 Facility :cycamore:BatchReactor Reactor3 12 -1 3 + + [7 rows x 8 columns] + +Indexing a metric with an empty slice (``[:]``), none (``[None]``), or an ellipsis +(``[...]``) will return the full metric. However, you can also index by condition +filters on the column names. The column names of the metric are thus also available for +use. For example, let's just grab all of the facilities out of the entry table: + +.. code-block:: bash + + $ cymetric test.h5 -e "print(AgentEntry[Kind == 'Facility'])" + SimId AgentId Kind Spec Prototype ParentId Lifetime EnterTime + 0 db805939-c565-404a-9483-adfb3da8b6d2 13 Facility :cycamore:Source UOX_Source 12 -1 1 + 1 db805939-c565-404a-9483-adfb3da8b6d2 14 Facility :cycamore:Source MOX_Source 12 -1 1 + 2 db805939-c565-404a-9483-adfb3da8b6d2 15 Facility :cycamore:BatchReactor Reactor1 12 -1 1 + 3 db805939-c565-404a-9483-adfb3da8b6d2 16 Facility :cycamore:BatchReactor Reactor2 12 -1 2 + 4 db805939-c565-404a-9483-adfb3da8b6d2 17 Facility :cycamore:BatchReactor Reactor3 12 -1 3 + + [5 rows x 8 columns] + +Separate the conditions by commas (``,``) to apply multiple filters at the same +time: + +.. code-block:: bash + + $ cymetric test.h5 -e "print(AgentEntry[Kind == 'Facility', AgentId > 14])" + SimId AgentId Kind Spec Prototype ParentId Lifetime EnterTime + 0 db805939-c565-404a-9483-adfb3da8b6d2 15 Facility :cycamore:BatchReactor Reactor1 12 -1 1 + 1 db805939-c565-404a-9483-adfb3da8b6d2 16 Facility :cycamore:BatchReactor Reactor2 12 -1 2 + 2 db805939-c565-404a-9483-adfb3da8b6d2 17 Facility :cycamore:BatchReactor Reactor3 12 -1 3 + + [3 rows x 8 columns] + +Because code execution is just pure Python, we can do *anything* that we would be +able to do in Python. Suppose that we have a ``Materials`` metric with a ``Mass`` +column. We can compute this metric, pull the column out, multiply it by 42, +save the result to a variable, and then print this variable all via the following. + +.. code-block:: bash + + $ cymetric test.h5 -e "mass = Materials[:]['Mass'] * 42; print(mass)" + 0 0.000000 + 1 0.000000 + 2 0.000000 + 3 0.000000 + 4 0.000000 + 5 0.000000 + 6 0.000000 + 7 0.000000 + 8 0.000000 + 9 0.000000 + 10 4.790314 + 11 0.007370 + 12 0.066327 + 13 0.368486 + 14 33.064222 + ... + 462 0.493771 + 463 0.313213 + 464 0.350812 + 465 0.228541 + 466 40.917474 + 467 0.030567 + 468 0.011288 + 469 0.238031 + 470 0.092571 + 471 0.081648 + 472 0.034441 + 473 0.002762 + 474 0.008074 + 475 0.000965 + 476 0.002827 + Name: Mass, Length: 477, dtype: float64 + +As a convenience, the following Python modules are available in the execution context +under standard aliases. This prevents you from having to import them manually yourself. + +===================== ============== +Module Alias +===================== ============== +``cymetric`` ``cym`` +``numpy`` ``np`` +``pandas`` ``pd`` +``uuid`` ``uuid`` +``matplotlib`` ``matplotlib`` +``matplotlib.pyplot`` ``plt`` +===================== ============== + +This let's you do neat things such as plot the metrics right from the command line. +For example, + +.. code-block:: bash + + $ cymetric test.h5 -e "Materials[ResourceId == 15].plot(x='NucId', y='Mass', kind='bar'); plt.show()" + +Will pop up with the following figure: + +.. image:: ../../astatic/tut_nucid_mass.png + +To write or not to write: ``--write`` and ``--no-write`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Cymetric automatically writes an evaluated metric to the database. There are +some scenarios when you may not want this to happen. For example, you might +want your script to do many metric calculations and save the results elsewhere; +in this case, writing to the database is unneccessary. While writing is the +default functionality when you use the ``-e`` flag, the lack of writing +can be accomplished with the ``--no-write`` flag. In the example below, the +table will not be written to the database: + +.. code-block:: bash + + $ cymetric test.h5 --no-write -e "Materials[:]" + +Since cymetric looks up an already evaluated metric in the database, +overwriting an existing table with a new one might be desired. This is where +the ``--write`` flag is useful: + +.. code-block:: bash + + $ cymetric test.h5 --write -e "Materials[:]" + diff --git a/_sources/user/cymetric/tutorial_metrics.rst.txt b/_sources/user/cymetric/tutorial_metrics.rst.txt new file mode 100755 index 000000000..1c89b8fa8 --- /dev/null +++ b/_sources/user/cymetric/tutorial_metrics.rst.txt @@ -0,0 +1,128 @@ +.. _cym_tutorial_metrics: + +Writing Your Own Metrics Tutorial +================================== +This tutorial will describe how to write your own metrics for your own +custom analyses. This takes place within Python, so you may want to check +out the Cymetric Python tutorial first. + +Writing Metrics +------------------ +Naturally, you do not want to be limited to the metrics that come predefined +by cymetric! You have +your own data and your own analysis that you want to perform. It is easy to +write metrics and fully hook into the cymetric tools. + +A metric is a function that accepts a pandas Series, returns a +pandas DataFrame, and is decorated by the ``@metric()`` decorator found in +cymetric. The general format is as follows: + +.. code-block:: python + + import cyclus.typesystem as ts + import cymetic as cym + + dependencies = [ + ('Table1', ('Col1', 'Col2'), 'Value1'), + ('Table2', ('Col3',), 'Value2') + ] + + schema = [('Id', ts.INT), ('MetricValue', ts.DOUBLE)] + + @cym.metric(name='MyMetric', depends=dependencies, schema=schema) + def my_metric(series): + one = series[0] + two = series[1] + #calculations and pandas manipulations go here + return dataframe + +This metric may be evaulated with: + +.. code-block:: python + + cym.eval('MyMetric', db) + + +In the above, the ``@metric()`` decorator takes three arguments. The first is +the ``name`` of the metric (e.g., ``'MyMetric'``). Note that this can be +distinct from the function name. + +The second is ``depends``, which represents the metric dependencies. This is a +list of 3-tuples that represents which ``series`` to pull out of the database +and pass into the metric function (e.g., ``my_metric()``). The entries in the +dependency list have three components. The first element is the table name as a +string (e.g., ``'Table1'``). The second element is a tuple of column names that +become the index of the series (e.g., ``('Col1', 'Col2')``). Finally, the last +element is the column of the table that becomes the values of the series (e.g., +``'Value1'``). A metric may have as many dependencies as required. Circular +dependencies are not allowed! + +Lastly, the ``@metric()`` decorator takes a ``schema`` argument. The schema is +defined by a list of 2-tuples. The first entry is the column name and the +second is the |cyclus| database type. This represents the structure of the +metric table on disk and in |cyclus|. Thus, it is highly tied to the |cyclus| +`type system `_. +The DataFrame that is returned should have column names that match +the schema provided. It is generally a good idea to include a ``SimId`` column. + +For a more concrete example, if you wanted to square the mass of materials as a +metric, you could write a ``MaterialsSquared`` metric. + +.. code-block:: python + + import pandas as pd + + import cyclus.typesystem as ts + import cymetic as cym + + deps = [('Materials', ('SimId', 'ResourceId', 'NucId'), 'Mass')] + + schema = [('SimId', ts.UUID), ('ResourceId', ts.INT), + ('NucId', ts.INT), ('MassSquared', ts.DOUBLE)] + + @cym.metric(name='MaterialsSquared', depends=deps, schema=schema) + def mats_sqrd(series): + mats = series[0].reset_index() + mats = pd.DataFrame(data={'SimId': mats.SimId, + 'ResourceId': mats.ResourceId, + 'NucId': mats.NucId, + 'MassSquared': mats.Mass.apply(lambda x: x**2)}, + columns=['SimId', 'ResourceId', 'NucId', 'MassSquared']) + mats.name = 'MaterialsSquared' + return mats + +This metric may be evaulated with: + +.. code-block:: python + + cym.eval('MaterialsSquared', db) + +Note that to write this metric, no knowledge of the database or any filters is +assumed. Cymetric handles all of these details for you! + +If the pandas functionality seems mysterious to you, it may be beneficial to +review a quick tutorial, `10 Minutes to pandas +`_. + +Making Metrics from Custom Database Tables +------------------------------------------ +The above shows how easy it is to incorporate metrics that are computed via +cymetric. Moreover, |cyclus| databases can be comprised of both `default tables +`_ and `custom tables +`_. Cymetric also helps you +bring in data that might come as a custom table in a |cyclus| database. All you +need to do is use the ``root_metric()`` function somewhere. This simply accepts +the name of the table. For example, + +.. code-block:: python + + my_root_table = cym.root_metric(name='MyRootTable') + + +This metric may be evaulated with: + +.. code-block:: python + + cym.eval('MyRootTable', db) + +And that is all! diff --git a/_sources/user/cymetric/tutorial_py.rst.txt b/_sources/user/cymetric/tutorial_py.rst.txt new file mode 100755 index 000000000..0f70f01b3 --- /dev/null +++ b/_sources/user/cymetric/tutorial_py.rst.txt @@ -0,0 +1,93 @@ +.. _cym_tutorial_py: + +Cymetric Python Interface Tutorial +==================================` +This tutorial will describe how to use cymetric from Python. + +Cymetric is an extension of |cyclus|, so it is assumed that |cyclus| is already +installed on your system. (If not, please visit `Getting and Building Cyclus +from Source `_.) Cymetric +installation instructions are available on `GitHub +`_. + +Cymetric operates by reading data from a |cyclus| database, computing metrics, +and writing those metrics back to the database. This way, previously seen +metrics are stored for later retrieval. The dependencies between metrics are +automatically computed and evaluated. + +Without further ado, let's dive in! + + +Python Interface +------------------ +While quick feedback is useful, it is more likely that cymetric will be of use +in a script. Therefore, this section details how to employ Python to interact +with cymetric. In addition to writing scripts to compute metrics and produce +figures, this is essential for the development of new metrics. + +Typically, it is recommended that you alias ``cymetric`` as ``cym``, because +all of the important functionality lives here. To start, use the ``dbopen()`` +function to open up a database: + +.. code-block:: python + + import cymetric as cym + + db = cym.dbopen('test.sqlite') + +Evaluating Metrics +~~~~~~~~~~~~~~~~~~~~~~~ +The main purpose of cymetric is to evaluate metrics. The easiest way to do this +is via the ``eval()`` function. This accepts a metric name and a database and +returns a pandas DataFrame: + +.. code-block:: python + + frame = cym.eval('Materials', db) + +You may also optionally supply a list of 3-tuples representing the conditions to +filter the metric on. + +.. code-block:: python + + filtered_frame = cym.eval('Materials', db, conds=[('NucId', '==', 922350000)]) + +Multiple filters can be applied at once. These filters are ``&&``-ed with each other. + +.. code-block:: python + + filtered_frame = cym.eval('AgentEntry', db, conds=[('Kind', '==','Facility'), ('AgentId', '>', 14)]) + +However, if you are evaluating many metrics, this method will be +computationally inefficient. Calling ``eval()`` creates a new ``Evaluator`` +object each time a metric is evaluated. Since each ``Evaluator`` object reads +the database individually, this means ``eval()`` reads the database each time +it is called. Alternatively, there is a way to ensure the database only gets +read once by accessing the ``eval()`` functionality directly within an +``Evaluator`` object. You can create an ``Evaluator`` instance with a single +database and call ``eval()`` from within it. For example, + +.. code-block:: python + + evaler = cym.Evaluator(db) + frame1 = evaler.eval('Materials') + frame2 = evaler.eval('AgentEntry', conds=[('Kind', '==', 'Facility')]) + +And you can run with the data from there! We recommend learning `pandas +`_ to get the most out of your analysis from this +point. + +Executing Code +~~~~~~~~~~~~~~~~~~~~~~~ +Sometimes, you just have a code snippet as a string like you might run from the +command line, even though you are in Python. The ``exec_code()`` function gives +you easy access to the exact same capabilities that you have on the command line. +This function accepts the code string and the database: + +.. code-block:: python + + cym.exec_code("print(AgentEntry[:])", db) + +For more exciting capabilities, please explore the `examples directory +`_ in the cymetric repository or ask us +questions on the |cyclus| users mailing list. diff --git a/_sources/user/dbdoc.rst.txt b/_sources/user/dbdoc.rst.txt new file mode 100755 index 000000000..68ecbd920 --- /dev/null +++ b/_sources/user/dbdoc.rst.txt @@ -0,0 +1,462 @@ +Understanding the Database +============================ + +A single database can store multiple simulations' results. In order for this to +work, every table in the database has a SimId column that identifies which +simulation each row belongs to. In order to robustly analyze the data, all +processing should be simulation-ID-aware. Because simulation ID's are UUID's, +databases can be safely merged without conflicts. + +|Cyclus| supports multiple database formats. While each format is allowed to +store information in its own way, the overall table structure in databases is +the same. |Cyclus| ships supporting two database formats: + +* `SQLite `_ (".sqlite" extension) - |cyclus|' + default database format. Some useful viewers: + + - `Sqliteman `_ (windows and linux) + - `SQLite Browser `_ (windows, mac, and linux) + - `SQLite Manager `_ + Firefox Add-on (windows, mac, and linux) + +* `HDF5 `_ (".h5" extension). Some useful + viewers: + + - `HDFView `_ + (windows, mac, and linux) + - `ViTables `_ (linux only) + +Below are a few sections that describe the data tables found in the database. + +Table Descriptions +++++++++++++++++++ + +Resources Table +--------------- + +Because resources are tracked as immutable objects, every time a resource is +changed in the simulation (split, combined, transmuted, decayed, etc.), it +gets a new entry in the Resources table. The heritage of resources is also +tracked. If two resources are combined into a new one, then the new resource +entry will have the ID's of the other two in its "Parent1" and "Parent2" +columns. The Resources table effectively encodes a heritage tree for all +resources. It is interesting to note that the Resources table does not encode +any information about where a resource is. This information can be inferred +by corroborating Resource ID's with the ``ResCreators`` and ``Transactions`` +tables. + +* **SimId** (uuid) + +* **ResourceId** (int): The unique ID for this resource entry. See + :ref:`resource-ids` for more details. + +* **ObjId** (int): A resources object id (obj_id) as it existed during the + simulation simulation. See :ref:`resource-ids` for more details. + +* **Type** (string): One of "Material" or "Product". These two types of + resources have different internal state stored in different tables. If the + type is "Product", then the internal state can be found in the ``Products`` + table. If it is Material, then it is in the ``Compositions`` table. + +* **TimeCreated** (int): The simulation time step at which this resource state + came into existence. + +* **Quantity** (double): Amount of the resource in "kg" for Material + resources. Amount in terms of the specific quality for Product resources. + +* **Units** (string): "kg" for all Material resources, "NONE" for Product + resources. + +* **QualId** (int): Used to identify the corresponding internal-state + entry (or entries) in the ``Products`` or ``Compositions`` table depending + on the resource's type. + +* **Parent1** (int): If a resource was newly created, this is zero. If this + resource came from another via is transmutation, combining, or splitting, + or decay then this is the parent ResourceId + +* **Parent2** (int): If a resource was newly created, this is zero. If this + resource came from another via transmutation, decay, or splitting, Parent2 + is also zero. If the resource came from another via combining this is the + second parent's ResourceId. + +.. _explicit-inv-table: + +ExplicitInventory Table +----------------------- + +This is an optional table that can be activated by setting +``true`` in the ```` section +of the input file. By default, it is disabled and will not be created in the +database. Note there is a significant runtime performance penalty for +activating this table. This table provides the material inventory of each +agent at each time step subdivided by internal buffers (e.g. +``cyclus::toolkit::ResBuf``). There is one row for each agent on each time +step for each sub-buffer for each nuclide. + +* **SimId** (uuid) + +* **AgentId** (int): ID of the agent holding the inventory + +* **Time** (int): Time Step this inventory was in the given agent. + +* **InventoryName** (string): Name of the internal sub inventory/buffer of + this material. This (usually) corresponds to the archetype state variable + names for each ResBuf. + +* **NucId** (int): Nuclide identifier in ``zzzaaammmm`` form. + +* **Quantity** (double): Amount in kg of the given nuclide in the specified + sub-inventory for the given agent on the given time step. + +.. _explicit-inv-compact-table: + +ExplicitInventoryCompact Table +------------------------------- + +This is an optional table that can be activated by setting +``true`` in the +```` section of the input file. By default, it is disabled and will +not be created in the database. Note there is a significant runtime +performance penalty for activating this table. This table provides the +material inventory of each agent at each time step subdivided by internal +buffers (e.g. ``cyclus::toolkit::ResBuf``). There is one row for each agent +on each time step for each sub-buffer. The fractional composition for each +nuclide are stored as a single value in the native format of the Cyclus +backend used to create the database. The sqlite backend, for example, stores +this data as an xml string from a boost-serialized ``std::map`` +(i.e. NucId-frac pairs). + +* **SimId** (uuid) + +* **AgentId** (int): ID of the agent holding the inventory + +* **Time** (int): time step this inventory was in the given agent. + +* **InventoryName** (string): Name of the internal sub inventory/buffer of + this material. This (usually) corresponds to the archetype state variable + names for each ResBuf. + +* **Quantity** (double): Amount in kg of the given material composition in + this sub-inventory for the given agent on the given time step. + +* **Composition** (int): Cyclus backend-specific format for a ``std::map`` object. + +Compositions Table +------------------ + +A composition consists of one or more nuclides and their respective mass +fractions. Each nuclide for a composition gets its own row and have the same +QualId. + +* **SimId** (uuid) + +* **QualId** (int): Key to associate this composition with one or more + entries in the ``Resources`` table. + +* **NucId** (int): Nuclide identifier in ``zzzaaammmm`` form. + +* **MassFrac** (double): Mass fraction for the nuclide in this composition. + +Recipes Table +------------- + +* **SimId** (uuid) + +* **Recipe** (string): Recipe name as given in the input file. + +* **QualId** (int): Key to identify the Composition for this recipe in the + ``Compositions`` table. + +Products Table +-------------- + +* **SimId** (uuid) + +* **QualId** (int): Key to associate this quality with one or more entries in + the ``Resources`` table. + +* **Quality** (string): Describes a product's quality (e.g. "bananas", "KWh", + etc.) + +ResCreators Table +----------------- + +Every time an agent creates a new resource from scratch, that event is +recorded in this table. + +* **SimId** (uuid) + +* **ResourceId** (int): ID of a resource that was created at some point in the + simulation. + +* **AgentId** (int): ID of the agent that created the resource associated with + the ResourceId. + +AgentEntry Table +---------------- + +Each agent that enters and participates in a simulation gets a row in this +table. + +* **SimId** (uuid) + +* **AgentId** (int): Every agent in a simulation gets its own, unique ID. + +* **Kind** (string): One of "Region", "Inst", "Facility", or "Agent". + +* **Spec** (string): The single-string of the :doc:`agent specification `. + +* **Prototype** (string): The prototype name, as defined in the input file, + that was used to create this agent. + +* **ParentId** (int): The AgentId of this agent's parent - the agent that + built/created this agent. + +* **Lifetime** (int): Number of time steps an agent is designed to operate + over. ``-1`` indicates an infinite lifetime. Note that depending on how + agents use the lifetime parameter, this may be entirely unrelated to how long + agents were actually operating in the simulation. + +* **EnterTime** (int): The time step when the agent was built and entered the + simulation. + +AgentExit Table +--------------- + +Due to implementation details in the |cyclus| kernel, this table is separate +from the ``AgentEntry`` table. If this table doesn't exist, then no agents +were decommissioned in the simulation. + +* **SimId** (uuid) + +* **AgentId** (int): Key to the AgentId on the ``AgentEntry`` table. + +* **ExitTime** (int): The time step when the agent was decommissioned and + exited the simulation. + +.. _agent-version-table: + +AgentVersion Table +------------------ + +This lists the version of each agent/archetype used in the simulation. Due to +backwards compatibility, this is in its own, new table instead of the +AgentEntry table. There is one entry in this table for each archetype used in +each simulation. + +* **SimId** (uuid) + +* **Spec** (string): Archetype spec - same as the Spec field in the AgentEntry + table. + +* **Version** (string): The version string provided by the archetype. + +Transactions Table +------------------ + +Every single resource transfer between two agents is recorded as a row +in this table. + +* **SimId** (uuid) + +* **TransactionId** (int): A unique identifier for this resource transfer. + +* **SenderId** (int): AgentId for the sending agent. + +* **ReceiverId** (int): AgentId for the receiving agent. + +* **ResourceId** (int): Key to the entry in the Resources table that describes + the transferred resource. + +* **Commodity** (string): The commodity under which this transfer was + negotiated. + +* **Time** (int): The time step at which the resource transfer took place. + +Info Table +---------- + +Each simulation gets a single row in this table describing global simulation +parameters and |cyclus| dependency version information. + +* **SimId** (uuid) + +* **Handle** (string): A custom user-specified value from the input file + allowing for convenient identification of simulations in a database (because + the simulation uuid's are not very memorable by mere mortals). + +* **InitialYear** (int): The year in which time step zero occurs. + +* **InitialMonth** (int): The month that time step zero represents. + +* **Duration** (int): The length of the simulation in time steps. Note that + it is possible a simulation to terminate early before running its entire + duration (see the ``Finish`` table section). + +* **ParentSimId** (uuid): The SimId for this simulation's parent. Zero if this + simulation has no parent. + +* **ParentType** (string): One of: + + - "init" for simulations that are not based on any other simulation. + + - "restart" for simulations that were restarted another simulation's + snapshot. + + - "branch" for simulations that were started from a perturbed state of + another simulation's snapshot. + +* **BranchTime** (int): Zero if this was not a restarted or branched + simulation. Otherwise, the time step of the ParentSim at which the + restart/branch occurred. + +* **CyclusVersion** (string): Version of |cyclus| used to run this simulation. + +* **CyclusVersionDescribe** (string): Detailed |cyclus| version info (with commit hash) + +* **SqliteVersion** (string) + +* **Hdf5Version** (string) + +* **BoostVersion** (string) + +* **LibXML2Version** (string) + +* **CoinCBCVersion** (string) + + +InfoExplicitInv Table +---------------------- +Each simulation gets one row in this table. + +* **SimId** (uuid) + +* **RecordInventory** (bool): True (or 1) if the ExplicitInventory table was + or should be activated for the simulation. + +* **RecordInventoryCompact** (bool): True (or 1) if the + ExplicitInventoryCompact table was or should be activated for the + simulation. + + +Finish Table +------------ + +Each simulation gets one row/entry in this table. + +* **SimId** (uuid) + +* **EarlyTerm** (bool): True (or 1) if the simulation terminated early and did + not complete normally. False (or 0) otherwise. + +* **EndTime** (int): The time step at which the simulation ended. + + +InputFiles Table +---------------- + +* **SimId** (uuid) + +* **Data** (blob): A dump of the entire input file used for this simulation. + + +DecomSchedule Table +------------------- + +When agents are scheduled to be decommissioned in the simulation, the details +are recorded in this table. Note that this table contains an entry for each +scheduling regardless of whether or not it actually occurred; if a simulation +ended before time reached the scheduled time, the agent would not have been +decommissioned. + +* **SimId** (uuid) + +* **AgentId** (int): ID of the agent that is/was to be decommissioned. + +* **SchedTime** (int): The time step on which this decommissioning event was + created. + +* **DecomTime** (int): The time step on which the agent was (or would have + been) decommissioned. + +BuildSchedule Table +------------------- + +When agents are scheduled to be built in the simulation, the details are +recorded in this table. Note that this table contains an entry for each +scheduling regardless of whether or not it actually occurred; if a simulation +ended before time reached the scheduled time, the agent would not have been +built. + +* **SimId** (uuid) + +* **ParentId** (piintd): The Id of the agent that will become this new agent's + parent. + +* **Prototype** (string): The name of the agent prototype that will be used to + generate the new agent. This corresponds to the prototypes defined in an + input files. + +* **SchedTime** (int): The time step on which this build event was created. + +* **BuildTime** (int): The time step on which the agent was (or would have + been) built and deployed into the simulation. + +Snapshots Table +--------------- + +Every snapshot made during the simulation gets an entry in this table. All +times in this table are candidates for simulation restart/branching. + +* **SimId** (uuid) + +* **Time** (int): The time step a snapshot was taken for this simulation. + +Debugging +--------- + +If |Cyclus| was run in debugging mode then the database will then contain +the following two extra tables: + +* **DebugRequests**: record of every resource request made in the simulation. + + - ``SimId``: simulation UUID + - ``Time``: time step of the request + - ``ReqId``, simulation-unique identifier for this request + - ``RequesterID``: ID of the requesting agent + - ``Commodity``: the commodity of the request + - ``Preference``: agent's preference for this particular request + - ``Exclusive``: true (non-zero) if this request is all-or-nothing (integral) + - ``ResType``: resource type (e.g. "Material", "Product") + - ``Quantity``: amount of the request + - ``ResUnits``: units of the request (e.g. kg) + +* **DebugBids**: record of every resource bid made in the simulation. + + - ``SimId``: simulation UUID + - ``ReqId``: simulation-unique identifier for the bid's request + - ``BidderId``: ID of the the bidding agent + - ``BidQuantity``: amount of thd bid + - ``Exclusive``: true(non-zero) if this request is all-or-nothing (integral) + + +Post Processing ++++++++++++++++ + +We are currently working on developing a post-process step for the database +that creates a few new tables to assist data analysis and visualization. +These tables are not set in stone and their schemas are subject to change. +Below is a summary of them. + +.. Inventories Table +.. ------------------- + +.. TODO: describe post-processed inventories table + +.. Agents Table +.. ------------------- + +.. TODO: describe post-processed agents table + diff --git a/_sources/user/find_agents.rst.txt b/_sources/user/find_agents.rst.txt new file mode 100755 index 000000000..19b580230 --- /dev/null +++ b/_sources/user/find_agents.rst.txt @@ -0,0 +1,108 @@ +Archetype Identification and Discovery +======================================= +|Cyclus| :term:`archetypes ` are uniquely identified by a 3-part +specification that includes: + +* a slash separated path, +* a library name, and +* an archetype name. + +The agents available for running simulations depend on which agent libraries +have been installed on your system. |Cyclus| ships with a default library +named "agents" containing a few simple archetypes + +* Source +* Sink +* NullInst +* KFacility +* ...and others... + +All archetypes used in a simulation must be defined in the ``archetypes`` +section in the input file: + +.. code-block:: xml + + + ... + + + + + agents + KFacility + myfac1 + + + + ... + + ... + + + ... + + + +.. code-block:: json + + {"simulation": { + "archetypes": { + "spec": { + "path": "", + "lib": "agents", + "name": "KFacility", + "alias": "myfac1" }, + "spec": { + } + } + } + } + +The ``path`` tag can be omitted if it is empty (as in the case of |Cyclus|' +default agents library). If the ``lib`` tag is omitted, it defaults to the +value of the ``name`` tag. The ``alias`` tag may also be omitted, in which case +it defaults to the value in the ``name`` tag. If multiple archetypes have the +same name, then aliases *must* be specified - no two aliases may have the same +value (including defaults). The values of the aliases are referenced later in +the input file when defining facility prototypes, institutions, and regions. + +Archetype specifications also have a single-string form where the three parts +are separated by colons. This form is used in places such as in the database +and on the command line. For example, to print out the schema for an agent +archetype on the command line (note the starting colon indicating an empty +path): + +.. code-block:: bash + + cyclus --agent-schema :agents:KFacility + +For more details, you can read :doc:`/cep/cep21` + +Cyclus Path +----------- +When running a simulation, |Cyclus| searches your system for the archetypes +specified in the input file. In addition to searching a few default install +directories, it is possible to manually specify other directories for |Cyclus| +to search by adding them as colon-separated entries to the CYCLUS_PATH +environment variable. For example: + +.. code-block:: bash + + export CYCLUS_PATH=my/agent/lib/dir:/my/other/agent/dir + +Directories specified in your ``CYCLUS_PATH`` are searched *before* |Cyclus|' +default search directories. ``CYCLUS_PATH`` directories mark the *starting +points* for archetype specifications. This meaning that the path portion of an +agent specification is appended to the CYCLUS_PATH directories. For example +using the above defined ``CYCLUS_PATH``, |Cyclus| would search for:: + + my/path:myagentlib:MyAgent + +In the following directories in order: + +* my/agent/lib/dir/agent/path/ +* /my/other/agent/dir/agent/path/ +* [default-locations]/agent/path/ + +For more details, you can read :doc:`/cep/cep21` + diff --git a/_sources/user/index.rst.txt b/_sources/user/index.rst.txt new file mode 100755 index 000000000..8080cf339 --- /dev/null +++ b/_sources/user/index.rst.txt @@ -0,0 +1,177 @@ +.. summary Documentation for |Cyclus| Users + +|Cyclus| User Guide +=================== + +This guide covers the basics of installation, creating simulation input files, +and running them. If you haven't already, you should take a look at +:ref:`Fundamental Concepts in Cyclus `. + + +Installing |Cyclus| +-------------------- + +.. toctree:: + :maxdepth: 1 + + install + + +Writing Input Files +--------------------- + +.. toctree:: + :glob: + :maxdepth: 1 + + writing_input + find_agents + sim_schema + +.. + input_specs/overview/* + input_specs/region/* + input_specs/inst/* + input_specs/facility/* + input_specs/examples/* + +Running Simulations +-------------------- + +.. toctree:: + :maxdepth: 1 + + running_sims + server + +You can also run a simulation right now from the comfort of your browser :ref:`here +`! + +Tutorials +---------- + +* :doc:`ANS 2015 Annual Meeting Tutorial ` - using the user interface and cloud simulation environment + +.. toctree:: + :hidden: + + tutorial/index + +Archetypes +---------- + +Collections of :term:`archetypes ` are provided by various teams +and individuals for use by |Cyclus| users. + +Cycamore +~~~~~~~~ + The Cycamore library of archetypes is provided by the |Cyclus| development + team as a basic set of archetypes for modeling simple nuclear fuel cycles. + +.. toctree:: + :maxdepth: 2 + + cycamoreagents + +Cyclus Testing +~~~~~~~~~~~~~~ + The |Cyclus| kernel includes some archetype for testing the basic + functionality of the kenel. + +.. toctree:: + :maxdepth: 2 + + cyclusagents + + +Third-Party Archetypes +~~~~~~~~~~~~~~~~~~~~~~ + +Several useful archetypes have been developed by the community outside the +purview of the Cyclus project itself and are listed here. These archetypes do +not necessarily adhere to the same standards of quality (documentation, +testint, etc.) as Cyclus and Cycamore code - users are responsible for +evaluating their suitability. + +**Bright-lite** + The University of Texas - Austin is developing a set of archetypes for fuel + fabrication and reactors that rely on interpolation tables for more + accurate prediction of fresh fuel compositions and estimates of fuel + depletion. + +**Cyborg** + The University of Tennessee is working with Oak Ridge National Lab to + develop archetypes that will use ORIGEN calculations to improve the + estimate of nuclear fuel properties. + +**Mbmore Archetypes** (https://github.com/mbmcgarry/mbmore) + Facility archetypes that utilize a random number generator to create + non-deterministic behaviors. General methods controlling the behavior + (including random number generation and Gaussian distributions) are defined in + the `behavior functions + `_. + +- `:mbmore:RandomEnrich + `_ + Based on cycamore enrichment facility, it can have variable tails assay, + and bidding behavior can be set to occur at Every X timestep or at Random + timesteps. + +- `:mbmore:RandomSink + `_ + Based on cycamore sink facility, it can accept multiple recipes, has + modifiable material preference, material request behavior can be set, + trading can be suppressed before a specified timestep, material requests + can occur at Every X timestep or at Random timesteps, and quantity + requested can be varied using a Gaussian distribution function. + +**rwc Archetypes** (https://github.com/rwcarlsen/rwc-archetypes) + This is a collection of miscellaneous archetypes made by Robert Carlsen to + support optimization work and other side projects: + +- `:rwc:LookInst + `_ + This archetype allows the user to specify an arbitrary power capacity + time series that the institution will automatically deploy power + generating facilities (of multiple types) to match. It uses a look-ahead + mechanism to see if its chosen deployments were not "good" and adjusts + its deployment decisions accordingly. This archetype currently requires + rwcarlsen/cyclus#restart branch of Cyclus to work. + +- `:rwc:FleetReactor + `_ + This reactor models an entire reactor fleet as a single, homogenous + unit. Like the Cycamore reactor, it just uses static, user-specified + compositions for fresh and spent fuel. Refueling is incremental - + occuring every time step. It is approximately a continuous flow fleet + model much like the way system-dynamics simulators represent facilities. + It "pretends" to be many reactors to the Cyclus kernel - allowing other + agents to deploy/decommission single-reactor units, but these + single-reactors just adjust the size/capacity of the homogenous fleet. + +- `:rwc:PatternSink + `_ + Pattern sink is identical to the Cycamore sink facility except it has an + additional parameter that allows the user to control the frequency with + which the facility requests material - i.e. the user can tell the + facility to only request material every Nth time step. + +- `:rwc:Storage + `_ + This facility is very similar to the Cycamore storage facility, and was + originally created before Cycamore's existed. It has slightly more + careful handling of discrete material objects (e.g. not ever splitting + them) and is a bit more sophisticated with respect to resource exchange + for offering/bidding its inventory. It would be good to use + implementation details from this archetype to improve the Cycamore + storage archetype. + +Visualization & Analysis +-------------------------- + +.. toctree:: + :maxdepth: 2 + + cymetric/index + dbdoc + analysis_usecases diff --git a/_sources/user/input_specs/archetypes.rst.txt b/_sources/user/input_specs/archetypes.rst.txt new file mode 100755 index 000000000..3f186b1c6 --- /dev/null +++ b/_sources/user/input_specs/archetypes.rst.txt @@ -0,0 +1,102 @@ +``Archetypes`` - List of available agent archetypes (required once) +=================================================================== + +Every agent that participates in a |cyclus| simulation is based on a +:term:`prototype` that is formed by configuring an :term:`archetype`. The +``archetypes`` block defines the set of archetypes that are available to a +simulation, and provides specifications that uniquely identify each archetype. + +A single ``archetypes`` block is required, and contains one or more ``spec`` +blocks. Each ``spec`` block has these blocks in the following order: + +* ``path`` (optional) - a slash-separated path +* ``lib`` (optional) - a library name +* ``name`` (required) - a name +* ``alias`` (optional) - a alternative name for the archetype + +In addition to the unambiguous specification (as defined in +:doc:`../find_agents`) formed by the ``path``, ``lib``, and ``name``, the +``alias`` provides an alternative name by which to refer to the archetype +elsewhere in the file. If an alias is defined, it is the **only way** to +refer to that archetype in other locations. + +Example +++++++++ + +.. code-block:: xml + + + + my/custom/path + myAgentCollection + myFirstReactorAgent + ReactorAgent + + + simpleSource + + + simpleRegion + + + simpleInst + + + +This example introduces four different archetypes into the simulation to be +used elsewhere when defining agent prototypes. The first archetype is named +`myFirstReactorAgent`, found in a library file such as +`libmyAgentCollection.so` (on linux), in the filesystem path +`my/custom/path`. All references to this archetype will use the alias +`ReactorAgent`. The other archetypes are named `simpleSource`, +`simpleRegion`, and `simpleInst`, all of which are found in standard locations +defined in :doc:`../find_agents`. For example, `simpleSource` will be found +in a library file with a name such as `libsimpleSource.so`, in the standard +|Cyclus| archetype path. + +This is what the example above would look like if written in JSON. + +.. code-block:: json + + { + "archetypes": { + "spec": [ { + "path": "my/custom/path", + "lib": "myAgentCollection", + "alias": "ReactorAgent" }, + {"name": "simpleSource" }, + {"name": "simpleRegion" }, + {"name": "simpleInst" } + ] + }} + +And similarly, in Python: + +.. code-block:: python + + {"archetypes": {"spec": [ + {"path": "my/custom/path", "lib": "myAgentCollection", "alias": "ReactorAgent"}, + {"name": "simpleSource"}, + {"name": "simpleRegion"}, + {"name": "simpleInst" }, + ] + }} + +.. rst-class:: html-toggle + +Grammar Definition +++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + + + diff --git a/_sources/user/input_specs/commodity.rst.txt b/_sources/user/input_specs/commodity.rst.txt new file mode 100755 index 000000000..69bf85160 --- /dev/null +++ b/_sources/user/input_specs/commodity.rst.txt @@ -0,0 +1,78 @@ +``Commodity`` - Commodity Priority (optional, may appear multiple times) +========================================================================== + +In |Cyclus|, a commodity is used to define how agents can interact. +Commodities are simply used to define which resources a facility can request +and/or offer. The list of commodities in a problem is defined exclusively by +the commodities that are used in the definition of facility prototypes. + +The ``commodity`` input block is only used to indicate a non-default priority +for a particular commodity in the dynamic resource exchange solution. + +A ``commodity`` block has the following sections in the following order: + + * ``name`` (required once) - the unique name for this commodity + * ``solution_priority`` (required once) - a number that defines the relative + priority for resolution in the dynamic resource exchange (Default: -1) + + +Example ++++++++ + +**XML:** + +.. code-block:: xml + + + enriched_u + 5.5 + + + + waste + 4.5 + + + +**JSON:** + +.. code-block:: json + + {"commodity": [ + {"name": "enriched_u", "solution_priority": 5.5}, + {"name": "waste", "solution_priority": 4.5} + ] + } + + +**Python:** + +.. code-block:: python + + {"commodity": [ + {"name": "enriched_u", "solution_priority": 5.5}, + {"name": "waste", "solution_priority": 4.5}, + ], + } + + +In this example, while there may be many commodities used in the problem, two +of them are given explicit priorities. The ``enriched_u`` has the highest +priority followed by ``waste``. Note that these particular names do not imply +any specific composition of the commodity; this will be determined later by +the facilities that trade in these commodities. + + +.. rst-class:: html-toggle + +Grammar Definition ++++++++++++++++++++ + +.. code-block:: xml + + + + + + + diff --git a/_sources/user/input_specs/control.rst.txt b/_sources/user/input_specs/control.rst.txt new file mode 100755 index 000000000..0f650d088 --- /dev/null +++ b/_sources/user/input_specs/control.rst.txt @@ -0,0 +1,175 @@ +``Control`` - Simulation Control (required once) +================================================ + +Simulation control is the input portion relating to time, uses the ``control`` +tag, and has the following sections in any order: + + * duration (required once) - the time duration of the simulation (in months) + + * startmonth (required once) - the starting month (1 -> January, 12->December) + + * startyear (required once) - the starting year + + * simhandle (optional, once) - a user-defined identifier for this simulation + + * explicit_inventory (optional, once) - boolean specifying whether or not to + create the :ref:`ExplicitInventory ` table in the + database. Because this significantly impacts simulation performance, it + is deactivated by default. + + * explicit_inventory_compact (optional, once) - boolean specifying whether + or not to create the :ref:`ExplicitInventoryCompact + ` table in the database. Because this + significantly impacts simulation performance, it is deactivated by default. + + * dt (optional, once) - the duration of a single time step in seconds. If + omitted, a default value of 1/12 of a year is used (i.e. 2,629,846 + seconds). + + * decay (optional, once) - choose one of: + + - ``never``: turns decay completely off. + - ``manual``: decay is only computed if archetypes/agents explicilty decay + their own material objects. + - ``lazy``: decay is only computed whenever archetypes/agents "look" at a + composition. + + * solver (optional, once) - configure the DRE solver. + + - choose one of: + + - ``greedy``: use a greedy heuristic (not guaranteed optimal, but fast) + that orders trades based on the average preference of exchange groups + + - preconditioner (optional) - precondition greedy-solved graphs + + - choose one of: + + - ``greedy``: use an average-preference greedy preconditioner + + - ``coin-or``: use the COIN-OR CLP/CBC solver suite + + - timeout (optional): kill solutions after this time (in seconds) + - verbose (optional): print information about problems being solved + - mps (optional): write MPS files for each exchange + + - ``allow_exclusive_orders`` (optional) - exclusive orders should be + allowed, `True` by default. **NOTE** many Cycamore archetypes depend on + this option being `True` and will not work as expected if it is + `False`. This option can be turned to `False` to guarantee LP solves of + the DRE. + +Example ++++++++ + + +**XML:** + +.. code-block:: xml + + + 2007 + 11 + 1200 +
86400
+ lazy +
+ + +**JSON:** + +.. code-block:: json + + { + "control": { + "startyear": 2007, + "startmonth": 11, + "duration": 1200, + "dt": 86400, + "decay": "lazy" } + } + + +**Python:** + +.. code-block:: python + + {"control": { + "startyear": 2007, + "startmonth": 11, + "duration": 12 * 100, + "dt": 86400, + "decay": "lazy", + } + } + + +This example starts in November 2007, and runs for 100 years (1200 months). + + +.. rst-class:: html-toggle + +Grammar Definition +++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_sources/user/input_specs/facility.rst.txt b/_sources/user/input_specs/facility.rst.txt new file mode 100755 index 000000000..73e2af915 --- /dev/null +++ b/_sources/user/input_specs/facility.rst.txt @@ -0,0 +1,102 @@ +``Facility`` - Facility Prototypes (at least one required) +============================================================ + +Every agent that participates in a |cyclus| simulation represents either a +facility, an institution or a region. Each ``facility`` block defines a +single prototype for an agent that acts as a facility in the simulation. + +Each ``facility`` block has the follwoing sections in any order: + +* ``name`` (required once) - a name for the prototype +* ``lifetime`` (optional once) - a non-negative integer indicating the number + of time steps that an agent of this prototype will be active in the + simulation +* ``config`` (required once) - the archetype-specific configuration + + +Example ++++++++ +This example introduces two facility prototypes. The first has the name +`LongTermStorage`, and is configured from the :term:`archetype` with the name +(or alias) `Sink`. The contents of the ``Sink`` section are defined by the +author of the `Sink` archetype. The second has the name ``PBMR``, has a +lifetime of 720 time steps (60 years) and is based on the archetype with the +name (or alias) `RecipeReactor`. The contents of the ``RecipeReactor`` +section are defined by the author of the `RecipeReactor` archetype. + +**XML:** + +.. code-block:: xml + + + LongTermStorage + + + ... archetype-specific input for a `Sink` archetype + + + + + + PBMR + 720 + + + ... archetype-specific input for a `RecipeReactor` archetype + + + + +**JSON:** + +.. code-block:: json + + {"facility": [ + {"config": {"Sink": "(... archetype-specific input for a `Sink` archetype)"}, + "name": "LongTermStorage" + }, + {"config": { + "RecipeReactor": "(... archetype-specific input for a `RecipeReactor` archetype)"}, + "lifetime": 720, + "name": "PBMR" + } + ] + } + + +**Python:** + +.. code-block:: python + + {"facility": [ + {"config": {"Sink": "(... archetype-specific input for a `Sink` archetype)"}, + "name": "LongTermStorage", + }, + {"config": { + "RecipeReactor": "(... archetype-specific input for a `RecipeReactor` archetype)"}, + "lifetime": 720, + "name": "PBMR", + }, + ], + } + +.. rst-class:: html-toggle + +Grammar Definition +++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + @Facility_REFS@ + + + + diff --git a/_sources/user/input_specs/inst.rst.txt b/_sources/user/input_specs/inst.rst.txt new file mode 100755 index 000000000..1b5fd54f9 --- /dev/null +++ b/_sources/user/input_specs/inst.rst.txt @@ -0,0 +1,136 @@ +``Institution`` - Institution agents (at least one required in each ``Region``) +=============================================================================== + +Every agent that participates in a |cyclus| simulation represents either a +facility, an institution or a region. Each ``institution`` block defines an +agent that acts as an institution in the simulation. In contrast to the +``facility`` block that defines a :term:`prototype`, this block defines an +:term:`agent`. + +An ``institution`` block can only appear within a ``region`` block. + +Each ``institution`` block has the following sections in any order: + +* ``name`` (required once) - a name for the prototype +* ``lifetime`` (optional once) - a non-negative integer indicating the number + of time steps that this institution agent will be active in the simulation +* ``config`` (required once) - the archetype-specific configuration +* ``initialfacilitylist`` (optional, may appear multiple times) - a list of + facility agents operating at the beginning of the simulation + +Each ``initialfacilitylist`` block contains one or more ``entry`` blocks that +each contain the following sections, in the following order: + +* ``prototype`` - the name of a facility prototype defined elsewhere in the input file +* ``number`` - the number of such facilities that are operating at the beginning of the simulation + +Example ++++++++ +This example introduces two institution agents (the region section that +encloses them is not shown). The first institution has the name +`SingleInstitution`, and is configured from the :term:`archetype` with the +name (or alias) `NullInst`. The author of the ``NullInst`` archetype has +defined no archetype-specific data. This agent begins the simulation with two +facility agents, one based on the ``FacilityA`` prototype and another based on +the ``FacilityB`` prototype. The second institution has the name +`AnotherInstitution`, is also configured from the archetype with the name (or +alias) ``NullInst``. This institution has no initial facilities. + +**XML:** + +.. code-block:: xml + + + SingleInstitution + + + FacilityA + 1 + + + FacilityB + 1 + + + + + + + AnotherInstitution + + + + +**JSON:** + +.. code-block:: json + + {"institution": [ + {"config": {"NullInst": null}, + "initialfacilitylist": { + "entry": [ + {"number": 1, "prototype": "FacilityA"}, + {"number": 1, "prototype": "FacilityB"} + ] + }, + "name": "SingleInstitution" + }, + {"config": {"NullInst": null}, + "name": "AnotherInstitution" + } + ] + } + + +**Python:** + +.. code-block:: Python + + {"institution": [ + {"config": {"NullInst": None}, + "initialfacilitylist": { + "entry": [ + {"number": 1, "prototype": "FacilityA"}, + {"number": 1, "prototype": "FacilityB"}, + ], + }, + "name": "SingleInstitution", + }, + {"config": {"NullInst": None}, + "name": "AnotherInstitution", + }, + ], + } + + +.. rst-class:: html-toggle + +Grammar Definition +++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + @Inst_REFS@ + + + + diff --git a/_sources/user/input_specs/recipe.rst.txt b/_sources/user/input_specs/recipe.rst.txt new file mode 100755 index 000000000..97744ed34 --- /dev/null +++ b/_sources/user/input_specs/recipe.rst.txt @@ -0,0 +1,127 @@ +``Recipe`` - Recipe Definition (optional, may appear multiple times) +========================================================================== + +The most common resources being exchanged by |Cyclus| agents is a +:term:`material` which has both a :term:`composition` and a mass. While the +composition of a material object may be manipulated over time by the agents +that transact it, it is often necessary for the user to define a specific +recipe for a material. Each ``recipe`` section can be used to define a named +composition that can then be referenced elsewhere, such as in the data for an +archetype. + +A ``recipe`` block has the following sections in the following order: + + * ``name`` (required once) - the unique name for this commodity + + * ``basis`` (required once) - an indication of whether the composition is + based on the atom fractions or mass fractions; one of: + + * `atom` - atom fractions are given in the nuclide list + * `mass` - mass fractions are given in the nuclude list + + * ``nuclide`` (required at least once) - a list of nuclides and their + relative quantities, where each section includes: + + * ``id`` - identifies a particular nuclide either with its canonical + integer ID in the form ZZAAAMMMM or one of a few other common forms. + Here are some acceptable forms: 922350000, U-235, U235, Am242M. + The canonical integer nuclide format is a general format that encodes + the atomic number (Z), the mass number (A) and the energy state (M) + with the formula (Z*1000 + A) * 10000 + M. + + * ``comp`` - a number indicating the quantity of this nuclide to that + of other nuclides in the material. The quantities are normalized to + the sum of all a composition's constituents, so the user need not + provide quantities normalized to any particular value. + +Example ++++++++ +This example defines two material compositions. The first has the name +``commod_recipe``, is defined using mass fractions, and contains a single +nuclide of H-1. The second recipe is named ``natU_recipe``, is defined using +atom fractions, and contains two nuclides: 0.7% of the atoms are U-235 and +99.3% of the atoms are U-238. + + +**XML:** + +.. code-block:: xml + + + proton_recipe + mass + + 010010000 + 1 + + + + + natU_recipe + atom + + 9223500000.007 + + + 9223800000.993 + + + + +**JSON:** + +.. code-block:: json + + { + "recipe": [ + {"name": "proton_recipe", + "basis": "mass", + "nuclide": {"id": "H1", "comp": 1} + }, + {"name": "natU_recipe", + "basis": "atom", + "nuclide": [ + {"id": "U235", "comp": 0.007}, + {"id": "U238", "comp": 0.993} + ] + } + ] + } + + +**Python:** + +.. code-block:: python + + {"recipe": [ + {"name": "proton_recipe", + "basis": "mass", + "nuclide": {"id": "H1", "comp": 1}, + }, + {"name": "natU_recipe", + "basis": "atom", + "nuclide": [ + {"id": "U235", "comp": 0.007}, + {"id": "U238", "comp": 0.993}, + ], + }, + ], + } + +.. rst-class:: html-toggle + +Grammar Definition ++++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + + diff --git a/_sources/user/input_specs/region.rst.txt b/_sources/user/input_specs/region.rst.txt new file mode 100755 index 000000000..d75e51ffa --- /dev/null +++ b/_sources/user/input_specs/region.rst.txt @@ -0,0 +1,111 @@ +``Region`` - Region agents (at least one required) +============================================================ + +Every agent that participates in a |cyclus| simulation represents either a +facility, an institution or a region. Each ``region`` block defines an agent +that acts as a region in the simulation. In contrast to the ``facility`` +block that defines a :term:`prototype`, this block defines an :term:`agent`. + +Each ``region`` block has the following sections in any order: + +* ``name`` (required once) - a name for the prototype +* ``lifetime`` (optional once) - a non-negative integer indicating the number + of time steps that this region agent will be active in the simulation +* ``config`` (required once) - the archetype-specific configuration +* ``institution`` (required at least once ) - an institution agent operating in this region + +Example ++++++++ +This example introduces two region agents. The first has the name +`MyHomeRegion`, and is configured from the :term:`archetype` with the name (or +alias) `NullRegion`. The author of the ``NullRegion`` archetype has defined +no archetype-specific data. The second has the name ``MyNeighborRegion`` and +is based on the archetype with the name (or alias) `GrowthRegion`. The +contents of the ``GrowthRegion`` section are defined by the author of the +`GrowthRegion` archetype. + +**XML:** + +.. code-block:: xml + + + MyHomeRegion + + + ... data for this institution goes here + + + + + + MyNeighborRegion + + + ... archetype-specific input for a `GrowthRegion` archetype + + + + ... data for this institution goes here + + + + +**JSON:** + +.. code-block:: json + + { + "region": [ + {"name": "MyHomeRegion", + "config": { }, + "institution": "... data for this institution goes here"} + }, + {"name": "MyNeighborRegion", + "config": {"GrowthRegion": "... archetype-specific input for a GrowthRegion archetype"}, + "institution": "... data for this institution goes here"} + ] + } + + +**Python:** + +.. code-block:: python + + {"region": [ + {"name": "MyHomeRegion", + "config": { }, + "institution": "... data for this institution goes here"}, + }, + {"name": "MyNeighborRegion", + "config": {"GrowthRegion": "... archetype-specific input for a GrowthRegion archetype"}, + "institution": "... data for this institution goes here"}, + ], + } + + + +.. rst-class:: html-toggle + +Grammar Definition +++++++++++++++++++ + +.. code-block:: xml + + + + + + + + + + @Region_REFS@ + + + + + + + + + diff --git a/_sources/user/install.rst.txt b/_sources/user/install.rst.txt new file mode 100755 index 000000000..fc3fef8a0 --- /dev/null +++ b/_sources/user/install.rst.txt @@ -0,0 +1,68 @@ +Getting Started with |Cyclus| +============================== + +To model fuel cycles, you will need to install two things: first the main +codebase (called :doc:`Cyclus <../basics/index>`), and then a set of fuel-cycle +specific archetypes (called :doc:`Cycamore `). + +.. warning:: + + In the cyclus ecosystem, only versions whose micro or patch number + (the third and last number) are zero are considered **stable**. + Other releases where the version number is greater than zero are + bugfix and maintainence releases and are considered **unstable**. + For example, a release number of ``1.42.0`` is stable, while + ``1.42.3`` is unstable. + + +1. Install |Cyclus| and Cycamore +--------------------------------- + +The following methods of installation are listed in order of increasing +sophistication, choose the option that best fits your needs. If you feel like +none correspond to your needs please feel free to contact us using the `Cyclus +User mailing list `_, we +will identify the best approach for you. + +* :doc:`Binary installation on Linux (via Debian package or Conda) `: + + - *Requires familiarity with Linux* + - **Recommended** for users wanting to **run simulations locally** (without internet) + +* :doc:`Virtualbox `: + + - *Requires familiarity with Linux* + - **Required for Windows users** + + +* :doc:`Install Stable From Source (via Tarball) `: + + - *Requires programming skills/familiarity with compiling code* + - **Recommended** for users wanting to **modify existing archetypes** or **write new archetypes** (aka developers) + +* :doc:`Install Develop from Source (via Repository) `: + + - *Requires programming skills/familiarity with compiling code, basic understanding of Git/GitHub* + - **Recommended** for developers or users who **require the bleeding edge version** of |Cyclus| + - **Required** for developers who wish to **contribute to kernel development** of |Cyclus| + + +.. toctree:: + :maxdepth: 1 + + install_binary + install_custom + install_from_git + install_from_tarball + virtualbox + + +2. Run Cyclus with a Sample XML File +------------------------------------- + +Try running |Cyclus| for yourself. The result will be a :doc:`database ` named cyclus.sqlite. Use the drop down menu to load the sqlite file into Cyclist for data visualization, or use your favorite sqlite browser to peruse. + +.. code-block:: bash + + $ cyclus ~/path/to/cycamore/input/recycle.xml + diff --git a/_sources/user/install_binary.rst.txt b/_sources/user/install_binary.rst.txt new file mode 100755 index 000000000..f6dce059a --- /dev/null +++ b/_sources/user/install_binary.rst.txt @@ -0,0 +1,53 @@ +################################# +Installing |Cyclus| with Binaries +################################# + +|Cyclus| supports two binary installation options: + +.. include:: CYCAMORE_DEPS.rst + :start-after: .. website_include_binary_start + :end-before: .. website_include_binary_end + +.. include:: CYCAMORE_DEPS.rst + :start-after: .. website_include_conda_start + :end-before: .. website_include_conda_end + + +#. Once you have conda installed, installing |Cyclus| and Cycamore is + straightforward. If you are having issues with certificate verification + you may install using the second set of commands to fix these issues. + + .. code-block:: bash + + $ conda install -c conda-forge cycamore + + .. code-block:: bash + + $ conda config --set ssl_verify false + $ conda install -c conda-forge cycamore + +#. .. include:: unit_test.rst + +.. include:: CYCAMORE_DEPS.rst + :start-after: .. website_include_deb_start + :end-before: .. website_include_deb_end + +#. Download the Cycamore Debian installation package corresponding to your Ubuntu version (`14.04 + `_ or + `16.04 + `_). You can + download previous/different version `here `_. + +#. Install the package by running: + + .. code-block:: bash + + $ sudo dpkg -i cycamore_latest.deb + +#. .. include:: unit_test.rst + +Happy simulating! + +.. _Anaconda: https://www.continuum.io/downloads +.. _miniconda: http://conda.pydata.org/miniconda.html +.. _`dependency installation documentation`: DEPENDENCIES.html diff --git a/_sources/user/install_custom.rst.txt b/_sources/user/install_custom.rst.txt new file mode 100755 index 000000000..061f77490 --- /dev/null +++ b/_sources/user/install_custom.rst.txt @@ -0,0 +1,5 @@ + + +.. include:: CYCLUS_INSTALL.rst + :start-after: .. website_custom_start + :end-before: .. website_custom_end diff --git a/_sources/user/install_from_git.rst.txt b/_sources/user/install_from_git.rst.txt new file mode 100755 index 000000000..c8caf8b07 --- /dev/null +++ b/_sources/user/install_from_git.rst.txt @@ -0,0 +1,80 @@ +================================================ +Installing |Cyclus| Using the GitHub Repository +================================================ +Installing Cyclus is a two step process. First get and compile the +|Cyclus| core, then get and compile the Cyclus Additional Modules (Cycamore), +which provides nuclear fuel cycle facilities such the reactor, fuel fabrication +facility, storage, etc. + + +.. contents:: + :local: + + +-------------- +Dependencies +-------------- + +.. include:: DEPENDENCIES.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + +Instructions on how to install those dependencies on the major platforms can be found +:doc:`here `. + + + +-------------- +Install Cyclus +-------------- + +Get the Source Code from the Git Repo +===================================== + +.. code-block:: bash + + git clone https://github.com/cyclus/cyclus . + git fetch + git checkout master + +Compiling Cyclus +================ + +.. include:: CYCLUS_INSTALL.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + +If you were successful then Cyclus has been installed and you can skip down to Installing Cycamore! + +Alternative instructions are also available for doing a :doc:`Custom Installation `. + + +---------------- +Install Cycamore +---------------- + +Get the Source Code from the Git Repo +===================================== + +.. code-block:: bash + + git clone https://github.com/cyclus/cycamore . + git fetch + git checkout master + + +Compiling Cycamore +================== + +.. include:: CYCAMORE_INSTALL.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + + + +------------------ +Run the Unit Tests +------------------ + +.. include:: unit_test.rst + diff --git a/_sources/user/install_from_tarball.rst.txt b/_sources/user/install_from_tarball.rst.txt new file mode 100755 index 000000000..6b2ceff8c --- /dev/null +++ b/_sources/user/install_from_tarball.rst.txt @@ -0,0 +1,90 @@ +=================================== +Installing |Cyclus| using a Tarball +=================================== + +Installing Cyclus is a two step process. First one needs to get and compile the +|Cyclus| core, then the Cyclus Additional Modules (*Cycamore*), which provide the nuclear fuel cycle facilities such as the reactor, fuel fabrication facility, storage, etc. + + +.. contents:: + :local: + + +-------------- +Dependencies +-------------- + +.. include:: DEPENDENCIES.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + +Instructions to install dependencies on the major platforms can be found +:doc:`here `. + + + +-------------- +Install Cyclus +-------------- + +Get the Tarball +=============== + +Download the most recent stable version of Cyclus source (either .zip or .gz): + +- `cyclus-1.5.5.zip `_ +- `cyclus-1.5.5.tar.gz `_ + +(`Previous versions of Cyclus `_ ) + +Compiling Cyclus +================ +.. include:: CYCLUS_INSTALL.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + +If you were successful then Cyclus has been installed and you can skip down to Installing Cycamore! + +If you received an error message concerning the Cyclus Core Version, please use: + +.. code-block:: bash + + python install.py --core-version=x.y.z + +Replace x.y.z with the Cyclus version number you are installing. + + +Alternative instructions are also available for doing a :doc:`Custom Installation `. + + +---------------- +Install Cycamore +---------------- + +Get the Tarball +================ + +Download the most recent stable version of Cycamore source (either .zip or .gz): + +- `cycamore-1.5.5.zip `_ +- `cycamore-1.5.5.tar.gz `_ + +(`Previous versions of Cycamore `_ ) + + +Compiling Cycamore +================== + +.. include:: CYCAMORE_INSTALL.rst + :start-after: .. website_include_start + :end-before: .. website_include_end + + + +*********************** +Run the Unit Tests +*********************** + +.. include:: unit_test.rst + +.. _`for installing those dependencies for the major supported systems`: DEPENDENCIES.html diff --git a/_sources/user/running_sims.rst.txt b/_sources/user/running_sims.rst.txt new file mode 100755 index 000000000..62cbefc29 --- /dev/null +++ b/_sources/user/running_sims.rst.txt @@ -0,0 +1,69 @@ +Running Simulations +=================== + +To run a simulation you must use the |cyclus| command line utility: + +.. code-block:: bash + + $ ./path/to/cyclus [options] [input-file] + +Or you may run directly through Python: + +.. code-block:: bash + + $ python -m cyclus [options] [input-file] + +For more information, please refer to the help: + +.. code-block:: bash + + $ cyclus -h + Usage: cyclus [opts] [input-file] + + -h [ --help ] produce help message + -V [ --version ] print cyclus core and dependency versions and quit + --restart arg restart from the specified simulation snapshot + [db-file]:[sim-id]:[timestep] + --schema dump the cyclus master schema including all + installed module schemas + --agent-schema arg dump the schema for the named agent + --schema-path arg manually specify the path to the cyclus master + schema + --flat-schema use the flat master simulation schema + --agent-annotations arg dump the annotations for the named agent + --no-agent only print log entries from cyclus core code + --no-mem exclude memory log statement from logger output + -v [ --verb ] arg output log verbosity. Can be text: + + LEV_ERROR (least verbose, default), LEV_WARN, + LEV_INFO1 (through 5), and LEV_DEBUG1 (through + 5). + + Or an integer: + + 0 (LEV_ERROR equiv) through 11 (LEV_DEBUG5 equiv) + + -o [ --output-path ] arg output path + --input-file arg input file + --warn-limit arg number of warnings to issue per kind, defaults to 1 + --warn-as-error throw errors when warnings are issued + -p [ --path ] print the CYCLUS_PATH + --include print the cyclus include directory + --install-path print the cyclus install directory + --build-path print the cyclus build directory + --rng-schema print the path to cyclus.rng.in + --nuc-data print the path to cyclus_nuc_data.h5 + +Examples +++++++++ + +.. code-block:: bash + + $ cyclus ./path/to/myinput.xml + + $ cyclus -v LEV_DEBUG5 myinput.py + + $ python -m cyclus -v LEV_INFO3 myinput.json + + $ cyclus -v 4 myinput.xml + diff --git a/_sources/user/server.rst.txt b/_sources/user/server.rst.txt new file mode 100755 index 000000000..8c23e7733 --- /dev/null +++ b/_sources/user/server.rst.txt @@ -0,0 +1,73 @@ +Cyclus Server +=================== +Cyclus may also be run as an interactive server if it was compiled with Python v3.5.2+ support. + +The Cyclus server is a websockets server that uses JSON to send and recieve instructuctions +from the websockets client (typically a webbrowser). The Cyclus server works by having a queue +of actions that are executed at the end of each time step (repeating actions). +Additionally, certain actions +may be registered to occur only when the server first loads (initial actions). Server actions +may include anything from returning database queries, simple echo messages, or shutting down +the server itself. + +To start up the Cyclus server, use the following command line utility, spawned via Python. + +.. code-block:: bash + + $ python -m cyclus.server + +For more information, please refer to the help: + +.. code-block:: bash + + $ python -m cyclus.server -h + usage: cyclus [-h] [-o OUTPUT_PATH] [--debug] [--host HOST] [-p PORT] + [-n NTHREADS] [-r REPEATING_ACTIONS [REPEATING_ACTIONS ...]] + [-i INITIAL_ACTIONS [INITIAL_ACTIONS ...]] + [input_file] + + Cyclus Server CLI + + positional arguments: + input_file path to input file + + optional arguments: + -h, --help show this help message and exit + -o OUTPUT_PATH, --output-path OUTPUT_PATH + output path + --debug runs the server in debug mode. + --host HOST hostname to run the server on + -p PORT, --port PORT port to run the server on + -n NTHREADS, --nthreads NTHREADS + Maximum number of thread workers to run with. + -r REPEATING_ACTIONS [REPEATING_ACTIONS ...], --repeating-actions REPEATING_ACTIONS [REPEATING_ACTIONS ...] + list of repeating actions + -i INITIAL_ACTIONS [INITIAL_ACTIONS ...], --initial-actions INITIAL_ACTIONS [INITIAL_ACTIONS ...] + list of initial actions to queue + + +Examples +--------- + +.. code-block:: bash + + # Run an input file in server mode, returning all of the output + # table data over the websocket each time step. + $ python -m cyclus.server input.json + + # print the NullRegion annotations and exit + $ python -m cyclus.server -i agent_annotations spec=":agents:NullRegion" shutdown + + + +Web Application for Testing +--------------------------- +Cyclus also ships with a simple web application that is an example client for Cyclus server. +You may start this web app (after starting Cyclus Server) with the following command in a new +terminal: + +.. code-block:: bash + + $ python -m cyclus.webapp + +To access this web application, point your browser to `http://localhost:4200`_. diff --git a/_sources/user/sim_schema.rst.txt b/_sources/user/sim_schema.rst.txt new file mode 100755 index 000000000..0dd6f3e73 --- /dev/null +++ b/_sources/user/sim_schema.rst.txt @@ -0,0 +1,327 @@ +Simulation Schema +================= +|Cyclus| currently has two top-level schema that all input XML files must +adhere to be valid and executable. If you have questions about how an input +file should look, please refer to the schema. Both of these are also printable +from the command line as well, should you ever need them. + +Default Schema +-------------- +This is the recommended schema to use for most simulations. It imposes a +Region, Institution, and Facility hierarchy that is natural for modeling +the relationship between different actors in the nuclear fuel cycle. You +can print this schema from the command line with the ``--schema`` option: + +.. code-block:: bash + + $ cyclus --schema + +This returns the following: + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @Facility_REFS@ + + + + + + + + + + + + + + + + @Region_REFS@ + + + + + + + + + + + + + + + + + + + + + + + + + + @Inst_REFS@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Flat Schema +----------- +The flat schema is an option schema for advanced users. It 'flattens' the +Region, Institution, and Facility hierarchy. This make it easier to model +collections of facilities in cases where regional and institutional effects +are not of primary interest. You can print this from the command line +with the combination of the ``--schema`` and ``--flat-schema`` options: + +.. code-block:: bash + + $ cyclus --flat-schema --schema + +This displays the following: + +.. code-block:: xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @MODEL_SCHEMAS@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/_sources/user/tutorial/add_arche.rst.txt b/_sources/user/tutorial/add_arche.rst.txt new file mode 100755 index 000000000..7cc0dea41 --- /dev/null +++ b/_sources/user/tutorial/add_arche.rst.txt @@ -0,0 +1,207 @@ +Understanding Archetypes +++++++++++++++++++++++++ + +Concept: Archetypes +=================== + +One of the principal features of |Cyclus| is the ability for users to easily +switch between different models of fuel cycle facilities. Models may differ +in the way they choose to represent the physics of the facility, or in the way +they choose for the facility to interact with other facilities, or both. In +|Cyclus|, we call each of these different models an :term:`archetype`. + +Archetype Example +----------------- + +The easiest way for most fuel cycle analysts to understand the difference +between archetypes is through the example of a reactor model. + +* The simplest possible reactor archetype uses the concept of fixed input and + output recipes to define the transmutation of material. Such a reactor + might assume that all material that it receives matches its desired input + recipe, and that all the material that it then ships as used fuel will match + its prescribed output recipe. This will probably run the fastest. +* A more sophisticated reactor archetype uses some form of tabulated data to + determine both **performance characteristics** and **used fuel discharge + composition**. It could be as simple as interpolating between a set of + possible input recipes and then using that interpolation on a set of + corresponding output recipes. A more complex version of such an archetype + could even have tabulated reactor physics parameters for more fidelity. +* The most sophisticated reactor archetype may actually be a wrapper for fuel + depletion software, and perform a full depletion calculation each time new + fuel arrives at the reactor. This will probably take the most computer time + to complete. + +Assuming that such archetypes are available, the user is welcome to choose +which archetype to use, based on the modeling fidelity they are interested in +and/or the performance requirements they have for their simulations. + +Cycamore: The |Cyclus| Additional Module Repository +---------------------------------------------------- + +The |Cyclus| team has developed a simple standard set of archetypes to support +basic fuel cycle modeling situations. In most cases they implement very +simple models and are useful for tutorials such as this, and as a standard way +to model facilities that may be at the peripheral of a problem. The Cycamore +facility archetypes are: + +* **Source:** `Source `_ + is a generic source of material may fill the role of any + facility that produces fresh material. Depending on how much of the fuel + cycle a user wants to model explicitly, this could fill the role of a uranium + mine, an enrichment facility, a fuel fabrication facility, import of a commodity from + outside simulated facilities, etc. The Source facility produces resources at a user-specified + rate and may be limited to a user-specified total inventory. +* **Enrichment:** `Enrichment `_ + is a facility archetype that implements the standard equations for + enrichment of U-235 in U-238, with a constrained total enrichment capacity. +* **Reactor:** `Reactor `_ + is a facility archetype which uses fresh and spent fuel recipes to model fuel transmutation. + Fuel is modeled as batches and assemblies that are reloaded at regular intervals. +* **Separations:** `Separations `_ + is a facility archetype that receives one or more material streams and + separates all the isotopes into a number of output streams. +* **FuelFab:** `FuelFab `_ is + a facility archetype that mixes streams of fissile and + fissionable material in order to best approximate a given recipe using the + d-factor approach. +* **Sink:** `Sink `_ is a generic + sink of material that may fill the role of any facility + that permanently holds used nuclear material. Depending on how much of the + fuel cycle a user wants to model explicitly, this could fill the role of a + geologic repository, an interim storage facility, export of a commodity to outside simulated facilities, etc. + + +Activity: Discover the Available Archetypes +=========================================== +If using |Cyclus| on your machine, the archetypes available to you are only those that you have downloaded. +To check which archetypes are downloaded on your machine run the command ``cyclus -a`` from your terminal. + +If you are not running |Cyclus| on your machine, the archetypes available to you include those in Cycamore, which +can be found on the `archetypes +`_ webpage. + + +What archetypes can you see yourself using in your research? + +Concept: Third-Party Archetypes +========================================= +`Third-Party `_ Archetypes +complement the initial archetypes available in Cycamore and are not necessarily +maintained by the |Cyclus| core development team. Popular Third-Party Archetypes are: + +* Bright-lite +* Cyborg +* Mbmore Archetypes +* rwc Archetypes + +Review the `archetype developer tutorial `_ +for more information on making your own Archetypes. + +Activity: Adding archetypes +=========================== + +After discovering which archetypes are available, we will select which +subset of archetypes to use in this particular scenario. + +The archetypes we will use in our simulation include: + +- ``cycamore Source``: to act as the mine +- ``cycamore Enrichment``:to act as the enrichment facility +- ``cycamore Reactor``: to act as the LWR +- ``cycamore Sink``: to act as the geological repository. + +A user identifies the simulation ``archetypes`` in the archetype block of the |Cyclus| input file. +The ``archetype`` block is located after the simulation control block and takes the form: + +.. code-block:: XML + + + + lib1 + arch_1 + + + lib2 + arch_2 + + + +where ``lib`` is the library in which the archetype came from and ``name`` is +the archetype name. Let's build our archetypes! +Using the template below and the table below, +fill in the template with the variables listed in the table below. + ++-------------+------------------+----------------------------+ +| Variable | Value | Purpose | ++=============+==================+============================+ +| ``lib1`` | ``cycamore`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch1`` | ``Enrichment`` | Name of archetype | ++-------------+------------------+----------------------------+ +| ``lib2`` | ``cycamore`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch2`` | ``Reactor`` | Name of archetype | ++-------------+------------------+----------------------------+ +| ``lib3`` | ``cycamore`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch3`` | ``Source`` | Name of archetype | ++-------------+------------------+----------------------------+ +| ``lib4`` | ``cycamore`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch4`` | ``Sink`` | Name of archetype | ++-------------+------------------+----------------------------+ + + +Archetype Block Template +------------------------ +.. code-block:: XML + + + + lib1 + arch1 + + + lib2 + arch2 + + + lib3 + arch3 + + + lib4 + arch4 + + + + +Once complete, your ``archetypes`` block should look like: + +.. code-block:: XML + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + +Once complete, append the archetypes section under the control section of input file [#f1]_. + +.. rubric:: Footnotes + +.. [#f1] The exact order of the sections in a |Cyclus| input file are of minor consequence. The ``control`` sequence must go first, but the other sequences can go in any order that makes sense to the user. The traditional organization of an input file is: control, archetypes, commodities, facilities, regions/institutions, and recipes. diff --git a/_sources/user/tutorial/add_arche_commod_recipe.rst.txt b/_sources/user/tutorial/add_arche_commod_recipe.rst.txt new file mode 100755 index 000000000..c7b150822 --- /dev/null +++ b/_sources/user/tutorial/add_arche_commod_recipe.rst.txt @@ -0,0 +1,41 @@ +Getting Started on Recycle +============================ + +This exercise will start with some simple activities based on what you learned +in the first exercise. + +Activity: Adding Archetypes +----------------------------- + +We will need two additional archetypes: + +1. Add the *cycamore FuelFab* archetype +2. Add the *cycamore Separations* archetype + +Activity: Adding Commodities +----------------------------- + +We will need 4 additional commodities: + +1. Fresh-MOX-Fuel +2. Used-MOx-Fuel +3. Separated-Fissile +4. Separated-Waste + +Activity: Adding Recipes +-------------------------- + +We'll continue with very approximate recipes by adding a single recipe for Used-MOX-Fuel-4: + ++------------+-----------------+ +| U-235 | 0.002 | ++------------+-----------------+ +| U-238 | 0.94 | ++------------+-----------------+ +| Pu-239 | 0.01 | ++------------+-----------------+ +| Pu-240 | 0.002 | ++------------+-----------------+ +| Cs-137 | 0.046 | ++------------+-----------------+ + diff --git a/_sources/user/tutorial/add_commod_recipe.rst.txt b/_sources/user/tutorial/add_commod_recipe.rst.txt new file mode 100755 index 000000000..9c27a33b4 --- /dev/null +++ b/_sources/user/tutorial/add_commod_recipe.rst.txt @@ -0,0 +1,377 @@ +Understanding Commodities +------------------------- + +Concept: Commodities +++++++++++++++++++++ + +|Cyclus| exchanges resources between facilities using a market-like mechanism +called the **dynamic resource exchange (DRE)**. The concept of a **commodity** is +used to simply indicate which facilities may be interested in trading with +each other through the DRE. A commodity is therefore nothing more than a +unique name that is used to define a set of producers and consumers of a +common resource. A commodity does not necessarily have a specific +composition; this will be determined by the agents during the simulation. +Suppliers then respond to the series of requests with a **bid**. A bid +supplies a notion of the quantity and quality of a resource to match a +request. Suppliers may add an arbitrary number of constraints to +accompany bids. For example, an enriched UOX supplier may be constrained +by its current inventory of natural uranium or its total capacity to +provide enrichment in Separative Work Units (SWUs). + +Any potential resource transfer (i.e., a bid or a request) may be +denoted as **exclusive**. An exclusive transfer excludes partial fulfillment; +it must either be met fully or not at all. This mode supports concepts +such as the trading of individual reactor assemblies. In combination +with the notion of mutual requests, complex instances of supply and +demand are enabled. + +Finally, requesting facilities, institutions and +regions may apply **preferences** to each potential request-bid pairing +based on the proposed resource transfer. Facilities can apply arbitrary +complex logic to **rank the bids** that they have received, whether based on +the quantity available in each bid or on the quality of each bid, and +the consequent implications of the physics behavior of that facility. In +addition, an institution can apply a higher preference to a partner to +which it is congenial; similarly, a region may negate any transfers of +material which have a higher uranium enrichment than is allowable. + +For example, the flow graph below shows three suppliers (left) and two +consumers (right), and the potential flows of various commodities among +them. The second consumer makes two different requests. Meanwhile, the +second supplier can supply the commodities requested by both consumers +and provides two bids accordingly. + +.. image:: trade.png + :align: center + :alt: Commodity trade flowchart + +Activity: Create fuel commodities (optional) ++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +Let's build ``u-ore``, ``fresh-uox``, ``spent-uox``, and ``tails``, +the four commodities available for trade in our simulation. Note that +this part is **optional**, and is only needed if the user wants +to specify the solution priority of each commodity. + +* ``u-ore`` : natural uranium that is mined +* ``tails`` : waste from the enrichment process +* ``fresh-uox``: fresh 4.0% enriched Uranium Oxide fuel that enters the reactor +* ``spent-uox``: spent uranium oxide fuel that leaves the reactor after depletion + +When |Cyclus| needs +to know the isotopic composition of a material, it looks at the recipe for that +material given in the input file. Until now, ``recipe`` has been used to +refer to fuel recipes, but the ``recipe`` section of the input file can +describe any isotopic vector (e.g. natural uranium, spent fuel, fresh fuel, or any +other material whose isotopic composition needs to be tracked.) + +The commodities section follows the ``archetype`` section +and takes the form: + +.. code-block:: XML + + + com1 + 1.0 + + + com2 + 1.0 + + + com3 + 1.0 + + + com4 + 1.0 + + +where: + +* name: name of the commodity +* solution priority: number defining the relative priority for resolution in the dynamic + resource exchange. + + We will model four commodities: u-ore, fresh-uox, spent-uox, and tails. + + +Activity: Building commodities +++++++++++++++++++++++++++++++++++++++++++ + +Using the table below and the commodities template above, fill out the commodities +template. + ++-------------+-------------+---------------------+ +| Commodity | Name | Solution Priority | ++=============+=============+=====================+ +| com1 | u-ore | 1.0 | ++-------------+-------------+---------------------+ +| com2 | fresh-uox | 1.0 | ++-------------+-------------+---------------------+ +| com3 | spent-uox | 1.0 | ++-------------+-------------+---------------------+ +| com4 | tails | 1.0 | ++-------------+-------------+---------------------+ + +1. Let's start with ``u-ore``. In the ```` line replace ``com1`` with ``u-ore`` +inside a ``commodity`` block. + +.. code-block:: XML + + + u-ore + + +2. In the ```` section replace ``val1`` with ``1.0``. + +.. code-block:: XML + + + + u-ore + 1.0 + + + + +3. Repeat this process for the other three commodities. Your final result should look like: + +.. code-block:: XML + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + +Once complete, append the commodities section under the archetypes section [#f1]_. + +Understanding Recipes +--------------------- + +Concept: Recipes +++++++++++++++++ + +Most commodities are materials, which have a quantity and an +isotopic composition. +Recipes are the isotopic composition of a certain material. For +example, u-ore has an isotropic composition of 0.711% :math:`^{235}`\ U and +99.284% :math:`^{238}`\ U. The recipe section of a |Cyclus| input file is +typically located at the end of the input and is of the form: + +.. code-block:: XML + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + +where ``id`` is the Nuc Id of the isotope in form ZZAAA and ``comp`` is the +composition of that isotope in the recipe. Other isotope formats are +also acceptable, such as those used by `pyne `_. +For example, :math:`^{235}`\ U can be expressed as: + +* 922350 (ZZAAAM) +* 92235 (ZZAAA) +* U235 (name) +* U-235 (name) + +For more details, reference the `Recipe definition +<../input_specs/recipe.html>`_ page. + +First, we can declare the isotopic compositions of the fresh and spent +fuel. We'll be using simple recipes: fresh fuel is 4.0% :math:`^{235}`\ U by mass, +remainder U-238. Spent fuel is 1.1% :math:`^{235}`\ U, 94.0% :math:`^{238}`\ U, 0.9% :math:`^{239}`\ Pu, and +4.0% :math:`^{137}`\ Cs. + +Activity: Creating a Recipe +++++++++++++++++++++++++++++ + + +Using the tables below, fill out the recipe +template for natural uranium, fresh fuel, and spent fuel. + ++---------------------+--------------------+--------------------+ +| Natural Uranium Composition | ++---------------------+--------------------+--------------------+ +| Nuclide | Spent ids | Mass composition | ++=====================+====================+====================+ +| :math:`^{235}`\ U | 92235 | 0.00711 | ++---------------------+--------------------+--------------------+ +| :math:`^{238}`\ U | 92238 | 0.99289 | ++---------------------+--------------------+--------------------+ + ++---------------------+--------------------+--------------------+ +| Fresh Fuel Composition | ++---------------------+--------------------+--------------------+ +| Nuclide | Spent ids | Mass composition | ++=====================+====================+====================+ +| :math:`^{235}`\ U | 92235 | 0.04 | ++---------------------+--------------------+--------------------+ +| :math:`^{238}`\ U | 92238 | 0.96 | ++---------------------+--------------------+--------------------+ + ++---------------------+--------------------+--------------------+ +| Spent Fuel Composition | ++---------------------+--------------------+--------------------+ +| Nuclide | Spent ids | Mass composition | ++=====================+====================+====================+ +| :math:`^{235}`\ U | 92235 | 0.011 | ++---------------------+--------------------+--------------------+ +| :math:`^{238}`\ U | 92238 | 0.94 | ++---------------------+--------------------+--------------------+ +| :math:`^{239}`\ Pu | 94239 | 0.009 | ++---------------------+--------------------+--------------------+ +| :math:`^{137}`\ Cs | 55137 | 0.04 | ++---------------------+--------------------+--------------------+ + +1. Let's start with the Natural Uranium recipe. Start by placing a ```` +block to signify that this is a recipe and tab in and place the fill +```` tag such as: + +.. code-block:: XML + + + nat-u + + +2. To signify that the composition of this recipe is in terms of Mass, fill the +```` tag with ``mass``. + +.. code-block:: XML + + + nat-u + mass + + +3. To add a nuclide to this recipe, call the ``nuclide`` tag, tab in, add the +```` and ```` tags: + +.. code-block:: XML + + + nat-u + mass + + id1 + comp1 + + + +4. We will fill the ```` tag with the uranium-235 ``Nuc Id``, ``92235``, and +fill the composition tag with its mass composition, ``0.00711``. + +.. code-block:: XML + + + nat-u + mass + + 92235 + 0.00711 + + + +5. Following the same procedure, we can add uranium-238 to this recipe such as: + +.. code-block:: XML + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + +6. We can add other recipes in separate ``recipe`` blocks. +The recipe section of this tutorial is placed below. + +.. code-block:: XML + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + +Once complete, append this facility under the commodity section of your input file [#f1]_. + + +Let's take a look at the ``fresh-uox`` fuel recipe: + +.. image:: fuel_com.png + :align: center + :alt: Fuel recipe for fresh-uox +The recipe name ``fresh-uox`` is specified, as are the isotope nuclide IDs and the +corresponding mass fraction of each nuclide. The ``fresh-uox`` is composed of 4% U-235 and 96% U-238. + +.. rubric:: Footnotes +.. [#f1] The exact order of the sections in a |Cyclus| input file are of minor consequence. The ``control`` sequence must go first, but the other sequences can go in any order that makes sense to the user. The traditional organization of an input file is: control, archetypes, commodities, facilities, regions/institutions, and recipes. diff --git a/_sources/user/tutorial/add_deploy.rst.txt b/_sources/user/tutorial/add_deploy.rst.txt new file mode 100755 index 000000000..1c0c24b41 --- /dev/null +++ b/_sources/user/tutorial/add_deploy.rst.txt @@ -0,0 +1,136 @@ +Deploying New Facilities +========================== + +Often in fuel cycle analysis, transition scenarios are considered. These ask +questins like: "How does the +commissioning and decommissioning of reactors affect electrity production or +material transactions?". Transition analysis will +require an institution that can deploy additional facilities at given time +steps: the ``cycamore DeployInst`` archetype. This is the simplest institution +that can deploy +new facilities, in which the user simply defines the times at which new agents +should be deployed as copies of available prototypes. + +In this case, we will keep the current institutions and add another +institution that will deploy more facilities over time. + +Example: DeployInst +-------------------------------- +The ``DeployInst`` archetype must be added to the ```` block +of the input file: + +.. code-block:: xml + + + ... + ... + cycamoreDeployInst + + + +**Recall:** in `Adding a Second Reactor `_ we left +a blank spot in between our ```` and ```` handles. +We will now use this to add the institution for ``DeployInst``. + +``DeployInst`` takes the form: + +.. code-block:: XML + + ExampleInstitution + + + + prototype_name1 + prototype_name2 + prototype_name3 + prototype_name4 + + + + time1 + time2 + time3 + time4 + + + + n_build1 + n_build2 + n_build3 + n_build4 + + + + + + +where: + +* prototype: Ordered list of prototypes to build +* build_times: Time step on which to deploy agents given in prototype list +* n_build: Number of each prototype given in prototype list to build + +Activity: Add a New Institution +++++++++++++++++++++++++++++++++++++++++++ + +Using the table below and the DeployInst template above, fill out the commodities +template. + ++-------------+-------------+---------------------+ +| Prototype | build_times | n_build | ++=============+=============+=====================+ +| UraniumMine | 1 | 1 | ++-------------+-------------+---------------------+ +| FuelFab | 1 | 1 | ++-------------+-------------+---------------------+ +| 1178MWe BRAIDWOOD-1 | 2 | 1 | ++-------------+-------------+---------------------+ +| 1000MWe Lightwater-1 | 3 | 1 | ++-------------+-------------+---------------------+ + +Using the prototype facilities already created, the new institution should +look like the following: + +.. code-block:: xml + + + ExampleInstitution + + + + UraniumMine + FuelFab + 1178MWe BRAIDWOOD-1 + 1000We Lightwater-1 + + + + 1 + 1 + 2 + 3 + + + + 1 + 1 + 1 + 1 + + + + + +The above institution will create 1 ``UraniumMine`` and 1 ``FuelFab`` facility on +time step 1. The next time step will deploy the ``1178MWe BRAIDWOOD-1`` reactor +prototype. And finally, at time step 3, the ``1000We Lightwater-1`` will be deployed. +This institution block goes inside the Region block, with the previously created +insitutions blocks. + +**ExampleInstitution** is a placeholder for your institution name, and in this scenario +only one of each prototype will be deployed since ``n_build`` has a value of 1 for each. + +This example is now complete. Save your file as the desired file name (with ``.xml`` +extension) and run your code through |Cyclus|. If your simulation runs into errors, +sample files can be found `here `_ under +``input_deployinst.xml`` or ``ouput_deployinst.sqlite``. diff --git a/_sources/user/tutorial/add_fab.rst.txt b/_sources/user/tutorial/add_fab.rst.txt new file mode 100755 index 000000000..e24a363ff --- /dev/null +++ b/_sources/user/tutorial/add_fab.rst.txt @@ -0,0 +1,69 @@ +Adding a Stream Mixing Fuel Fabrication Facility +================================================== + +The cycamore FuelFab archetype uses the _equivalence method_ to mix streams of +fissile material with so-called "filler" material in an attempt to match +neutronics of the +requested material. More details about the archetype and the state +variables are in the +`cycamore archetype documentation +<../cycamoreagents.html>`_ page. + +The following is the input template for the ``Cycamore::FuelFab`` +archetype: + +.. code-block:: XML + + + FuelFab + + + + _______ + + _______ + _______ + + _______ + + _______ + _______ + _______ + _______ + + + + + +The following configuration will be for a +MOX fuel fabrication plant that mixes separated +plutonium and natural uranium into MOX fuel: + +* Filler stream commodity: ``u-ore`` +* Filler stream recipe: ``nat-u`` +* Filler stream inventory capacity: 1000 tonnes +* Fissile stream commodity: Separated-Fissile +* Fissile stream inventory capacity: 5 tonnes +* Output Commodity: Fresh-MOX-Fuel +* Maximum Throughput: 2 tonnes/timestep +* Specturm type: "thermal" + +Filling in the template, the input block looks like: + +.. code-block:: XML + + + FuelFab + + + U-ore + Nat-U + 1000000 + Separated-Fissile + 5000 + thermal + Fresh-MOX-Fuel + 2000 + + + diff --git a/_sources/user/tutorial/add_proto.rst.txt b/_sources/user/tutorial/add_proto.rst.txt new file mode 100755 index 000000000..e7069ede7 --- /dev/null +++ b/_sources/user/tutorial/add_proto.rst.txt @@ -0,0 +1,576 @@ +Understanding Prototypes +------------------------ + +One key feature of |Cyclus| is its ability to switch between +different models of the facilities within the fuel cycle. These models, +called **archetypes**, may change how the facility interacts with other +facilities or how the physics of the facility are represented. For +example, reactor archetypes determine the reactor's fresh and spent fuel +compositions and how the reactor experiences fuel burn-up. A reactor +model can have three varying fidelity levels: + +* A very simple model that uses recipe to deplete fuel +* A more complex model may tabulate reactor performance and + physics parameters, and interpolate its input and output recipes. +* The most complex model could perform a full depletion calculation each time + new fuel enters the reactor. + +A simple set of archetypes have been created in `Cycamore `__. +While the archetype describes the form of the model used to represent a +facility, a variety of parameters are generally available to configure the +specific behavior. For the example of a reactor, the developer will probably +allow the user to define the power level of the reactor, independent of the +specific model chosen to represent the behavior of the model. Other common +reactor parameters are fuel loading parameters such as cycle length and batch +size. + +In |Cyclus|, when an archetype has been configured with a +specific set of parameters, it is called a **prototype**. + +Example: Source Prototype ++++++++++++++++++++++++++ +The Source facility acts as a source of material with a fixed throughput (per +time step) capacity and a lifetime capacity defined by a total inventory size. +It offers its material as a single commodity. If a composition recipe is +specified, it provides that single material composition to requesters. If +unspecified, the source provides materials with the exact requested compositions. +The inventory size and throughput both default to infinite. Supplies material +results in corresponding decrease in inventory, and when the inventory size +reaches zero, the source can provide no more material. + +The Source archetype is of the form: + +.. code-block:: XML + + + Source + + + out_commodity + + + + +Optional parameters: + +outrecipe: + Name of the isotopic composition of the material that this source provides + regardless of the requested composition. If empty, the Source creates and + provides whatever composition is requested. + +.. code-block:: XML + + [outrecipe] + + + +inventory_size: default = 1e+299, range: [0.0, 1e+299] + Total amount of material this source has remaining. Every trade decreases + this value by the supplied material quantity. When it reaches zero, the + source cannot provide any more material. + +.. code-block:: xml + + [double ( kg )] + +throughput: default=1e+299,range: [0.0, 1e+299] + Amount (kg) of the commodity that the Source can supply at each time step + +.. code-block:: xml + + [double ( kg/(time step) )] + +Activity: Configure the Source prototype +++++++++++++++++++++++++++++++++++++++++ +Our source, ``UraniumMine``, will provide the natural uranium ore for our enrichment facility. +This facility takes two inputs, ``name`` and ``outcommd``. Using the Source +Archetype and the table below, create the UraniumMine prototype. + ++-----------------------+---------------------------+ +| Variable | Value | ++=======================+===========================+ +| ``name`` | ``UraniumMine`` | ++-----------------------+---------------------------+ +| ``Archetype`` | ``Source`` | ++-----------------------+---------------------------+ +| ``out_commod`` | ``u-ore`` | ++-----------------------+---------------------------+ + +1. The template for the Source archetype is of the form: + +.. code-block:: XML + + + name + + + outcommod + + + + +2. Filling in the variables ``name``, ``Archetype``, and ``out_commod`` as +``UraniumMine``, ``Source``, and ``fresh-uox`` leads to: + +.. code-block:: XML + + + UraniumMine + + + u-ore + + + + +Once complete, append this facility under the commodity section and before the recipe section of your input file [#f1]_. + +Example: Enrichment Prototype ++++++++++++++++++++++++++++++ +The Enrichment facility is a simple agent that enriches natural uranium in a |Cyclus| simulation. It does not +explicitly compute the physical enrichment process, rather it calculates the SWU required to convert an +incoming isotopic vector (i.e. natural uranium) into a requested enriched recipe (i.e. 4% enriched uranium), +given the natural uranium inventory constraint and its SWU capacity constraint. +The Enrichment archetype is of the form: + +.. code-block:: XML + + + EnrichmentPlant + + + feed_commodity + feed_recipe + product_commodity + tails_commodity + + + + +Optional parameters: + +max_feed_inventory: default = 1e+299, range: [0.0, 1e+299] + Maximum total inventory of natural uranium in the enrichment facility (kg) + +.. code-block:: XML + + 1000000[double] + +initial_feed: default = 0 + Amount of natural uranium stored at the enrichment facility at the beginning of the simulation (kg) + +.. code-block:: XML + + [double] + +max_enrich: default = 1.0, range: [0.0,1.0] + maximum allowed weight fraction of U235 in product + +.. code-block:: XML + + [double] + +order_prefs: default = 1, userlevel: 10 + Turn on preference ordering for input material so that EF chooses higher U235 content first + +.. code-block:: XML + + [boolean] + +swu_capacity: default = 1e+299, range: [0.0, 1e+299] + Separative work unit (SWU) capacity of enrichment facility (kgSWU/timestep) + +.. code-block:: XML + + [double] + +Activity: Creating the Enrichment Prototype ++++++++++++++++++++++++++++++++++++++++++++ +The enrichment facility, ``EnrichmentPlant`` will intake the natural ``u-ore`` +from ``UraniumMine`` and create ``fresh-uox`` and ``tails`` as its products. +The template for the Enrichment archetype is of the form: + +.. code-block:: XML + + + enrichment_plant_name + + + feed_commodity + feed_recipe + product_commodity + tails_commodity + 1000000 + + + + +Using the template above and the table below, generate the input enrichment facility prototype. + ++-------------------------+---------------------------+ +| Variable | Value | ++=========================+===========================+ +| ``name`` | ``EnrichmentPlant`` | ++-------------------------+---------------------------+ +| ``Archetype`` | ``Enrichment`` | ++-------------------------+---------------------------+ +| ``feed_commod`` | ``u-ore`` | ++-------------------------+---------------------------+ +| ``feed_recipe`` | ``nat-u`` | ++-------------------------+---------------------------+ +| ``product_commod`` | ``fresh-uox`` | ++-------------------------+---------------------------+ +| ``tails_commod`` | ``tails`` | ++-------------------------+---------------------------+ +| ``max_feed_inventory`` | 1000000 | ++-------------------------+---------------------------+ + + +After filling in these variables, your enrichment facility prototype will look like: + +.. code-block:: XML + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + +Once complete, append this facility under the Source prototype of your input file [#f1]_. + + +Example: Reactor Prototype +++++++++++++++++++++++++++ +The Reactor is a simple, general reactor based on static compositional transformations to model fuel burnup. +The user specifies a set of fresh fuel compositions the Reactor accepts and corresponding spent fuel +compositions the reactor discharges from the core. No incremental transmutation takes place. Rather, +at the end of an operational cycle, the batch being discharged from the core is instantaneously transmuted +from its original fresh fuel composition into its spent fuel form. + +Each fuel is identified by a specific input commodity and has an associated input recipe (nuclide composition), +output recipe, output commodity, and preference. The preference identifies which input fuels are preferred +when requesting. Changes in these preferences can be specified as a function of time using the pref_change +variables. Changes in the input-output recipe compositions can also be specified as a function of time using +the recipe_change variables. + +The reactor treats fuel as individual assemblies. Fuel is requested in assembly-sized quanta. If real-world +assembly modeling is unnecessary, parameters can be adjusted (e.g. ``n_assem_core``, ``assem_size``, +``n_assem_batch``). At the end of every cycle, a full batch is discharged from the core consisting of +``n_assem_batch`` assemblies of ``assem_size`` kg. The reactor also has a specifiable refueling time +period following the end of each cycle at the end of which it will resume operation on the next cycle if it +has enough fuel for a full core; otherwise it waits until it has enough fresh fuel assemblies. +When the reactor reaches the end of its lifetime, it will discharge all material from its core and trade away all its +spent fuel as quickly as possible. Full decommissioning will be delayed until all spent fuel is gone. If the reactor +has a full core when it is decommissioned (i.e. is mid-cycle) when the reactor is decommissioned, half (rounded +up to nearest int) of its assemblies are transmuted to their respective burnt compositions. +The Reactor archetype is of the form: + +.. code-block:: XML + + + reactor_name + + + + input_fuel_commodity + + + input_fuel_recipe + + + output_fuel_commodity + + + output_fuel_recipe + + 18 + 1 + 33000 + 3 + 1 + power_out + + + + + +Activity: Creating the Reactor Prototype +++++++++++++++++++++++++++++++++++++++++ + +Now let's model the reactor this fuel will go through! In this simple example, +let's model a single PWR in the United States. It has a power capacity of 1178 +MWe, and there is only one of them in the region. +The template for the reactor is given below: + +.. code-block:: XML + + + Reactor + + + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + [VALUE] + + + + +Where: + +* ``fuel_incommods``: input fuel commodity +* ``fuel_inrecipes``" input fuel recipe +* ``fuel_outcommods``: output fuel commodity +* ``fuel_outrecipes``: output fuel recipe. +* ``cycle_time``: amount of time the reactor operates between refueling outages +* ``refuel_time``: duration of refueling outage +* ``assem_size``" size of a single assembly +* ``n_assem_core`` : number of assemblies in the core +* ``n_assem_batch``: number of batches replaced per refueling. +* ``power_cap``: amount of electricity the reactor generates. + +Using the template above and the table below, create the Reactor prototype. + ++-----------------------+---------------------------+ +| Variable | Value | ++=======================+===========================+ +| ``name`` | ``1178MWe BRAIDWOOD-1`` | ++-----------------------+---------------------------+ +| ``Archetype`` | ``Reactor`` | ++-----------------------+---------------------------+ +| ``fuel_incommods`` | ``fresh-uox`` | ++-----------------------+---------------------------+ +| ``fuel_inrecipes`` | ``fresh-uox`` | ++-----------------------+---------------------------+ +| ``fuel_outcommods`` | ``spent-uox`` | ++-----------------------+---------------------------+ +| ``fuel_outrecipes`` | ``spent-uox`` | ++-----------------------+---------------------------+ +| ``cycle_time`` | ``18`` | ++-----------------------+---------------------------+ +| ``refuel_time`` | ``1`` | ++-----------------------+---------------------------+ +| ``assem_size`` | ``33000`` | ++-----------------------+---------------------------+ +| ``n_assem_core`` | ``3`` | ++-----------------------+---------------------------+ +| ``n_assem_batch`` | ``1`` | ++-----------------------+---------------------------+ +| ``power_cap`` | ``1178`` | ++-----------------------+---------------------------+ + +Once completed, your prototype should look like: + +.. code-block:: XML + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + +Once complete, append this facility under the Enrichment facility of your input file [#f1]_. + + +Example: Sink Prototype ++++++++++++++++++++++++ + +A sink facility that accepts materials and products with a fixed throughput (per time step) capacity and a lifetime +capacity defined by a total inventory size. The inventory size and throughput capacity both default to infinite. If a +recipe is provided, it will request material with that recipe. Requests are made for any number of specified +commodities. +The Sink archetype section is of the form: + +.. code-block:: xml + + + Sink_name + + + + input_commodity + input_commodity + + + + + +Optional parameters: + +in_commod_prefs: default=[], range: [None, [1e-299, 1e+299]] + Commodities that the sink facility accepts + +.. code-block:: XML + + + [double] + [double] + + +recipe_name: default=”” + Name of recipe to use for material requests, where the default (empty string) is to accept everything + +.. code-block:: XML + + [inrecipe][double] + +capacity: default = 1e+299, range: [0.0, 1e+299] + capacity the sink facility can accept at each time step + +.. code-block:: XML + + [double] + +Activity: Creating the Sink Prototype ++++++++++++++++++++++++++++++++++++++ +Our sink, ``NuclearRepository``, will store the ``spent-uox`` and ``tails`` after +their use in the fuel cycle. Using the Sink Archetype template and the table below, +create the UraniumMine prototype. + ++-------------------------+---------------------------+ +| Variable | Value | ++=========================+===========================+ +| ``name`` | ``NuclearRepository`` | ++-------------------------+---------------------------+ +| ``Archetype`` | ``Sink`` | ++-------------------------+---------------------------+ +| ``val`` | ``spent-uox`` | ++-------------------------+---------------------------+ +| ``val`` | ``tails`` | ++-------------------------+---------------------------+ + +The sink facility archetype is: + +.. code-block:: XML + + + Sink_name + + + + input_commodity + input_commodity + + + + + +After filling in these variables, your sink facility prototype will look like: + +.. code-block:: XML + + + NuclearRepository + + + + spent-uox + tails + + + + + +Once complete, append this facility under the Reactor prototype of your input file [#f1]_. + +Check: Complete Facility block +++++++++++++++++++++++++++++++++++++++++ + +The facility section of your input file should be of the form: + +.. code-block:: XML + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + NuclearRepository + + + + spent-uox + tails + + + + + +.. rubric:: Footnotes +.. [#f1] The exact order of the sections in a |Cyclus| input file are of minor consequence. The ``control`` sequence must go first, but the other sequences can go in any order that makes sense to the user. The traditional organization of an input file is: control, archetypes, commodities, facilities, regions/institutions, and recipes. diff --git a/_sources/user/tutorial/add_reg_inst.rst.txt b/_sources/user/tutorial/add_reg_inst.rst.txt new file mode 100755 index 000000000..ebf9dc730 --- /dev/null +++ b/_sources/user/tutorial/add_reg_inst.rst.txt @@ -0,0 +1,438 @@ +Adding Regions and Institutions +=============================== + +Concept: Regions & Institutions +------------------------------- + +|Cyclus| establishes a hierarchy of agents: Facility agents are managed by +Institution agents that exist within a Region agent. This series of ownership +allow for control of the interaction behavior +between agents. For example, two facilities +may not be allowed to trade if they are in two different regions. + +Every |Cyclus| simulation needs at least one Region and one Institution, and +in this case, we'll use the simplest options: + +* a Null Institution (*NullInst*) that holds a set of facilities that are + deployed at the start of a simulation. +* a Null Region (*NullRegion*) that holds a set of Institutions. + +Defining these is done in the archetypes section of the code. This is done +in a similar manner as the other archetypes previously defined, except regions +and insitutions used in this tutorial come from the ``agents`` library, rather +than the ``cycamore`` library. + +Using the template and table below, +properly fill the template with the variables listed in the table below. +In the template, the dots represent the archetypes already defined in the +simulation. + ++-------------+------------------+----------------------------+ +| Variable | Value | Purpose | ++=============+==================+============================+ +| ``lib6`` | ``agents`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch6`` | ``NullRegion`` | Name of archetype | ++-------------+------------------+----------------------------+ +| ``lib7`` | ``agents`` | Library of the archetype | ++-------------+------------------+----------------------------+ +| ``arch7`` | ``NullInst`` | Name of archetype | ++-------------+------------------+----------------------------+ + +.. code-block:: XML + + ... + ... + + lib6 + arch6 + + + lib7 + arch7 + + + +Once complete, your `agent` Archetypes block should be: + +.. code-block:: XML + + ... + ... + + agents + NullRegion + + + agents + NullInst + + + +Since these are all archetypes, no matter what library they're from, we must append +these two``spec`` blocks into the the arechtype block that we already have. This +results in the full archetype block: + +.. code-block:: XML + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + agents + NullRegion + + + agents + NullInst + + + + +Concept: Regions +---------------- + +Regions tie together a fuel cycle as they designate what facilities are +in the region's fuel cycle. Regions may apply preferences to each +potential request-bid pairing based on the proposed resource transfer. +The basic structure of a region is: + +.. code-block:: XML + + + Region_name + + + + + ... + ... + + + + +Where: + +* ``name``: name of the region +* ``config``: Region archetype to use + +In between the two dotted lines +is where the institution and facility information goes. + +Concept: Institution +----------------------------------------------------------------------- +In |Cyclus| input files, each institution block defines an agent that +acts as an institution in the simulation. An institution block can only +appear within a region block. Each institution block has the following +sections in any order: + +- ``name`` (required, once) - a name for the prototype +- ``lifetime`` (optional, once) - a non-negative integer indicating the + number of time steps that this region agent will be active in the + simulation +- ``config`` (required, once) - the archetype-specific configuration +- ``initialfacilitylist`` (optional, may appear multiple times) - a + list of facility agents operating at the beginning of the simulation + +Each ``initialfacilitylist`` block contains one or more ``entry`` blocks +that each contain the following sections, in the following order: + +- ``prototype`` - the name of a facility prototype defined elsewhere in + the input file +- ``number`` - the number of such facilities that are operating at the + beginning of the simulation + +Put together, the institution block is the form: + +.. code-block:: XML + + + + + Prototype_name + number_of_prototype_names + + + Inst_name + + + + + +There can be multiple ``entry`` blocks within the same institution. + + +The example below +introduces two institution agents (the region section that encloses them +is not shown). The first institution has the name *SingleInstitution*, +and is configured from the archetype with the name +``NullInst``. +The ``NullInst`` has no defined archetype-specific data. +This institution begins the simulation with two +facility agents, one based on the ``FacilityA`` prototype and another +based on the ``FacilityB`` prototype. The second institution has the +name *AnotherInstitution*, is also configured from the archetype with +the name (or alias) ``NullInst``. This institution has no initial +facilities. + +.. code-block:: XML + + + + + FacilityA + 1 + + + FacilityB + 1 + + + SingleInstitution + + + + + + + AnotherInstitution + + + + + +Putting it all together, a complete region template is of the form: + +.. code-block:: XML + + + Region_name + + + + + + + Prototype_name + number_of_prototype_names + + + Inst_name + + + + + + +Activity: Write the Region template +----------------------------------- + +Using the template below, let's create the region section of our input file. + +.. code-block:: XML + + + [VALUE] + + + + + + + [VALUE] + [VALUE] + + + [VALUE] + + + + + + +Now the next part of the region template is the other facilities in the +region's fuel cycle. In our example, these facilities are +``UraniumMine``, ``EnrichmentPlant``, and ``NuclearRepository``. Using +the above exercise and the table below, fill out the rest of the region +template. + ++-----------------+-----------------------------+----------+ +| Variable | Name | Amount | ++=================+=============================+==========+ +| ``prototype`` | ``UraniumMine`` | ``1`` | ++-----------------+-----------------------------+----------+ +| ``prototype`` | ``EnrichmentPlant`` | ``1`` | ++-----------------+-----------------------------+----------+ +| ``prototype`` | ``NuclearRepository`` | ``1`` | ++-----------------+-----------------------------+----------+ +| ``name`` | ``United States Nuclear`` | ``1`` | ++-----------------+-----------------------------+----------+ + + +Check: Complete Region block ++++++++++++++++++++++++++++++++++++ + +.. code-block:: XML + + + region1 + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + + + +Activity: Save your input file +------------------------------ + +Save your input file as ``cyclus_intro_file.xml`` + + +Activity: Add an extra insitution into the Region +------------------------------------------------- +Having multiple insitutions help organize facilities and their affiliation. +Let's create region, ``USA``, that contains two institutions, ``Exelon`` and ``United States Nuclear``. +``Exelon`` is the institution that holds the ``1178MWe BRAIDWOOD-1`` reactor and ``United States Nuclear`` holds the ``UraniumMine``, ``EnrichmentPlant``, and ``NuclearRepository``. + +.. image:: RIF_tutorial.png + +Using the template above and the table below, let's build the region. + +1. Since there are two institutions, ``Exelon`` and ``United States Nuclear``, we will split the region into two parts. +Let's first build the ``Exelon`` institution. This institution has one ``1178MWe BRAIDWOOD-1`` prototype. Using this information we can write this institution as: + +.. code-block:: XML + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + Exelon + + + + + +2. Now let's build the second institution, ``United States Nuclear``. This institution has one ``UraniumMine`` prototype, ``EnrichmentPlant`` prototype, and one ``NuclearRepository`` prototype. Using this information we can write this institution as: + +.. code-block:: XML + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + +3. We will close the region section by appending the two sections together and appending a ```` tag to the end of the section. Once complete, your region prototype should look like: + +.. code-block:: XML + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + + +Activity: Save your Input File +------------------------------ + +You are now ready to generate a full |Cyclus| input file. + +1. Save your input file as 'cyclus_intro_file.xml' + + +Check: Full Input File ++++++++++++++++++++++++++++++++++++++++++++++++ +`Full input file +`_ diff --git a/_sources/user/tutorial/add_second_reactor.rst.txt b/_sources/user/tutorial/add_second_reactor.rst.txt new file mode 100755 index 000000000..5bca34dfd --- /dev/null +++ b/_sources/user/tutorial/add_second_reactor.rst.txt @@ -0,0 +1,123 @@ +Adding a second reactor +======================= + +Simple simulations can easily be expanded into more complex problems. To demonstrate this, +we will now add a second reactor, ``1000We Lightwater-1``, to our +simulation. This reactor will have a lifetime of 360 months (30 years), +cycle time of 12 months, assembly size of 30160 kg, and power capacity 1000 +MWe. Using this information, let's construct the facility input section +of this reactor. + +Activity: Second Reactor +++++++++++++++++++++++++ + +Using the reactor facility archetype and the table below, create the reactor +prototype. + ++-----------------------+---------------------------+ +| Variable | Value | ++=======================+===========================+ +| ``name`` | ``1000We Lightwater-1`` | ++-----------------------+---------------------------+ +| ``lifetime`` | ``360`` | ++-----------------------+---------------------------+ +| ``Archetype`` | ``Reactor`` | ++-----------------------+---------------------------+ +| ``fuel_incommods`` | ``fresh-uox`` | ++-----------------------+---------------------------+ +| ``fuel_inrecipes`` | ``fresh-uox`` | ++-----------------------+---------------------------+ +| ``fuel_outcommods`` | ``spent-uox`` | ++-----------------------+---------------------------+ +| ``fuel_outrecipes`` | ``spent-uox`` | ++-----------------------+---------------------------+ +| ``cycle_time`` | ``12`` | ++-----------------------+---------------------------+ +| ``refuel_time`` | ``1`` | ++-----------------------+---------------------------+ +| ``assem_size`` | ``30160`` | ++-----------------------+---------------------------+ +| ``n_assem_core`` | ``3`` | ++-----------------------+---------------------------+ +| ``n_assem_batch`` | ``1`` | ++-----------------------+---------------------------+ +| ``power_cap`` | ``1000`` | ++-----------------------+---------------------------+ + +Once complete, your reactor prototype should look like: + +.. code-block:: xml + + + 1000We Lightwater-1 + 360 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 12 + 1 + 30160 + 3 + 1 + 1000 + + + + +Append this prototype right after the ``1178MWe BRAIDWOOD-1`` prototype. + +Activity: Second reactor Institution +++++++++++++++++++++++++++++++++++++ + +We must add this second reactor into the region and facility section of +our |Cyclus| input file. To do so, go to the ``entry`` header under the +``initialfacilitylist`` section of the region block of the input file +and add + +.. code-block:: xml + + + 1000We Lightwater-1 + 1 + + +below the ``1178MWe BRAIDWOOD-1`` entry block. The Reactor section +of the region block should now look like, + +.. code-block:: xml + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + 1000We Lightwater-1 + 1 + + + Exelon Reactors + + + + + + + + +Note: the blank space between ```` and ```` is +for additional institutions in the future. + +Save your input file as input_file2.xml and run the |Cyclus| simulation. +If your simulation runs into errors, sample files can be found `here +`_ under ``input_secondreactor.xml`` +or ``ouput_secondreactor.sqlite``. diff --git a/_sources/user/tutorial/add_sep.rst.txt b/_sources/user/tutorial/add_sep.rst.txt new file mode 100755 index 000000000..927c6a3cb --- /dev/null +++ b/_sources/user/tutorial/add_sep.rst.txt @@ -0,0 +1,94 @@ +Adding a Separations Facility +================================ + +The separations facility will request all the commodities in its Feed +Commodity List, and separate them into any number of streams, plus a waste +stream. + +The following is the input template for ``Cycamore::Separations`` archetype: + +.. code-block:: XML + + + SeparationsFacility + + + + _______ + + + _______ + + _______ + _______ + _______ + _______ + + + _______ + + _______ + + + _______ + _______ + + + + + + + + + +* Our feed commodity list should include both: + * Used-UOX-Fuel + * Used-MOX-Fuel +* The maximum feed inventory is the most feed material that we'll have on + hand: 1000 tonnes. +* The maxium separations throughout is the size of our plant: 80 tonnes/timestep +* This simple scenario will have a single output stream: Separated-Fissile + * we will hold no more than 5 tonnes of separated material on hand at any time + * 99% of all Pu (94000) will go into that stream +* all other material will go to Separated-Waste + +Filling in the template, the input block looks like: + +.. code-block:: XML + + + SeparationsFacility + + + + spent-uox + used-mox + + + 1.0 + 1.0 + + 1000E+3_ + 80e+3 + Separated-Waste + 1000e+3 + + + Separated-Fissile + + 5e+3 + + + 94000 + 0.99 + + + + + + + + + diff --git a/_sources/user/tutorial/cyclist_tour.rst.txt b/_sources/user/tutorial/cyclist_tour.rst.txt new file mode 100755 index 000000000..e61c2b9e8 --- /dev/null +++ b/_sources/user/tutorial/cyclist_tour.rst.txt @@ -0,0 +1,17 @@ +A Tour of the Cyclist User Interface +===================================== + +The Cyclist user interface has four main areas: + +* A **menu** bar, like many applications you have used in the past +* A **workspace** that currently has two modes: + * Scenario Builder: to build a particular fuel cycle scenario + * Data Exploration: to explore the output of a particular scenario or set of scnearios +* A set of **tools** that can be imported into the workspace +* A **message window** in which Cyclist may occasionally report updates. + +.. image:: cyclist_tour_annotated.png + :align: center + :width: 100% + :alt: Annotated view of Cyclist upon loading + diff --git a/_sources/user/tutorial/cyclus_tour.rst.txt b/_sources/user/tutorial/cyclus_tour.rst.txt new file mode 100755 index 000000000..852356afc --- /dev/null +++ b/_sources/user/tutorial/cyclus_tour.rst.txt @@ -0,0 +1,16 @@ +A Tour of the Cyclus User Interface with Jupyter Notebook +========================================================= + +A Jupyter notebook has four main areas: + +* A **Run** button that runs the cell you're in +* A **Up and Down** buttons that move the cell up or down +* A vertical blue line that shows what cell you're currently active in +* A **Stop** button that stops running the cell you're in + +.. image:: ipython_tour.png + :align: center + :width: 100% + :alt: Annotated view of an IPython notebook upon loading + +The Github Repository that holds this tutorial is at https://github.com/arfc/cyclus-tutorial diff --git a/_sources/user/tutorial/cyclus_tutorial_recap.rst.txt b/_sources/user/tutorial/cyclus_tutorial_recap.rst.txt new file mode 100755 index 000000000..3f03fff59 --- /dev/null +++ b/_sources/user/tutorial/cyclus_tutorial_recap.rst.txt @@ -0,0 +1,1202 @@ +Cyclus Tutorial Recap +===================== +Below are complete input files for each of the exercises performed in this +tutorial. + + +Basic Tutorial Input +-------------------- + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + agents + NullRegion + + + agents + NullInst + + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + NuclearRepository + + + + spent-uox + tails + + + + + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + + + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + + + + + +Add a Second Reactor Input +-------------------------- + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + agents + NullRegion + + + agents + NullInst + + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + 1000We Lightwater-1 + 360 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 12 + 1 + 30160 + 3 + 1 + 1000 + + + + + + NuclearRepository + + + + spent-uox + tails + + + + + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + 1000We Lightwater-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + + + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + + + +Recycle Input +----------------- + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + cycamore + FuelFab + + + cycamore + Separations + + + agents + NullRegion + + + agents + NullInst + + + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + + used-mox-fuel + 1.0 + + + fresh-mox + 1.0 + + + separated-fissile + 1.0 + + + separated-waste + 1.0 + + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + 1000MWe Lightwater-1 + 360 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 12 + 1 + 33000 + 3 + 1 + 1000 + + + + + + uox-mox-reprocessing + + + + used-mox-fuel + spent-uox + + + 1.0 + 1.0 + + 1000e+3 + 80e+3 + separated-waste + + + separated-fissile + + 5e+4 + + + Pu .99 + + + + + + + + + + + + + + u-ore + + nat-u + 1000e+3 + + 1 + + + separated-fissile + + 5e+4 + fresh-mox + thermal + 2e+3 + + + uox-mox-fuel-fab + + + + 1000MWe ALWR-1 + 360 + + + + fresh-uox + fresh-mox + + + fresh-uox + fresh-uox + + + 1.0 + 2.0 + + + spent-uox + used-mox-fuel + + + spent-uox + used-mox + + 18 + 1 + 33000 + 3 + 1 + 1000 + + + + + + + NuclearRepository + + + + spent-uox + tails + separated-waste + + + + + + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + 1000MWe Lightwater-1 + 1 + + + 1000MWe ALWR-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + uox-mox-reprocessing + 1 + + + uox-mox-fuel-fab + 1 + + + United States Nuclear + + + + + + + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + used-mox + mass + + 92235 + 0.002 + + + 92238 + 0.94 + + + 94239 + 0.01 + + + 94240 + 0.002 + + + 55137 + 0.046 + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + + + + + +DeployInst Input +----------------- + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + cycamore + FuelFab + + + cycamore + Separations + + + cycamore + DeployInst + + + agents + NullRegion + + + agents + NullInst + + + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + + used-mox-fuel + 1.0 + + + fresh-mox + 1.0 + + + separated-fissile + 1.0 + + + separated-waste + 1.0 + + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + 1000MWe Lightwater-1 + 360 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 12 + 1 + 33000 + 3 + 1 + 1000 + + + + + + uox-mox-reprocessing + + + + used-mox-fuel + spent-uox + + + 1.0 + 1.0 + + 1000e+3 + 80e+3 + separated-waste + + + separated-fissile + + 5e+4 + + + Pu .99 + + + + + + + + + + + + + + u-ore + + nat-u + 1000e+3 + + 1 + + + separated-fissile + + 5e+4 + fresh-mox + thermal + 2e+3 + + + uox-mox-fuel-fab + + + + 1000MWe ALWR-1 + 360 + + + + fresh-uox + fresh-mox + + + fresh-uox + fresh-uox + + + 1.0 + 2.0 + + + spent-uox + used-mox-fuel + + + spent-uox + used-mox + + 18 + 1 + 33000 + 3 + 1 + 1000 + + + + + + + NuclearRepository + + + + spent-uox + tails + separated-waste + + + + + + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + 1000MWe Lightwater-1 + 1 + + + 1000MWe ALWR-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + uox-mox-reprocessing + 1 + + + uox-mox-fuel-fab + 1 + + + United States Nuclear + + + + + + ExampleInsitution + + + + UraniumMine + FuelFab + 1178MWe BRAIDWOOD-1 + 1000MWe Lightwater-1 + + + 1 + 1 + 2 + 3 + + + 1 + 1 + 1 + 1 + + + + + + + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + used-mox + mass + + 92235 + 0.002 + + + 92238 + 0.94 + + + 94239 + 0.01 + + + 94240 + 0.002 + + + 55137 + 0.046 + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + + + diff --git a/_sources/user/tutorial/data_explorer.rst.txt b/_sources/user/tutorial/data_explorer.rst.txt new file mode 100755 index 000000000..0209b9b40 --- /dev/null +++ b/_sources/user/tutorial/data_explorer.rst.txt @@ -0,0 +1,636 @@ +An Introduction to Data Exploration +===================================== + +Cymetric provides a way to fluidly explore the +data that arises from a |cyclus| simulation. A variety of metrics, plots, and information can be +manipulated and viewed in a straightforward and interactive way to develop a thorough +understanding of the features that matter the most. + +Concept: Cyclus Output file +--------------------------- +|Cyclus| creates an SQLite (``.sqlite``) database file as its output. SQLite is a database file +type that consists of a series of tables. A few functions have been +included in ``analysis.py``, a file in downloaded the github repository of this tutorial, to pull information from the sqlite +database and create figures. + +An sqlite database can be opened by viewers like ``sqlitebrowser`` or ``sqliteman``, +but these database browsers aren't intended for powerful analysis. +Importing the data into an external function and analyzing it +is a more powerful approach. However, it can still be helpful to +open and view the tables. + +Analyze the results: +~~~~~~~~~~~~~~~~~~~~ + + +This is a view of the tables within the database +(using DB browser for SQLite). To view the data within these +tables, switch to the **Browse Data** tab and select the table of interest. +Some tables have data that may need to be manipulated or used alongside +other data in other tables, which is why using a python script is often +ideal. + +.. code:: ipython3 + + from pyne import nucname + import write as write + import analysis as analysis + import matplotlib.pyplot as plt + import numpy as np + from numpy import isclose + import matplotlib.pyplot as plt + + +.. parsed-literal:: + + Usage: python write_input.py [csv][init_date] [duration] [output_file_name] + + +First, a *cursor* that points to the sqlite file is created to the output file. A *cursor* points to the cyclus output file you wish to use and its commonly used when running analysis functions as it 'bookmarks' the file you wish to analyze. + +1. To make a cursor, use the ``analysis.cursor(output_filename)`` function where output_filename is name of the cyclus output file. + +.. code:: ipython3 + + cur = analysis.cursor('cyclus.sqlite') + +Simulation Time Info +-------------------- + +.. code:: ipython3 + + init_year, init_month, duration, timestep = analysis.simulation_timesteps(cur) + print('Start year:' + str(init_year)) + print('Start month:' + str(init_month)) + print('Duration of simulation months:' + str(duration)) + print('List of timesteps:' + str(timestep[0:3]) +' . . . ' +str(timestep[-4:-1])) + + + +.. parsed-literal:: + + Start year:2018 + Start month:1 + Duration of simulation months:720 + List of timesteps:[ 0. 1. 2.] . . . [ 716. 717. 718.] + + +.. code:: ipython3 + + # prints maximum required sfr fuel throughput per timestep + fuel = cur.execute('SELECT time, sum(quantity) FROM transactions ' + 'INNER JOIN resources ON resources.resourceid = ' + 'transactions.resourceid WHERE commodity = "fresh-uox"' + ' GROUP BY time').fetchall() + + fresh_uox = np.array(fuel) + fuel_transaction = [fuel[1] for fuel in fresh_uox] + fuel_timestep = [fuel[0] for fuel in fresh_uox] + + maximum_fuel_moved = np.amax(np.array(fuel)) + print('Maximum amount of fresh-uox moved: ' + str(maximum_fuel_moved)) + + first_fuel_transaction = np.array(fuel)[0][1] + print('Amount of fresh-uox moved at first timestep: ' + str(first_fuel_transaction)) + #print(max(analysis.simulation_timesteps(fuel, duration, True))) + + plt.plot(fuel_timestep,fuel_transaction) + plt.xlabel('Time (months)') + plt.ylabel('Mass of Fresh-uox moved (kg)') + plt.title('Fresh-uox transaction timeseries') + + +.. parsed-literal:: + + Maximum amount of fresh-uox moved: 99000.0 + Amount of fresh-uox moved at first timestep: 99000.0 + + + + +.. parsed-literal:: + + Text(0.5,1,'Fresh-uox transaction timeseries') + + + + +.. image:: output_6_2.png + + +Activity: Track Uranium ++++++++++++++++++++++++ + +Total mass traded +^^^^^^^^^^^^^^^^^ + +How much :math:`^{235}`\ U left the 1178MWe BRAIDWOOD-1? To find out, +lets use the ``total_isotope_traded`` function! The +``total_isotope_traded`` takes three input arguments: - cur (cursor to +*CYCLUS* output file) - facility (facility of interest) - flux +(direction of isotope transaction) - nucid (nuclide id) + +.. raw:: html + +
+ +**Interactive Input** Using the table below, create the following +variables. Include appropriate comments. + +.. raw:: html + +
+ ++----------------+-----------------------------+----------------------------------+ +| Variable | Value | Purpose | ++================+=============================+==================================+ +| ``cur`` | ``cur`` | cursor to *CYCLUS* output file | ++----------------+-----------------------------+----------------------------------+ +| ``facility`` | ``'1178MWe BRAIDWOOD-1'`` | facility of interest | ++----------------+-----------------------------+----------------------------------+ +| ``flux`` | ``'out'`` | isotope transaction direction | ++----------------+-----------------------------+----------------------------------+ +| ``nucid`` | ``922350000`` | nuclide id | ++----------------+-----------------------------+----------------------------------+ + + +Using the table above, let's find out how much :math:`^{235}`\ U left the 1178MWe BRAIDWOOD-1? +1. In your IPython notebook create the variables: + +* ``facility`` that is equal to ``'1178MWe BRAIDWOOD-1'`` +* ``flux`` that is equal to ``'out'`` +* ``nucid`` that is equal to ``922350000`` + +.. code:: ipython3 + + cur = cur # cursor to CYCLUS output file + facility = '1178MWe BRAIDWOOD-1' # facility of interest + flux = 'out' # isotope transaction direction + nucid = 922350000 # nuclide id + print('Total amount of U235 that left the '+ str(facility) +' reactor:') + analysis.total_isotope_traded(cur,facility,flux,nucid) + + +2. When ready, click the ``run`` button. + +3. As you see the answer is: + +.. parsed-literal:: + + Total amount of U235 that left the 1178MWe BRAIDWOOD-1 reactor: + + + + +.. parsed-literal:: + + 13431.0 + + + + +Activity: Plot SNF Mass ++++++++++++++++++++++++ +Now let's plot the cumulative mass of the spent nuclear fuel that is +taken out of the 1178MWe BRAIDWOOD-1. Again, let's use the handy +``analysis.plot_out_flux_cumulative``\ function which takes input +arguments: - cur (cursor to *CYCLUS* output file) - facility (facility +of interest) - title (title of plot) + +.. raw:: html + +
+ +**Interactive Input** Using the table below, create the following +variables. Include appropriate comments. + +.. raw:: html + +
+ ++----------------+-----------------------------------------------------------+----------------------------------+ +| Variable | Value | Purpose | ++================+===========================================================+==================================+ +| ``cur`` | ``cur`` | cursor to *CYCLUS* output file | ++----------------+-----------------------------------------------------------+----------------------------------+ +| ``facility`` | ``'1178MWe BRAIDWOOD-1'`` | facility of interest | ++----------------+-----------------------------------------------------------+----------------------------------+ +| ``title`` | ``'Cumulative Isotope Outflux of 1178MWe BRAIDWOOD-1'`` | title of plot | ++----------------+-----------------------------------------------------------+----------------------------------+ + +.. code:: ipython3 + + plt.rcParams['figure.figsize'] = [10, 8] + plt.rcParams['legend.fontsize'] = 12 + facility = '1178MWe BRAIDWOOD-1' + title = 'Cumulative Isotope Outflux of 1178MWe BRAIDWOOD-1' + analysis.plot_out_flux_cumulative(cur, facility, title) + + + +Activity: Plot Fresh Fuel Mass +++++++++++++++++++++++++++++++ + Now let's plot the cumulative mass of the fresh nuclear fuel that is + put into the 1178MWe BRAIDWOOD-1. Again, let's use + ``analysis.plot_in_flux`` which takes the arguments: + + * cur + * facility = ``'1178MWe BRAIDWOOD-1'`` + * title = ``'Cumulative Isotope Influx of 1178MWe BRAIDWOOD-1'`` + +.. code:: ipython3 + + facility = '1178MWe BRAIDWOOD-1' + title = 'Cumulative Isotope Influx of 1178MWe BRAIDWOOD-1' + analysis.plot_in_flux(cur, facility, title) + + + +.. parsed-literal:: + + The agent_id for Reactor is: + + + + +.. parsed-literal:: + + ['21'] + + + +In cyclus, facilities are defined by their ``prototype_id``. For example +if the simualtion had 20 different reactors, we could still find a +certain one via its ``prototype_id``. + +.. raw:: html + +
+ +**Interactive Input** In the cell below use type, find the prototype\_id +of the ``'1178MWe BRAIDWOOD-1'`` reactor by making variable called: +``facility`` and making it equal to ``'1178MWe BRAIDWOOD-1'`` and then +run the cell. + +.. raw:: html + +
+ +.. code:: ipython3 + + facility = '1178MWe BRAIDWOOD-1' + print('The prototype_ids for' + ' ' + facility + ' ' +'' + 'are:') + analysis.prototype_id(cur, facility) + + +.. parsed-literal:: + + The prototype_ids for 1178MWe BRAIDWOOD-1 are: + + + + +.. parsed-literal:: + + ['21'] + + + +Let's find out what the ``prototype_id`` for the ``'UraniumMine'`` in +our simulation is. + +.. code:: ipython3 + + facility = 'UraniumMine' + print('The prototype_ids for' + ' ' + facility + ' ' +'' + 'are:') + analysis.prototype_id(cur, facility) + + +.. parsed-literal:: + + The prototype_ids for UraniumMine are: + + + + +.. parsed-literal:: + + ['23'] + + + +We can use these agent\_ids and prototype\_ids to find out more +information on these facilities. For example, let's say we wanted to +find out how much ``'fresh-uox'`` goes through the +``'1178MWe BRAIDWOOD-1'`` reactor? We can use the +``facility_commodity_flux`` function to find out. + +.. raw:: html + +
+ +**Interactive Input** Using the table below, create the following +variables. Include appropriate comments. + +.. raw:: html + +
+ ++----------------------------+---------------------+------------------------------------+ +| Variable | Value | Purpose | ++============================+=====================+====================================+ +| ``cur`` | ``cur`` | cursor to *CYCLUS* output file | ++----------------------------+---------------------+------------------------------------+ +| ``agentids`` | ``[21]`` | ``agent_id`` of reactor | ++----------------------------+---------------------+------------------------------------+ +| ``facility_commodities`` | ``['fresh-uox']`` | commodity of interest | ++----------------------------+---------------------+------------------------------------+ +| ``is_cum`` | True | cumulative of commodity amount | ++----------------------------+---------------------+------------------------------------+ +| ``is_outflux`` | False | Influx of commodity into reactor | ++----------------------------+---------------------+------------------------------------+ + +.. code:: ipython3 + + analysis.facility_commodity_flux(cur,agentids=[21],facility_commodities=['fresh-uox'],is_cum=True,is_outflux=False) + + + + + + +As seen above, the ``facility_commodity_flux`` function returns a +dictionary of the cumulative amount of ``fresh-uox`` fuel that enters +the reactor over time. We can make this dictionary non-cumulative by +setting ``is_cum = False`` as seen below. + +.. code:: ipython3 + + analysis.facility_commodity_flux(cur,agentids=[21],facility_commodities=['fresh-uox'],is_cum=False,is_outflux=False) + + + + + +.. code:: ipython3 + + analysis.facility_commodity_flux(cur,agentids=[21],facility_commodities=['fresh-uox'],is_cum=True,is_outflux=False) + +As expected, the only time that ``fresh-uox`` enters the reactor is at +times where the reactor is being refueled. + +Now, let's plot the storage of the sink over time to see what +commodities are stored in the sink. + +Let's take a look at the total mass of spent nuclear fuel stored at the +Nuclear Waste Repository. To plot, use the +``analysis.plot_in_flux_cumulative(cur, facility, title)`` function. + +.. raw:: html + +
+ +**Interactive Input** Using the table below, create the following +variables. Include appropriate comments. + +.. raw:: html + +
+ ++----------------+----------------------------------------------------+------------------------+ +| Variable | Value | Purpose | ++================+====================================================+========================+ +| ``facility`` | ``'NuclearRepository'`` | facility of interest | ++----------------+----------------------------------------------------+------------------------+ +| ``title`` | ``'Cumulative Isotope Inventory of Repository'`` | title of plot | ++----------------+----------------------------------------------------+------------------------+ + +.. code:: ipython3 + + facility = 'NuclearRepository' # facility of interest + title = 'Cumulative Isotope Inventory of Repository' # title of plot + + analysis.plot_commodities(cur,archetype='sink',facility_commodity=['tails','spent-uox'],title = 'Sink storage', + filename='sink',is_cum=True,is_outflux=False) + from IPython.display import Image + Image(filename='sink.png') + + + + +.. image:: output_31_0.png + + + +Now let's plot the cumulative mass of the spent nuclear fuel that is +mined from the Uranium mine. To plot the outflux of a facility, use the +analysis.plot\_out\_flux\_cumulative(cur,sender,plot title) function. + +.. code:: ipython3 + + analysis.plot_out_flux_cumulative(cur, 'UraniumMine','Cumulative Isotope Outflux of Uranium Mine') + + + + +.. image:: output_33_0.png + + +.. code:: ipython3 + + analysis.plot_out_flux_cumulative(cur, '1178MWe BRAIDWOOD-1','Cumulative Isotope Outflux of 1178MWe BRAIDWOOD-1') + + + +.. image:: output_34_0.png + + +Now let's plot the mass series and cumulative mass of the fresh nuclear +fuel that is received by the 1178MWe BRAIDWOOD-1. + +.. code:: ipython3 + + analysis.plot_in_flux(cur, '1178MWe BRAIDWOOD-1','Isotope Influx of 1178MWe BRAIDWOOD-1') + analysis.plot_in_flux_cumulative(cur, '1178MWe BRAIDWOOD-1','Cumulative Isotope Influx of 1178MWe BRAIDWOOD-1') + + + +.. image:: output_36_0.png + + + +.. image:: output_36_1.png + + +We can also find the total amount [kg] of an isotope that was used/sent +from a facility using the ``total_isotope_used`` function. For example, +if we wanted to find out how much :math:`^{235}`\ U and +:math:`^{238}`\ U was mined from the Uranium Mine, we can call: + +.. code:: ipython3 + + uranium_mined = analysis.total_isotope_used(cur, 'UraniumMine') + print("Total amount of U-235 mined:" + ' ' + str(uranium_mined['U235']) + ' ' + 'kg') + print("Total amount of U-238 mined:" + ' ' + str(uranium_mined['U238']) + ' ' + 'kg') + + + +.. parsed-literal:: + + Total amount of U-235 mined: 91599.6350365 kg + Total amount of U-238 mined: 12791612.0438 kg + + +Let's say we wanted to see the composition of the spent nuclear fuel +from the reactor. We could call ``total_isotope_used`` with ``facility`` += ``'1178MWe BRAIDWOOD-1'`` to find out! + +.. raw:: html + +
+ +**Interactive Input** Using the table below, create the following +variable. Include appropriate comments. + +.. raw:: html + +
+ ++----------------+-----------------------------+------------------------+ +| Variable | Value | Purpose | ++================+=============================+========================+ +| ``facility`` | ``'1178MWe BRAIDWOOD-1'`` | facility of interest | ++----------------+-----------------------------+------------------------+ + +.. code:: ipython3 + + facility = '1178MWe BRAIDWOOD-1' # facility of interest + snf_comp = analysis.total_isotope_used(cur, facility) + snf_comp + isotopes = [item[0] for item in snf_comp.items()] + masses = [item[1] for item in snf_comp.items()] + plt.bar(isotopes,masses) + plt.xlabel('Isotopes') + plt.ylabel('Total Mass [kg]') + plt.title('SNF mass composition') + + + + +.. parsed-literal:: + + Text(0.5,1,'SNF mass composition') + + + + +.. image:: output_40_1.png + + +.. code:: ipython3 + + analysis.plot_uranium_utilization(cur) + + + +.. image:: output_41_0.png + + +.. code:: ipython3 + + fuel_dict = analysis.fuel_usage_timeseries(cur, ['fresh-uox']) + fuel_dict + analysis.stacked_bar_chart(fuel_dict, timestep, + 'Years', 'Mass[MTHM]', + 'Total Fresh-Uox Fuel Mass vs Time', + 'total_fuel', + init_year) + from IPython.display import Image + Image(filename='total_fuel.png') + + + + +.. image:: output_42_0.png + + + +.. code:: ipython3 + + # natural uranium demand + import collections + nat_u = collections.OrderedDict() + nat_u['nat_u'] = analysis.nat_u_timeseries(cur) + analysis.stacked_bar_chart(nat_u, timestep, + 'Years', 'Natural Uranium Mass', + 'Natural Uranium Demand vs Time', + 'nat_u', init_year) + from IPython.display import Image + Image(filename='nat_u.png') + + + + +.. image:: output_43_0.png + + + +Ask: Why is the orange line steeper in slope than the green line? +----------------------------------------------------------------- + +.. code:: ipython3 + + tails = cur.execute('SELECT time, sum(quantity) FROM transactions ' + 'INNER JOIN resources ON resources.resourceid = ' + 'transactions.resourceid WHERE commodity = "tails"' + ' GROUP BY time').fetchall() + + tails_array = np.array(fuel) + tails_transaction = [tail[1] for tail in tails_array] + tails_timeseries = [fuel[0] for fuel in tails_array] + + maximum_fuel_moved = np.amax(tails_array) + print('Maximum amount of tails moved during one time step: ' + str(maximum_fuel_moved)) + + analysis.plot_commodities(cur,archetype='sink',facility_commodity=['tails'],title='Tails in Sink',filename='tails',is_cum=True,is_outflux=False) + from IPython.display import Image + Image(filename='tails.png') + + +.. parsed-literal:: + + Maximum amount of tails moved during one time step: 99000.0 + + + + +.. image:: output_45_1.png + + + +Decay heat +---------- + +Using our ``spent`` fuel composition from above, lets see which isotope +causes the most decay heat! + +.. code:: ipython3 + + analysis.plot_reactor_events(cur,reactors = []) + + + + +.. image:: output_47_0.png + + +.. code:: ipython3 + + analysis.plot_commodity(cur,archetype='Sink',facility_commodity=['spent-uox'],is_outflux=False,is_cum=True) + from IPython.display import Image + Image(filename='cum_mass_spent-uoxdischarge.png') + + + + +.. image:: output_48_0.png diff --git a/_sources/user/tutorial/full_input_1.rst.txt b/_sources/user/tutorial/full_input_1.rst.txt new file mode 100755 index 000000000..f5a123925 --- /dev/null +++ b/_sources/user/tutorial/full_input_1.rst.txt @@ -0,0 +1,199 @@ + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + + + cycamore + Enrichment + + + cycamore + Reactor + + + cycamore + Source + + + cycamore + Sink + + + agents + NullRegion + + + agents + NullInst + + + + + + u-ore + 1.0 + + + fresh-uox + 1.0 + + + tails + 1.0 + + + spent-uox + 1.0 + + + + nat-u + mass + + 92235 + 0.00711 + + + 92238 + 0.99289 + + + + + fresh-uox + mass + + 92235 + 0.04 + + + 92238 + 0.96 + + + + + spent-uox + mass + + 92235 + 0.011 + + + 92238 + 0.94 + + + 94239 + 0.009 + + + 55137 + 0.04 + + + + + + UraniumMine + + + u-ore + + + + + + EnrichmentPlant + + + u-ore + nat-u + fresh-uox + tails + 1000000 + + + + + + 1178MWe BRAIDWOOD-1 + + + fresh-uox + fresh-uox + spent-uox + spent-uox + 18 + 1 + 33000 + 3 + 1 + 1178 + + + + + + NuclearRepository + + + + spent-uox + tails + + + + + + + + USA + + + + + + + 1178MWe BRAIDWOOD-1 + 1 + + + Exelon + + + + + + + + + UraniumMine + 1 + + + EnrichmentPlant + 1 + + + NuclearRepository + 1 + + + United States Nuclear + + + + + + + diff --git a/_sources/user/tutorial/future_work.rst.txt b/_sources/user/tutorial/future_work.rst.txt new file mode 100755 index 000000000..b3a6698b5 --- /dev/null +++ b/_sources/user/tutorial/future_work.rst.txt @@ -0,0 +1,25 @@ +Future work +=========== + +Work needs to be made on files: + - Prior typos found and fixed but many more may remain + - install_launch_cyclus.rst + - Links to cyclus download need to be made available as current links are to cyclist download + - Undefined substitution referenced: "Cyclus" on many files + - add_reg_inst.html + - More content needed on regions and institutions + - run_cyclus_native needs to be more thought out + - names of file names and output files needs to be addressed earlier in the tutorial + - data_explorer.rst + - More content needs to be added, See cyclus tutorial IPython notebook for more content + - plot_output.rst needs to be repurposed or deleted entirely + +Symbol Table + + +-------------+-------------------------+ + | Variable | Purpose | + +=============+=========================+ + | **???** | I don't know how to fix | + +-------------+------------------+------+ + | **!!!** | More content needed | + +-------------+------------------+------+ diff --git a/_sources/user/tutorial/index.rst.txt b/_sources/user/tutorial/index.rst.txt new file mode 100755 index 000000000..855e5c9a6 --- /dev/null +++ b/_sources/user/tutorial/index.rst.txt @@ -0,0 +1,61 @@ +|Cyclus| User Tutorial +====================== + +In this tutorial, we will build, run and analyze a fuel cycle scenario using +|Cyclus|, a nuclear fuel cycle simulator. This tutorial assumes that the learner is already +familiar with the purpose of a nuclear fuel cycle simulator. This tutorial will +require an internet connection so that |Cyclus| can be run remotely. + +Overview +--------- + +During this tutorial, we will create two separate fuel cycle scenarios: + +1. A simple once-through scenario: The purpose of this exercise is to + introduce the basic concepts of |Cyclus| and the layout of the user + interface. + +2. A MOX recycle scenario with growing energy demand: The purpose of this + exercise is to demonstrate a more complete set of current capabilities. + +Exercise #1 +------------ + +.. toctree:: + :maxdepth: 2 + + install_launch_cyclus + sim_parm + add_arche + add_commod_recipe + add_proto + add_reg_inst + launch_cyclus + run_cyclus_native + add_second_reactor + +Exercise #2 +------------- + +The description of this exercise will be described with less detail and more +flexibility than the previous exercise. This should allow you to test your +new-found knowledge, learn to explore your own analysis, and try some things +on your own, all with the support of the Cyclus development team. + + +.. toctree:: + :maxdepth: 1 + + add_arche_commod_recipe + add_sep + add_fab + mod_rxtr + add_deploy + +Recap +----- + +.. toctree:: + :maxdepth: 1 + + cyclus_tutorial_recap diff --git a/_sources/user/tutorial/install_launch_cyclist.rst.txt b/_sources/user/tutorial/install_launch_cyclist.rst.txt new file mode 100755 index 000000000..9a4fe55ff --- /dev/null +++ b/_sources/user/tutorial/install_launch_cyclist.rst.txt @@ -0,0 +1,34 @@ +Installing and Launching Cyclist +================================= + +For this tutorial, we only require the Cyclist user interface. You can +install Cyclist using the following steps: + +**Windows** + +1. Download `this Windows installer `_. +2. Find the downloaded file and double-click to start the install. +3. Once complete go the the "Start" menu and type "Cyclist". +4. Click on the icon to start Cyclist. + +**Mac OSX** + +1. Download `this Mac OSX installer `_. +2. Click OK when asked to open the .dmg file. +3. Drag the cyclist icon to the Desktop folder icon. +4. Click on the icon to start Cyclist. + +**Linux (Ubuntu/Debian)** + +1. Download `this package `_. +2. Find the downloaded file and double-click to start the install. +3. Once complete search for the Cyclist application and start it. + + + +**Try a Tutorial!** + +To become familiar with the capabilities of |Cyclus|, read the :doc:`User's +Guide` or work your way through the :doc:`Cyclus User Tutorial `. + + diff --git a/_sources/user/tutorial/install_launch_cyclus.rst.txt b/_sources/user/tutorial/install_launch_cyclus.rst.txt new file mode 100755 index 000000000..36e9c0e7e --- /dev/null +++ b/_sources/user/tutorial/install_launch_cyclus.rst.txt @@ -0,0 +1,10 @@ +Installing and Launching Cyclus +=============================== + +For this tutorial, the |Cyclus|, and Cycamore programs are utilized. You can +install |Cyclus| using the following steps listed on the `Install Cyclus `_ page. +You can install Cycamore from the `Cycamore github repository `_. It is not required to +install these programs because there is a cloud service available to running |Cyclus| input files, as discussed +`here `_. + + diff --git a/_sources/user/tutorial/ipython_tour.rst.txt b/_sources/user/tutorial/ipython_tour.rst.txt new file mode 100755 index 000000000..08be4ff9e --- /dev/null +++ b/_sources/user/tutorial/ipython_tour.rst.txt @@ -0,0 +1,50 @@ +Using Cyclus with Jupyter Notebook +========================================================= +For more ease of running Cyclus input files and managing the output +files, the **Jupyter Notebook** tool can be utilized. + +Why is it useful? +----------------- + +A user can input the code required to run the simulation and analyze +its output in one **Jupyter Notebook** with clear descriptions. + +Here is a tutorial on how to get `Jupyter Notebook `_ set up on your +computer. + +Brief Introduction to Jupyter Notebook +-------------------------------------- + +A Jupyter notebook has four main areas: + +* A **Run** button that runs the cell you're in +* A **Up and Down** buttons that move you up or down a cell +* A vertical blue line that shows what cell you're currently in +* A **Stop** button that stops running the cell you're in + +.. image:: ipython_tour.png + :align: center + :width: 100% + :alt: Annotated view of an Jupyter notebook upon loading + +Jupyter Notebook Scenario Execution +-------------------------------------------- +1. Go to the Jupyter notebook +2. Remove any old cyclus output files by: ``!rm tutorial.sqlite`` +3. Run CYCLUS by: ``!cyclus input.xml -o tutorial.sqlite`` + +.. image:: cyclus_in_IP.png + :align: center + :alt: Running CYCLUS in an IPython Notebook + +Retrieve your Results for Analysis +---------------------------------- +When your simulation has finished, a file of the name ``tutorial.sqlite`` will be in your file folder + +Backup: Files for Success +++++++++++++++++++++++++++ + +If your run did not succeed, you can retrieve these files to continue: + +* `Successful input file `_ +* `Successful output db file `_ diff --git a/_sources/user/tutorial/launch_cyclus.rst.txt b/_sources/user/tutorial/launch_cyclus.rst.txt new file mode 100755 index 000000000..a6536a7cf --- /dev/null +++ b/_sources/user/tutorial/launch_cyclus.rst.txt @@ -0,0 +1,55 @@ +Using |Cyclus| in the Cloud +================================= + +Choosing Where to Run +----------------------- +For this tutorial, there are 2 options for places to run the |Cyclus| simulation. + +1. Our cloud resource where |Cyclus| is installed. + +2. A `Jupyter Notebook `_ +in the local machine where you have |Cyclus| installed. + +The advantage of using your local machine is that you can determine which +version of |Cyclus| you want to use and if you wanted to include archetypes +that are not available on the cloud resource. The advantage of using a remote +machine is that you don't have to install the entire |Cyclus| toolset on your +local machine. + +For this tutorial, the cloud resource has been made available at +``_. This is the same resources that is used to run |Cyclus| +from the |Cyclus| home page. If it is desired to run |Cyclus| on your local +machine, then this section of the tutorial can be skipped. + +Execute your Scenario in the Cloud +++++++++++++++++++++++++++++++++++++++++++++ + +1. Open the XML input file that you created in Exercise 1 +2. Go to the Server: http://cycrun.fuelcycle.org +3. Copy and paste the input file content into the window +4. Click the "Submit" button +5. This will launch a job and show you the "Job Id" + +.. image:: cycrun.png + :align: center + :alt: Job status is shown when executing in the cloud + +Retrieve your Results for Analysis +++++++++++++++++++++++++++++++++++++++++++++++ + +1. When your simulation in the cloud has finished, it will indicate in the + Jobs pane. + +.. image:: cycrun_final.png + :align: center + :alt: Job status is shown when executing in the cloud + +2. Right-click on the job number's Output result and download the output file. + +Backup: Files for Success +++++++++++++++++++++++++++ + +If your run did not succeed, you can retrieve correct input and output files `here +`_ under ``input_oncethrough.xml`` +or ``ouput_oncethrough.sqlite``. This link contains input and +output files for each of the examples in this tutorial. diff --git a/_sources/user/tutorial/mod_rxtr.rst.txt b/_sources/user/tutorial/mod_rxtr.rst.txt new file mode 100755 index 000000000..8ccf6828a --- /dev/null +++ b/_sources/user/tutorial/mod_rxtr.rst.txt @@ -0,0 +1,45 @@ +Updating the Reactor and Repository +===================================== + +We can add in Advanced Light Water Reactors that will flexibly switch between +UOX and MOX fuel based on their availability. This protoype uses the same +template as the other reactors with a few additional entries. + +Reactor Modifications +---------------------- + +Add additional entries for: + +* Fresh Fuel Commodity: Fresh-MOX-Fuel [#f1]_ +* Fresh Fuel Recipe: Fresh-UOX-Fuel +* Spent Fuel Commidity: Used-MOX-Fuel +* Used Fuel Recipe: Used-MOX-Fuel-4 + + + +Under user level 1, add 2 entries for the "Fresh Fuel Preference List, +one for each requested commodity. Since MOX fuel is preferred, the +preference for MOX should be 2 times higher than that or UOX. Perhaps: + +* MOX = 2 +* UOX = 1 + +The new reactor must be added to the ``Exelon Reactors`` institution in the region. + + +Repository Modifications +-------------------------- +Add an accepted commodity for the repository to be Separated-Waste. + +Activity: Save your Input File +-------------------- +The input for this example is now complete. Save your input file as 'recycle_input.xml'. If +your simulation runs into errors, sample files can be found `here +`_ under ``input_recycle.xml`` +or ``ouput_recycle.sqlite``. + + +.. rubric:: Footnotes + +.. [#f1] Note that we are using the UOX recipe for the MOX recipe in order to have +our fuel fabrication facility do its best to match that recipe by blending streams of Pu with natural U. diff --git a/_sources/user/tutorial/plot_output.rst.txt b/_sources/user/tutorial/plot_output.rst.txt new file mode 100755 index 000000000..43efd18c6 --- /dev/null +++ b/_sources/user/tutorial/plot_output.rst.txt @@ -0,0 +1,105 @@ +Advanced Data Exploration Topics +================================= + +|Cyclus|-specific Views +------------------------- + +The previous session allowed you to explore data in conventional views. The +Flow view has been designed specifically for |Cyclus| to visualize the amount +of material flowing between pairs or collections of facilities. + +1. Drag the "Prototypes" table into the workspace. +2. From the "Tools" menu, click on "Flow" + +.. image:: flow-01-01.png + :align: center + :alt: Setting up for a flow view + +3. Select the "ALWR" prototype in the Prototypes table, and drag it to the + Material Flow view and drop it on the vertical line under "Sender". +4. Repeat this process to drop "NuclearUnderground" on the "Receiver". +5. Change the "Time" in the Material Flow from a single time (1) step to a + range (1-50). + +.. image:: flow-01-02.png + :align: center + :alt: First flow in a flow view. + +This shows the total amount of material that flowed from all ALWR agents to +all NuclearUnderground agents during the time from 0-50 time steps. + +6. When hovering the mouse over the ALWR block, a small chart icon appears. + Click it to see details in the strip chart below. + +.. image:: flow-01-03.png + :align: center + :alt: Adding the strip chart in a flow iew + +7. Notice that the first 50 time steps of that strip chart are highlighted in + gray. You can slide it to the left and right to see how the total, shown at + the top, changes. + +.. image:: flow-01-04-annotated.png + :align: center + :alt: Moving window in a flow view + +8. You can add additional flows, e.g. by dragging the EnrichPlant to the + Sender column. Turn on the chart data for the EnrichPlant and compare to + the ALWRs, noting the accumulation of depleted uranium tails at the + enrichment plant. + +.. image:: flow-01-05.png + :align: center + :alt: Two flows in a flow view + +Table to Loading Custom Tables +---------------------------------- + +Be default, Cyclist only loads the most common tables, but you are able to +load any table that is in the database. + +1. Select "Datatable" from the "Data" menu. +2. Choose the database that was loaded for this session and click on "Connect:" + +.. image:: timeseries-01.png + :align: center + :alt: Adding a new datatable + +3. Scroll down to find the "TimeSeriesPower" and click "Ok". Note that it + adds this table to the tool bar on the left. + +.. image:: timeseries-02.png + :align: center + :alt: A new datatable has been added. + +4. As a custom table, you need to tell Cyclist a little more about this + data. Select the TimeSeriesPower table and right-click on the "Time" field, + choosing IntTime. + +5. Right-click on the TimeSeriesPower Table and select "Plot". + +6. Drag the "Time" field to the x-axis and the "Value" field to the y-axis. + +.. image:: timeseries-03.png + :align: center + :alt: A plot of reactor power vs time. + +Here we can see the periodic refueling outages of the reactors, with each one +offline for 1 month of each year. They are not synchronized because sthere +were delays in starting the reactors due to constraints in the acquisition of +U ore by the EnrichPlant. + +7. Right-click on the "AgentID" field and select "Dimension". Then drag this + field first to the "Group By" box and also to become a filter at the top of + the plot. + +.. image:: timeseries-04-annotated.png + :align: center + :alt: Power curves for each reactor + +8. Turn on & off different agents to compare their profiles. + + + + + diff --git a/_sources/user/tutorial/run_cyclus_native.rst.txt b/_sources/user/tutorial/run_cyclus_native.rst.txt new file mode 100755 index 000000000..d6a2f5ab3 --- /dev/null +++ b/_sources/user/tutorial/run_cyclus_native.rst.txt @@ -0,0 +1,67 @@ +Working with |Cyclus| in on your machine +====================================== + +Choosing Where to Run +--------------------- + +|Cyclus| can be used to run simulations on your local +machine, if you have |Cyclus| installed, or in an appropriately configured +cloud resource. The advantage of using a local machine is that you can +control which archetypes are available. The advantage of using a remote +machine is that you don't have to install the entire |Cyclus| toolset on your +local machine. + +For this tutorial, |Cyclus| has been installed natively so it can be +run from either the IPython notebook or in the command prompt: + +.. image:: cyclus_in_IP.png + :align: center + :alt: Running |Cyclus| in an IPython Notebook + + +Brief Introduction to Jupyter Notebook +-------------------------------------- +A user can input the code required to run the simulation and analyze +its output in one **Jupyter Notebook** with clear descriptions. + +A tutorial on how to get Jupyter Notebook set up on your computer is available +`here `_ + + +A Jupyter notebook has four main areas: + +* A **Run** button that runs the cell you're in +* A **Up and Down** buttons that move you up or down a cell +* A vertical blue line that shows what cell you're currently in +* A **Stop** button that stops running the cell you're in + +.. image:: ipython_tour.png + :align: center + :width: 100% + :alt: Annotated view of an Jupyter notebook upon loading + + +Jupyter Notebook Scenario Execution +-------------------------------------------- +1. Go to the Jupyter notebook, making sure you are in the same folder as the input file +2. Remove any old |Cyclus| output files by: ``!rm tutorial.sqlite`` +3. Run |Cyclus| by: ``!cyclus input.xml -o tutorial_singlerx.sqlite`` + +.. image:: cyclus_in_IP.png + :align: center + :alt: Running |Cyclus| in an IPython Notebook + +When your simulation has finished, a file of the name ``tutorial_singlerx.sqlite`` +will be in your file folder. Your Jupyter Notebook can then be used with +`Cymetric `_ to analyze your +data. Examples of how to use Cymetric can be found in the `GitHub +`_. + + +Backup: Files for Success ++++++++++++++++++++++++++ + +If your run did not succeed, you can retrieve correct input and output files `here +`_ under ``input_oncethrough.xml`` +or ``ouput_oncethrough.sqlite``. This link contains input and +output files for each of the examples in this tutorial. diff --git a/_sources/user/tutorial/sim_parm.rst.txt b/_sources/user/tutorial/sim_parm.rst.txt new file mode 100755 index 000000000..2d9b10439 --- /dev/null +++ b/_sources/user/tutorial/sim_parm.rst.txt @@ -0,0 +1,140 @@ +Starting a New Scenario +============================ + +Problem Definition +-------------------- + +We will start with a new scenario representing a simplified once-through fuel +cycle. For the purpose of this tutorial, the scenario will include: + +* mine producing natural uranium +* enrichment facility producing 4% enriched uranium oxide fuel +* LWR reactor consuming fresh fuel and producing used fuel +* repository to house all spent fuel and waste + +More details about each of these facilities will discussed when we are +required to provide that input. + +Concept: Simulation Time Steps +------------------------------ + +A |Cyclus| input file can be written in `multiple formats `_, +including XML, JSON, and Python. That page also walks through the +basic structure for each type of input file. This tutorial will walk through +how to build an XML input. + +The XML |Cyclus| input file begins with the ```` tag and ends with the +```` tag. Within this space, the ```` block is the first +section of the CYCLUS input file and is of the form: + +.. code-block:: XML + + + + duration_val + start_month_val + start_year_val + decay_val + + + + + +Each of the elements shown are user-defined and required for each +|Cyclus| simulation: + +1. Simulation: the simulation handle contains all the parameters in the simulation. + +2. Duration: the number of timesteps to be simulated + +3. Start month: the first month of the simulation (e.g.: 1 for January) + +4. Start year: the first year of the simulation + +5. Decay mode:The |Cyclus| kernel has built-in experimental support for +`Decay `_ calculations. Materials +store the time since their last decay and agents are free to invoke the +decay function on them as desired to decay them to the current simulation +time. |Cyclus| can operate in 3 decay modes, with 1 additional mode +likely to be added in a future release: + +- 'never', all decay is turned off +- 'manual', meaning it is only on if the individual archetype decays their own inventory +- 'lazy', which will compute decay only when archetypes fetch a particular composition. +- 'periodic' (future), automatically decays all materials in a simulation with some fixed frequency. + +There are other `optional parameters `_ +that could be given but are not in the scope of this tutorial. For simplicity, +we will not model decay in this tutorial. + +The lifetime of a |Cyclus| simulation is determined by its `duration`, the +number of timesteps |Cyclus| will model the fuel cycle. |Cyclus| uses a +time-step approach to march through time and determine what actions are +taken by each agent at each point in time. Each time step includes the following phases: + +* new agents may enter the system (deployment) +* each agent prepares for exchange of material +* agents engage in material trades +* each agent acts after the exchange of material +* agents may leave the system (decommissioning) + +This tutorial assumes a time step of 1 month + + +Activity: Set Simulation Parameters +----------------------------------- +Using the simulation control template above and the table below, properly fill the template +with the variables listed in the table below in your favorite text editor. + ++-------------------+---------------+---------------------------------+ +| Variable | Value | Purpose | ++===================+===============+=================================+ +| ``duration`` | ``720`` | length of simulation (months) | ++-------------------+---------------+---------------------------------+ +| ``start_month`` | ``1`` | start month of simulation | ++-------------------+---------------+---------------------------------+ +| ``start_year`` | ``2018`` | start year of simulation | ++-------------------+---------------+---------------------------------+ +| ``decay`` | ``never`` | radioactive decay | ++-------------------+---------------+---------------------------------+ + +Using this table, let's set the simulation parameters. + +1. To tell |Cyclus| that this is the simulation section of the input file, +first add a ``simulation`` block: + +.. code-block:: XML + + + + +2. Place the ``control`` header in as such + +.. code-block:: XML + + + + + + +Adding spaces to indent the ``control`` header improves ease of reading. + +3. After filling in the parameters listed in the table above, close the control and simulation sections as: + +.. code-block:: XML + + + + 720 + 1 + 2018 + never + + + + + +**Note**: There are two blank lines between the end of the control section and +end of the simulation section. This section of the simulation block will hold +the rest of the simulation parameter blocks (commodities, facilities, regions, +institutions, and recipe blocks). diff --git a/_sources/user/unit_test.rst.txt b/_sources/user/unit_test.rst.txt new file mode 100755 index 000000000..558649acf --- /dev/null +++ b/_sources/user/unit_test.rst.txt @@ -0,0 +1,13 @@ +To ensure the proper installation of |Cyclus| and Cycamore, you can run the +|Cyclus| and Cycamore unit tests, they should report that **all tests** have +**passed** (or been disabled): + +.. code-block:: bash + + $ cyclus_unit_tests + $ cycamore_unit_tests + + + + + diff --git a/_sources/user/virtualbox.rst.txt b/_sources/user/virtualbox.rst.txt new file mode 100755 index 000000000..f9a08f520 --- /dev/null +++ b/_sources/user/virtualbox.rst.txt @@ -0,0 +1,19 @@ + +Installing a |Cyclus| VirtualBox +================================ + +A native Windows installation is not currently explicitly supported. However, a +Virtual Machine image can be downloaded that includes a pre-installation of all +of these dependencies as well as a pre-installation of |Cyclus| and Cycamore. If +you do not have access to a Linux or Unix (MacOS) machine, please follow these +steps: + +#. Install `VirtualBox `_ +#. Download `cyclus_user_environment.ova + `_ +#. Open the .ova file using VirtualBox (File->Import Appliance). +#. Login with the username ``ubuntu`` and pw ``reverse`` +#. Open a terminal and type ``conda update`` + +Congratulations! You now have the same user environment as someone who installed +|Cyclus| on an Ubuntu Linux machine. diff --git a/_sources/user/writing_input.rst.txt b/_sources/user/writing_input.rst.txt new file mode 100755 index 000000000..5ac25c451 --- /dev/null +++ b/_sources/user/writing_input.rst.txt @@ -0,0 +1,187 @@ +Writing a |Cyclus| Input File +============================= +This section will provide an introduction to creating a valid input file for +|Cyclus| by hand. Because |Cyclus| uses XML, JSON, or Python, input files have clearly defined +sections, or blocks, that can be automatically validated for correctness. + +Work is underway to provide a drag-and-drop graphical user interface to +facilitate building |Cyclus| input files in the future. + + +A Brief Introduction to XML +------------------------------------ +`XML`_ stands for EXtensible Markup Language, and was designed to provide +structure to data in a generic way by grouping the data between starting and +ending "tags". The tags used to provide that structure are not defined +universally, but each project can invent their own language for those tags. +The data that lies between a pair starting and ending tags may be additional +sections defined by other tags. + +Here is an example of a XML code block. + +.. code-block:: xml + + + Matt + Anthony + Cyclus released today + We have released Cyclus v1.0 for everyone to use. + + +In this example, a section named ``note`` includes four other sections named +``to``, ``from``, ``heading``, and ``body``, respectively. + +The set of tags for any given project, and their relationship to each other in +the hierarchy, is referred to as a grammar. In addition to defining which +tags exist, the grammar defines how many times each tag must or may exist +in a given section. A tag may be completely optional, required one or more +times, or allowed to appear as many times as the user desires. + +Although XML grammars are designed to be self-documenting, comments can be +inserted into XML files anywhere using the ```` syntax, +as shown above. + + +A Brief Introduction to JSON +------------------------------------ +`JSON`_ stands for JavaScript Object Notation, and is similar in many ways to XML. JSON was created to replace XML with a more user friendly language. It was designed to be a simpler and easier to use markup language. It does this by cutting out unnecessary parts of the XML language, such as closing tags. One area where JSON excels is that it is a data-oriented language, compared to XML, which is document-oriented. + +Here is the same code block using JSON. + +.. code-block:: json + + { + "note": { + "to": "Matt", + "from": "Anthony", + "heading": "Cyclus released today", + "body": "We have released Cyclus v1.0 for everyone to use." + } + } + + +A Brief Introduction to Python +------------------------------------ +`Python`_ is a fully featured dynamic programming language. It hosts a wide variety of +primitives built in to the language as well as powerful 3rd part libraries. Python +input files allow for the computation of mathematical expressions in the input file +itself. Static, proecomputed values are not required (as with XML and JSON). + +Here is the same code block using Python. + +.. code-block:: python + + {"note": { + "to": "Matt", # message recipient + "from": "Anthony", # message sender + "heading": "Cyclus released today", + "body": "We have released Cyclus v1.0 for everyone to use.", + } + } + + +In this example, a dictionary with a ``note`` key is has a dictionary vary that includes +four other keys named ``to``, ``from``, ``heading``, and ``body`` respectively. + + +The |Cyclus| Input File +------------------------ +Every |Cyclus| input file must have exactly one ``simulation`` section that +contains all data for a simulation. + +**XML:** + +.. code-block:: xml + + + ... simulation data will go here ... + + +**JSON:** + +.. code-block:: json + + { + "simulation": { + "… simulation data will go here …" + } + +**Python:** + +.. code-block:: python + + # Python input files will look for a variable named + # simulation, Simulation, or SIMULATION. It's value should be a + # dictionary with a single "simulation" key. + simulation = {"simulation": {...}} + + # Alternitavely, the simualtion variable can also be a Python function or + # callable that returns a simulation dictionary. This function should not + # take any arguments. + def simulation(): + return {"simulation": {...}} + + +Although not all sections are required, the following sections may appear in +any order in the input file: + +.. toctree:: + :maxdepth: 1 + + input_specs/control + input_specs/commodity + input_specs/archetypes + input_specs/facility + input_specs/region + input_specs/inst + input_specs/recipe + +Including XML Files +-------------------- +One feature of XML is that you are able to include external XML files inside of +your current document. This lets you reuse common parts of your input file that +do not change across multiple simulations. To enable XML include semantics +the attribute ``xmlns:xi="http://www.w3.org/2001/XInclude"`` *must* be added to the +```` tag. Then to include an external +file use the ```` tag where you want the included +file to go. + +A common inclusion pattern is to have a recipe book of materials in one file +and then include this in your simulation. + +**input.xml:** + +.. code-block:: xml + + + ... + + ... + + +**recipebook.xml:** + +.. code-block:: xml + + + proton_recipe + mass + + 010010000 + 1 + + + + + natU_recipe + atom + + 9223500000.007 + + + 9223800000.993 + + + +.. _XML : http://www.w3schools.com/xml/default.asp +.. _JSON : http://www.json.org/ diff --git a/_static/AnlLogo.png b/_static/AnlLogo.png new file mode 100755 index 000000000..4ff7e157c Binary files /dev/null and b/_static/AnlLogo.png differ diff --git a/_static/CVT-logo-250pix1.png b/_static/CVT-logo-250pix1.png new file mode 100755 index 000000000..60ebe8b7f Binary files /dev/null and b/_static/CVT-logo-250pix1.png differ diff --git a/_static/USNRC.png b/_static/USNRC.png new file mode 100755 index 000000000..2f4e870b9 Binary files /dev/null and b/_static/USNRC.png differ diff --git a/_static/ajax-loader.gif b/_static/ajax-loader.gif new file mode 100644 index 000000000..61faf8cab Binary files /dev/null and b/_static/ajax-loader.gif differ diff --git a/_static/alarmclock.png b/_static/alarmclock.png new file mode 100755 index 000000000..402d64c92 Binary files /dev/null and b/_static/alarmclock.png differ diff --git a/_static/antipode-bike.jpg b/_static/antipode-bike.jpg new file mode 100755 index 000000000..89bdc59de Binary files /dev/null and b/_static/antipode-bike.jpg differ diff --git a/_static/basic.css b/_static/basic.css new file mode 100755 index 000000000..2dc4751fb --- /dev/null +++ b/_static/basic.css @@ -0,0 +1,925 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 322px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li p.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 360px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +a:visited { + color: #551A8B; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, figure.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, figure.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, figure.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +img.align-default, figure.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-default { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar, +aside.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px; + background-color: #ffe; + width: 40%; + float: right; + clear: right; + overflow-x: auto; +} + +p.sidebar-title { + font-weight: bold; +} + +nav.contents, +aside.topic, +div.admonition, div.topic, blockquote { + clear: left; +} + +/* -- topics ---------------------------------------------------------------- */ + +nav.contents, +aside.topic, +div.topic { + border: 1px solid #ccc; + padding: 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +aside.sidebar > :last-child, +nav.contents > :last-child, +aside.topic > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +aside.sidebar::after, +nav.contents::after, +aside.topic::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + margin-top: 10px; + margin-bottom: 10px; + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure, figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption, figcaption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number, +figcaption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text, +figcaption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + +/* -- object description styles --------------------------------------------- */ + +.sig { + font-family: 'Consolas', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace; +} + +.sig-name, code.descname { + background-color: transparent; + font-weight: bold; +} + +.sig-name { + font-size: 1.1em; +} + +code.descname { + font-size: 1.2em; +} + +.sig-prename, code.descclassname { + background-color: transparent; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.sig-param.n { + font-style: italic; +} + +/* C++ specific styling */ + +.sig-inline.c-texpr, +.sig-inline.cpp-texpr { + font-family: unset; +} + +.sig.c .k, .sig.c .kt, +.sig.cpp .k, .sig.cpp .kt { + color: #0033B3; +} + +.sig.c .m, +.sig.cpp .m { + color: #1750EB; +} + +.sig.c .s, .sig.c .sc, +.sig.cpp .s, .sig.cpp .sc { + color: #067D17; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +aside.footnote > span, +div.citation > span { + float: left; +} +aside.footnote > span:last-of-type, +div.citation > span:last-of-type { + padding-right: 0.5em; +} +aside.footnote > p { + margin-left: 2em; +} +div.citation > p { + margin-left: 4em; +} +aside.footnote > p:last-of-type, +div.citation > p:last-of-type { + margin-bottom: 0em; +} +aside.footnote > p:last-of-type:after, +div.citation > p:last-of-type:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + +dl { + margin-bottom: 15px; +} + +dd > :first-child { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +.sig dd { + margin-top: 0px; + margin-bottom: 0px; +} + +.sig dl { + margin-top: 0px; + margin-bottom: 0px; +} + +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +.classifier:before { + font-style: normal; + margin: 0 0.5em; + content: ":"; + display: inline-block; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +.translated { + background-color: rgba(207, 255, 207, 0.2) +} + +.untranslated { + background-color: rgba(255, 207, 207, 0.2) +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; + white-space: nowrap; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + +td.linenos pre { + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; +} + +table.highlighttable td { + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; +} + +div.code-block-caption { + margin-top: 1em; + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +table.highlighttable td.linenos, +span.linenos, +div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; + -webkit-user-select: text; /* Safari fallback only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10+ */ +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + margin: 1em 0; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/_static/bicyclelady.jpg b/_static/bicyclelady.jpg new file mode 100755 index 000000000..6f5857a48 Binary files /dev/null and b/_static/bicyclelady.jpg differ diff --git a/_static/big_c.ico b/_static/big_c.ico new file mode 100755 index 000000000..1d4411d10 Binary files /dev/null and b/_static/big_c.ico differ diff --git a/_static/big_c.png b/_static/big_c.png new file mode 100755 index 000000000..e041757a1 Binary files /dev/null and b/_static/big_c.png differ diff --git a/_static/cloud.base.js b/_static/cloud.base.js new file mode 100755 index 000000000..de32432fb --- /dev/null +++ b/_static/cloud.base.js @@ -0,0 +1,154 @@ +/* ~~~~~~~~~~~~~~ + * cloud.base.js + *~~~~~~~~~~~~~~ + * + * Base JS utils needed by cloud js instrumentation. + * Split out so they can be used by theme-independant extensions (e.g. auto_redirect) + * + * This initializes a "window.CSP.utils" object + * + * :copyright: Copyright 2017 by Assurance Technologies + * :license: BSD + */ + +// begin encapsulation +(function (window, $, _) { + + /*========================================================================== + * internal helpers + *==========================================================================*/ + var location = document.location, + // hosturl is url to root of host, without trailing '/' + // NOTE: regex allows netloc segment to be empty, to support 'file:///' urls + hosturl = location.href.match(/^[a-z0-9]+:(?:\/\/)?(?:[^@/]*@)?[^/]*/)[0], + docpath = location.pathname, + sphinx = window.DOCUMENTATION_OPTIONS; + + /*========================================================================== + * utils + *==========================================================================*/ + var utils = { + + /*========================================================================== + * url helpers + *==========================================================================*/ + + // helper to generate an absolute url path from a relative one. + // absolute paths passed through unchanged. + // paths treated as relative to , + // if base is omitted, uses directory of current document. + abspath: function (path, base) { + var parts = path.split("/"), + stack = []; + if (parts[0]) { + // if path is relative, put base on stack + stack = (base || location.pathname).split("/"); + // remove blank from leading '/' + if (!stack[0]) { + stack.shift(); + } + // discard filename & blank from trailing '/' + if (stack.length && !(base && stack[stack.length - 1])) { + stack.pop(); + } + } + for (var i = 0; i < parts.length; ++i) { + if (parts[i] && parts[i] != '.') { + if (parts[i] == '..') { + stack.pop(); + } else { + stack.push(parts[i]); + } + } + } + return "/" + stack.join("/"); + }, + + // return subpath of url, if it starts with base ("" or non-empty string) + // returns undefined if url doesn't start with base. + // base url search params & fragments are ignored. + getSubUrl: function(url, base){ + base = base.replace(/(?:\/|[#?].*)$/, ''); + if(url.startsWith(base)) { + var suffix = url.slice(base.length); + if(suffix == '' || suffix.match(/^[/#?]/)){ return suffix; } + } + return; + }, + + // helper to normalize urls for comparison + // * strips current document's scheme, host, & path from local document links (just fragment will be left) + // * strips current document's scheme & host from internal urls (just path + fragment will be left) + // * makes all internal url paths absolute + // * external urls returned unchanged. + shortenUrl: function(url) { + if (!url){ + return ""; + } else if (url.indexOf(hosturl) == 0) { + // absolute path to same host + url = url.substr(hosturl.length) || '/'; + } else if (url[0] == '.') { + // relative path + url = utils.abspath(url); + } else if (!url.match(/^[/#?]|[a-z0-9]+:/)) { + // not abs path, or fragment, or query, or uri:// -- + // another page in current dir + url = utils.abspath('./' + url); + } + + if (url.indexOf(docpath) == 0) { + // strip current doc's url; only thing left will be e.g. #anchor + url = url.substr(docpath.length); + } + if (url == "#" || url == "#top") { + // normalize to empty string + url = ""; + } + return url; + }, + + // url w/ query params & hash stripped + baseUrl: function(url){ + return utils.shortenUrl(url).replace(/[#?].*$/, ''); + } + }; + + /*========================================================================== + * misc es5 polyfills + *==========================================================================*/ + var StrProto = String.prototype; + if (!StrProto.startsWith) { + StrProto.startsWith = function(search, pos){ + return this.substr(pos || 0, search.length) === search; + }; + } + + /*========================================================================== + * jquery patches + *==========================================================================*/ + + // custom helper to toggle visibility + $.fn.toggleVis = function (state){ + if(state) { this.show(); } else { this.hide(); } + return this; + }; + + /*========================================================================== + * initialize namespace + *==========================================================================*/ + + window.CST = window.CloudSphinxTheme = { + // url to root of host, without trailing "/" + hosturl: hosturl, + // path to root of document dir, without trailing "/" or index.html + rootpath: sphinx && utils.abspath(sphinx.URL_ROOT || ""), + utils: utils + }; + + /*========================================================================== + * eof + *==========================================================================*/ + +// end encapsulation +// NOTE: sphinx provides underscore.js as $u +}(window, jQuery, $u)); diff --git a/_static/cloud.css b/_static/cloud.css new file mode 100755 index 000000000..fc42a220f --- /dev/null +++ b/_static/cloud.css @@ -0,0 +1,2364 @@ +/***************************************************** +* cloud.css_t +* ~~~~~~~~~~~ +* +* stylesheet for "Cloud" theme for Sphinx. +* +* :copyright: Copyright 2011-2012 by Assurance Technologies +* :license: BSD +* +*****************************************************/ + +@import url("basic.css"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +* { + box-sizing: border-box; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; +} + +body +{ + padding: 0; + color: #000; + font-family: "Open Sans", sans-serif; + font-size: 100%; + line-height: 1.5em; + + + margin: 1em 1em 0; + background: #d5b683; + background-attachment: fixed; + +} + + + + + + + + + + + + + + + + + + + + + + + + + +div.related +{ + margin: 0 auto; + max-width: 1250px; + background: #34312e; + line-height: 1.5em; + padding: .75em 0; + color: #ffffff; + text-shadow: 1px 1px 1px rgba(0,0,0,.3); + + + + +} + +div.relbar-top div.related +{ + + + -moz-border-radius: .7em .7em 0 0; + -webkit-border-radius: .7em .7em 0 0; + -o-border-radius: .7em .7em 0 0; + -ms-border-radius: .7em .7em 0 0; + border-radius: .7em .7em 0 0; + + + +} + +div.relbar-bottom div.related +{ + + + -moz-border-radius: 0 0 .7em .7em; + -webkit-border-radius: 0 0 .7em .7em; + -o-border-radius: 0 0 .7em .7em; + -ms-border-radius: 0 0 .7em .7em; + border-radius: 0 0 .7em .7em; + + + + + +} + + + + + + + + + + + +div.related a +{ + display: inline-block; + padding: 0.3em 0.6em; + + + -moz-border-radius: 0.8em; + -webkit-border-radius: 0.8em; + -o-border-radius: 0.8em; + -ms-border-radius: 0.8em; + border-radius: 0.8em; + + + + font-weight: bold; + color: #ffffff; + border: 1px solid transparent; +} + +div.related li.right a +{ + background: rgba(0,0,0,.1); + font-weight: normal; +} + +div.related a:hover, +div.related li.right a:hover +{ + background: #fff9e4; + color: #d39110; + border-color: #F8D186; + text-decoration: none; + text-shadow: none; + + + -moz-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -webkit-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -o-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -ms-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + + + +} + + + + + + + + + + + +div.document +{ + + position: relative; + margin: 0 auto; + max-width: 1250px; + background: #fcf1df; + + +} + + + +div.documentwrapper +{ + float: left; + width: 100%; +} + +div.bodywrapper +{ + margin: 0 0 0 3in; + +} + + + + + + + + + + + + + + + + + +div.document.sidebar-hidden div.bodywrapper { + margin-left: 0; +} + +div.body +{ + min-height: 6in; + + + + background-color: #ffffff; + border-left: 1px solid rgba(0,0,0,.05); + + + + + -moz-box-shadow: -1px 0 2px rgba(0,0,0,.05); + -webkit-box-shadow: -1px 0 2px rgba(0,0,0,.05); + -o-box-shadow: -1px 0 2px rgba(0,0,0,.05); + -ms-box-shadow: -1px 0 2px rgba(0,0,0,.05); + box-shadow: -1px 0 2px rgba(0,0,0,.05); + + + + + + + line-height: 1.5em; + + color: #000000; + padding: 30px 20px; + + + + + + min-width: 0; + max-width: none; +} + + + + + + + + + + + + + +div.sphinxsidebar +{ + margin-top: 0; + width: 3in; + + font-size: 90%; + line-height: 1.25em; + + +} + + + + + + + + + + + + + + + + + +div.document.sidebar-hidden div.sphinxsidebar { display: none; } + +div.sphinxsidebarwrapper +{ + padding: 1em 0 0 10px; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 +{ + padding: 0; + margin: 24px 16px 0 0; + + font-family: "Noticia Text", serif; + font-weight: normal; + color: #777777; +} + +div.sphinxsidebar h3 { font-size: 1.4em; } +div.sphinxsidebar h4 { font-size: 1.3em; } + +div.sphinxsidebar h3 a, +div.sphinxsidebar h4 a +{ + color: #777777; +} + +div.sphinxsidebar p +{ + color: #777777; +} + +div.sphinxsidebar p.topless +{ + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul +{ + margin: 10px; + margin-right: 0; + padding: 0; + color: #777777; +} + +div.sphinxsidebar a +{ + color: #4b1a07; + border: 1px solid transparent; + border-width: 1px 0; +} + +div.sphinxsidebar a:hover +{ + color: #d39110; + background: #fff9e4; + border-color: #F8D186; + text-decoration: none; +} + +div.sphinxsidebar ul li a +{ + overflow: hidden; + white-space: nowrap; +} + +div.sphinxsidebar ul li a:hover +{ + + display: inline-table; + min-width: 98%; + min-width: calc(100% - 5px); + +} + +div.sphinxsidebar a:active +{ + color: #777777; +} + +div.sphinxsidebar p.logo +{ + margin: 1em 0 0 -10px; + text-align: center; + max-width: 100%; +} + +div.sphinxsidebar p.logo a +{ + display: inline-block; + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + +} + + +div.sphinxsidebarwrapper > h3:first-child, +div.sphinxsidebarwrapper > h4:first-child, +div.sphinxsidebarwrapper > div:first-child > h3:first-child, +div.sphinxsidebarwrapper > div:first-child > h4:first-child +{ + margin-top: .2em; +} + + + + +div.sphinxsidebar ul, +div.sphinxsidebar ul ul, +div.sphinxprev p.topless, +div.sphinxnext p.topless +{ + list-style: none; + margin-left: 0; +} + +div.sphinxsidebar ul ul +{ + margin-left: 1.5em; +} + + +div.sphinxsidebar ul a, +div.sphinxprev a, +div.sphinxnext a +{ + position: relative; + display: block; + padding: 1px 4px 3px 5px; + margin: 0 5px 0 0; + border: 1px solid transparent; + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + +} + + +div.sphinxsidebar ul a:hover, +div.sphinxprev a:hover, +div.sphinxnext a:hover +{ + background: #fff9e4; + border-color: #F8D186; + color: #d39110; + text-decoration: none; +} + + + div.sphinx-toc ul a:not([href^="#"]):hover + { + position: relative; + overflow: visible; + } + + div.sphinx-toc ul a:not([href^="#"]):hover:before + { + content: "⇒"; + position: absolute; + right: 100%; + font-size: 1.5em; + margin-right: 4px; + opacity: 0.7; + } + + + + + + + + +div.sphinxglobaltoc ul a[href="#"] +{ + font-style: italic; +} + +div.sphinxglobaltoc ul a:not([href*="#"]) +{ + font-size: 0.95em; + font-style: italic; +} + + +div.sphinx-toc li +{ + position: relative; +} + +div.sphinx-toc li:before +{ + position: absolute; + left: -0.8em; + color: #d39110; +} + + + + div.sphinx-toc li.current.active:not(.focus):before + { + content: "▼"; + top: 0.1em; + opacity: 0.5; + } + + + + div.sphinx-toc li.focus.local:before + { + content: "▶"; + opacity: 0.7; + + + + } + + + div.sphinx-toc > ul:not(:hover) li.focus.child:before + { + content: "⇒"; + opacity: 0.5; + font-size: 1.5em; + margin-left: -4px; + } + + +div.sphinx-toc li.focus.local > a:not(:hover) +{ + color: #d39110; +} + + +div.sphinx-toc li.toc-toggle > a:after +{ + content: "[–]"; + padding-left: .25em; + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 50); + opacity: 0.5; + +} + +div.sphinx-toc li.toc-toggle.closed > a:after +{ + content: "[+]"; +} + + + + + +div#searchbox { + margin-right: 10px; /* make this match sphinxsidebarwrapper left margin */ +} + +div#searchbox form > div { + display: inline-block; + margin-right: -0.4em; +} + +div.sphinxsidebar input, +h1#search-documentation ~ form input +{ + border: 1px solid rgba(0,0,0,.15); + font-family: sans-serif; + font-size: 1em; +} + +div#searchbox input[type="submit"], +h1#search-documentation ~ form > input[type="submit"] +{ + background: #F2F2F2; + + + -moz-border-radius: 0 5px 5px 0; + -webkit-border-radius: 0 5px 5px 0; + -o-border-radius: 0 5px 5px 0; + -ms-border-radius: 0 5px 5px 0; + border-radius: 0 5px 5px 0; + + + +} + +div#searchbox input[type="submit"]:hover, +h1#search-documentation ~ form input[type="submit"]:hover, +button.sidebar-toggle#sidebar-hide:hover, +button.sidebar-toggle#sidebar-show:hover, +.highlight .copybutton:hover +{ + background: #fff9e4; + color: #d39110; + border-color: #F8D186; +} + +h1#search-documentation ~ form input[type="text"]:focus, +div.sphinxsidebar input[type="text"]:focus +{ + border-color: #F8D186; +} + +.highlight .copybutton:hover:not(:active), +div.sphinxsidebar button:hover:not(:active), +div.sphinxsidebar input[type="submit"]:hover:not(:active), +h1#search-documentation ~ form input[type="submit"]:hover, +button.sidebar-toggle:hover:not(:active) +{ + + + -moz-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -webkit-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -o-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -ms-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + + + +} + +button.sidebar-toggle::-moz-focus-inner, +.highlight .copybutton::-moz-focus-inner +{ + border: 0; +} + +div.sphinxsidebar .searchtip +{ + color: #999999; +} + +#searchbox .highlight-link a[href$="hideSearchWords()"] +{ + display: block; + padding: 0 1em; + font-size: 80%; + text-align: right; +} + +#searchbox .highlight-link a[href$="hideSearchWords()"]:before +{ + content: "\00D7"; + font-weight: bold; + padding-right: 0.25em; +} + + +.sidebar-toggle-group +{ + position: absolute; + width: 3in; + top: 0; + left: 0; + z-index: 1; +} + + .sidebar-toggle-group.no-js { display: none; } + + + + + + + + + + + + + + + + + + div.document.sidebar-hidden .sidebar-toggle-group + { + width: auto; + } + + div.document.document-hidden .sidebar-toggle-group + { + width: 100%; + } + +button.sidebar-toggle +{ + margin: 0; + padding: 6px 12px; + + color: #777777; + font-size: 1em; + white-space: nowrap; +} + +button#sidebar-hide +{ + position: absolute; + + top: 0; + right: -1px; + + + background: transparent; + border: 1px solid rgba(0,0,0,.05); + + border-top-width: 0; + + + border-bottom-left-radius: 0.7em; + +} + + + + + + + + +button#sidebar-show +{ + position: absolute; + top: 0; + + left: 0; + + + background: #F2F2F2; + border: 1px solid rgba(0,0,0,.15); + + border-top-width: 0; + + + border-bottom-right-radius: 0.7em; + +} + + + + + +div.footer +{ + color: #34312e; + width: 100%; + padding: 9px 0; + text-align: center; + font-size: 75%; + + +} + +div.footer button.link +{ + margin: 0 -1px; + padding: 0; + background: none; + border: none; + font-size: inherit; + font-family: inherit; +} + +div.footer a, +div.footer button.link +{ + color: #34312e; + text-decoration: underline; +} + +div.footer a:hover, +div.footer button.link:hover +{ + color: white; +} + +div.footer + div.footer, +div.footer + script + div.footer +{ + margin-top: -12px; +} + + + + + + + + + +div.body h1, +div.body h2, +div.body p.rubric, +div.body h3, +div.body h4, +div.body h5, +div.body h6 +{ + font-family: "Noticia Text", serif; + font-weight: normal; + color: #333; + clear: both; + +} + + + + + + +div.body h1 +{ + + + + + + + font-size: 2.0em; + line-height: 1.5em; + margin: 1.5em + 0 + 1.5em + 0; + + text-align: center; + +} + + +div.body > .section > h1 +{ + + + + + margin: 0.562em + 0 + 1.5em + 0; + +} + + +div.body h1 + .subtitle { + opacity: 0.54; + font-style: italic; + font-weight: bold; + margin-bottom: 2.25rem; + margin-top: -2.25rem; + text-align: center; +}div.body h2, +div.body p.rubric +{ + + + + + + + font-size: 1.875em; + line-height: 1.6em; + margin: 0.8em + 0 + 0.8em + 0; + +} + +div.body h3 +{ + + + + + + + font-size: 1.625em; + line-height: 1.8461538461538463em; + margin: 0.692em + 0 + 0.692em + 0; + +} +div.body h2, +div.body p.rubric, +.section.emphasize-children > .section > h3, +#table-of-contents > h1, +h1#search-documentation +{ + + + padding: 6px 10px; + background-color: #84A6C7; + border: 1px solid rgba(0,0,0,.125); + border-width: 0 0 0 6px; + color: #ffffff; + text-shadow: 1px 1px rgba(0,0,0,.125); + + + + + + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + -o-border-radius: 5px; + -ms-border-radius: 5px; + border-radius: 5px; + + + +} + + + + + + + + + + + +div.body h2, +div.body p.rubric, +#table-of-contents > h1, +h1#search-documentation +{ + + + + + + + margin: 0.8em + 1px + 0.8em + 1px; + +} + + +.section.emphasize-children > .section > h3 +{ + + + + + + + margin: 0.923em + 1px + 0.923em + 1px; + +} + + +div.body p.rubric, +.section.emphasize-children > .section > h3 +{ + + background-color: #92BCDE; + + +} + + + + + div.body h2:hover a.headerlink:not(:hover), + .section.emphasize-children > .section > h3:hover a.headerlink:not(:hover) + { + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 40); + opacity: 0.4; + + } + + + div.body h2.highlighted, + .section.emphasize-children > .section > h3.highlighted + { + background-color: #fbe54e; + border-color: #F8D186; + color: #333; + } + + + + +div.body h4 { + + + + + + + font-size: 1.25em; + line-height: 1.2em; + margin: 1.2em + 0 + 1.2em + 0; + + clear: both; +} +div.body h5 { + + + + + + font-size: 1.1em; + line-height: 1.3636363636363635em; + margin: 1.364em + 0 + 1.364em + 0; + } +div.body h6 { + + + + + + font-size: 1.0em; + line-height: 1.5em; + margin: 1.5em + 0 + 1.5em + 0; + }#table-of-contents > h1, +h1#search-documentation +{ + margin-top: 0; +} + + +.toctree-wrapper.highlight-pages:not(.hide-sections) li.page > a +{ + font-weight: bold; +} + +.toctree-wrapper.space-pages li.page +{ + margin-top: 1em; +} + + +.toctree-wrapper.hide-sections li:not(.page) { + list-style: none; + margin-left: -2.5rem; +} +.toctree-wrapper.hide-sections li:not(.page) > a { display: none; } + +#hide-page-sections { float: right; opacity: 0.88; }a.headerlink +{ + color: #bb3f3f; + font-size: 0.8em; + margin: 0 0 0 1px; + padding: 0 5px 0 4px; + text-decoration: none; + border: 1px solid transparent; + border-width: 1px 0; + + + -moz-border-radius: 0.35em; + -webkit-border-radius: 0.35em; + -o-border-radius: 0.35em; + -ms-border-radius: 0.35em; + border-radius: 0.35em; + + + +} + +div.body a.headerlink:hover +{ + background-color: #fff9e4; + border-color: #F8D186; + color: #d39110; + text-decoration: none; + +} + +a.headerlink:hover:active +{ + + + -moz-box-shadow: none; + -webkit-box-shadow: none; + -o-box-shadow: none; + -ms-box-shadow: none; + box-shadow: none; + + + +} +.html-toggle-button +{ + position: relative; + cursor: pointer; +} + + +.html-toggle-button:hover:after, +.section.emphasize-children > .section > h3.html-toggle-button:hover:after +{ + background: #fff9e4; + + + border-color: #F8D186; + + + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -o-border-radius: 4px; + -ms-border-radius: 4px; + border-radius: 4px; + + + + + + -moz-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -webkit-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -o-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + -ms-box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + box-shadow: 1px 1px 2px -1px rgba(0,0,0,0.5); + + + + + color: #d39110; +} + + +.html-toggle-button:after +{ + position: relative; + top: -0.15em; + margin: 0; + padding: 0.15em 0.3em; + text-shadow: none; + font-size: 65%; + font-style: italic; + font-weight: bold; + border: 1px solid transparent; +} + + + +.html-toggle.collapsed > .html-toggle-button:after { content: "[+ show section]"; } +.html-toggle.expanded > .html-toggle-button:after { content: "[- hide section]"; } + + +.html-toggle-button:active:after, +.section.emphasize-children > .section > h3.html-toggle-button:active:after + +{ + position: relative; + top: calc(-0.15em + 1px); + left: 1px; +} + + + + + + + + +.clear, .clear-both { clear: both; } + +.clear-left { clear: left; } + +.clear-right { clear: right; } + +.clear-none { clear: none; } + + div.body .clear-none > h3 { clear: none; } + +.hidden { display: none; }div.body p +{ + text-align: justify; + + + + + + + margin: 1.5em + 0 + 1.5em + 0; + +} + + + +div.body li, +div.body dd +{ + text-align: justify; +} + +div.body hr { + margin: 0 10px; + background: none; + border: 1px dashed rgba(0,0,0,.15); + border-width: 1px 0 0 0; +} + +.strike +{ + text-decoration: line-through; +}a.footnote-reference +{ + font-size: 70%; + position: relative; + top: -.75em; +} + +table.docutils.footnote { margin: 1em 0 0 1em; }dl { margin-bottom: 1.5em; } +li > dl:only-child { margin-bottom: 0; } + +dd { margin-right: 10px; } + +dd ol { margin-bottom: 10px; } + +dl.docutils > dt { font-size: 1.1em; margin-bottom: .5em; } +dl.docutils > dd + dt { margin-top: 1.5em; } + + +ul + ul, +ul + div > ul:only-child, +div.toctree-wrapper + ul { margin-top: -1em; } + + +dd ul { margin-bottom: 1.5em; } + + +li > p ~ ul.simple { margin-bottom: 1.5em; } + + + +a +{ + color: #bb3f3f; + text-decoration: none; +} + +a:visited +{ + + text-decoration: none; +} + +a:hover +{ + color: #d39110; + background: #fff9e4; + text-decoration: underline; +} + +a:hover:active +{ + left: 1px; + top: 1px; + + + -moz-box-shadow: 0; + -webkit-box-shadow: 0; + -o-box-shadow: 0; + -ms-box-shadow: 0; + box-shadow: 0; + + + +} + +a.biglink +{ + font-size: 130%; +} + +dt:target, +.footnote:target, +.highlighted +{ + padding: 4px; + margin: -4px; + background-color: #fbe54e; + + + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + -o-border-radius: 10px; + -ms-border-radius: 10px; + border-radius: 10px; + + + +} + +table.fullwidth { width: 100%; } + +table.centered { margin-left: auto; margin-right: auto; } + +table.docutils.plain { border: none; } +table.docutils.plain tr.row-odd > * { background: none; } + + +table.docutils.html-plain-table tr.row-odd > * { background: none; } + + +table.docutils.align-right { margin-left: auto; } + table.docutils tbody + { + + vertical-align: top; + } + + + + table.docutils th p:first-child, + table.docutils td p:first-child + { + margin-top: 0; + } + + table.docutils th p:last-child, + table.docutils td p:last-child + { + margin-bottom: 0; + } + + +table.docutils th { + border: 0 solid transparent; + padding: .4em; + font-family: "Noticia Text", serif; + background: rgba(0,0,0,.15); +} + +table.docutils th.head:not(.stub) { + border-bottom: 1px solid rgba(0,0,0,.15); +} + +table.docutils th.stub + td +{ + border-left: 1px solid rgba(0,0,0,.15); +} + +table.docutils td { + padding: .4em; + border: 0 solid rgba(0,0,0,.15); +} +table.docutils tr.row-odd td { background: rgba(0,0,0,.06); } + +h2 + table.docutils { margin-top: 1em; } +table > caption { margin: 1em 0 .5em; font-style: italic; } + + + +table.docutils th + .single-left-divider, +table.docutils th + .double-left-divider { border-left-width: 0; } + + + + + + + dl.field-list > dd > p:first-child, + dl.field-list > dd > p:first-child:empty + ul.simple li > p:first-child, + dl.field-list > dd > ul:first-child.simple li > p:first-child + { margin-top: 0; } + + + dl.field-list > dd > p:first-child:empty { display: none; } + + + + + +div.admonition, p.deprecated +{ + background: #E7F0FE; + + + + + + + font-size: 0.88em; + line-height: 1.7045454545454546em; + margin: 0.705em + 0 + 0.705em + 0; + + padding: .5em 1em; + border: 1px solid rgba(0,0,0,.05); + border-width: 1px 0; + + + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + -o-border-radius: 5px; + -ms-border-radius: 5px; + border-radius: 5px; + + + + + + background-position: .6em .5em; + background-size: auto 1.58em; + background-repeat: no-repeat; + + + background-image: url("icon-note.png"); +} + + + +div.caution, div.important { background-color: #FFF7E0; background-image: url("icon-caution.png"); } +div.warning { background-color: #ffe4e4; background-image: url("icon-warning.png"); } +div.danger, div.admonition.error { background-color: #ffe4e4; background-image: url("icon-danger.png"); } + +div.seealso { background-color: #FFF7E0; background-image: url("icon-seealso.png"); } +div.admonition-todo { background-color: #FFF7E0; background-image: url("icon-todo.png"); } +p.deprecated { background-color: #fbece0; background-image: url("icon-deprecated.png"); } + + +div.admonition p, +div.admonition pre, +div.admonition ul, +div.admonition ol { + + + + + + + line-height: 1.7045454545454546em; + margin: 0.0em + 0 + 0.0em + 0; + +} + + +h1 ~ div.admonition { margin-left: 1.5em; margin-right: 1.5em; }div.admonition.float-right, +div.admonition.floater +{ + float: right; + max-width: 40%; + margin: 0 0 1.5em 1.5em; +} + +.admonition.float-left +{ + float: left; + max-width: 50%; + margin: 0 1.5em 1.5em 0; +} + +.admonition.float-center +{ + clear: both; + max-width: 65%; + margin: 0 auto 1.5em; +} + + + + + + + + + + p.admonition-title:first-child +{ + + margin: -.5em -1em .5em; + padding: .5em .5em .5em 2.65em; + background: rgba(0,0,0,.05); + + + -moz-border-radius: 3px 3px 0 0; + -webkit-border-radius: 3px 3px 0 0; + -o-border-radius: 3px 3px 0 0; + -ms-border-radius: 3px 3px 0 0; + border-radius: 3px 3px 0 0; + + + + +} + + + p.admonition-title:first-child { margin-top: -.5em !important; } + + +div.admonition.inline-title p.admonition-title +{ + display: inline; + margin: 0; + padding: 0 .25em 0 1.5em; +} + +div.admonition.inline-title p.admonition-title:after { content: ":"; } +div.admonition.inline-title p.admonition-title + p { display: inline; } +div.admonition.inline-title p.admonition-title + ul { margin-top: 0; } + + div.admonition.inline-title p.admonition-title { background: none; } + + + +div.admonition.without-title p.admonition-title { + display: none; +} + +div.admonition.without-title +{ + padding-left: 2.65em; +}div#todos p.admonition-title +{ + font-weight: normal; + color: #AAA; + font-size: 70%; +} + +div#todos div.admonition-todo + p +{ + font-size: 70%; + text-align: right; + margin-top: -.5em; + margin-bottom: 1.5em; + color: #AAA; +} + +div#todos div.admonition-todo + p a +{ + font-size: 130%; +} + + +div.deprecated, div.versionchanged, div.versionadded +{ + + + + + + + font-size: 0.88em; + line-height: 1.7045454545454546em; + margin: 1.705em + 0 + 1.705em + 0; + + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 60); + opacity: 0.6; +; +} + + +span.versionmodified +{ + font-weight: bold; +} + + + +div.highlight +{ + background: none; + margin: 1.5em 0; +} + +div.highlight pre, +td.linenos pre +{ + padding: 10px; + + font-family: "Roboto Mono", monospace; + font-size: 85%; + line-height: 1.5em; +} + +div.highlight pre +{ + background-color: white; + + border: 1px solid #AACC99; + border-width: 1px 0; + border-style: solid dotted dotted solid; + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + + color: #111111; +} + + +div[class|="highlight"] + div[class|="highlight"] +{ + margin-top: -1.5em; +} + + +p + [class|=highlight] > table.highlighttable +{ + margin-top: -1em; + + margin-bottom: -1em; +} + + +table.highlighttable { display: block; } +table.highlighttable tbody { display: block; } +table.highlighttable tr { display: flex; align-items: flex-start; justify-content: flex-start; } +table.highlighttable td { display: block; padding: 0; } +table.highlighttable td.code { width: 100%; max-width: calc(100% - 1em); } +table.highlighttable div.linenodiv { margin-top: 2.2em; } +table.highlighttable div.linenodiv pre +{ + background: none; + border: 0; + margin: 0; + padding: 0; + padding-right: .5em; +} + + + + + + +code +{ + font-family: "Roboto Mono", monospace; + font-size: 90%; +} + +code.literal +{ + background-color: rgba(0,0,0,.075); + border: 1px solid rgba(0,0,0,.05); + padding: 0px 4px; + margin: 1px; + + + + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -o-border-radius: 4px; + -ms-border-radius: 4px; + border-radius: 4px; + + + +} + +p code.literal { white-space: nowrap; } + +code.samp.literal > em +{ + font-family: "Roboto Mono", monospace; + padding: 0 1px; + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 60); + opacity: 0.6; + +} + +code.samp.literal > em:before { content: "{"; } +code.samp.literal > em:after { content: "}"; } + +h1 code.literal +{ + + font-size: 80%; +} + +h1 code.samp.literal > em +{ + font-weight: normal; +} + +div.sphinxsidebar code.literal, +a.reference code.literal, +div.related a code.literal, +code.literal.xref +{ + background-color: transparent; + border: none; + padding: 0; + margin: 0; +} + +.viewcode-back +{ + font-family: "Open Sans", sans-serif; +} + +div.viewcode-block:target +{ + background-color: #f4debf; + border-top: 1px solid #ac9; + border-bottom: 1px solid #ac9; +} + + +.highlight .copybutton +{ + position: absolute; + right: 0; + top: 0; + + margin: 0; + padding: 0 6px; + + background: transparent; + border: 1px solid transparent; + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + + + font-size: 75%; + color: #777777; + white-space: nowrap; + cursor: pointer; +} + +.highlight .copybutton.active +{ + text-decoration: line-through; + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 80); + opacity: 0.8; + +} + +.highlight:not(:hover) .copybutton:not(.active) +{ + filter: progid:DXImageTransform.Microsoft.Alpha(Opacity= + 70); + opacity: 0.7; + +} + + + + +.desc-section > .section-header +{ + position: relative; +} + +.desc-section-1 > .section-header +{ + + + + + + + margin: 0.8em + 0 + 0.8em + 0; + + border-bottom: 1px dotted #84A6C7; + color: #84A6C7; +} + +.desc-section-2 > .section-header +{ + color: #84A6C7; +} + +.desc-section > .section-header:before +{ + + content: attr(data-nested-label); + font-size: 0.75em; + opacity: 0.75; + letter-spacing: 1px; + font-style: italic; +} + + + + + + + + + + + + + + + dl.object > dt, + dl.data > dt, + dl.function > dt, + dl.method > dt, + dl.attribute > dt, + dl.class > dt, + dl.exception > dt, + dl.classmethod > dt, + dl.staticmethod > dt + { + display: inline-block; + + padding: 0.3em 1em 0.3em 0.6em; + + border: rgba(0,0,0,0.1) solid 1px; + border-width: 0 0 0 3px; + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + + } + + + + dl.has-headerlink > dt, + dl.has-headerlink > dt + { + padding-right: 0; + } + + + + dl.object > dt, + dl.data > dt, + dl.attribute > dt + { + background-color: + #e6e6e6; + } + + dl.function > dt, + dl.method > dt, + dl.classmethod > dt, + dl.staticmethod > dt + { + background-color: + #deebf5; + } + + dl.class > dt + { + background-color: + #eee3ce; + border-width: 0 0 0 6px; + } + + dl.exception > dt + { + background-color: + #eee3ce; + } + + + dl.object > dt:before, + dl.data > dt:before, + dl.function > dt:before, + dl.method > dt:before, + dl.attribute > dt:before, + dl.class > dt > .property:first-child, + dl.exception > dt > .property:first-child, + dl.classmethod > dt > .property:first-child, + dl.method[subtype] > dt > .property:first-child, + dl.staticmethod > dt > .property:first-child + { + font-size: 0.8em; + font-weight: bold; + font-style: italic; + letter-spacing: 0.1em; + color: rgba(0,0,0,0.3); + } + + + + + + .desc-section dl.attribute > dt:before + { + content: "attr"; + padding-right: 0.6em; + } + + .desc-section dl.function > dt:before + { + content: "func"; + padding-right: 0.6em; + } + + .desc-section dl.method:not([subtype]) > dt:before + { + content: "method"; + padding-right: 0.6em; + } + + + + + +dl > dt.highlighted +{ + background: #fbe54e; +} + + +.viewcode-link +{ + position: absolute; + right: 0; + margin-right: 1.5em; + margin-right: calc(1em + 10px); +} + + + +table.indextable span.category +{ + font-size: 80%; + font-style: italic; + color: #84ADBE; +} + +table.indextable a, +table.indextable a:hover span.category +{ + color: #bb3f3f; +} + +table.indextable span.category span.location +{ + font-weight: bold; +} + +table.indextable td > dl > dt +{ + margin-bottom: .5em; +} + +table.indextable td > dl > dd > dl +{ + margin-top: -.5em; + margin-bottom: .5em; +} + + + + +@media only screen and (min-device-width: 16in) +{ + + + +} + + +@media only screen and (min-width: 1250px) +{ + + + +} + + +@media only screen and (min-width: 700px) +{ + + + + + + .show-for-small { display: none !important; } +} + + +@media only screen and (max-width: 1250px), + only screen and (max-width: 700px), + only screen and (max-device-width: 700px), + handheld +{ + + + body + { + margin: 0; + } + + + div.relbar-top div.related, + div.relbar-bottom div.related + { + + + -moz-border-radius: 0; + -webkit-border-radius: 0; + -o-border-radius: 0; + -ms-border-radius: 0; + border-radius: 0; + + + + } + + + div.bodywrapper + { + margin: 0 0 0 322px; + + } + + + div.sphinxsidebar { width: 322px; } + + + .sidebar-toggle-group { width: 322px; } + + +} + + +@media only screen and (max-width: 700px), + only screen and (max-device-width: 700px), + handheld +{ + + + body { + font-size: 75%; + } + + + + div.related > ul > li.right + li:not(.right) { font-weight: bold; } + div.related > ul > li:not(.right) + li { display: none; } + + + div.bodywrapper + { + margin-left: 0; + } + + + div.document:not(.document-hidden) div.sphinxsidebar, + div.document.document-hidden div.documentwrapper + { + display: none; + } + + div.document.document-hidden div.sphinxsidebar + { + width: 100%; + margin: 0; + border: 0; + border-radius: 0; + } + + + button#sidebar-hide + { + left: auto; + top: 0; + right: 0; + background: #ffffff; + border-color: rgba(0,0,0,.15); + } + + + + div.body h2, + div.body p.rubric, + .section.emphasize-children > .section > h3 + { + + padding-top: 0.25em; + padding-bottom: .25em; + + + + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -o-border-radius: 3px; + -ms-border-radius: 3px; + border-radius: 3px; + + + + } + + + + + .hide-for-small { display: none; } +} + + +@media print +{ + + + div.body { + border: 0; + + + -moz-box-shadow: none; + -webkit-box-shadow: none; + -o-box-shadow: none; + -ms-box-shadow: none; + box-shadow: none; + + + + } + + + .sidebar-toggle-group { display: none; } + + + + div.body h1, + div.body h2, + div.body p.rubric, + div.body h3, + div.body h4, + div.body h5, + div.body h6 + { + color: #333 !important; + text-shadow: none !important; + border: none !important; + padding: 0; + } + + + + + .html-toggle.expanded > .html-toggle-button:after + { + display: none; + } + + + .html-toggle.collapsed > .html-toggle-button:after + { + content: "[not printed]" !important; + } + + + +} + + + + diff --git a/_static/cloud.js b/_static/cloud.js new file mode 100755 index 000000000..26a9b221a --- /dev/null +++ b/_static/cloud.js @@ -0,0 +1,549 @@ +/* ~~~~~~~~~~~~~~ + * cloud.js_t + *~~~~~~~~~~~~~~ + * + * Various bits of javascript driving the moving parts behind various + * parts of the cloud theme. Handles things such as toggleable sections, + * collapsing the sidebar, etc. + * + * :copyright: Copyright 2011-2012 by Assurance Technologies + * :license: BSD + */ + + + + + + + +// begin encapsulation +(function (window, $, _, CST) { + + /*========================================================================== + * common helpers + *==========================================================================*/ + var isUndef = _.isUndefined, + TEXT_NODE = 3, // could use Node.TEXT_NODE, but IE doesn't define it :( + $window = $(window), + utils = CST.utils, + shorten_url = utils.shortenUrl, + baseUrl = utils.baseUrl; + + // helper that retrieves css property in pixels + function csspx(elem, prop) { + return parseInt($(elem).css(prop).replace("px", ""), 10); + } + + // NOTE: would use $().offset(), but it's document-relative, + // and we need viewport-relative... which means getBoundingClientRect(). + // NOTE: 'window.frameElement' will only work we're embedded in an iframe on same domain. + var parentFrame = window.frameElement; + if (window.parent && window.parent !== window) { + $(window.parent).scroll(function () { + $window.scroll(); + }); + } + + function leftFrameOffset() { + return parentFrame ? parentFrame.getBoundingClientRect().left : 0; + } + + function topFrameOffset() { + return parentFrame ? parentFrame.getBoundingClientRect().top : 0; + } + + function leftViewOffset($node) { + return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().left + leftFrameOffset() : 0; + } + + function topViewOffset($node) { + return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().top + topFrameOffset() : 0; + } + + function bottomViewOffset($node) { + return ($node && $node.length > 0) ? $node[0].getBoundingClientRect().bottom + topFrameOffset() : 0; + } + + + function topOffset($target, $parent) { + if (!($target && $target[0])) { + return 0; + } + var offset = $target[0].getBoundingClientRect().top; + if ($parent && $parent[0]) { + offset -= $parent[0].getBoundingClientRect().top; + } + else { + offset += topFrameOffset(); + } + return offset; + } + + // return normalized nodename, takes in node or jquery selector + // (can't trust nodeName, per http://ejohn.org/blog/nodename-case-sensitivity/) + function nodeName(elem) { + if (elem && elem.length) { + elem = elem[0]; + } + return elem && elem.nodeName.toUpperCase(); + } + + /*========================================================================== + * Sythesize 'cloud-breakpoint' event + *========================================================================== + * Event emitted when crossing small <-> medium media breakpoint + *==========================================================================*/ + var smallScreen; + + $(function (){ + var $smallDiv = $('
').appendTo("body"), + $html = $("html"); + function update(){ + var test = $smallDiv.css("display") == "none"; + if(test !== smallScreen){ + smallScreen = test; + $html.toggleClass("small-screen", test) + .toggleClass("medium-up-screen", !test); + $window.trigger("cloud-breakpoint"); + } + } + $window.on("DOMContentLoaded load resize", update); + update(); + }); + + /*========================================================================== + * Highlighter Assist + *========================================================================== + * Sphinx's highlighter marks some objects when user follows link, + * but doesn't include section names, etc. This catches those. + *==========================================================================*/ + $(function () { + // helper to locate highlight target based on #fragment + function locate_target() { + // find id referenced by #fragment + var hash = document.location.hash; + if (!hash) return null; + var section = document.getElementById(hash.substr(1)); + if (!section) return null; + + // could be div.section, or hidden span at top of div.section + var name = nodeName(section); + if (name != "DIV") { + if (name == "SPAN" && section.innerHTML == "" && + nodeName(section.parentNode) == "DIV") { + section = section.parentNode; + } + else if (name == "DT" && section.children.length && + $(section).children("tt.descname, code.descname").length > 0) { + // not a section, but an object definition, e.g. a class, func, or attr + return $(section); + } + } + // now at section div and either way we have to find title element - h2, h3, etc. + var header = $(section).children("h2, h3, h4, h5, h6").first(); + return header.length ? header : null; + } + + // init highlight + var target = locate_target(); + if (target) target.addClass("highlighted"); + + // update highlight if hash changes + $window.on("hashchange", function () { + if (target) target.removeClass("highlighted"); + target = locate_target(); + if (target) target.addClass("highlighted"); + }); + }); + + /*========================================================================== + * Toggleable Sections + *========================================================================== + * Added expand/collapse button to any collapsible RST sections. + * Looks for sections with CSS class "html-toggle", + * along with the optional classes "expanded" or "collapsed". + * Button toggles "html-toggle.expanded/collapsed" classes, + * and relies on CSS to do the rest of the job displaying them as appropriate. + *==========================================================================*/ + + // given "#hash-name-with.periods", escape so it's usable as CSS selector + // (e.g. "#hash-name-with\\.periods") + // XXX: replace this with proper CSS.escape polyfill? + function escapeHash(hash) { + return hash.replace(/\./g, "\\."); + } + + $(function () { + function init() { + // get header & section, and add static classes + var header = $(this); + var section = header.parent(); + header.addClass("html-toggle-button"); + + // helper to test if url hash is within this section + function contains_hash() { + var hash = document.location.hash; + return hash && (section[0].id == hash.substr(1) || + section.find(escapeHash(hash)).length > 0); + } + + // helper to control toggle state + function set_state(expanded) { + expanded = !!expanded; // toggleClass et al need actual boolean + section.toggleClass("expanded", expanded); + section.toggleClass("collapsed", !expanded); + section.children().toggle(expanded); + if (!expanded) { + section.children("span:first-child:empty").show(); + /* for :ref: span tag */ + header.show(); + } + } + + // initialize state + set_state(section.hasClass("expanded") || contains_hash()); + + // bind toggle callback + header.click(function (evt) { + var state = section.hasClass("expanded") + if (state && $(evt.target).is(".headerlink")) { + return; + } + set_state(!state); + $window.trigger('cloud-section-toggled', section[0]); + }); + + // open section if user jumps to it from w/in page + $window.on("hashchange", function () { + if (contains_hash()) set_state(true); + }); + } + + $(".html-toggle.section > h2, .html-toggle.section > h3, .html-toggle.section > h4, .html-toggle.section > h5, .html-toggle.section > h6").each(init); + }); + + /*========================================================================== + * mobile menu / collapsible sidebar + *========================================================================== + * Instruments sidebar toggle buttons. Relies on applying classes + * to div.document in order to trigger css rules that show/hide sidebar. + * Persists sidebar state via session cookie. + * Sidebar state for small screens is tracked separately, + * and is NOT persisted. + *==========================================================================*/ + $(function () { + // get nodes + if (!$(".sphinxsidebar").length) { return; } + + var $doc = $('div.document'), + $hide = $('button#sidebar-hide'), + $show = $('button#sidebar-show'), + copts = { + // expires: 7, + path: utils.rootpath + }; + + // set sidebar state for current media size + var lastSmall = false, + smallState = false, + largeState = false; + function setState(visible){ + $doc.toggleClass("sidebar-hidden", !smallScreen && !visible) + .toggleClass("document-hidden", smallScreen && visible); + $hide.toggleVis(visible); + $show.toggleVis(!visible); + lastSmall = smallScreen; + if(smallScreen) { + smallState = visible; + if(visible) { largeState = true; } + } else { + largeState = visible; + if(!visible) { smallState = false; } + $.cookie("sidebar", visible ? "expanded" : "collapsed", copts); + } + $window.trigger("cloud-sidebar-toggled", visible); + } + + // change when buttons clicked + $show.click(function () { setState(true); }); + $hide.click(function () { setState(false); }); + + // refresh sidebar state when crossing breakpoints + $window.on("cloud-breakpoint", function (){ + setState(smallScreen ? smallState : largeState); + }); + + // load initial state + if(smallScreen){ + setState(false); + } else { + var value = $.cookie("sidebar"); + + setState(value != "collapsed"); + } + + // make buttons visible now that they're instrumented + $(".sidebar-toggle-group").removeClass("no-js"); + }); + + // flag set by smooth scroller to temporarily disable toc sliding. + var scrollingActive = false; + + /* ========================================================================== + * header breaker + * ========================================================================== + * attempts to intelligently insert linebreaks into page titles, where possible. + * currently only handles titles such as "module - description", + * adding a break after the "-". + * ==========================================================================*/ + $(function () { + // get header's content, insert linebreaks + var header = $("h1"); + var orig = header[0].innerHTML; + var shorter = orig; + if ($("h1 > a:first > tt > span.pre").length > 0) { + shorter = orig.replace(/(<\/tt><\/a>\s*[-\u2013\u2014:]\s+)/im, "$1
"); + } + else if ($("h1 > tt.literal:first").length > 0) { + shorter = orig.replace(/(<\/tt>\s*[-\u2013\u2014:]\s+)/im, "$1
"); + } + if (shorter == orig) { + return; + } + + // hack to determine full width of header + header.css({whiteSpace: "nowrap", position: "absolute"}); + var header_width = header.width(); + header.css({whiteSpace: "", position: ""}); + + // func to insert linebreaks when needed + function layout_header() { + header[0].innerHTML = (header_width > header.parent().width()) ? shorter : orig; + } + + // run function now, and every time window is resized + layout_header(); + $window.on('resize cloud-sidebar-toggled', layout_header); + }); + + + + + /*========================================================================== + * smooth scrolling + * instrument toc links w/in same page to use smooth scrolling + *==========================================================================*/ + var scrollSpeed = 500; + $(function () { + $('.sphinxsidebar a[href^="#"]').click(function (event) { + var hash = this.hash; + event.preventDefault(); + scrollingActive = true; // disable toc focus calc + $('html,body').animate({ + // NOTE: hash == "" for top of document + scrollTop: hash ? $(escapeHash(hash)).offset().top : 0 + }, scrollSpeed).promise().always(function (){ + // enable & redraw toc focus + // xxx: would really like to update *before* animation starts, + // so it's animation happened in parallel to scrolling animation + scrollingActive = false; + $window.trigger("cloud-sidebar-toggled"); + }); + if (window.history.pushState) { + window.history.pushState(null, "", hash || "#"); + } + $window.trigger("hashchange"); // for toggle section code + }); + }); + + + + /*========================================================================== + * auto determine when admonition should have inline / block title + * under this mode, the css will default to styling everything like a block, + * so we just mark everything that shouldn't be blocked out. + *==========================================================================*/ + $(function () { + $("div.body div.admonition:not(.inline-title):not(.block-title)" + + ":not(.danger):not(.error)" + + ":has(p:first-child + p:last-child)").addClass("inline-title"); + }); + + + /*========================================================================== + * patch sphinx search code to try to and prevent rest markup from showing up + * in search results + *==========================================================================*/ + var Search = window.Search; + if (Search && Search.makeSearchSummary) { + var sphinxSummary = Search.makeSearchSummary; + Search.makeSearchSummary = function (text, keywords, hlwords) { + /* very primitive regex hack to turn headers into dots */ + text = text.replace(/^(\s|\n)*([-#=.])\2{6,}\s*\n/, ''); + text = text.replace(/^([-#=.])\1{6,}\s*$/mg, '\u26AB'); + text = text.replace(/^\s*#\.\s*/mg, '\u2022 '); + //console.debug("makeSearchSummary: text=%o keywords=%o hlwords=%o", text, keywords, hlwords); + return sphinxSummary.call(this, text, keywords, hlwords); + } + } + + /*========================================================================== + * toc page styling + *========================================================================== + * adds some classes to TOC page so items can be styled. + * sets li.page and div.highlight-pages markers + *==========================================================================*/ + $(function () { + $("div.body div.toctree-wrapper").each(function (){ + var $div = $(this), + highlight = false; + $div.find("li").each(function (){ + var $li = $(this), + url = baseUrl($li.children("a").attr("href")), + $parent = $li.parent("ul").prev("a"), + parentUrl = baseUrl($parent.attr("href")); + if(!$parent.length || parentUrl != url){ + $li.addClass("page"); + } else { + highlight = true; + } + }); + if(highlight) { $div.addClass("highlight-pages"); } + }); + + var $toc = $("#table-of-contents div.toctree-wrapper.highlight-pages"); + if($toc.length){ + $('') + .insertBefore($toc).find("input") + .change(function (evt){ + $toc.toggleClass("hide-sections", evt.target.checked); + }).change(); + $(".sphinxglobaltoc > h3").css("margin-top", "4px").wrap('
'); + } + }); + + /* ========================================================================== + * codeblock lineno aligner + * if document contains multiple codeblocks, and some have different counts + * (e.g. 10 lines vs 300 lines), the alignment will look off, since the + * 300 line block will be indented 1 extra space to account for the hundreds. + * this unifies the widths of all such blocks (issue 19) + *==========================================================================*/ + $(function () { + var $lines = $(".linenodiv pre"); + if (!$lines.length) { + return; + } + // NOTE: using ems so this holds under font size changes + var largest = Math.max.apply(null, $lines.map(function () { + return $(this).innerWidth(); + })), + em_to_px = csspx($lines, "font-size"); + $lines.css("width", (largest / em_to_px) + "em").css("text-align", "right"); + }); + + /*========================================================================== + * codeblock copy helper button + *========================================================================== + * + * Add a [>>>] button on the top-right corner of code samples to hide + * the '>>>' and '...' prompts and the output and thus make the code + * copyable. Also hides linenumbers. + * + * Adapted from copybutton.js, + * Copyright 2014 PSF. Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 + * File originates from the cpython source found in Doc/tools/sphinxext/static/copybutton.js + *==========================================================================*/ + $(function () { + // TODO: enhance this to hide linenos for ALL highlighted code blocks, + // and only perform python-specific hiding as-needed. + + // static text + var hide_text = 'Hide the prompts and output', + show_text = 'Show the prompts and output'; + + // helper which sets button & codeblock state + function setButtonState($button, active) { + $button.parent().find('.go, .gp, .gt').toggle(!active); + $button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', active ? 'hidden' : 'visible'); + $button.closest(".highlighttable").find(".linenos pre").css('visibility', active ? 'hidden' : 'visible'); + $button.attr('title', active ? show_text : hide_text); + $button.toggleClass("active", active); + } + + // create and add the button to all the code blocks containing a python prompt + var $blocks = $('.highlight-python, .highlight-python3'); + $blocks.find(".highlight:has(pre .gp)").each(function () { + var $block = $(this); + + // tracebacks (.gt) contain bare text elements that need to be + // wrapped in a span to work with .nextUntil() call in setButtonState() + $block.find('pre:has(.gt)').contents().filter(function () { + return ((this.nodeType == TEXT_NODE) && (this.data.trim().length > 0)); + }).wrap(''); + + // insert button into block + var $button = $(''); + $block.css("position", "relative").prepend($button); + setButtonState($button, false); + }); + + // toggle button state when clicked + $('.copybutton').click( + function () { + var $button = $(this); + setButtonState($button, !$button.hasClass("active")); + }); + }); + + /*========================================================================== + * nested section helper + *========================================================================== + * fills out 'data-nested-label' for nested sections (e.g. those w/in a class def) + * based on name of containing class. this is used to generate a "return to top" + * link w/in nested section header. + *==========================================================================*/ + + $(function () { + var template = _.template(('<%- name %> \\2014\\0020').replace( + /\\(\d{4})/g, function (m, char) { return String.fromCharCode(parseInt(char,16)); } + )); + $(".desc-section > .section-header").each(function (idx, header) { + var $header = $(header), + $parent = $header.closest("dd").prev("dt"), + name = $parent.find(".descname").text(); + if (!name) { + return; + } + $header.attr("data-nested-label", template({name: name, parent: $parent})); + }); + }); + + + /*========================================================================== + * field definition markup + * XXX: could try to do this via an extension + *==========================================================================*/ + $(function () { + // sphinx2 doesn't distinguish classmethod/staticmethod, so add helper class for styling. + $("dl.method").each(function (){ + var $item = $(this), + type = $item.find("> dt > em.property:first-child").text().trim(); + if(type){ + $item.attr("subtype", type); + } + }); + + // detect which ones end w/ headerlink, to adjust markup + // NOTE: .classmethod & .staticmethod can be removed when sphinx 1.x is dropped. + $("dl.object, dl.data, dl.function, dl.method, dl.attribute, dl.class , dl.exception, dl.classmethod, dl.staticmethod") + .filter(":has(> dt > a.headerlink:last-child)").addClass("has-headerlink"); + }); + + /*========================================================================== + * eof + *==========================================================================*/ + +// end encapsulation +// NOTE: sphinx provides underscore.js as $u +}(window, jQuery, $u, CST)); \ No newline at end of file diff --git a/_static/comment-bright.png b/_static/comment-bright.png new file mode 100644 index 000000000..15e27edb1 Binary files /dev/null and b/_static/comment-bright.png differ diff --git a/_static/comment-close.png b/_static/comment-close.png new file mode 100644 index 000000000..4d91bcf57 Binary files /dev/null and b/_static/comment-close.png differ diff --git a/_static/comment.png b/_static/comment.png new file mode 100644 index 000000000..dfbc0cbd5 Binary files /dev/null and b/_static/comment.png differ diff --git a/_static/core-team-2014-05-30.jpg b/_static/core-team-2014-05-30.jpg new file mode 100755 index 000000000..3017b2dc6 Binary files /dev/null and b/_static/core-team-2014-05-30.jpg differ diff --git a/_static/corner_flourish.png b/_static/corner_flourish.png new file mode 100755 index 000000000..c880c4c0e Binary files /dev/null and b/_static/corner_flourish.png differ diff --git a/_static/crest.png b/_static/crest.png new file mode 100755 index 000000000..3198d44df Binary files /dev/null and b/_static/crest.png differ diff --git a/_static/curlydivider-left.png b/_static/curlydivider-left.png new file mode 100755 index 000000000..a30c9bba5 Binary files /dev/null and b/_static/curlydivider-left.png differ diff --git a/_static/curlydivider-right.png b/_static/curlydivider-right.png new file mode 100755 index 000000000..0563d6ba9 Binary files /dev/null and b/_static/curlydivider-right.png differ diff --git a/_static/cyclus.css b/_static/cyclus.css new file mode 100755 index 000000000..68769c348 --- /dev/null +++ b/_static/cyclus.css @@ -0,0 +1,121 @@ +@import url("cloud.css"); + +body { + background-image:url('gear_flourish_transp.png'), + url('curlydivider-right.png'), + url('curlydivider-left.png'), + url('metal.png'), + url('corner_flourish.png'), + url('pocket-watch.png'), + url('smallalarmclock.png'); + background-repeat: no-repeat, + repeat-y, + repeat-y, + repeat, + no-repeat, + no-repeat, + no-repeat; + background-position: bottom left, + top right, + top left, + 0 0, + 98% 0px, + 97% 99%, + 42px 42px; + background-attachment: scroll, scroll, scroll, scroll, scroll, scroll, scroll; + background-size:20%, 51px, 51px, auto, auto, auto, auto; +} + +table.docutils th.field-name { + white-space: nowrap; +} + +div.body h2 { + background-color: #7b7f82; +} + +div.body h2.highlighted { + border: 0.25em solid #ece48b; +} + +div.note { + background-color: #c8e8b0; +} + +h2 a { + color: #fff3b6; +} + +div.body h2.html-toggle-button:hover +{ + background: #4b1a07; + -moz-box-shadow: 0 0 2px #bb3f3f; + -webkit-box-shadow: 0 0 2px #bb3f3f; + -o-box-shadow: 0 0 2px #bb3f3f; + -ms-box-shadow: 0 0 2px #bb3f3f; + box-shadow: 0 0 2px #bb3f3f; +} + +div#cyclus.section h1 { + display: none; +} + +#dashboard { + max-height: 600px; + overflow: auto; +} + +#dashboard table { + width:80%; + border-color:#a9a9a9; + color:#333333; + border-collapse:collapse; + margin:auto; + border-width:1px; + text-align:center; +} +#dashboard th { + padding:4px; + border-style:solid; + border-color:#a9a9a9; + border-width:1px; + background-color:#b8b8b8; + text-align:left; +} +#dashboard tr { + background-color:#ffffff; + text-align:center; +} +#dashboard td { + padding:4px; + border-color:#a9a9a9; + border-style:solid; + border-width:1px; + text-align:center; +} +#dashboard tr.status-complete { + background-color:#E0FFC2; +} +#dashboard tr.status-queued { + background-color:#FFFFCC; +} +#dashboard tr.status-running { + background-color:#D1F0FF; +} +#dashboard tr.status-failed { + background-color:#F0C2B2; +} + +#infile-form { + width:80%; + margin:auto; +} +#infile-form textarea { + width: 100%; +} + +div.sphinxlocaltoc ul a, div.sphinxglobaltoc ul a{ + display: inline; + white-space: normal; + word-wrap: normal; +} \ No newline at end of file diff --git a/_static/doctools.js b/_static/doctools.js new file mode 100755 index 000000000..d06a71d75 --- /dev/null +++ b/_static/doctools.js @@ -0,0 +1,156 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Base JavaScript utilities for all Sphinx HTML documentation. + * + * :copyright: Copyright 2007-2023 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ +"use strict"; + +const BLACKLISTED_KEY_CONTROL_ELEMENTS = new Set([ + "TEXTAREA", + "INPUT", + "SELECT", + "BUTTON", +]); + +const _ready = (callback) => { + if (document.readyState !== "loading") { + callback(); + } else { + document.addEventListener("DOMContentLoaded", callback); + } +}; + +/** + * Small JavaScript module for the documentation. + */ +const Documentation = { + init: () => { + Documentation.initDomainIndexTable(); + Documentation.initOnKeyListeners(); + }, + + /** + * i18n support + */ + TRANSLATIONS: {}, + PLURAL_EXPR: (n) => (n === 1 ? 0 : 1), + LOCALE: "unknown", + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext: (string) => { + const translated = Documentation.TRANSLATIONS[string]; + switch (typeof translated) { + case "undefined": + return string; // no translation + case "string": + return translated; // translation exists + default: + return translated[0]; // (singular, plural) translation tuple exists + } + }, + + ngettext: (singular, plural, n) => { + const translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated !== "undefined") + return translated[Documentation.PLURAL_EXPR(n)]; + return n === 1 ? singular : plural; + }, + + addTranslations: (catalog) => { + Object.assign(Documentation.TRANSLATIONS, catalog.messages); + Documentation.PLURAL_EXPR = new Function( + "n", + `return (${catalog.plural_expr})` + ); + Documentation.LOCALE = catalog.locale; + }, + + /** + * helper function to focus on search bar + */ + focusSearchBar: () => { + document.querySelectorAll("input[name=q]")[0]?.focus(); + }, + + /** + * Initialise the domain index toggle buttons + */ + initDomainIndexTable: () => { + const toggler = (el) => { + const idNumber = el.id.substr(7); + const toggledRows = document.querySelectorAll(`tr.cg-${idNumber}`); + if (el.src.substr(-9) === "minus.png") { + el.src = `${el.src.substr(0, el.src.length - 9)}plus.png`; + toggledRows.forEach((el) => (el.style.display = "none")); + } else { + el.src = `${el.src.substr(0, el.src.length - 8)}minus.png`; + toggledRows.forEach((el) => (el.style.display = "")); + } + }; + + const togglerElements = document.querySelectorAll("img.toggler"); + togglerElements.forEach((el) => + el.addEventListener("click", (event) => toggler(event.currentTarget)) + ); + togglerElements.forEach((el) => (el.style.display = "")); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) togglerElements.forEach(toggler); + }, + + initOnKeyListeners: () => { + // only install a listener if it is really needed + if ( + !DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS && + !DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS + ) + return; + + document.addEventListener("keydown", (event) => { + // bail for input elements + if (BLACKLISTED_KEY_CONTROL_ELEMENTS.has(document.activeElement.tagName)) return; + // bail with special keys + if (event.altKey || event.ctrlKey || event.metaKey) return; + + if (!event.shiftKey) { + switch (event.key) { + case "ArrowLeft": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const prevLink = document.querySelector('link[rel="prev"]'); + if (prevLink && prevLink.href) { + window.location.href = prevLink.href; + event.preventDefault(); + } + break; + case "ArrowRight": + if (!DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) break; + + const nextLink = document.querySelector('link[rel="next"]'); + if (nextLink && nextLink.href) { + window.location.href = nextLink.href; + event.preventDefault(); + } + break; + } + } + + // some keyboard layouts may need Shift to get / + switch (event.key) { + case "/": + if (!DOCUMENTATION_OPTIONS.ENABLE_SEARCH_SHORTCUTS) break; + Documentation.focusSearchBar(); + event.preventDefault(); + } + }); + }, +}; + +// quick alias for translations +const _ = Documentation.gettext; + +_ready(Documentation.init); diff --git a/_static/documentation_options.js b/_static/documentation_options.js new file mode 100755 index 000000000..5e38838d9 --- /dev/null +++ b/_static/documentation_options.js @@ -0,0 +1,13 @@ +const DOCUMENTATION_OPTIONS = { + VERSION: '(999999.999999)', + LANGUAGE: 'en', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, + SHOW_SEARCH_SUMMARY: true, + ENABLE_SEARCH_SHORTCUTS: true, +}; \ No newline at end of file diff --git a/_static/down-pressed.png b/_static/down-pressed.png new file mode 100644 index 000000000..5756c8cad Binary files /dev/null and b/_static/down-pressed.png differ diff --git a/_static/down.png b/_static/down.png new file mode 100644 index 000000000..1b3bdad2c Binary files /dev/null and b/_static/down.png differ diff --git a/_static/file.png b/_static/file.png new file mode 100755 index 000000000..a858a410e Binary files /dev/null and b/_static/file.png differ diff --git a/_static/flying_gears.jpg b/_static/flying_gears.jpg new file mode 100755 index 000000000..182a8db52 Binary files /dev/null and b/_static/flying_gears.jpg differ diff --git a/_static/gear_flourish_transp.png b/_static/gear_flourish_transp.png new file mode 100755 index 000000000..450f9209c Binary files /dev/null and b/_static/gear_flourish_transp.png differ diff --git a/_static/header-image.png b/_static/header-image.png new file mode 100755 index 000000000..d5ff915b2 Binary files /dev/null and b/_static/header-image.png differ diff --git a/_static/icon-caution.png b/_static/icon-caution.png new file mode 100755 index 000000000..0437a0df3 Binary files /dev/null and b/_static/icon-caution.png differ diff --git a/_static/icon-danger.png b/_static/icon-danger.png new file mode 100755 index 000000000..b68290bf1 Binary files /dev/null and b/_static/icon-danger.png differ diff --git a/_static/icon-deprecated.png b/_static/icon-deprecated.png new file mode 100755 index 000000000..f98013820 Binary files /dev/null and b/_static/icon-deprecated.png differ diff --git a/_static/icon-note.png b/_static/icon-note.png new file mode 100755 index 000000000..07cf0102d Binary files /dev/null and b/_static/icon-note.png differ diff --git a/_static/icon-seealso.png b/_static/icon-seealso.png new file mode 100755 index 000000000..5a0d618e8 Binary files /dev/null and b/_static/icon-seealso.png differ diff --git a/_static/icon-todo.png b/_static/icon-todo.png new file mode 100755 index 000000000..8ef08e2e5 Binary files /dev/null and b/_static/icon-todo.png differ diff --git a/_static/icon-warning.png b/_static/icon-warning.png new file mode 100755 index 000000000..0ce38d936 Binary files /dev/null and b/_static/icon-warning.png differ diff --git a/_static/images/sort_asc.png b/_static/images/sort_asc.png new file mode 100755 index 000000000..a88d7975f Binary files /dev/null and b/_static/images/sort_asc.png differ diff --git a/_static/images/sort_asc_disabled.png b/_static/images/sort_asc_disabled.png new file mode 100755 index 000000000..4e144cf0b Binary files /dev/null and b/_static/images/sort_asc_disabled.png differ diff --git a/_static/images/sort_both.png b/_static/images/sort_both.png new file mode 100755 index 000000000..18670406b Binary files /dev/null and b/_static/images/sort_both.png differ diff --git a/_static/images/sort_desc.png b/_static/images/sort_desc.png new file mode 100755 index 000000000..def071ed5 Binary files /dev/null and b/_static/images/sort_desc.png differ diff --git a/_static/images/sort_desc_disabled.png b/_static/images/sort_desc_disabled.png new file mode 100755 index 000000000..7824973cc Binary files /dev/null and b/_static/images/sort_desc_disabled.png differ diff --git a/_static/jquery-3.1.0.js b/_static/jquery-3.1.0.js new file mode 100755 index 000000000..f2fc27478 --- /dev/null +++ b/_static/jquery-3.1.0.js @@ -0,0 +1,10074 @@ +/*eslint-disable no-unused-vars*/ +/*! + * jQuery JavaScript Library v3.1.0 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2016-07-07T21:44Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + + + + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* global Symbol */ +// Defining this global in .eslintrc would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.1.0", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); + }, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.0 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-01-04 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement("fieldset"); + + try { + return !!fn( el ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + // Known :disabled false positives: + // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) + // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Check form elements and option elements for explicit disabling + return "label" in elem && elem.disabled === disabled || + "form" in elem && elem.disabled === disabled || + + // Check non-disabled form elements for fieldset[disabled] ancestors + "form" in elem && elem.disabled === false && ( + // Support: IE6-11+ + // Ancestry is covered for us + elem.isDisabled === disabled || + + // Otherwise, assume any non-