diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c0cbe3c..8ac33f95 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -15,6 +15,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + submodules: true - name: Build sdist run: | pip install pybind11 diff --git a/.github/workflows/run_tests.yml b/.github/workflows/run_tests.yml index 8911dfdc..e930df1a 100644 --- a/.github/workflows/run_tests.yml +++ b/.github/workflows/run_tests.yml @@ -54,4 +54,4 @@ jobs: run: | export PATH="$pythonLocation:$PATH" python -m pip install -e .[Dev,Orso] - pytest tests/ --cov=RATapi --cov-report=term + pytest tests/ --cov=ratapi --cov-report=term diff --git a/RATapi/__init__.py b/RATapi/__init__.py deleted file mode 100644 index 31f83c85..00000000 --- a/RATapi/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -"""RATapi is a Python package for modelling, fitting and optimising reflectivity problems.""" - -from contextlib import suppress - -import RATapi.examples as examples -from RATapi import events, models -from RATapi.classlist import ClassList -from RATapi.controls import Controls -from RATapi.outputs import BayesResults, Results -from RATapi.project import Project -from RATapi.run import run -from RATapi.utils import convert, plotting - -with suppress(ImportError): # orsopy is an optional dependency - from RATapi.utils import orso as orso - -__all__ = [ - "examples", - "models", - "events", - "ClassList", - "Controls", - "BayesResults", - "Results", - "Project", - "run", - "plotting", - "convert", -] diff --git a/RATapi/examples/__init__.py b/RATapi/examples/__init__.py deleted file mode 100644 index 86de2334..00000000 --- a/RATapi/examples/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Usage examples for the Python RAT API.""" - -from RATapi.examples.absorption.absorption import absorption -from RATapi.examples.convert_rascal_project.convert_rascal import convert_rascal -from RATapi.examples.domains.domains_custom_layers import domains_custom_layers -from RATapi.examples.domains.domains_custom_XY import domains_custom_XY -from RATapi.examples.domains.domains_standard_layers import domains_standard_layers -from RATapi.examples.normal_reflectivity.DSPC_custom_layers import DSPC_custom_layers -from RATapi.examples.normal_reflectivity.DSPC_custom_XY import DSPC_custom_XY -from RATapi.examples.normal_reflectivity.DSPC_data_background import DSPC_data_background -from RATapi.examples.normal_reflectivity.DSPC_function_background import DSPC_function_background -from RATapi.examples.normal_reflectivity.DSPC_standard_layers import DSPC_standard_layers - -__all__ = [ - "absorption", - "domains_custom_layers", - "domains_custom_XY", - "domains_standard_layers", - "DSPC_custom_layers", - "DSPC_custom_XY", - "DSPC_standard_layers", - "DSPC_data_background", - "DSPC_function_background", - "convert_rascal", -] diff --git a/RATapi/utils/__init__.py b/RATapi/utils/__init__.py deleted file mode 100644 index f229eb5c..00000000 --- a/RATapi/utils/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Additional utilities for RATapi.""" diff --git a/ratapi/__init__.py b/ratapi/__init__.py new file mode 100644 index 00000000..98683c7e --- /dev/null +++ b/ratapi/__init__.py @@ -0,0 +1,29 @@ +"""ratapi is a Python package for modelling, fitting and optimising reflectivity problems.""" + +from contextlib import suppress + +import ratapi.examples as examples +from ratapi import events, models +from ratapi.classlist import ClassList +from ratapi.controls import Controls +from ratapi.outputs import BayesResults, Results +from ratapi.project import Project +from ratapi.run import run +from ratapi.utils import convert, plotting + +with suppress(ImportError): # orsopy is an optional dependency + from ratapi.utils import orso as orso + +__all__ = [ + "examples", + "models", + "events", + "ClassList", + "Controls", + "BayesResults", + "Results", + "Project", + "run", + "plotting", + "convert", +] diff --git a/RATapi/classlist.py b/ratapi/classlist.py similarity index 100% rename from RATapi/classlist.py rename to ratapi/classlist.py diff --git a/RATapi/controls.py b/ratapi/controls.py similarity index 98% rename from RATapi/controls.py rename to ratapi/controls.py index d696fb57..d035a32d 100644 --- a/RATapi/controls.py +++ b/ratapi/controls.py @@ -17,8 +17,8 @@ model_validator, ) -from RATapi.utils.custom_errors import custom_pydantic_validation_error -from RATapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies +from ratapi.utils.custom_errors import custom_pydantic_validation_error +from ratapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies common_fields = ["procedure", "parallel", "calcSldDuringFit", "resampleMinAngle", "resampleNPoints", "display"] update_fields = ["updateFreq", "updatePlotFreq"] diff --git a/RATapi/events.py b/ratapi/events.py similarity index 97% rename from RATapi/events.py rename to ratapi/events.py index c2348ecc..71993ddb 100644 --- a/RATapi/events.py +++ b/ratapi/events.py @@ -3,7 +3,7 @@ import os from typing import Callable, Union -from RATapi.rat_core import EventBridge, EventTypes, PlotEventData, ProgressEventData +from ratapi.rat_core import EventBridge, EventTypes, PlotEventData, ProgressEventData def notify(event_type: EventTypes, data: Union[str, PlotEventData, ProgressEventData]) -> None: diff --git a/ratapi/examples/__init__.py b/ratapi/examples/__init__.py new file mode 100644 index 00000000..b85aebed --- /dev/null +++ b/ratapi/examples/__init__.py @@ -0,0 +1,25 @@ +"""Usage examples for the Python RAT API.""" + +from ratapi.examples.absorption.absorption import absorption +from ratapi.examples.convert_rascal_project.convert_rascal import convert_rascal +from ratapi.examples.domains.domains_custom_layers import domains_custom_layers +from ratapi.examples.domains.domains_custom_XY import domains_custom_XY +from ratapi.examples.domains.domains_standard_layers import domains_standard_layers +from ratapi.examples.normal_reflectivity.DSPC_custom_layers import DSPC_custom_layers +from ratapi.examples.normal_reflectivity.DSPC_custom_XY import DSPC_custom_XY +from ratapi.examples.normal_reflectivity.DSPC_data_background import DSPC_data_background +from ratapi.examples.normal_reflectivity.DSPC_function_background import DSPC_function_background +from ratapi.examples.normal_reflectivity.DSPC_standard_layers import DSPC_standard_layers + +__all__ = [ + "absorption", + "domains_custom_layers", + "domains_custom_XY", + "domains_standard_layers", + "DSPC_custom_layers", + "DSPC_custom_XY", + "DSPC_standard_layers", + "DSPC_data_background", + "DSPC_function_background", + "convert_rascal", +] diff --git a/RATapi/examples/absorption/__init__.py b/ratapi/examples/absorption/__init__.py similarity index 100% rename from RATapi/examples/absorption/__init__.py rename to ratapi/examples/absorption/__init__.py diff --git a/RATapi/examples/absorption/absorption.ipynb b/ratapi/examples/absorption/absorption.ipynb similarity index 99% rename from RATapi/examples/absorption/absorption.ipynb rename to ratapi/examples/absorption/absorption.ipynb index 10f3cda0..696103bc 100644 --- a/RATapi/examples/absorption/absorption.ipynb +++ b/ratapi/examples/absorption/absorption.ipynb @@ -11,8 +11,8 @@ "import numpy as np\n", "from IPython.display import Code\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Parameter" ] }, { diff --git a/RATapi/examples/absorption/absorption.py b/ratapi/examples/absorption/absorption.py similarity index 99% rename from RATapi/examples/absorption/absorption.py rename to ratapi/examples/absorption/absorption.py index 416a3b32..5d100aff 100644 --- a/RATapi/examples/absorption/absorption.py +++ b/ratapi/examples/absorption/absorption.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def absorption(): diff --git a/RATapi/examples/absorption/volume_thiol_bilayer.py b/ratapi/examples/absorption/volume_thiol_bilayer.py similarity index 100% rename from RATapi/examples/absorption/volume_thiol_bilayer.py rename to ratapi/examples/absorption/volume_thiol_bilayer.py diff --git a/RATapi/examples/bayes_benchmark/bayes_benchmark.ipynb b/ratapi/examples/bayes_benchmark/bayes_benchmark.ipynb similarity index 99% rename from RATapi/examples/bayes_benchmark/bayes_benchmark.ipynb rename to ratapi/examples/bayes_benchmark/bayes_benchmark.ipynb index 79e4ae95..0c083924 100644 --- a/RATapi/examples/bayes_benchmark/bayes_benchmark.ipynb +++ b/ratapi/examples/bayes_benchmark/bayes_benchmark.ipynb @@ -41,8 +41,8 @@ "source": [ "import numpy as np\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter, Background, Resolution, Data, Contrast" + "import ratapi as RAT\n", + "from ratapi.models import Parameter, Background, Resolution, Data, Contrast" ] }, { @@ -263,7 +263,7 @@ "source": [ "import matplotlib.pyplot as plt\n", "from matplotlib import colormaps\n", - "import RATapi.utils.plotting as RATplot\n", + "import ratapi.utils.plotting as RATplot\n", "\n", "fig, axes = plt.subplots(3, 2, figsize=(6, 9))\n", "\n", diff --git a/RATapi/examples/bayes_benchmark/bayes_benchmark.py b/ratapi/examples/bayes_benchmark/bayes_benchmark.py similarity index 99% rename from RATapi/examples/bayes_benchmark/bayes_benchmark.py rename to ratapi/examples/bayes_benchmark/bayes_benchmark.py index 80ac9a24..9840b002 100644 --- a/RATapi/examples/bayes_benchmark/bayes_benchmark.py +++ b/ratapi/examples/bayes_benchmark/bayes_benchmark.py @@ -24,9 +24,9 @@ import matplotlib.pyplot as plt import numpy as np -import RATapi as RAT -import RATapi.utils.plotting as RATplot -from RATapi.models import Background, Contrast, Data, Parameter, Resolution +import ratapi as RAT +import ratapi.utils.plotting as RATplot +from ratapi.models import Background, Contrast, Data, Parameter, Resolution PWD = Path(__file__).parents[0] diff --git a/RATapi/examples/convert_rascal_project/Model_IIb.m b/ratapi/examples/convert_rascal_project/Model_IIb.m similarity index 100% rename from RATapi/examples/convert_rascal_project/Model_IIb.m rename to ratapi/examples/convert_rascal_project/Model_IIb.m diff --git a/RATapi/examples/convert_rascal_project/Model_IIb.py b/ratapi/examples/convert_rascal_project/Model_IIb.py similarity index 100% rename from RATapi/examples/convert_rascal_project/Model_IIb.py rename to ratapi/examples/convert_rascal_project/Model_IIb.py diff --git a/RATapi/examples/convert_rascal_project/R1monolayerVolumeModel.mat b/ratapi/examples/convert_rascal_project/R1monolayerVolumeModel.mat similarity index 100% rename from RATapi/examples/convert_rascal_project/R1monolayerVolumeModel.mat rename to ratapi/examples/convert_rascal_project/R1monolayerVolumeModel.mat diff --git a/RATapi/examples/convert_rascal_project/__init__.py b/ratapi/examples/convert_rascal_project/__init__.py similarity index 100% rename from RATapi/examples/convert_rascal_project/__init__.py rename to ratapi/examples/convert_rascal_project/__init__.py diff --git a/RATapi/examples/convert_rascal_project/convert_rascal.ipynb b/ratapi/examples/convert_rascal_project/convert_rascal.ipynb similarity index 96% rename from RATapi/examples/convert_rascal_project/convert_rascal.ipynb rename to ratapi/examples/convert_rascal_project/convert_rascal.ipynb index fbae2d5b..aebd749a 100644 --- a/RATapi/examples/convert_rascal_project/convert_rascal.ipynb +++ b/ratapi/examples/convert_rascal_project/convert_rascal.ipynb @@ -24,7 +24,7 @@ "metadata": {}, "outputs": [], "source": [ - "from RATapi.utils.convert import r1_to_project\n", + "from ratapi.utils.convert import r1_to_project\n", "\n", "project = r1_to_project(\"R1monolayerVolumeModel.mat\")\n", "print(project)" @@ -99,7 +99,7 @@ "metadata": {}, "outputs": [], "source": [ - "from RATapi.examples import DSPC_standard_layers\n", + "from ratapi.examples import DSPC_standard_layers\n", "lipid_bilayer_project = DSPC_standard_layers()[0]\n", "print(lipid_bilayer_project)" ] @@ -121,7 +121,7 @@ "metadata": {}, "outputs": [], "source": [ - "from RATapi.utils.convert import project_to_r1\n", + "from ratapi.utils.convert import project_to_r1\n", "from pprint import pp # for printing the struct\n", "\n", "# save to a file called lipid_bilayer.mat\n", diff --git a/RATapi/examples/convert_rascal_project/convert_rascal.py b/ratapi/examples/convert_rascal_project/convert_rascal.py similarity index 98% rename from RATapi/examples/convert_rascal_project/convert_rascal.py rename to ratapi/examples/convert_rascal_project/convert_rascal.py index 2a41b61f..15179b35 100644 --- a/RATapi/examples/convert_rascal_project/convert_rascal.py +++ b/ratapi/examples/convert_rascal_project/convert_rascal.py @@ -3,7 +3,7 @@ import pathlib from pprint import pp -import RATapi as RAT +import ratapi as RAT # convert R1 project to Project class diff --git a/RATapi/examples/data/D2O_spin_down.dat b/ratapi/examples/data/D2O_spin_down.dat similarity index 100% rename from RATapi/examples/data/D2O_spin_down.dat rename to ratapi/examples/data/D2O_spin_down.dat diff --git a/RATapi/examples/data/D2O_spin_up.dat b/ratapi/examples/data/D2O_spin_up.dat similarity index 100% rename from RATapi/examples/data/D2O_spin_up.dat rename to ratapi/examples/data/D2O_spin_up.dat diff --git a/RATapi/examples/data/DSPC_D2O.dat b/ratapi/examples/data/DSPC_D2O.dat similarity index 100% rename from RATapi/examples/data/DSPC_D2O.dat rename to ratapi/examples/data/DSPC_D2O.dat diff --git a/RATapi/examples/data/DSPC_SMW.dat b/ratapi/examples/data/DSPC_SMW.dat similarity index 100% rename from RATapi/examples/data/DSPC_SMW.dat rename to ratapi/examples/data/DSPC_SMW.dat diff --git a/RATapi/examples/data/H2O_spin_down.dat b/ratapi/examples/data/H2O_spin_down.dat similarity index 100% rename from RATapi/examples/data/H2O_spin_down.dat rename to ratapi/examples/data/H2O_spin_down.dat diff --git a/RATapi/examples/data/H2O_spin_up.dat b/ratapi/examples/data/H2O_spin_up.dat similarity index 100% rename from RATapi/examples/data/H2O_spin_up.dat rename to ratapi/examples/data/H2O_spin_up.dat diff --git a/RATapi/examples/data/__init__.py b/ratapi/examples/data/__init__.py similarity index 100% rename from RATapi/examples/data/__init__.py rename to ratapi/examples/data/__init__.py diff --git a/RATapi/examples/data/c_PLP0011859_q.ort b/ratapi/examples/data/c_PLP0011859_q.ort similarity index 100% rename from RATapi/examples/data/c_PLP0011859_q.ort rename to ratapi/examples/data/c_PLP0011859_q.ort diff --git a/RATapi/examples/data/c_PLP0016596.dat b/ratapi/examples/data/c_PLP0016596.dat similarity index 100% rename from RATapi/examples/data/c_PLP0016596.dat rename to ratapi/examples/data/c_PLP0016596.dat diff --git a/RATapi/examples/data/c_PLP0016601.dat b/ratapi/examples/data/c_PLP0016601.dat similarity index 100% rename from RATapi/examples/data/c_PLP0016601.dat rename to ratapi/examples/data/c_PLP0016601.dat diff --git a/RATapi/examples/data/c_PLP0016607.dat b/ratapi/examples/data/c_PLP0016607.dat similarity index 100% rename from RATapi/examples/data/c_PLP0016607.dat rename to ratapi/examples/data/c_PLP0016607.dat diff --git a/RATapi/examples/data/d2o_background_data.dat b/ratapi/examples/data/d2o_background_data.dat similarity index 100% rename from RATapi/examples/data/d2o_background_data.dat rename to ratapi/examples/data/d2o_background_data.dat diff --git a/RATapi/examples/domains/__init__.py b/ratapi/examples/domains/__init__.py similarity index 100% rename from RATapi/examples/domains/__init__.py rename to ratapi/examples/domains/__init__.py diff --git a/RATapi/examples/domains/alloy_domains.py b/ratapi/examples/domains/alloy_domains.py similarity index 100% rename from RATapi/examples/domains/alloy_domains.py rename to ratapi/examples/domains/alloy_domains.py diff --git a/RATapi/examples/domains/domains_XY_model.py b/ratapi/examples/domains/domains_XY_model.py similarity index 100% rename from RATapi/examples/domains/domains_XY_model.py rename to ratapi/examples/domains/domains_XY_model.py diff --git a/RATapi/examples/domains/domains_custom_XY.ipynb b/ratapi/examples/domains/domains_custom_XY.ipynb similarity index 98% rename from RATapi/examples/domains/domains_custom_XY.ipynb rename to ratapi/examples/domains/domains_custom_XY.ipynb index fa8f317d..0a153e9d 100644 --- a/RATapi/examples/domains/domains_custom_XY.ipynb +++ b/ratapi/examples/domains/domains_custom_XY.ipynb @@ -9,8 +9,8 @@ "import pathlib\n", "from IPython.display import Code\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Parameter" ] }, { diff --git a/RATapi/examples/domains/domains_custom_XY.py b/ratapi/examples/domains/domains_custom_XY.py similarity index 99% rename from RATapi/examples/domains/domains_custom_XY.py rename to ratapi/examples/domains/domains_custom_XY.py index a9c1846e..38d4f031 100644 --- a/RATapi/examples/domains/domains_custom_XY.py +++ b/ratapi/examples/domains/domains_custom_XY.py @@ -2,7 +2,7 @@ import pathlib -import RATapi as RAT +import ratapi as RAT def domains_custom_XY(): diff --git a/RATapi/examples/domains/domains_custom_layers.ipynb b/ratapi/examples/domains/domains_custom_layers.ipynb similarity index 99% rename from RATapi/examples/domains/domains_custom_layers.ipynb rename to ratapi/examples/domains/domains_custom_layers.ipynb index 03179d54..3016e977 100644 --- a/RATapi/examples/domains/domains_custom_layers.ipynb +++ b/ratapi/examples/domains/domains_custom_layers.ipynb @@ -9,8 +9,8 @@ "import pathlib\n", "from IPython.display import Code\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Parameter" ] }, { diff --git a/RATapi/examples/domains/domains_custom_layers.py b/ratapi/examples/domains/domains_custom_layers.py similarity index 99% rename from RATapi/examples/domains/domains_custom_layers.py rename to ratapi/examples/domains/domains_custom_layers.py index 439728a0..92b5e037 100644 --- a/RATapi/examples/domains/domains_custom_layers.py +++ b/ratapi/examples/domains/domains_custom_layers.py @@ -2,7 +2,7 @@ import pathlib -import RATapi as RAT +import ratapi as RAT def domains_custom_layers(): diff --git a/RATapi/examples/domains/domains_standard_layers.ipynb b/ratapi/examples/domains/domains_standard_layers.ipynb similarity index 99% rename from RATapi/examples/domains/domains_standard_layers.ipynb rename to ratapi/examples/domains/domains_standard_layers.ipynb index 2b5a29f0..300207d3 100644 --- a/RATapi/examples/domains/domains_standard_layers.ipynb +++ b/ratapi/examples/domains/domains_standard_layers.ipynb @@ -6,8 +6,8 @@ "metadata": {}, "outputs": [], "source": [ - "import RATapi as RAT\n", - "from RATapi.models import Layer, Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Layer, Parameter" ] }, { diff --git a/RATapi/examples/domains/domains_standard_layers.py b/ratapi/examples/domains/domains_standard_layers.py similarity index 99% rename from RATapi/examples/domains/domains_standard_layers.py rename to ratapi/examples/domains/domains_standard_layers.py index 9e821a8d..9a251233 100644 --- a/RATapi/examples/domains/domains_standard_layers.py +++ b/ratapi/examples/domains/domains_standard_layers.py @@ -1,6 +1,6 @@ """An example using domains with standard layers.""" -import RATapi as RAT +import ratapi as RAT def domains_standard_layers(): diff --git a/RATapi/examples/extras/two_contrast_example.py b/ratapi/examples/extras/two_contrast_example.py similarity index 99% rename from RATapi/examples/extras/two_contrast_example.py rename to ratapi/examples/extras/two_contrast_example.py index ca441e14..86811056 100644 --- a/RATapi/examples/extras/two_contrast_example.py +++ b/ratapi/examples/extras/two_contrast_example.py @@ -2,7 +2,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def two_contrast_example(): diff --git a/RATapi/examples/languages/__init__.py b/ratapi/examples/languages/__init__.py similarity index 100% rename from RATapi/examples/languages/__init__.py rename to ratapi/examples/languages/__init__.py diff --git a/RATapi/examples/languages/custom_bilayer.cpp b/ratapi/examples/languages/custom_bilayer.cpp similarity index 100% rename from RATapi/examples/languages/custom_bilayer.cpp rename to ratapi/examples/languages/custom_bilayer.cpp diff --git a/RATapi/examples/languages/custom_bilayer.m b/ratapi/examples/languages/custom_bilayer.m similarity index 100% rename from RATapi/examples/languages/custom_bilayer.m rename to ratapi/examples/languages/custom_bilayer.m diff --git a/RATapi/examples/languages/custom_bilayer.py b/ratapi/examples/languages/custom_bilayer.py similarity index 100% rename from RATapi/examples/languages/custom_bilayer.py rename to ratapi/examples/languages/custom_bilayer.py diff --git a/RATapi/examples/languages/run_custom_file_languages.py b/ratapi/examples/languages/run_custom_file_languages.py similarity index 97% rename from RATapi/examples/languages/run_custom_file_languages.py rename to ratapi/examples/languages/run_custom_file_languages.py index 29776b52..6e69f80e 100644 --- a/RATapi/examples/languages/run_custom_file_languages.py +++ b/ratapi/examples/languages/run_custom_file_languages.py @@ -5,7 +5,7 @@ import setup_problem -import RATapi as RAT +import ratapi as RAT path = pathlib.Path(__file__).parent diff --git a/RATapi/examples/languages/setup_problem.py b/ratapi/examples/languages/setup_problem.py similarity index 99% rename from RATapi/examples/languages/setup_problem.py rename to ratapi/examples/languages/setup_problem.py index 7c294126..dbf300db 100644 --- a/RATapi/examples/languages/setup_problem.py +++ b/ratapi/examples/languages/setup_problem.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def make_example_problem(): diff --git a/RATapi/examples/normal_reflectivity/DSPC_custom_XY.py b/ratapi/examples/normal_reflectivity/DSPC_custom_XY.py similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_custom_XY.py rename to ratapi/examples/normal_reflectivity/DSPC_custom_XY.py index 442d6707..72511977 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_custom_XY.py +++ b/ratapi/examples/normal_reflectivity/DSPC_custom_XY.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def DSPC_custom_XY(): diff --git a/RATapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb b/ratapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb rename to ratapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb index 0adac7eb..d2fd6ed3 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb +++ b/ratapi/examples/normal_reflectivity/DSPC_custom_layers.ipynb @@ -12,8 +12,8 @@ "import numpy as np\n", "from IPython.display import Code\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Parameter" ] }, { @@ -730,7 +730,7 @@ "+-------+------------+------------------------+---------------------+----------+-------------------------------------------------------------------------+\n", "| index | name | filename | function name | language | path |\n", "+-------+------------+------------------------+---------------------+----------+-------------------------------------------------------------------------+\n", - "| 0 | DSPC Model | custom_bilayer_DSPC.py | custom_bilayer_DSPC | python | /mnt/c/Users/gnn85523/projects/python-RAT/RATapi/examples/non_polarised |\n", + "| 0 | DSPC Model | custom_bilayer_DSPC.py | custom_bilayer_DSPC | python | /mnt/c/Users/gnn85523/projects/python-RAT/ratapi/examples/non_polarised |\n", "+-------+------------+------------------------+---------------------+----------+-------------------------------------------------------------------------+\n", "\n", "Data: ----------------------------------------------------------------------------------------------\n", diff --git a/RATapi/examples/normal_reflectivity/DSPC_custom_layers.py b/ratapi/examples/normal_reflectivity/DSPC_custom_layers.py similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_custom_layers.py rename to ratapi/examples/normal_reflectivity/DSPC_custom_layers.py index adcba5d3..8de14903 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_custom_layers.py +++ b/ratapi/examples/normal_reflectivity/DSPC_custom_layers.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def DSPC_custom_layers(): diff --git a/RATapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb b/ratapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb rename to ratapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb index 8925865c..0c0472c9 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb +++ b/ratapi/examples/normal_reflectivity/DSPC_custom_xy.ipynb @@ -12,8 +12,8 @@ "import numpy as np\n", "from IPython.display import Code\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Parameter" ] }, { diff --git a/RATapi/examples/normal_reflectivity/DSPC_data_background.py b/ratapi/examples/normal_reflectivity/DSPC_data_background.py similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_data_background.py rename to ratapi/examples/normal_reflectivity/DSPC_data_background.py index e4b6869f..11a14730 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_data_background.py +++ b/ratapi/examples/normal_reflectivity/DSPC_data_background.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def DSPC_data_background(): diff --git a/RATapi/examples/normal_reflectivity/DSPC_function_background.py b/ratapi/examples/normal_reflectivity/DSPC_function_background.py similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_function_background.py rename to ratapi/examples/normal_reflectivity/DSPC_function_background.py index f149cfbb..e6a87b69 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_function_background.py +++ b/ratapi/examples/normal_reflectivity/DSPC_function_background.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def DSPC_function_background(): diff --git a/RATapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb b/ratapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb rename to ratapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb index 050b7497..3110cfe5 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb +++ b/ratapi/examples/normal_reflectivity/DSPC_standard_layers.ipynb @@ -11,8 +11,8 @@ "\n", "import numpy as np\n", "\n", - "import RATapi as RAT\n", - "from RATapi.models import Layer, Parameter" + "import ratapi as RAT\n", + "from ratapi.models import Layer, Parameter" ] }, { diff --git a/RATapi/examples/normal_reflectivity/DSPC_standard_layers.py b/ratapi/examples/normal_reflectivity/DSPC_standard_layers.py similarity index 99% rename from RATapi/examples/normal_reflectivity/DSPC_standard_layers.py rename to ratapi/examples/normal_reflectivity/DSPC_standard_layers.py index f4cc2ce4..6962f036 100644 --- a/RATapi/examples/normal_reflectivity/DSPC_standard_layers.py +++ b/ratapi/examples/normal_reflectivity/DSPC_standard_layers.py @@ -4,7 +4,7 @@ import numpy as np -import RATapi as RAT +import ratapi as RAT def DSPC_standard_layers(): diff --git a/RATapi/examples/normal_reflectivity/__init__.py b/ratapi/examples/normal_reflectivity/__init__.py similarity index 100% rename from RATapi/examples/normal_reflectivity/__init__.py rename to ratapi/examples/normal_reflectivity/__init__.py diff --git a/RATapi/examples/normal_reflectivity/background_function.py b/ratapi/examples/normal_reflectivity/background_function.py similarity index 100% rename from RATapi/examples/normal_reflectivity/background_function.py rename to ratapi/examples/normal_reflectivity/background_function.py diff --git a/RATapi/examples/normal_reflectivity/custom_XY_DSPC.py b/ratapi/examples/normal_reflectivity/custom_XY_DSPC.py similarity index 100% rename from RATapi/examples/normal_reflectivity/custom_XY_DSPC.py rename to ratapi/examples/normal_reflectivity/custom_XY_DSPC.py diff --git a/RATapi/examples/normal_reflectivity/custom_bilayer_DSPC.py b/ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py similarity index 100% rename from RATapi/examples/normal_reflectivity/custom_bilayer_DSPC.py rename to ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py diff --git a/RATapi/examples/orso_integration/orso_integration.ipynb b/ratapi/examples/orso_integration/orso_integration.ipynb similarity index 90% rename from RATapi/examples/orso_integration/orso_integration.ipynb rename to ratapi/examples/orso_integration/orso_integration.ipynb index aa6f0797..03ec671e 100644 --- a/RATapi/examples/orso_integration/orso_integration.ipynb +++ b/ratapi/examples/orso_integration/orso_integration.ipynb @@ -11,7 +11,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "``python-RAT`` contains some integration with ``orsopy``, allowing for convenient interaction with the ``.ort`` file format. This integration is available through the `RATapi.utils.orso` submodule." + "``python-RAT`` contains some integration with ``orsopy``, allowing for convenient interaction with the ``.ort`` file format. This integration is available through the `ratapi.utils.orso` submodule." ] }, { @@ -20,7 +20,7 @@ "metadata": {}, "outputs": [], "source": [ - "import RATapi.utils.orso" + "import ratapi.utils.orso" ] }, { @@ -31,7 +31,7 @@ "\n", "The [ORSO model description format](https://www.reflectometry.org/advanced_and_expert_level/file_format/simple_model) allows the description of a standard slab model as a one-line string, provided that all the layer materials are defined [in the ORSO SLD database](https://slddb.esss.dk/slddb/).\n", "\n", - "The function `RATapi.utils.orso.orso_model_to_rat` function can read a model and return an `ORSOSample` dataclass, which gives bulk in and bulk out parameters for the model, a list of all layers defined in the model, and all the parameters needed to define those layers as RAT models. \n", + "The function `ratapi.utils.orso.orso_model_to_rat` function can read a model and return an `ORSOSample` dataclass, which gives bulk in and bulk out parameters for the model, a list of all layers defined in the model, and all the parameters needed to define those layers as RAT models. \n", "\n", "**Note:** the ORSO format gives the thicknesses of materials in *nanometres*. When we convert them to RAT parameters, the units will be converted to Angstroms.\n", "\n", @@ -45,7 +45,7 @@ "outputs": [], "source": [ "# create the RAT parameters and layers from this model\n", - "sample = RATapi.utils.orso.orso_model_to_rat(\"air | Ni 100 | SiO2 0.5 | Si\")\n", + "sample = ratapi.utils.orso.orso_model_to_rat(\"air | Ni 100 | SiO2 0.5 | Si\")\n", "print(sample)" ] }, @@ -62,7 +62,7 @@ "metadata": {}, "outputs": [], "source": [ - "sample = RATapi.utils.orso.orso_model_to_rat(\"vacuum | B4C 100 | SiO2 0.5 | Si\", absorption=True)\n", + "sample = ratapi.utils.orso.orso_model_to_rat(\"vacuum | B4C 100 | SiO2 0.5 | Si\", absorption=True)\n", "print(sample)" ] }, @@ -81,7 +81,7 @@ "metadata": {}, "outputs": [], "source": [ - "sample = RATapi.utils.orso.orso_model_to_rat(\"air | 5 ( Si 7 | Fe 7 ) | Si\")\n", + "sample = ratapi.utils.orso.orso_model_to_rat(\"air | 5 ( Si 7 | Fe 7 ) | Si\")\n", "print(sample)" ] }, @@ -110,7 +110,7 @@ "import pathlib\n", "data_path = pathlib.Path(\"../data\")\n", "\n", - "orso_data = RATapi.utils.orso.ORSOProject(data_path / \"c_PLP0011859_q.ort\")\n", + "orso_data = ratapi.utils.orso.ORSOProject(data_path / \"c_PLP0011859_q.ort\")\n", "print(orso_data)" ] }, @@ -129,12 +129,12 @@ "metadata": {}, "outputs": [], "source": [ - "from RATapi.models import Background, Contrast, Parameter, Resolution\n", + "from ratapi.models import Background, Contrast, Parameter, Resolution\n", "\n", "dataset = orso_data.data[0]\n", "sample = orso_data.samples[0]\n", "\n", - "project = RATapi.Project(\n", + "project = ratapi.Project(\n", " name = \"Example Project\",\n", " geometry = \"substrate/liquid\",\n", " parameters = sample.parameters,\n", @@ -158,9 +158,9 @@ " )]\n", ")\n", "\n", - "controls = RATapi.Controls()\n", - "project, results = RATapi.run(project, controls)\n", - "RATapi.plotting.plot_ref_sld(project, results)" + "controls = ratapi.Controls()\n", + "project, results = ratapi.run(project, controls)\n", + "ratapi.plotting.plot_ref_sld(project, results)" ] } ], diff --git a/RATapi/inputs.py b/ratapi/inputs.py similarity index 94% rename from RATapi/inputs.py rename to ratapi/inputs.py index 757aa78a..d9b0b729 100644 --- a/RATapi/inputs.py +++ b/ratapi/inputs.py @@ -7,11 +7,11 @@ import numpy as np -import RATapi -import RATapi.controls -import RATapi.wrappers -from RATapi.rat_core import Checks, Control, NameStore, ProblemDefinition -from RATapi.utils.enums import Calculations, Languages, LayerModels, TypeOptions +import ratapi +import ratapi.controls +import ratapi.wrappers +from ratapi.rat_core import Checks, Control, NameStore, ProblemDefinition +from ratapi.utils.enums import Calculations, Languages, LayerModels, TypeOptions parameter_field = { "parameters": "params", @@ -81,9 +81,9 @@ def get_handle(self, index: int): if custom_file["language"] == Languages.Python: file_handle = get_python_handle(custom_file["filename"], custom_file["function_name"], custom_file["path"]) elif custom_file["language"] == Languages.Matlab: - file_handle = RATapi.wrappers.MatlabWrapper(full_path).getHandle() + file_handle = ratapi.wrappers.MatlabWrapper(full_path).getHandle() elif custom_file["language"] == Languages.Cpp: - file_handle = RATapi.wrappers.DylibWrapper(full_path, custom_file["function_name"]).getHandle() + file_handle = ratapi.wrappers.DylibWrapper(full_path, custom_file["function_name"]).getHandle() return file_handle @@ -113,7 +113,7 @@ def __len__(self): return len(self.files) -def make_input(project: RATapi.Project, controls: RATapi.Controls) -> tuple[ProblemDefinition, Control]: +def make_input(project: ratapi.Project, controls: ratapi.Controls) -> tuple[ProblemDefinition, Control]: """Construct the inputs required for the compiled RAT code using the data defined in the input project and controls. Parameters @@ -137,7 +137,7 @@ def make_input(project: RATapi.Project, controls: RATapi.Controls) -> tuple[Prob return problem, cpp_controls -def make_problem(project: RATapi.Project) -> ProblemDefinition: +def make_problem(project: ratapi.Project) -> ProblemDefinition: """Construct the problem input required for the compiled RAT code. Parameters @@ -174,12 +174,12 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition: raise ValueError( f"All backgrounds must have a source defined. For a {background.type} type background, " f"the source must be defined in " - f'"{RATapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"' + f'"{ratapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"' ) if resolution.source == "" and resolution.type != TypeOptions.Data: raise ValueError( f"Constant resolutions must have a source defined. The source must be defined in " - f'"{RATapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"' + f'"{ratapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"' ) # Set contrast parameters according to model type @@ -347,34 +347,34 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition: ] problem.fitParams = [ param.value - for class_list in RATapi.project.parameter_class_lists + for class_list in ratapi.project.parameter_class_lists for param in getattr(project, class_list) if param.fit ] problem.fitLimits = [ [param.min, param.max] - for class_list in RATapi.project.parameter_class_lists + for class_list in ratapi.project.parameter_class_lists for param in getattr(project, class_list) if param.fit ] problem.priorNames = [ - param.name for class_list in RATapi.project.parameter_class_lists for param in getattr(project, class_list) + param.name for class_list in ratapi.project.parameter_class_lists for param in getattr(project, class_list) ] problem.priorValues = [ [prior_id[param.prior_type], param.mu, param.sigma] - for class_list in RATapi.project.parameter_class_lists + for class_list in ratapi.project.parameter_class_lists for param in getattr(project, class_list) ] # Names problem.names = NameStore() - for class_list in RATapi.project.parameter_class_lists: + for class_list in ratapi.project.parameter_class_lists: setattr(problem.names, parameter_field[class_list], [param.name for param in getattr(project, class_list)]) problem.names.contrasts = [contrast.name for contrast in project.contrasts] # Checks problem.checks = Checks() - for class_list in RATapi.project.parameter_class_lists: + for class_list in ratapi.project.parameter_class_lists: setattr( problem.checks, parameter_field[class_list], [int(element.fit) for element in getattr(project, class_list)] ) @@ -384,16 +384,16 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition: return problem -def get_layer_details(project: RATapi.Project) -> list[int]: +def get_layer_details(project: ratapi.Project) -> list[int]: """Get parameter indices for all layers defined in the project.""" hydrate_id = {"bulk in": 1, "bulk out": 2} layer_details = [] # Get the thickness, SLD, roughness fields from the appropriate model if project.absorption: - layer_fields = list(RATapi.models.AbsorptionLayer.model_fields.keys())[1:-2] + layer_fields = list(ratapi.models.AbsorptionLayer.model_fields.keys())[1:-2] else: - layer_fields = list(RATapi.models.Layer.model_fields.keys())[1:-2] + layer_fields = list(ratapi.models.Layer.model_fields.keys())[1:-2] for layer in project.layers: for field in layer_fields: @@ -413,7 +413,7 @@ def get_layer_details(project: RATapi.Project) -> list[int]: return layer_details -def make_resample(project: RATapi.Project) -> list[int]: +def make_resample(project: ratapi.Project) -> list[int]: """Construct the "resample" field of the problem input required for the compiled RAT code. Parameters @@ -430,7 +430,7 @@ def make_resample(project: RATapi.Project) -> list[int]: return [contrast.resample for contrast in project.contrasts] -def make_data_present(project: RATapi.Project) -> list[int]: +def make_data_present(project: ratapi.Project) -> list[int]: """Construct the "dataPresent" field of the problem input required for the compiled RAT code. Parameters @@ -535,7 +535,7 @@ def append_data_background(data: np.array, background: np.array) -> np.array: return np.hstack((data, np.zeros((data.shape[0], 4 - data.shape[1])), background[:, 1:])) -def make_controls(input_controls: RATapi.Controls) -> Control: +def make_controls(input_controls: ratapi.Controls) -> Control: """Convert the controls object to the format required by the compiled RAT code. Parameters diff --git a/ratapi/matlab.txt b/ratapi/matlab.txt new file mode 100644 index 00000000..710371e7 --- /dev/null +++ b/ratapi/matlab.txt @@ -0,0 +1 @@ +C:\Program Files\MATLAB\R2024b\bin\matlab.EXE \ No newline at end of file diff --git a/RATapi/models.py b/ratapi/models.py similarity index 99% rename from RATapi/models.py rename to ratapi/models.py index ae20fcf6..e882af65 100644 --- a/RATapi/models.py +++ b/ratapi/models.py @@ -9,7 +9,7 @@ import prettytable from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator -from RATapi.utils.enums import BackgroundActions, Hydration, Languages, Priors, TypeOptions +from ratapi.utils.enums import BackgroundActions, Hydration, Languages, Priors, TypeOptions try: from enum import StrEnum diff --git a/RATapi/outputs.py b/ratapi/outputs.py similarity index 98% rename from RATapi/outputs.py rename to ratapi/outputs.py index e4c54c34..b60547d8 100644 --- a/RATapi/outputs.py +++ b/ratapi/outputs.py @@ -7,8 +7,8 @@ import numpy as np -import RATapi.rat_core -from RATapi.utils.enums import Procedures +import ratapi.rat_core +from ratapi.utils.enums import Procedures bayes_results_subclasses = [ "predictionIntervals", @@ -683,8 +683,8 @@ def read_bayes_results_fields(results_dict: dict) -> dict: def make_results( procedure: Procedures, - output_results: RATapi.rat_core.OutputResult, - bayes_results: Optional[RATapi.rat_core.OutputBayesResult] = None, + output_results: ratapi.rat_core.OutputResult, + bayes_results: Optional[ratapi.rat_core.OutputBayesResult] = None, ) -> Union[Results, BayesResults]: """Initialise a python Results or BayesResults object using the outputs from a RAT calculation. @@ -692,9 +692,9 @@ def make_results( ---------- procedure : Procedures The procedure used by the calculation. - output_results : RATapi.rat_core.OutputResult + output_results : ratapi.rat_core.OutputResult The C++ output results from the calculation. - bayes_results : Optional[RATapi.rat_core.OutputBayesResult] + bayes_results : Optional[ratapi.rat_core.OutputBayesResult] The optional extra C++ Bayesian output results from a Bayesian calculation. Returns diff --git a/RATapi/project.py b/ratapi/project.py similarity index 92% rename from RATapi/project.py rename to ratapi/project.py index 02c2cfec..860f23b7 100644 --- a/RATapi/project.py +++ b/ratapi/project.py @@ -23,10 +23,10 @@ ) from typing_extensions import get_args, get_origin -import RATapi.models -from RATapi.classlist import ClassList -from RATapi.utils.custom_errors import custom_pydantic_validation_error -from RATapi.utils.enums import Calculations, Geometries, LayerModels, Priors, TypeOptions +import ratapi.models +from ratapi.classlist import ClassList +from ratapi.utils.custom_errors import custom_pydantic_validation_error +from ratapi.utils.enums import Calculations, Geometries, LayerModels, Priors, TypeOptions # note for these discriminators that the before-validator discriminate_ambiguous_dicts @@ -35,7 +35,7 @@ def discriminate_layers(layer_input): """Union discriminator for layers.""" if isinstance(layer_input, collections.abc.Sequence): # if classlist is empty, just label it as no absorption and it'll get fixed in post_init - if len(layer_input) > 0 and isinstance(layer_input[0], RATapi.models.AbsorptionLayer): + if len(layer_input) > 0 and isinstance(layer_input[0], ratapi.models.AbsorptionLayer): return "abs" return "no_abs" @@ -44,7 +44,7 @@ def discriminate_contrasts(contrast_input): """Union discriminator for contrasts.""" if isinstance(contrast_input, collections.abc.Sequence): # if classlist is empty, just label it as no ratio and it'll get fixed in post_init - if len(contrast_input) > 0 and isinstance(contrast_input[0], RATapi.models.ContrastWithRatio): + if len(contrast_input) > 0 and isinstance(contrast_input[0], ratapi.models.ContrastWithRatio): return "ratio" return "no_ratio" @@ -145,11 +145,11 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute absorption: bool = False """Whether imaginary SLD (absorption) should be accounted for.""" - parameters: ClassList[RATapi.models.Parameter] = ClassList() + parameters: ClassList[ratapi.models.Parameter] = ClassList() """The list of parameters used in the layers of a model.""" - bulk_in: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + bulk_in: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="SLD Air", min=0.0, value=0.0, @@ -162,8 +162,8 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for SLD of the entry interfaces of a model.""" - bulk_out: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + bulk_out: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="SLD D2O", min=6.2e-6, value=6.35e-6, @@ -176,8 +176,8 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for SLD of the exit interfaces of a model.""" - scalefactors: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + scalefactors: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="Scalefactor 1", min=0.02, value=0.23, @@ -190,8 +190,8 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for scale factors to handle systematic error in model data.""" - domain_ratios: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + domain_ratios: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="Domain Ratio 1", min=0.4, value=0.5, @@ -204,8 +204,8 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for weighting between domains of a domains model.""" - background_parameters: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + background_parameters: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="Background Param 1", min=1e-7, value=1e-6, @@ -218,13 +218,13 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for models of backgrounds.""" - backgrounds: ClassList[RATapi.models.Background] = ClassList( - RATapi.models.Background(name="Background 1", type=TypeOptions.Constant, source="Background Param 1"), + backgrounds: ClassList[ratapi.models.Background] = ClassList( + ratapi.models.Background(name="Background 1", type=TypeOptions.Constant, source="Background Param 1"), ) """The list of models for background noise in the project.""" - resolution_parameters: ClassList[RATapi.models.Parameter] = ClassList( - RATapi.models.Parameter( + resolution_parameters: ClassList[ratapi.models.Parameter] = ClassList( + ratapi.models.Parameter( name="Resolution Param 1", min=0.01, value=0.03, @@ -237,20 +237,20 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The list of parameters for models of resolutions.""" - resolutions: ClassList[RATapi.models.Resolution] = ClassList( - RATapi.models.Resolution(name="Resolution 1", type=TypeOptions.Constant, source="Resolution Param 1"), + resolutions: ClassList[ratapi.models.Resolution] = ClassList( + ratapi.models.Resolution(name="Resolution 1", type=TypeOptions.Constant, source="Resolution Param 1"), ) """The list of models for instrument resolution in the project.""" - custom_files: ClassList[RATapi.models.CustomFile] = ClassList() + custom_files: ClassList[ratapi.models.CustomFile] = ClassList() """Handles for custom files used by the project.""" - data: ClassList[RATapi.models.Data] = ClassList() + data: ClassList[ratapi.models.Data] = ClassList() """Experimental data for a model.""" layers: Union[ - Annotated[ClassList[RATapi.models.Layer], Tag("no_abs")], - Annotated[ClassList[RATapi.models.AbsorptionLayer], Tag("abs")], + Annotated[ClassList[ratapi.models.Layer], Tag("no_abs")], + Annotated[ClassList[ratapi.models.AbsorptionLayer], Tag("abs")], ] = Field( default=ClassList(), discriminator=Discriminator( @@ -262,12 +262,12 @@ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute ) """The layers of a standard layer model.""" - domain_contrasts: ClassList[RATapi.models.DomainContrast] = ClassList() + domain_contrasts: ClassList[ratapi.models.DomainContrast] = ClassList() """The groups of layers required by each domain in a domains model.""" contrasts: Union[ - Annotated[ClassList[RATapi.models.Contrast], Tag("no_ratio")], - Annotated[ClassList[RATapi.models.ContrastWithRatio], Tag("ratio")], + Annotated[ClassList[ratapi.models.Contrast], Tag("no_ratio")], + Annotated[ClassList[ratapi.models.ContrastWithRatio], Tag("ratio")], ] = Field( default=ClassList(), discriminator=Discriminator( @@ -290,11 +290,11 @@ def discriminate_ambiguous_dicts(cls, data: Any) -> Any: # pydantic docs says data can be anything, but i can't see anywhere where it isn't a dict. # if it's not a dict, just return and let the library handle it if isinstance(data, dict): - layer_model = RATapi.models.AbsorptionLayer if data.get("absorption", False) else RATapi.models.Layer + layer_model = ratapi.models.AbsorptionLayer if data.get("absorption", False) else ratapi.models.Layer if data.get("calculation", Calculations.Normal) == Calculations.Domains: - contrast_model = RATapi.models.ContrastWithRatio + contrast_model = ratapi.models.ContrastWithRatio else: - contrast_model = RATapi.models.Contrast + contrast_model = ratapi.models.Contrast # note we aren't modifying the layers and contrasts in-place: # if a ClassList of dicts is passed, in-place conversion would make the ClassList heterogenous @@ -327,7 +327,7 @@ def check_layers(cls, value: ClassList, info: ValidationInfo): else: model_name = "Layer" other_model = "AbsorptionLayer" - model = getattr(RATapi.models, model_name) + model = getattr(ratapi.models, model_name) if not all(isinstance(element, model) for element in value): raise ValueError( f'"The layers attribute contains {other_model}s, ' @@ -347,7 +347,7 @@ def check_contrasts(cls, value: ClassList, info: ValidationInfo): else: model_name = "Contrast" error_word = "with" - model = getattr(RATapi.models, model_name) + model = getattr(ratapi.models, model_name) if not all(isinstance(element, model) for element in value): raise ValueError( f'"The contrasts attribute contains contrasts {error_word} ratio, ' @@ -375,27 +375,27 @@ def model_post_init(self, __context: Any) -> None: layers_field = self.layers if not hasattr(layers_field, "_class_handle"): if self.absorption: - layers_field._class_handle = RATapi.models.AbsorptionLayer + layers_field._class_handle = ratapi.models.AbsorptionLayer else: - layers_field._class_handle = RATapi.models.Layer + layers_field._class_handle = ratapi.models.Layer contrast_field = self.contrasts if not hasattr(contrast_field, "_class_handle"): if self.calculation == Calculations.Domains: - contrast_field._class_handle = RATapi.models.ContrastWithRatio + contrast_field._class_handle = ratapi.models.ContrastWithRatio else: - contrast_field._class_handle = RATapi.models.Contrast + contrast_field._class_handle = ratapi.models.Contrast if "Substrate Roughness" not in [name.title() for name in self.parameters.get_names()]: self.parameters.insert( 0, - RATapi.models.ProtectedParameter( + ratapi.models.ProtectedParameter( name="Substrate Roughness", min=1.0, value=3.0, max=5.0, fit=True, - prior_type=RATapi.models.Priors.Uniform, + prior_type=ratapi.models.Priors.Uniform, mu=0.0, sigma=np.inf, ), @@ -404,10 +404,10 @@ def model_post_init(self, __context: Any) -> None: # If substrate roughness is included as a standard parameter replace it with a protected parameter substrate_roughness_values = self.parameters["Substrate Roughness"].model_dump() self.parameters.remove("Substrate Roughness") - self.parameters.insert(0, RATapi.models.ProtectedParameter(**substrate_roughness_values)) + self.parameters.insert(0, ratapi.models.ProtectedParameter(**substrate_roughness_values)) if "Simulation" not in [name.title() for name in self.data.get_names()]: - self.data.insert(0, RATapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7])) + self.data.insert(0, ratapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7])) self._all_names = self.get_all_names() self._contrast_model_field = self.get_contrast_model_field() @@ -461,28 +461,28 @@ def set_calculation(self) -> "Project": handle = self.contrasts._class_handle.__name__ if self.calculation == Calculations.Domains and handle == "Contrast": for contrast in self.contrasts: - contrast_list.append(RATapi.models.ContrastWithRatio(**contrast.model_dump())) + contrast_list.append(ratapi.models.ContrastWithRatio(**contrast.model_dump())) self.contrasts.data = contrast_list self.domain_ratios.data = [ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Domain Ratio 1", min=0.4, value=0.5, max=0.6, fit=False, - prior_type=RATapi.models.Priors.Uniform, + prior_type=ratapi.models.Priors.Uniform, mu=0.0, sigma=np.inf, ), ] - self.contrasts._class_handle = RATapi.models.ContrastWithRatio + self.contrasts._class_handle = ratapi.models.ContrastWithRatio elif self.calculation != Calculations.Domains and handle == "ContrastWithRatio": for contrast in self.contrasts: contrast_params = contrast.model_dump() del contrast_params["domain_ratio"] - contrast_list.append(RATapi.models.Contrast(**contrast_params)) + contrast_list.append(ratapi.models.Contrast(**contrast_params)) self.contrasts.data = contrast_list - self.contrasts._class_handle = RATapi.models.Contrast + self.contrasts._class_handle = ratapi.models.Contrast return self @model_validator(mode="after") @@ -531,16 +531,16 @@ def set_absorption(self) -> "Project": for layer in self.layers: layer_params = layer.model_dump() layer_params["SLD_imaginary"] = "" - layer_list.append(RATapi.models.AbsorptionLayer(**layer_params)) + layer_list.append(ratapi.models.AbsorptionLayer(**layer_params)) self.layers.data = layer_list - self.layers._class_handle = RATapi.models.AbsorptionLayer + self.layers._class_handle = ratapi.models.AbsorptionLayer elif not self.absorption and handle == "AbsorptionLayer": for layer in self.layers: layer_params = layer.model_dump() del layer_params["SLD_imaginary"] - layer_list.append(RATapi.models.Layer(**layer_params)) + layer_list.append(ratapi.models.Layer(**layer_params)) self.layers.data = layer_list - self.layers._class_handle = RATapi.models.Layer + self.layers._class_handle = ratapi.models.Layer return self @model_validator(mode="after") @@ -613,7 +613,7 @@ def check_protected_parameters(self) -> "Project": """Protected parameters should not be deleted. If this is attempted, raise an error.""" for class_list in parameter_class_lists: protected_parameters = [ - param.name for param in getattr(self, class_list) if isinstance(param, RATapi.models.ProtectedParameter) + param.name for param in getattr(self, class_list) if isinstance(param, ratapi.models.ProtectedParameter) ] # All previously existing protected parameters should be present in new list if not all(element in protected_parameters for element in self._protected_parameters[class_list]): @@ -649,7 +649,7 @@ def get_all_protected_parameters(self): """Record the protected parameters defined in the project.""" return { class_list: [ - param.name for param in getattr(self, class_list) if isinstance(param, RATapi.models.ProtectedParameter) + param.name for param in getattr(self, class_list) if isinstance(param, ratapi.models.ProtectedParameter) ] for class_list in parameter_class_lists } @@ -847,7 +847,7 @@ def write_script(self, obj_name: str = "problem", script: str = "project_script. def write_item(item): """Write a model item as a string of a dictionary.""" - if isinstance(item, RATapi.models.Data): + if isinstance(item, ratapi.models.Data): item_str = "{" + f"'name': '{item.name}'," if not np.any(item.data): # if array is empty, e.g. in simulation data item_str += "'data': empty([0, 3]), " @@ -860,7 +860,7 @@ def write_item(item): item_str += "}" return item_str - if isinstance(item, RATapi.models.CustomFile): + if isinstance(item, ratapi.models.CustomFile): # convert file paths to strings because pathlib gets too specific item_str = ( "{" @@ -883,10 +883,10 @@ def classlist_script(name, classlist): script_path.write_text( f"""# THIS FILE IS GENERATED FROM RAT VIA THE "WRITE_SCRIPT" ROUTINE. IT IS NOT PART OF THE RAT CODE. -import RATapi +import ratapi from numpy import array, empty, inf -{obj_name} = RATapi.Project( +{obj_name} = ratapi.Project( name="{self.name}", calculation="{self.calculation}", model="{self.model}", diff --git a/RATapi/run.py b/ratapi/run.py similarity index 87% rename from RATapi/run.py rename to ratapi/run.py index 476daa39..d973d068 100644 --- a/RATapi/run.py +++ b/ratapi/run.py @@ -4,10 +4,10 @@ from tqdm.auto import tqdm -import RATapi.rat_core -from RATapi.inputs import make_input -from RATapi.outputs import make_results -from RATapi.utils.enums import Display +import ratapi.rat_core +from ratapi.inputs import make_input +from ratapi.outputs import make_results +from ratapi.utils.enums import Display class ProgressBar: @@ -32,7 +32,7 @@ def __init__(self, display=True): def __enter__(self): if self.display: - RATapi.events.register(RATapi.events.EventTypes.Progress, self.updateProgress) + ratapi.events.register(ratapi.events.EventTypes.Progress, self.updateProgress) return self @@ -57,7 +57,7 @@ def __exit__(self, _exc_type, _exc_val, _traceback): print("") # Print new line after bar if self.display: - RATapi.events.clear(RATapi.events.EventTypes.Progress, self.updateProgress) + ratapi.events.clear(ratapi.events.EventTypes.Progress, self.updateProgress) class TextOutput: @@ -75,7 +75,7 @@ def __init__(self, display=True): def __enter__(self): if self.display: - RATapi.events.register(RATapi.events.EventTypes.Message, self.printMessage) + ratapi.events.register(ratapi.events.EventTypes.Message, self.printMessage) return self @@ -92,7 +92,7 @@ def printMessage(self, msg): def __exit__(self, _exc_type, _exc_val, _traceback): if self.display: - RATapi.events.clear(RATapi.events.EventTypes.Message, self.printMessage) + ratapi.events.clear(ratapi.events.EventTypes.Message, self.printMessage) def run(project, controls): @@ -116,7 +116,7 @@ def run(project, controls): start = time.time() with ProgressBar(display=display_on), TextOutput(display=display_on): - problem_definition, output_results, bayes_results = RATapi.rat_core.RATMain( + problem_definition, output_results, bayes_results = ratapi.rat_core.RATMain( problem_definition, cpp_controls, ) @@ -128,7 +128,7 @@ def run(project, controls): results = make_results(controls.procedure, output_results, bayes_results) # Update parameter values in project - for class_list in RATapi.project.parameter_class_lists: + for class_list in ratapi.project.parameter_class_lists: for index, value in enumerate(getattr(problem_definition, parameter_field[class_list])): getattr(project, class_list)[index].value = value diff --git a/ratapi/utils/__init__.py b/ratapi/utils/__init__.py new file mode 100644 index 00000000..56b312d4 --- /dev/null +++ b/ratapi/utils/__init__.py @@ -0,0 +1 @@ +"""Additional utilities for ratapi.""" diff --git a/RATapi/utils/convert.py b/ratapi/utils/convert.py similarity index 99% rename from RATapi/utils/convert.py rename to ratapi/utils/convert.py index 7c94ab50..b689317f 100644 --- a/RATapi/utils/convert.py +++ b/ratapi/utils/convert.py @@ -9,10 +9,10 @@ from numpy import array, empty from scipy.io.matlab import MatlabOpaque, loadmat -from RATapi import Project, wrappers -from RATapi.classlist import ClassList -from RATapi.models import Background, Contrast, CustomFile, Data, Layer, Parameter, Resolution -from RATapi.utils.enums import Geometries, Languages, LayerModels +from ratapi import Project, wrappers +from ratapi.classlist import ClassList +from ratapi.models import Background, Contrast, CustomFile, Data, Layer, Parameter, Resolution +from ratapi.utils.enums import Geometries, Languages, LayerModels def r1_to_project(filename: Union[str, PathLike]) -> Project: diff --git a/RATapi/utils/custom_errors.py b/ratapi/utils/custom_errors.py similarity index 100% rename from RATapi/utils/custom_errors.py rename to ratapi/utils/custom_errors.py diff --git a/RATapi/utils/enums.py b/ratapi/utils/enums.py similarity index 98% rename from RATapi/utils/enums.py rename to ratapi/utils/enums.py index ff14b340..43272355 100644 --- a/RATapi/utils/enums.py +++ b/ratapi/utils/enums.py @@ -1,4 +1,4 @@ -"""The Enum values used in the parameters of various RATapi classes and functions.""" +"""The Enum values used in the parameters of various ratapi classes and functions.""" from typing import Union diff --git a/RATapi/utils/orso.py b/ratapi/utils/orso.py similarity index 98% rename from RATapi/utils/orso.py rename to ratapi/utils/orso.py index 50550619..403597b4 100644 --- a/RATapi/utils/orso.py +++ b/ratapi/utils/orso.py @@ -10,8 +10,8 @@ import prettytable from orsopy.fileio import load_orso -from RATapi import ClassList -from RATapi.models import AbsorptionLayer, Data, Layer, Parameter +from ratapi import ClassList +from ratapi.models import AbsorptionLayer, Data, Layer, Parameter class ORSOProject: diff --git a/RATapi/utils/plotting.py b/ratapi/utils/plotting.py similarity index 97% rename from RATapi/utils/plotting.py rename to ratapi/utils/plotting.py index e6d925a3..fd4480cd 100644 --- a/RATapi/utils/plotting.py +++ b/ratapi/utils/plotting.py @@ -15,10 +15,10 @@ from scipy.ndimage import gaussian_filter1d from scipy.stats import gaussian_kde, lognorm, norm -import RATapi -import RATapi.inputs -import RATapi.outputs -from RATapi.rat_core import PlotEventData, makeSLDProfile +import ratapi +import ratapi.inputs +import ratapi.outputs +from ratapi.rat_core import PlotEventData, makeSLDProfile def _extract_plot_data(event_data: PlotEventData, q4: bool, show_error_bar: bool): @@ -417,8 +417,8 @@ def plot_ref_sld_helper( def plot_ref_sld( - project: RATapi.Project, - results: Union[RATapi.outputs.Results, RATapi.outputs.BayesResults], + project: ratapi.Project, + results: Union[ratapi.outputs.Results, ratapi.outputs.BayesResults], block: bool = False, return_fig: bool = False, bayes: Literal[65, 95, None] = None, @@ -471,13 +471,13 @@ def plot_ref_sld( data.shiftedData = results.shiftedData data.sldProfiles = copy.deepcopy(results.sldProfiles) data.resampledLayers = results.resampledLayers - data.dataPresent = RATapi.inputs.make_data_present(project) + data.dataPresent = ratapi.inputs.make_data_present(project) data.subRoughs = results.contrastParams.subRoughs - data.resample = RATapi.inputs.make_resample(project) + data.resample = ratapi.inputs.make_resample(project) data.contrastNames = [contrast.name for contrast in project.contrasts] if bayes: - if isinstance(results, RATapi.outputs.BayesResults): + if isinstance(results, ratapi.outputs.BayesResults): # the predictionIntervals data consists of 5 rows: # row 0: min with 95% confidence # row 1: min with 65% confidence @@ -550,7 +550,7 @@ def __enter__(self): self.figure = plt.subplots(1, 2)[0] self.figure.canvas.mpl_connect("close_event", self._setCloseState) self.figure.show() - RATapi.events.register(RATapi.events.EventTypes.Plot, self.plotEvent) + ratapi.events.register(ratapi.events.EventTypes.Plot, self.plotEvent) return self.figure @@ -573,7 +573,7 @@ def plotEvent(self, event): plot_ref_sld_helper(event, self.figure) def __exit__(self, _exc_type, _exc_val, _traceback): - RATapi.events.clear(RATapi.events.EventTypes.Plot, self.plotEvent) + ratapi.events.clear(ratapi.events.EventTypes.Plot, self.plotEvent) if not self.closed and self.figure.number in plt.get_fignums(): plt.show(block=self.block) @@ -593,7 +593,7 @@ def assert_bayesian(name: str): def decorator(func: Callable): @wraps(func) def inner(results, *args, **kwargs): - if isinstance(results, RATapi.outputs.BayesResults): + if isinstance(results, ratapi.outputs.BayesResults): return func(results, *args, **kwargs) raise ValueError(f"{name} plots are only available for the results of Bayesian analysis (NS or DREAM)") @@ -618,7 +618,7 @@ def name_to_index(param: Union[str, int], names: list[str]): @assert_bayesian("Corner") def plot_corner( - results: RATapi.outputs.BayesResults, + results: ratapi.outputs.BayesResults, params: Union[list[Union[int, str]], None] = None, smooth: bool = True, block: bool = False, @@ -705,7 +705,7 @@ def plot_corner( @assert_bayesian("Histogram") def plot_one_hist( - results: RATapi.outputs.BayesResults, + results: ratapi.outputs.BayesResults, param: Union[int, str], smooth: bool = True, sigma: Union[float, None] = None, @@ -856,7 +856,7 @@ def _y_update_offset_text_position(axis, _bboxes, bboxes2): @assert_bayesian("Contour") def plot_contour( - results: RATapi.outputs.BayesResults, + results: ratapi.outputs.BayesResults, x_param: Union[int, str], y_param: Union[int, str], smooth: bool = True, @@ -870,7 +870,7 @@ def plot_contour( Parameters ---------- - results : RATapi.outputs.BayesResults + results : ratapi.outputs.BayesResults The results of a Bayesian analysis. x_param : int The index or name of the parameter on the x-axis. @@ -963,7 +963,7 @@ def panel_plot_helper(plot_func: Callable, indices: list[int]) -> matplotlib.fig @assert_bayesian("Histogram") def plot_hists( - results: RATapi.outputs.BayesResults, + results: ratapi.outputs.BayesResults, params: Union[list[Union[int, str]], None] = None, smooth: bool = True, sigma: Union[float, None] = None, @@ -1071,7 +1071,7 @@ def validate_dens_type(dens_type: Union[str, None], param: str): @assert_bayesian("Chain") def plot_chain( - results: RATapi.outputs.BayesResults, + results: ratapi.outputs.BayesResults, params: Union[list[Union[int, str]], None] = None, maxpoints: int = 15000, block: bool = False, @@ -1081,7 +1081,7 @@ def plot_chain( Parameters ---------- - results : RATapi.outputs.BayesResults + results : ratapi.outputs.BayesResults The results of a Bayesian analysis. params : list[int], default None The indices or names of a subset of parameters if required. @@ -1123,7 +1123,7 @@ def plot_one_chain(axes: Axes, i: int): plt.show(block=block) -def plot_bayes(project: RATapi.Project, results: RATapi.outputs.BayesResults): +def plot_bayes(project: ratapi.Project, results: ratapi.outputs.BayesResults): """Plot the results of a Bayesian analysis with confidence information. This produces an unshaded reflectivity/SLD plot, a reflectivity/SLD plot with shaded 95% confidence @@ -1140,7 +1140,7 @@ def plot_bayes(project: RATapi.Project, results: RATapi.outputs.BayesResults): Indicates the plot should block until it is closed """ - if isinstance(results, RATapi.outputs.BayesResults): + if isinstance(results, ratapi.outputs.BayesResults): plot_ref_sld(project, results) plot_ref_sld(project, results, bayes=95) plot_hists(results) diff --git a/RATapi/wrappers.py b/ratapi/wrappers.py similarity index 95% rename from RATapi/wrappers.py rename to ratapi/wrappers.py index ab5f5fa6..6c3d55db 100644 --- a/RATapi/wrappers.py +++ b/ratapi/wrappers.py @@ -1,4 +1,4 @@ -"""Wrappers for the interface between RATapi and MATLAB custom files.""" +"""Wrappers for the interface between ratapi and MATLAB custom files.""" import pathlib from contextlib import suppress @@ -7,7 +7,7 @@ import numpy as np from numpy.typing import ArrayLike -import RATapi.rat_core +import ratapi.rat_core def start_matlab(): @@ -99,7 +99,7 @@ class DylibWrapper: """ def __init__(self, filename, function_name) -> None: - self.engine = RATapi.rat_core.DylibEngine(filename, function_name) + self.engine = ratapi.rat_core.DylibEngine(filename, function_name) def getHandle(self) -> Callable[[ArrayLike, ArrayLike, ArrayLike, int, int], tuple[ArrayLike, float]]: """Return a wrapper for the custom dynamic library function. diff --git a/setup.py b/setup.py index 4da0357b..d5493fbc 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ from setuptools.command.build_ext import build_ext __version__ = "0.0.0.dev6" -PACKAGE_NAME = "RATapi" +PACKAGE_NAME = "ratapi" with open("README.md") as f: LONG_DESCRIPTION = f.read() @@ -19,7 +19,7 @@ ext_modules = [ Extension( - "RATapi.rat_core", + "ratapi.rat_core", sources=["cpp/rat.cpp", *glob("cpp/RAT/*.c*")], include_dirs=[ # Path to pybind11 headers @@ -121,7 +121,7 @@ def build_libraries(self, libraries): compiler_type = self.compiler.compiler_type if compiler_type == "msvc": - compile_args = ["/EHsc", "/LD"] + compile_args = ["/EHsc", "/LD", "-D_DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR"] else: compile_args = ["-std=c++11", "-fPIC"] @@ -161,7 +161,7 @@ def build_libraries(self, libraries): long_description_content_type="text/markdown", packages=find_packages(), include_package_data=True, - package_data={"": [get_shared_object_name(libevent[0])], "RATapi.examples": ["data/*.dat"]}, + package_data={"": [get_shared_object_name(libevent[0])], "ratapi.examples": ["data/*.dat"]}, cmdclass={"build_clib": BuildClib, "build_ext": BuildExt}, libraries=[libevent], ext_modules=ext_modules, diff --git a/tests/conftest.py b/tests/conftest.py index f92ad836..4d5ecc00 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,10 +5,10 @@ import numpy as np import pytest -import RATapi -import RATapi.classlist -import RATapi.outputs -import RATapi.rat_core +import ratapi +import ratapi.classlist +import ratapi.outputs +import ratapi.rat_core @pytest.fixture @@ -23,7 +23,7 @@ def input_project(): """A cut-down version of the input Project object for a reflectivity calculation set out in "DSPC_standard_layers.py". """ - project = RATapi.Project( + project = ratapi.Project( name="original_dspc_bilayer", calculation="normal", model="standard layers", @@ -269,7 +269,7 @@ def input_project(): @pytest.fixture def reflectivity_calculation_output_results(): """The C++ results object for a reflectivity calculation of the project set out in "DSPC_standard_layers.py".""" - results = RATapi.rat_core.OutputResult() + results = ratapi.rat_core.OutputResult() results.reflectivity = [ np.array( [ @@ -867,10 +867,10 @@ def reflectivity_calculation_output_results(): ], ] results.resampledLayers = [[np.array([[0.0, 0.0, 0.0]])], [np.array([[0.0, 0.0, 0.0]])]] - results.calculationResults = RATapi.rat_core.Calculation() + results.calculationResults = ratapi.rat_core.Calculation() results.calculationResults.chiValues = np.array([202.83057377, 1641.4024969]) results.calculationResults.sumChi = 1844.2330706690975 - results.contrastParams = RATapi.rat_core.ContrastParams() + results.contrastParams = ratapi.rat_core.ContrastParams() results.contrastParams.scalefactors = np.array([0.1, 0.15]) results.contrastParams.bulkIn = np.array([2.073e-06, 2.073e-06]) results.contrastParams.bulkOut = np.array([5.98e-06, 2.21e-06]) @@ -925,7 +925,7 @@ def reflectivity_calculation_output_results(): @pytest.fixture def reflectivity_calculation_results(): """The python results object for a reflectivity calculation of the project set out in "DSPC_standard_layers.py".""" - return RATapi.outputs.Results( + return ratapi.outputs.Results( reflectivity=[ np.array( [ @@ -1523,11 +1523,11 @@ def reflectivity_calculation_results(): ], ], resampledLayers=[[np.array([[0.0, 0.0, 0.0]])], [np.array([[0.0, 0.0, 0.0]])]], - calculationResults=RATapi.outputs.CalculationResults( + calculationResults=ratapi.outputs.CalculationResults( chiValues=np.array([202.83057377, 1641.4024969]), sumChi=1844.2330706690975, ), - contrastParams=RATapi.outputs.ContrastParams( + contrastParams=ratapi.outputs.ContrastParams( scalefactors=np.array([0.1, 0.15]), bulkIn=np.array([2.073e-06, 2.073e-06]), bulkOut=np.array([5.98e-06, 2.21e-06]), @@ -1586,7 +1586,7 @@ def dream_output_results(): This optimisation used the parameters: nSamples=1, nChains=1. However, the calculationResults, contrastParams, and fitParams are taken from an optimisation with the parameters: nSamples=50000, nChains=10. """ - results = RATapi.rat_core.OutputResult() + results = ratapi.rat_core.OutputResult() results.reflectivity = [ np.array( [ @@ -2192,10 +2192,10 @@ def dream_output_results(): ], ] results.resampledLayers = [[np.array([[0.0, 0.0, 0.0]])], [np.array([[0.0, 0.0, 0.0]])]] - results.calculationResults = RATapi.rat_core.Calculation() + results.calculationResults = ratapi.rat_core.Calculation() results.calculationResults.chiValues = (np.array([4.6077885, 7.00028098]),) results.calculationResults.sumChi = 11.608069475997699 - results.contrastParams = RATapi.rat_core.ContrastParams() + results.contrastParams = ratapi.rat_core.ContrastParams() results.contrastParams.scalefactors = np.array([0.1, 0.15]) results.contrastParams.bulkIn = np.array([2.073e-06, 2.073e-06]) results.contrastParams.bulkOut = np.array([6.01489149e-06, 1.59371685e-06]) @@ -2253,8 +2253,8 @@ def dream_bayes(): This optimisation used the parameters: nSamples=1, nChains=1. """ - bayes = RATapi.rat_core.OutputBayesResult() - bayes.predictionIntervals = RATapi.rat_core.PredictionIntervals() + bayes = ratapi.rat_core.OutputBayesResult() + bayes.predictionIntervals = ratapi.rat_core.PredictionIntervals() bayes.predictionIntervals.reflectivity = [ np.array( [ @@ -3821,7 +3821,7 @@ def dream_bayes(): 1.46133559e16, ], ) - bayes.confidenceIntervals = RATapi.rat_core.ConfidenceIntervals() + bayes.confidenceIntervals = ratapi.rat_core.ConfidenceIntervals() bayes.confidenceIntervals.percentile65 = np.array( [ [ @@ -3934,7 +3934,7 @@ def dream_bayes(): ], ], ) - bayes.dreamParams = RATapi.rat_core.DreamParams() + bayes.dreamParams = ratapi.rat_core.DreamParams() bayes.dreamParams.nParams = 18.0 bayes.dreamParams.nChains = 1.0 bayes.dreamParams.nGenerations = 1.0 @@ -3954,7 +3954,7 @@ def dream_bayes(): bayes.dreamParams.IO = 0 bayes.dreamParams.storeOutput = 0 bayes.dreamParams.R = np.array([[0.0]]) - bayes.dreamOutput = RATapi.rat_core.DreamOutput() + bayes.dreamOutput = ratapi.rat_core.DreamOutput() bayes.dreamOutput.allChains = np.array( [ [ @@ -4011,7 +4011,7 @@ def dream_bayes(): ], ) bayes.dreamOutput.CR = np.array([[1.00000000, 0.33333333, 0.33333333, 0.33333333]]) - bayes.nestedSamplerOutput = RATapi.rat_core.NestedSamplerOutput() + bayes.nestedSamplerOutput = ratapi.rat_core.NestedSamplerOutput() bayes.nestedSamplerOutput.logZ = 0.0 bayes.nestedSamplerOutput.nestSamples = np.array([[0.0, 0.0]]) bayes.nestedSamplerOutput.postSamples = np.array([[0.0, 0.0]]) @@ -4070,7 +4070,7 @@ def dream_results(): This optimisation used the parameters: nSamples=1, nChains=1. However, the calculationResults, contrastParams, and fitParams are taken from an optimisation with the parameters: nSamples=50000, nChains=10. """ - return RATapi.outputs.BayesResults( + return ratapi.outputs.BayesResults( reflectivity=[ np.array( [ @@ -4676,11 +4676,11 @@ def dream_results(): ], ], resampledLayers=[[np.array([[0.0, 0.0, 0.0]])], [np.array([[0.0, 0.0, 0.0]])]], - calculationResults=RATapi.outputs.CalculationResults( + calculationResults=ratapi.outputs.CalculationResults( chiValues=np.array([4.6077885, 7.00028098]), sumChi=11.608069475997699, ), - contrastParams=RATapi.outputs.ContrastParams( + contrastParams=ratapi.outputs.ContrastParams( scalefactors=np.array([0.1, 0.15]), bulkIn=np.array([2.073e-06, 2.073e-06]), bulkOut=np.array([6.01489149e-06, 1.59371685e-06]), @@ -4729,7 +4729,7 @@ def dream_results(): "D2O", "SMW", ], - predictionIntervals=RATapi.outputs.PredictionIntervals( + predictionIntervals=ratapi.outputs.PredictionIntervals( reflectivity=[ np.array( [ @@ -6297,7 +6297,7 @@ def dream_results(): ], ), ), - confidenceIntervals=RATapi.outputs.ConfidenceIntervals( + confidenceIntervals=ratapi.outputs.ConfidenceIntervals( percentile65=np.array( [ [ @@ -6411,7 +6411,7 @@ def dream_results(): ], ), ), - dreamParams=RATapi.outputs.DreamParams( + dreamParams=ratapi.outputs.DreamParams( nParams=18.0, nChains=1.0, nGenerations=1.0, @@ -6432,7 +6432,7 @@ def dream_results(): storeOutput=False, R=np.array([[0.0]]), ), - dreamOutput=RATapi.outputs.DreamOutput( + dreamOutput=ratapi.outputs.DreamOutput( allChains=np.array( [ [ @@ -6490,7 +6490,7 @@ def dream_results(): ), CR=np.array([[1.0, 0.33333333, 0.33333333, 0.33333333]]), ), - nestedSamplerOutput=RATapi.outputs.NestedSamplerOutput( + nestedSamplerOutput=ratapi.outputs.NestedSamplerOutput( logZ=0.0, logZErr=0.0, nestSamples=np.array([[0.0, 0.0]]), @@ -6546,14 +6546,14 @@ def dream_results(): @pytest.fixture def r1_default_project(): """The Project corresponding to the data in R1defaultProject.mat.""" - project = RATapi.Project( + project = ratapi.Project( name="defaultProject", calculation="normal", model="standard layers", geometry="air/substrate", absorption=False, - parameters=RATapi.ClassList( - RATapi.models.Parameter( + parameters=ratapi.ClassList( + ratapi.models.Parameter( name="Substrate Roughness", min=3.0, value=4.844363132849221, @@ -6564,8 +6564,8 @@ def r1_default_project(): sigma=np.inf, ) ), - bulk_in=RATapi.ClassList( - RATapi.models.Parameter( + bulk_in=ratapi.ClassList( + ratapi.models.Parameter( name="Air", min=0.0, value=0.0, @@ -6576,8 +6576,8 @@ def r1_default_project(): sigma=np.inf, ) ), - bulk_out=RATapi.ClassList( - RATapi.models.Parameter( + bulk_out=ratapi.ClassList( + ratapi.models.Parameter( name="D2O", min=6.3e-06, value=6.35e-06, @@ -6588,8 +6588,8 @@ def r1_default_project(): sigma=np.inf, ) ), - scalefactors=RATapi.ClassList( - RATapi.models.Parameter( + scalefactors=ratapi.ClassList( + ratapi.models.Parameter( name="Scalefactor 1", min=0.009999999776482582, value=0.10141560336360426, @@ -6600,11 +6600,11 @@ def r1_default_project(): sigma=np.inf, ) ), - backgrounds=RATapi.ClassList( - RATapi.models.Background(name="Background 1", type="constant", source="Background parameter 1") + backgrounds=ratapi.ClassList( + ratapi.models.Background(name="Background 1", type="constant", source="Background parameter 1") ), - background_parameters=RATapi.ClassList( - RATapi.models.Parameter( + background_parameters=ratapi.ClassList( + ratapi.models.Parameter( name="Background parameter 1", min=5e-08, value=3.069003361230152e-06, @@ -6615,11 +6615,11 @@ def r1_default_project(): sigma=np.inf, ) ), - resolutions=RATapi.ClassList( - RATapi.models.Resolution(name="Resolution 1", type="constant", source="Resolution parameter 1") + resolutions=ratapi.ClassList( + ratapi.models.Resolution(name="Resolution 1", type="constant", source="Resolution parameter 1") ), - resolution_parameters=RATapi.ClassList( - RATapi.models.Parameter( + resolution_parameters=ratapi.ClassList( + ratapi.models.Parameter( name="Resolution parameter 1", min=0.01, value=0.03, @@ -6711,15 +6711,15 @@ def r1_default_project(): @pytest.fixture def r1_monolayer(): """The Project file corresponding to the data in R1monolayerVolumeModel.mat.""" - project = RATapi.Project( + project = ratapi.Project( name="monolayerVolumeModel", calculation="normal", model="custom layers", geometry="air/substrate", absorption=False, - parameters=RATapi.ClassList( + parameters=ratapi.ClassList( [ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Substrate Roughness", min=1.0, value=2.9979642781948908, @@ -6729,7 +6729,7 @@ def r1_monolayer(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Area per molecule", min=47.0, value=53.052680457664785, @@ -6739,7 +6739,7 @@ def r1_monolayer(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Head Thickness", min=7.0, value=12.276333836779942, @@ -6749,7 +6749,7 @@ def r1_monolayer(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Theta", min=0.0, value=28.870541049836262, @@ -6761,8 +6761,8 @@ def r1_monolayer(): ), ] ), - bulk_in=RATapi.ClassList( - RATapi.models.Parameter( + bulk_in=ratapi.ClassList( + ratapi.models.Parameter( name="Air", min=0.0, value=0.0, @@ -6774,9 +6774,9 @@ def r1_monolayer(): ) ), bulk_out=( - RATapi.ClassList( + ratapi.ClassList( [ - RATapi.models.Parameter( + ratapi.models.Parameter( name="D2O", min=6.3e-06, value=6.35e-06, @@ -6786,7 +6786,7 @@ def r1_monolayer(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="ACMW", min=-5e-07, value=0.0, @@ -6799,8 +6799,8 @@ def r1_monolayer(): ] ) ), - scalefactors=RATapi.ClassList( - RATapi.models.Parameter( + scalefactors=ratapi.ClassList( + ratapi.models.Parameter( name="Scalefactor 1", min=0.1, value=0.2272676786810902, @@ -6811,15 +6811,15 @@ def r1_monolayer(): sigma=np.inf, ) ), - backgrounds=RATapi.ClassList( + backgrounds=ratapi.ClassList( [ - RATapi.models.Background(name="Background D2O", type="constant", source="Background parameter 1"), - RATapi.models.Background(name="Background ACMW", type="constant", source="Background parameter 2"), + ratapi.models.Background(name="Background D2O", type="constant", source="Background parameter 1"), + ratapi.models.Background(name="Background ACMW", type="constant", source="Background parameter 2"), ] ), - background_parameters=RATapi.ClassList( + background_parameters=ratapi.ClassList( [ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 1", min=1e-07, value=2.2653463958223856e-06, @@ -6829,7 +6829,7 @@ def r1_monolayer(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 2", min=1e-07, value=5.7431759430575025e-06, @@ -6841,11 +6841,11 @@ def r1_monolayer(): ), ] ), - resolutions=RATapi.ClassList( - RATapi.models.Resolution(name="Resolution 1", type="constant", source="Resolution parameter 1") + resolutions=ratapi.ClassList( + ratapi.models.Resolution(name="Resolution 1", type="constant", source="Resolution parameter 1") ), - resolution_parameters=RATapi.ClassList( - RATapi.models.Parameter( + resolution_parameters=ratapi.ClassList( + ratapi.models.Parameter( name="Resolution parameter 1", min=0.01, value=0.03, @@ -6856,8 +6856,8 @@ def r1_monolayer(): sigma=np.inf, ) ), - custom_files=RATapi.ClassList( - RATapi.models.CustomFile( + custom_files=ratapi.ClassList( + ratapi.models.CustomFile( name="Model_IIb", filename="Model_IIb.m", function_name="Model_IIb", language="matlab" ) ), @@ -7376,14 +7376,14 @@ def r1_monolayer(): @pytest.fixture def r1_monolayer_8_contrasts(): """The Project equivalent of the R1 Monolayer_8_contrasts RasCAL-1 project.""" - return RATapi.Project( + return ratapi.Project( name="20nM_data", calculation="normal", model="standard layers", geometry="air/substrate", absorption=False, parameters=[ - RATapi.models.ProtectedParameter( + ratapi.models.ProtectedParameter( name="Substrate Roughness", min=3.0, value=6.990825828311747, @@ -7393,7 +7393,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Tails thick", min=12.0, value=18.769067940891517, @@ -7403,7 +7403,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Deuterated tails SLD", min=5e-06, value=6.935587727961928e-06, @@ -7413,7 +7413,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Tails roughness", min=3.0, value=3.0000000000074776, @@ -7423,7 +7423,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Hydrogenated tails SLD", min=-6e-07, value=-2.1907853109709215e-07, @@ -7433,7 +7433,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Head thickness", min=7.0, value=7.000000000117902, @@ -7443,7 +7443,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Deuterated head SLD", min=3e-06, value=5.855129143529369e-06, @@ -7453,7 +7453,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Head roughness", min=3.0, value=3.0000000000000258, @@ -7463,7 +7463,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Hydrogenated head SLD", min=1e-06, value=1.8079398141440577e-06, @@ -7473,7 +7473,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Head hydration", min=0.0, value=9.33740417574095, @@ -7485,7 +7485,7 @@ def r1_monolayer_8_contrasts(): ), ], bulk_in=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Air", min=0.0, value=0.0, @@ -7497,7 +7497,7 @@ def r1_monolayer_8_contrasts(): ) ], bulk_out=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="D2O", min=6.3e-06, value=6.349999999999999e-06, @@ -7507,7 +7507,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="ACMW", min=-5e-07, value=3.492898018624419e-08, @@ -7519,7 +7519,7 @@ def r1_monolayer_8_contrasts(): ), ], scalefactors=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Scalefactor 1", min=0.1, value=0.23251357931599084, @@ -7532,7 +7532,7 @@ def r1_monolayer_8_contrasts(): ], domain_ratios=[], background_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 1", min=1e-07, value=2.889465920816701e-06, @@ -7542,7 +7542,7 @@ def r1_monolayer_8_contrasts(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 2", min=1e-07, value=5.172884539063037e-06, @@ -7554,19 +7554,19 @@ def r1_monolayer_8_contrasts(): ), ], backgrounds=[ - RATapi.models.Background( + ratapi.models.Background( name="Background D2O", type="constant", source="Background parameter 1", ), - RATapi.models.Background( + ratapi.models.Background( name="Background ACMW", type="constant", source="Background parameter 2", ), ], resolution_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Resolution parameter 1", min=0.01, value=0.029999999999999964, @@ -7578,7 +7578,7 @@ def r1_monolayer_8_contrasts(): ) ], resolutions=[ - RATapi.models.Resolution( + ratapi.models.Resolution( name="Resolution 1", type="constant", source="Resolution parameter 1", @@ -7586,7 +7586,7 @@ def r1_monolayer_8_contrasts(): ], custom_files=[], data=[ - RATapi.models.Data( + ratapi.models.Data( name="d70acmw20", data=np.array( [ @@ -7646,7 +7646,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="d70d2o20", data=np.array( [ @@ -7706,7 +7706,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="d13acmw20", data=np.array( [ @@ -7766,7 +7766,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="d13d2o20", data=np.array( [ @@ -7826,7 +7826,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="d83acmw20", data=np.array( [ @@ -7886,7 +7886,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="d83d2o20", data=np.array( [ @@ -7946,7 +7946,7 @@ def r1_monolayer_8_contrasts(): data_range=[0.051793, 0.58877], simulation_range=[0.051793, 0.58877], ), - RATapi.models.Data( + ratapi.models.Data( name="hd2o20", data=np.array( [ @@ -8008,7 +8008,7 @@ def r1_monolayer_8_contrasts(): ), ], layers=[ - RATapi.models.Layer( + ratapi.models.Layer( name="Deuterated tails", thickness="Tails thick", SLD="Deuterated tails SLD", @@ -8016,7 +8016,7 @@ def r1_monolayer_8_contrasts(): hydration="", hydrate_with="bulk out", ), - RATapi.models.Layer( + ratapi.models.Layer( name="Hydrogenated tails", thickness="Tails thick", SLD="Hydrogenated tails SLD", @@ -8024,7 +8024,7 @@ def r1_monolayer_8_contrasts(): hydration="", hydrate_with="bulk out", ), - RATapi.models.Layer( + ratapi.models.Layer( name="Deuterated heads", thickness="Head thickness", SLD="Deuterated head SLD", @@ -8032,7 +8032,7 @@ def r1_monolayer_8_contrasts(): hydration="Head hydration", hydrate_with="bulk out", ), - RATapi.models.Layer( + ratapi.models.Layer( name="Hydrogenated heads", thickness="Head thickness", SLD="Hydrogenated head SLD", @@ -8043,7 +8043,7 @@ def r1_monolayer_8_contrasts(): ], domain_contrasts=[], contrasts=[ - RATapi.models.Contrast( + ratapi.models.Contrast( name="d70, acmw", data="d70acmw20", background="Background ACMW", @@ -8055,7 +8055,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Deuterated tails", "Hydrogenated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="d70 d2o", data="d70d2o20", background="Background D2O", @@ -8067,7 +8067,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Deuterated tails", "Hydrogenated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="d13 acmw", data="d13acmw20", background="Background ACMW", @@ -8079,7 +8079,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Hydrogenated tails", "Deuterated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="d13 d2o", data="d13d2o20", background="Background D2O", @@ -8091,7 +8091,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Hydrogenated tails", "Deuterated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="d83 acmw", data="d83acmw20", background="Background ACMW", @@ -8103,7 +8103,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Deuterated tails", "Deuterated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="d83 d2o", data="d83d2o20", background="Background D2O", @@ -8115,7 +8115,7 @@ def r1_monolayer_8_contrasts(): resample=False, model=["Deuterated tails", "Deuterated heads"], ), - RATapi.models.Contrast( + ratapi.models.Contrast( name="fully h, D2O", data="hd2o20", background="Background D2O", @@ -8137,14 +8137,14 @@ def r1_orso_polymer(): # the test data is BIG (400 lines) so it's easier to just load it in orso_poly_data = np.loadtxt(Path(__file__).parent / "test_data/orso_poly.dat") - return RATapi.Project( + return ratapi.Project( name="orsoPolymerExample", calculation="normal", model="standard layers", geometry="air/substrate", absorption=False, parameters=[ - RATapi.models.ProtectedParameter( + ratapi.models.ProtectedParameter( name="Substrate Roughness", min=3.0, value=4.844363132849221, @@ -8156,7 +8156,7 @@ def r1_orso_polymer(): ) ], bulk_in=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Air", min=0.0, value=0.0, @@ -8168,7 +8168,7 @@ def r1_orso_polymer(): ) ], bulk_out=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="D2O", min=6.3e-06, value=6.35e-06, @@ -8180,7 +8180,7 @@ def r1_orso_polymer(): ) ], scalefactors=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Scalefactor 1", min=0.05, value=0.10141560336360426, @@ -8193,7 +8193,7 @@ def r1_orso_polymer(): ], domain_ratios=[], background_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 1", min=5e-08, value=3.069003361230152e-06, @@ -8205,14 +8205,14 @@ def r1_orso_polymer(): ) ], backgrounds=[ - RATapi.models.Background( + ratapi.models.Background( name="Background 1", type="constant", source="Background parameter 1", ) ], resolution_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Resolution parameter 1", min=0.01, value=0.03, @@ -8224,7 +8224,7 @@ def r1_orso_polymer(): ) ], resolutions=[ - RATapi.models.Resolution( + ratapi.models.Resolution( name="Resolution 1", type="constant", source="Resolution parameter 1", @@ -8232,7 +8232,7 @@ def r1_orso_polymer(): ], custom_files=[], data=[ - RATapi.models.Data( + ratapi.models.Data( name="polymerData", data=orso_poly_data, data_range=[0.0080602, 0.46555], @@ -8242,7 +8242,7 @@ def r1_orso_polymer(): layers=[], domain_contrasts=[], contrasts=[ - RATapi.models.Contrast( + ratapi.models.Contrast( name="Chain-d, acmw", data="polymerData", background="Background 1", @@ -8263,14 +8263,14 @@ def r1_motofit_bench_mark(): """The project from the R1motofitBenchMark RasCAL-1 project file.""" moto_data = np.loadtxt(Path(__file__).parent / "test_data/moto.dat") - return RATapi.Project( + return ratapi.Project( name="motofitBenchMark", calculation="normal", model="standard layers", geometry="air/substrate", absorption=False, parameters=[ - RATapi.models.ProtectedParameter( + ratapi.models.ProtectedParameter( name="Substrate Roughness", min=1.0, value=3.0, @@ -8280,7 +8280,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="sub rough", min=3.0, value=3.9949146424129665, @@ -8290,7 +8290,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Thick", min=0.0, value=33.2791896400743, @@ -8300,7 +8300,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="SLD 1", min=0.0, value=1.074484187182878e-06, @@ -8310,7 +8310,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="SLD 2", min=9e-06, value=1.0658506835478824e-05, @@ -8320,7 +8320,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Thick2", min=100.0, value=498.6676783112137, @@ -8330,7 +8330,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Rough 1", min=2.0, value=4.563688983733924, @@ -8340,7 +8340,7 @@ def r1_motofit_bench_mark(): mu=0.0, sigma=np.inf, ), - RATapi.models.Parameter( + ratapi.models.Parameter( name="Rough 2", min=2.0, value=4.410704485333302, @@ -8352,7 +8352,7 @@ def r1_motofit_bench_mark(): ), ], bulk_in=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Air", min=0.0, value=0.0, @@ -8364,7 +8364,7 @@ def r1_motofit_bench_mark(): ) ], bulk_out=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="D2O", min=2e-05, value=2.01e-05, @@ -8376,7 +8376,7 @@ def r1_motofit_bench_mark(): ) ], scalefactors=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Scalefactor 1", min=0.99, value=0.9999894027309877, @@ -8389,7 +8389,7 @@ def r1_motofit_bench_mark(): ], domain_ratios=[], background_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Background parameter 1", min=5e-08, value=1.306895319301746e-07, @@ -8401,14 +8401,14 @@ def r1_motofit_bench_mark(): ) ], backgrounds=[ - RATapi.models.Background( + ratapi.models.Background( name="Background 1", type="constant", source="Background parameter 1", ) ], resolution_parameters=[ - RATapi.models.Parameter( + ratapi.models.Parameter( name="Resolution parameter 1", min=0.0, value=0.0, @@ -8420,7 +8420,7 @@ def r1_motofit_bench_mark(): ) ], resolutions=[ - RATapi.models.Resolution( + ratapi.models.Resolution( name="Resolution 1", type="constant", source="Resolution parameter 1", @@ -8428,7 +8428,7 @@ def r1_motofit_bench_mark(): ], custom_files=[], data=[ - RATapi.models.Data( + ratapi.models.Data( name="mFitBench", data=moto_data, data_range=[0.02, 0.59188], @@ -8436,7 +8436,7 @@ def r1_motofit_bench_mark(): ) ], layers=[ - RATapi.models.Layer( + ratapi.models.Layer( name="New Layer 0", thickness="Thick", SLD="SLD 1", @@ -8444,7 +8444,7 @@ def r1_motofit_bench_mark(): hydration="", hydrate_with="bulk out", ), - RATapi.models.Layer( + ratapi.models.Layer( name="New Layer 1", thickness="Thick2", SLD="SLD 2", @@ -8455,7 +8455,7 @@ def r1_motofit_bench_mark(): ], domain_contrasts=[], contrasts=[ - RATapi.models.Contrast( + ratapi.models.Contrast( name="Chain-d, acmw", data="mFitBench", background="Background 1", @@ -8474,47 +8474,47 @@ def r1_motofit_bench_mark(): @pytest.fixture def dspc_standard_layers(): """The project from the DSPC Standard Layers example.""" - project, _ = RATapi.examples.DSPC_standard_layers() + project, _ = ratapi.examples.DSPC_standard_layers() return project @pytest.fixture def dspc_custom_layers(): """The project from the DSPC Custom Layers example.""" - project, _ = RATapi.examples.DSPC_custom_layers() + project, _ = ratapi.examples.DSPC_custom_layers() return project @pytest.fixture def dspc_custom_xy(): """The project from the DSPC Custom XY example.""" - project, _ = RATapi.examples.DSPC_custom_XY() + project, _ = ratapi.examples.DSPC_custom_XY() return project @pytest.fixture def domains_standard_layers(): """The project from the domains Standard Layers example.""" - project, _ = RATapi.examples.domains_standard_layers() + project, _ = ratapi.examples.domains_standard_layers() return project @pytest.fixture def domains_custom_layers(): """The project from the domains Custom Layers example.""" - project, _ = RATapi.examples.domains_custom_layers() + project, _ = ratapi.examples.domains_custom_layers() return project @pytest.fixture def domains_custom_xy(): """The project from the domains Custom XY example.""" - project, _ = RATapi.examples.domains_custom_XY() + project, _ = ratapi.examples.domains_custom_XY() return project @pytest.fixture def absorption(): """The project from the absorption example.""" - project, _ = RATapi.examples.absorption() + project, _ = ratapi.examples.absorption() return project diff --git a/tests/test_classlist.py b/tests/test_classlist.py index 3fa874ab..04130ff8 100644 --- a/tests/test_classlist.py +++ b/tests/test_classlist.py @@ -10,7 +10,7 @@ import prettytable import pytest -from RATapi.classlist import ClassList +from ratapi.classlist import ClassList from tests.utils import InputAttributes, SubInputAttributes diff --git a/tests/test_controls.py b/tests/test_controls.py index 5c4400a3..75f5d705 100644 --- a/tests/test_controls.py +++ b/tests/test_controls.py @@ -8,8 +8,8 @@ import pydantic import pytest -from RATapi.controls import Controls, fields -from RATapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies +from ratapi.controls import Controls, fields +from ratapi.utils.enums import BoundHandling, Display, Parallel, Procedures, Strategies @pytest.fixture diff --git a/tests/test_convert.py b/tests/test_convert.py index 8dc3ecdb..29738346 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -7,8 +7,8 @@ import pytest -import RATapi -from RATapi.utils.convert import project_to_r1, r1_to_project +import ratapi +from ratapi.utils.convert import project_to_r1, r1_to_project TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data") @@ -19,10 +19,10 @@ def dspc_bilayer(): with some changes to make it compatible with R1. """ - project, _ = RATapi.examples.DSPC_standard_layers() + project, _ = ratapi.examples.DSPC_standard_layers() # change parameters to standardise arguments not in R1 - for class_list in RATapi.project.parameter_class_lists: + for class_list in ratapi.project.parameter_class_lists: params = getattr(project, class_list) for param in params: param.prior_type = "uniform" @@ -65,7 +65,7 @@ def test_r1_to_project(file, project, path_type, request): # assert statements have to be more careful due to R1 missing features # e.g. R1 doesn't support background parameter names, mu, sigma... - for class_list in RATapi.project.class_lists: + for class_list in ratapi.project.class_lists: assert getattr(output_project, class_list) == getattr(expected_project, class_list) @@ -91,11 +91,11 @@ def mock_load(ignored_filename, **ignored_settings): """Load the generated R1 struct instead of reading a file.""" return {"problem": r1_struct} - monkeypatch.setattr("RATapi.utils.convert.loadmat", mock_load, raising=True) + monkeypatch.setattr("ratapi.utils.convert.loadmat", mock_load, raising=True) converted_project = r1_to_project(project) - for class_list in RATapi.project.class_lists: + for class_list in ratapi.project.class_lists: assert getattr(converted_project, class_list) == getattr(original_project, class_list) diff --git a/tests/test_custom_errors.py b/tests/test_custom_errors.py index 7793ff85..92dbcab8 100644 --- a/tests/test_custom_errors.py +++ b/tests/test_custom_errors.py @@ -5,7 +5,7 @@ import pytest from pydantic import ValidationError, create_model -import RATapi.utils.custom_errors +import ratapi.utils.custom_errors @pytest.fixture @@ -43,7 +43,7 @@ def test_custom_pydantic_validation_error( try: TestModel(int_field="string", str_field=5) except ValidationError as exc: - custom_error_list = RATapi.utils.custom_errors.custom_pydantic_validation_error(exc.errors(), custom_errors) + custom_error_list = ratapi.utils.custom_errors.custom_pydantic_validation_error(exc.errors(), custom_errors) with pytest.raises(ValidationError, match=re.escape(expected_error_message)): raise ValidationError.from_exception_data("TestModel", custom_error_list) diff --git a/tests/test_data/make_orso_project.py b/tests/test_data/make_orso_project.py index 7e8662e6..4e4ef174 100644 --- a/tests/test_data/make_orso_project.py +++ b/tests/test_data/make_orso_project.py @@ -2,8 +2,8 @@ import numpy as np -import RATapi as RAT -from RATapi.utils.enums import BackgroundActions +import ratapi as RAT +from ratapi.utils.enums import BackgroundActions DATA_PATH = pathlib.Path(__file__).parents[0] / "ORSO_data" sld_values = np.loadtxt(DATA_PATH / "test_3_sld.dat") diff --git a/tests/test_enums.py b/tests/test_enums.py index 9da1f8c0..9984185c 100644 --- a/tests/test_enums.py +++ b/tests/test_enums.py @@ -4,7 +4,7 @@ import pytest -from RATapi.utils.enums import ( +from ratapi.utils.enums import ( BackgroundActions, BoundHandling, Calculations, diff --git a/tests/test_events.py b/tests/test_events.py index 7baa3e32..06b43c39 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -4,7 +4,7 @@ import numpy as np import pytest -import RATapi.events +import ratapi.events def test_event_register() -> None: @@ -12,69 +12,69 @@ def test_event_register() -> None: second_callback = mock.Mock() with pytest.raises(ValueError): - RATapi.events.register("Message", first_callback) + ratapi.events.register("Message", first_callback) - RATapi.events.register(RATapi.events.EventTypes.Message, first_callback) - result = RATapi.events.get_event_callback(RATapi.events.EventTypes.Message) + ratapi.events.register(ratapi.events.EventTypes.Message, first_callback) + result = ratapi.events.get_event_callback(ratapi.events.EventTypes.Message) assert result == [first_callback] - RATapi.events.register(RATapi.events.EventTypes.Plot, second_callback) - assert RATapi.events.get_event_callback(RATapi.events.EventTypes.Plot) == [second_callback] + ratapi.events.register(ratapi.events.EventTypes.Plot, second_callback) + assert ratapi.events.get_event_callback(ratapi.events.EventTypes.Plot) == [second_callback] - RATapi.events.register(RATapi.events.EventTypes.Message, second_callback) + ratapi.events.register(ratapi.events.EventTypes.Message, second_callback) # the list is not guaranteed to be in the same order as inputted hence the set - assert set(RATapi.events.get_event_callback(RATapi.events.EventTypes.Message)) == {first_callback, second_callback} + assert set(ratapi.events.get_event_callback(ratapi.events.EventTypes.Message)) == {first_callback, second_callback} - RATapi.events.clear(RATapi.events.EventTypes.Message, second_callback) - result = RATapi.events.get_event_callback(RATapi.events.EventTypes.Message) + ratapi.events.clear(ratapi.events.EventTypes.Message, second_callback) + result = ratapi.events.get_event_callback(ratapi.events.EventTypes.Message) assert result == [first_callback] - result = RATapi.events.get_event_callback(RATapi.events.EventTypes.Plot) + result = ratapi.events.get_event_callback(ratapi.events.EventTypes.Plot) assert result == [second_callback] - RATapi.events.clear() - assert RATapi.events.get_event_callback(RATapi.events.EventTypes.Plot) == [] - assert RATapi.events.get_event_callback(RATapi.events.EventTypes.Message) == [] + ratapi.events.clear() + assert ratapi.events.get_event_callback(ratapi.events.EventTypes.Plot) == [] + assert ratapi.events.get_event_callback(ratapi.events.EventTypes.Message) == [] def test_event_notify() -> None: first_callback = mock.Mock() second_callback = mock.Mock() third_callback = mock.Mock() - RATapi.events.register(RATapi.events.EventTypes.Message, first_callback) - RATapi.events.register(RATapi.events.EventTypes.Plot, second_callback) - RATapi.events.register(RATapi.events.EventTypes.Progress, third_callback) + ratapi.events.register(ratapi.events.EventTypes.Message, first_callback) + ratapi.events.register(ratapi.events.EventTypes.Plot, second_callback) + ratapi.events.register(ratapi.events.EventTypes.Progress, third_callback) - RATapi.events.notify(RATapi.events.EventTypes.Message, "Hello World") + ratapi.events.notify(ratapi.events.EventTypes.Message, "Hello World") first_callback.assert_called_once_with("Hello World") second_callback.assert_not_called() - data = RATapi.events.PlotEventData() - RATapi.events.notify(RATapi.events.EventTypes.Plot, data) + data = ratapi.events.PlotEventData() + ratapi.events.notify(ratapi.events.EventTypes.Plot, data) first_callback.assert_called_once() second_callback.assert_called_once_with(data) - data = RATapi.events.ProgressEventData() - RATapi.events.notify(RATapi.events.EventTypes.Progress, data) + data = ratapi.events.ProgressEventData() + ratapi.events.notify(ratapi.events.EventTypes.Progress, data) first_callback.assert_called_once() second_callback.assert_called_once() third_callback.assert_called_once_with(data) - RATapi.events.clear() - RATapi.events.notify(RATapi.events.EventTypes.Message, "Hello World") - RATapi.events.notify(RATapi.events.EventTypes.Plot, data) + ratapi.events.clear() + ratapi.events.notify(ratapi.events.EventTypes.Message, "Hello World") + ratapi.events.notify(ratapi.events.EventTypes.Plot, data) assert first_callback.call_count == 1 assert second_callback.call_count == 1 assert third_callback.call_count == 1 def test_event_data_pickle(): - data = RATapi.events.ProgressEventData() + data = ratapi.events.ProgressEventData() data.message = "Hello" data.percent = 0.5 pickled_data = pickle.loads(pickle.dumps(data)) assert pickled_data.message == data.message assert pickled_data.percent == data.percent - data = RATapi.events.PlotEventData() + data = ratapi.events.PlotEventData() data.modelType = "custom layers" data.dataPresent = np.ones(2) data.subRoughs = np.ones((20, 2)) diff --git a/tests/test_examples.py b/tests/test_examples.py index de2a4e5a..532a5854 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -5,7 +5,7 @@ import pytest -import RATapi.examples as examples +import ratapi.examples as examples @pytest.mark.parametrize( diff --git a/tests/test_inputs.py b/tests/test_inputs.py index 7d768495..4e65501a 100644 --- a/tests/test_inputs.py +++ b/tests/test_inputs.py @@ -6,11 +6,11 @@ import numpy as np import pytest -import RATapi -import RATapi.wrappers -from RATapi.inputs import FileHandles, check_indices, make_controls, make_input, make_problem -from RATapi.rat_core import Checks, Control, NameStore, ProblemDefinition -from RATapi.utils.enums import ( +import ratapi +import ratapi.wrappers +from ratapi.inputs import FileHandles, check_indices, make_controls, make_input, make_problem +from ratapi.rat_core import Checks, Control, NameStore, ProblemDefinition +from ratapi.utils.enums import ( BackgroundActions, BoundHandling, Calculations, @@ -26,8 +26,8 @@ @pytest.fixture def standard_layers_project(): """Add parameters to the default project for a normal calculation.""" - test_project = RATapi.Project( - data=RATapi.ClassList([RATapi.models.Data(name="Test Data", data=np.array([[1.0, 1.0, 1.0]]))]), + test_project = ratapi.Project( + data=ratapi.ClassList([ratapi.models.Data(name="Test Data", data=np.array([[1.0, 1.0, 1.0]]))]), ) test_project.parameters.append(name="Test Thickness") test_project.parameters.append(name="Test SLD") @@ -60,9 +60,9 @@ def standard_layers_project(): @pytest.fixture def domains_project(): """Add parameters to the default project for a domains calculation.""" - test_project = RATapi.Project( + test_project = ratapi.Project( calculation=Calculations.Domains, - data=RATapi.ClassList([RATapi.models.Data(name="Test Data", data=np.array([[1.0, 1.0, 1.0]]))]), + data=ratapi.ClassList([ratapi.models.Data(name="Test Data", data=np.array([[1.0, 1.0, 1.0]]))]), ) test_project.parameters.append(name="Test Thickness") test_project.parameters.append(name="Test SLD") @@ -93,7 +93,7 @@ def domains_project(): @pytest.fixture def custom_xy_project(): """Add parameters to the default project for a normal calculation and use the custom xy model.""" - test_project = RATapi.Project(model=LayerModels.CustomXY) + test_project = ratapi.Project(model=LayerModels.CustomXY) test_project.parameters.append(name="Test Thickness") test_project.parameters.append(name="Test SLD") test_project.parameters.append(name="Test Roughness") @@ -343,7 +343,7 @@ def custom_xy_problem(test_names, test_checks): [1, 0.0, np.inf], ] problem.customFiles = FileHandles( - [RATapi.models.CustomFile(name="Test Custom File", filename="cpp_test.dll", language="cpp")] + [ratapi.models.CustomFile(name="Test Custom File", filename="cpp_test.dll", language="cpp")] ) problem.names = test_names problem.checks = test_checks @@ -455,7 +455,7 @@ def test_make_input(test_project, test_problem, test_controls, request) -> None: test_problem = request.getfixturevalue(test_problem) test_controls = request.getfixturevalue(test_controls) - problem, controls = make_input(test_project, RATapi.Controls()) + problem, controls = make_input(test_project, ratapi.Controls()) problem = pickle.loads(pickle.dumps(problem)) check_problem_equal(problem, test_problem) @@ -599,7 +599,7 @@ def test_undefined_background(test_project, request): ValueError, match=f"All backgrounds must have a source defined. For a {background.type} type " f"background, the source must be defined in " - f'"{RATapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"', + f'"{ratapi.project.values_defined_in[f"backgrounds.{background.type}.source"]}"', ): make_problem(test_project) @@ -614,7 +614,7 @@ def test_undefined_resolution(test_project, request): with pytest.raises( ValueError, match=f"Constant resolutions must have a source defined. The source must be defined in " - f'"{RATapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"', + f'"{ratapi.project.values_defined_in[f"resolutions.{resolution.type}.source"]}"', ): make_problem(test_project) @@ -640,7 +640,7 @@ def test_append_data_background(): data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) background = np.array([[1, 10, 11], [4, 12, 13], [7, 14, 15]]) - result = RATapi.inputs.append_data_background(data, background) + result = ratapi.inputs.append_data_background(data, background) np.testing.assert_allclose(result, np.array([[1, 2, 3, 0, 10, 11], [4, 5, 6, 0, 12, 13], [7, 8, 9, 0, 14, 15]])) @@ -649,7 +649,7 @@ def test_append_data_background_res(): data = np.array([[1, 2, 3, 4], [4, 5, 6, 6], [7, 8, 9, 72]]) background = np.array([[1, 10, 11], [4, 12, 13], [7, 14, 15]]) - result = RATapi.inputs.append_data_background(data, background) + result = ratapi.inputs.append_data_background(data, background) np.testing.assert_allclose(result, np.array([[1, 2, 3, 4, 10, 11], [4, 5, 6, 6, 12, 13], [7, 8, 9, 72, 14, 15]])) @@ -659,19 +659,19 @@ def test_append_data_background_error(): background = np.array([[56, 10, 11], [41, 12, 13], [7, 14, 15]]) with pytest.raises(ValueError, match=("The q-values of the data and background must be equal.")): - RATapi.inputs.append_data_background(data, background) + ratapi.inputs.append_data_background(data, background) def test_get_python_handle(): path = pathlib.Path(__file__).parent - assert RATapi.inputs.get_python_handle("utils.py", "dummy_function", path).__code__ == dummy_function.__code__ + assert ratapi.inputs.get_python_handle("utils.py", "dummy_function", path).__code__ == dummy_function.__code__ def test_make_controls(standard_layers_controls) -> None: """The controls object should contain the full set of controls parameters, with the appropriate set defined by the input controls. """ - controls = make_controls(RATapi.Controls()) + controls = make_controls(ratapi.Controls()) check_controls_equal(controls, standard_layers_controls) diff --git a/tests/test_models.py b/tests/test_models.py index 8e90183e..0b00dea9 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -8,24 +8,24 @@ import pydantic import pytest -import RATapi.models +import ratapi.models @pytest.mark.parametrize( ["model", "model_name", "model_params"], [ - (RATapi.models.Background, "Background", {}), - (RATapi.models.Contrast, "Contrast", {}), - (RATapi.models.CustomFile, "Custom File", {}), - (RATapi.models.Data, "Data", {}), - (RATapi.models.DomainContrast, "Domain Contrast", {}), + (ratapi.models.Background, "Background", {}), + (ratapi.models.Contrast, "Contrast", {}), + (ratapi.models.CustomFile, "Custom File", {}), + (ratapi.models.Data, "Data", {}), + (ratapi.models.DomainContrast, "Domain Contrast", {}), ( - RATapi.models.Layer, + ratapi.models.Layer, "Layer", {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}, ), - (RATapi.models.Parameter, "Parameter", {}), - (RATapi.models.Resolution, "Resolution", {}), + (ratapi.models.Parameter, "Parameter", {}), + (ratapi.models.Resolution, "Resolution", {}), ], ) def test_default_names(model: Callable, model_name: str, model_params: dict) -> None: @@ -46,15 +46,15 @@ def test_default_names(model: Callable, model_name: str, model_params: dict) -> @pytest.mark.parametrize( ["model", "model_params"], [ - (RATapi.models.Background, {}), - (RATapi.models.Contrast, {}), - (RATapi.models.ContrastWithRatio, {}), - (RATapi.models.CustomFile, {}), - (RATapi.models.Data, {}), - (RATapi.models.DomainContrast, {}), - (RATapi.models.Layer, {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}), + (ratapi.models.Background, {}), + (ratapi.models.Contrast, {}), + (ratapi.models.ContrastWithRatio, {}), + (ratapi.models.CustomFile, {}), + (ratapi.models.Data, {}), + (ratapi.models.DomainContrast, {}), + (ratapi.models.Layer, {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"}), ( - RATapi.models.AbsorptionLayer, + ratapi.models.AbsorptionLayer, { "thickness": "Test Thickness", "SLD_real": "Test SLD", @@ -62,8 +62,8 @@ def test_default_names(model: Callable, model_name: str, model_params: dict) -> "roughness": "Test Roughness", }, ), - (RATapi.models.Parameter, {}), - (RATapi.models.Resolution, {}), + (ratapi.models.Parameter, {}), + (ratapi.models.Resolution, {}), ], ) class TestModels: @@ -104,7 +104,7 @@ def test_initialise_with_extra_fields(self, model: Callable, model_params: dict) def test_custom_file_path_is_absolute() -> None: """If we use provide a relative path to the custom file model, it should be converted to an absolute path.""" relative_path = pathlib.Path("./relative_path") - custom_file = RATapi.models.CustomFile(path=relative_path) + custom_file = ratapi.models.CustomFile(path=relative_path) assert custom_file.path.is_absolute() @@ -112,7 +112,7 @@ def test_data_eq() -> None: """If we use the Data.__eq__ method with an object that is not a pydantic BaseModel, we should return "NotImplemented". """ - assert RATapi.models.Data().__eq__("data") == NotImplemented + assert ratapi.models.Data().__eq__("data") == NotImplemented @pytest.mark.parametrize( @@ -125,7 +125,7 @@ def test_data_dimension(input_data: np.ndarray[float]) -> None: """The "data" field of the "Data" model should be a two-dimensional numpy array with at least three values in the second dimension. """ - test_data = RATapi.models.Data(data=input_data) + test_data = ratapi.models.Data(data=input_data) assert (test_data.data == input_data).all() @@ -144,7 +144,7 @@ def test_data_too_few_dimensions(input_data: np.ndarray[float]) -> None: pydantic.ValidationError, match='1 validation error for Data\ndata\n Value error, "data" must have at least two dimensions', ): - RATapi.models.Data(data=input_data) + ratapi.models.Data(data=input_data) @pytest.mark.parametrize( @@ -163,7 +163,7 @@ def test_data_too_few_values(input_data: np.ndarray[float]) -> None: pydantic.ValidationError, match='1 validation error for Data\ndata\n Value error, "data" must have at least three columns', ): - RATapi.models.Data(data=input_data) + ratapi.models.Data(data=input_data) @pytest.mark.parametrize( @@ -174,8 +174,8 @@ def test_data_too_few_values(input_data: np.ndarray[float]) -> None: ) def test_data_ranges(input_range: list[float]) -> None: """The "data_range" and "simulation_range" fields of the "Data" model should contain exactly two values.""" - assert RATapi.models.Data(data_range=input_range).data_range == input_range - assert RATapi.models.Data(simulation_range=input_range).simulation_range == input_range + assert ratapi.models.Data(data_range=input_range).data_range == input_range + assert ratapi.models.Data(simulation_range=input_range).simulation_range == input_range @pytest.mark.parametrize( @@ -196,7 +196,7 @@ def test_two_values_in_data_range(input_range: list[float]) -> None: f"at {'least' if len(input_range) < 2 else 'most'} 2 items " f"after validation, not {len(input_range)}", ): - RATapi.models.Data(data_range=input_range) + ratapi.models.Data(data_range=input_range) @pytest.mark.parametrize( @@ -217,7 +217,7 @@ def test_two_values_in_simulation_range(input_range: list[float]) -> None: f"have at {'least' if len(input_range) < 2 else 'most'} 2 items " f"after validation, not {len(input_range)}", ): - RATapi.models.Data(simulation_range=input_range) + ratapi.models.Data(simulation_range=input_range) @pytest.mark.parametrize( @@ -236,14 +236,14 @@ def test_min_max_in_range(field: str) -> None: match=f"1 validation error for Data\n{field}\n Value error, {field} " f'"min" value is greater than the "max" value', ): - RATapi.models.Data(**{field: [1.0, 0.0]}) + ratapi.models.Data(**{field: [1.0, 0.0]}) def test_default_ranges() -> None: """If "data" is specified but either the "data_range" or "simulation_range" fields are not, we set the ranges to the minimum and maximum values of the first column of the data. """ - test_data = RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]])) + test_data = ratapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]])) assert test_data.data_range == [1.0, 3.0] assert test_data.simulation_range == [1.0, 3.0] @@ -268,7 +268,7 @@ def test_data_range(test_range) -> None: f"the min/max values of the data: [1.0, 3.0]", ), ): - RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), data_range=test_range) + ratapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), data_range=test_range) @pytest.mark.parametrize( @@ -292,7 +292,7 @@ def test_simulation_range(test_range) -> None: f"[1.0, 3.0]", ), ): - RATapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), simulation_range=test_range) + ratapi.models.Data(data=np.array([[1.0, 0.0, 0.0], [3.0, 0.0, 0.0]]), simulation_range=test_range) @pytest.mark.parametrize( @@ -313,7 +313,7 @@ def test_parameter_range(minimum: float, value: float, maximum: float) -> None: f"{float(value)} is not within the defined range: " f"{float(minimum)} <= value <= {float(maximum)}", ): - RATapi.models.Parameter(min=minimum, value=value, max=maximum) + ratapi.models.Parameter(min=minimum, value=value, max=maximum) def test_layer_bad_imaginary_SLD(): @@ -326,7 +326,7 @@ def test_layer_bad_imaginary_SLD(): " Use the AbsorptionLayer class instead." ), ): - RATapi.models.Layer(name="My Layer", SLD_imaginary="bad sld") + ratapi.models.Layer(name="My Layer", SLD_imaginary="bad sld") def test_contrast_bad_ratio(): @@ -339,14 +339,14 @@ def test_contrast_bad_ratio(): " Use the ContrastWithRatio class instead." ), ): - RATapi.models.Contrast(name="My Contrast", domain_ratio="bad ratio") + ratapi.models.Contrast(name="My Contrast", domain_ratio="bad ratio") @pytest.mark.parametrize( ["model", "type", "values"], [ - (RATapi.models.Background, "function", ["val1", "val2", "val3", "val4", "val5"]), - (RATapi.models.Resolution, "constant", ["", "", "", "", ""]), + (ratapi.models.Background, "function", ["val1", "val2", "val3", "val4", "val5"]), + (ratapi.models.Resolution, "constant", ["", "", "", "", ""]), ], ) def test_type_change_clear(model, type, values): @@ -371,10 +371,10 @@ def test_type_change_clear(model, type, values): @pytest.mark.parametrize( ["model", "signal_type", "values"], [ - (RATapi.models.Background, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]), - (RATapi.models.Background, "data", ["value_2", "value_3", "value_4", "value_5"]), - (RATapi.models.Resolution, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]), - (RATapi.models.Resolution, "data", ["value_1", "value_2", "value_3", "value_4", "value_5"]), + (ratapi.models.Background, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]), + (ratapi.models.Background, "data", ["value_2", "value_3", "value_4", "value_5"]), + (ratapi.models.Resolution, "constant", ["value_1", "value_2", "value_3", "value_4", "value_5"]), + (ratapi.models.Resolution, "data", ["value_1", "value_2", "value_3", "value_4", "value_5"]), ], ) def test_unsupported_parameters_error(model, signal_type, values): diff --git a/tests/test_orso_utils.py b/tests/test_orso_utils.py index 958abd88..39137fe9 100644 --- a/tests/test_orso_utils.py +++ b/tests/test_orso_utils.py @@ -1,4 +1,4 @@ -"""Tests for the RATapi.utils.orso module.""" +"""Tests for the ratapi.utils.orso module.""" import os from io import StringIO @@ -8,9 +8,9 @@ import pytest from orsopy.fileio.model_language import SampleModel -from RATapi.examples.bayes_benchmark.bayes_benchmark import get_project -from RATapi.project import Project -from RATapi.utils.orso import ORSOProject, orso_model_to_rat +from ratapi.examples.bayes_benchmark.bayes_benchmark import get_project +from ratapi.project import Project +from ratapi.utils.orso import ORSOProject, orso_model_to_rat TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data") diff --git a/tests/test_orso_validation.py b/tests/test_orso_validation.py index 99c2e449..95a510f2 100644 --- a/tests/test_orso_validation.py +++ b/tests/test_orso_validation.py @@ -2,8 +2,8 @@ import pytest -import RATapi as RAT -from RATapi.utils.plotting import plot_ref_sld +import ratapi as RAT +from ratapi.utils.plotting import plot_ref_sld PROJECT_PATH = pathlib.Path(__file__).parents[0] / "test_data" diff --git a/tests/test_outputs.py b/tests/test_outputs.py index 0fce4697..9cd1ad90 100644 --- a/tests/test_outputs.py +++ b/tests/test_outputs.py @@ -9,10 +9,10 @@ import numpy as np import pytest -import RATapi -import RATapi.outputs -import RATapi.rat_core -from RATapi.utils.enums import Procedures +import ratapi +import ratapi.outputs +import ratapi.rat_core +from ratapi.utils.enums import Procedures from tests.utils import check_results_equal @@ -167,7 +167,7 @@ def test_get_field_string(test_value, array_limit, expected_field_string) -> Non """For the string representation of output classes, we represent multidimensional and large arrays by their shape, with other variables printed normally. """ - field_string = RATapi.outputs.get_field_string("test_field", test_value, array_limit) + field_string = ratapi.outputs.get_field_string("test_field", test_value, array_limit) assert field_string == expected_field_string @@ -186,7 +186,7 @@ def test_make_results(test_procedure, test_output_results, test_bayes, test_resu test_bayes = request.getfixturevalue(test_bayes) test_results = request.getfixturevalue(test_results) - results = RATapi.outputs.make_results(test_procedure, test_output_results, test_bayes) + results = ratapi.outputs.make_results(test_procedure, test_output_results, test_bayes) check_results_equal(test_results, results) @@ -208,7 +208,7 @@ def test_results_str(test_output_results, test_str, request) -> None: assert test_output_results.__str__() == test_str -@pytest.mark.parametrize("result_class", [RATapi.Results, RATapi.BayesResults]) +@pytest.mark.parametrize("result_class", [ratapi.Results, ratapi.BayesResults]) @pytest.mark.parametrize("test_results", ["reflectivity_calculation_results", "dream_results"]) def test_save_load(result_class, test_results, request): """Test that saving and loading an output object returns the same object.""" diff --git a/tests/test_plotting.py b/tests/test_plotting.py index abeb4177..3bb3f69c 100644 --- a/tests/test_plotting.py +++ b/tests/test_plotting.py @@ -9,9 +9,9 @@ from matplotlib.collections import PolyCollection, QuadMesh from matplotlib.patches import Rectangle -import RATapi.utils.plotting as RATplot -from RATapi.events import notify -from RATapi.rat_core import EventTypes, PlotEventData +import ratapi.utils.plotting as RATplot +from ratapi.events import notify +from ratapi.rat_core import EventTypes, PlotEventData TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data") @@ -132,7 +132,7 @@ def test_ref_sld_bayes(fig, bayes_fig, bayes): assert any(isinstance(comp, PolyCollection) for comp in components) -@patch("RATapi.utils.plotting.makeSLDProfile") +@patch("ratapi.utils.plotting.makeSLDProfile") def test_sld_profile_function_call(mock: MagicMock) -> None: """Tests the makeSLDProfile function called with correct args. @@ -156,7 +156,7 @@ def test_sld_profile_function_call(mock: MagicMock) -> None: assert mock.call_args_list[2].args[4] == 1 -@patch("RATapi.utils.plotting.makeSLDProfile") +@patch("ratapi.utils.plotting.makeSLDProfile") def test_live_plot(mock: MagicMock) -> None: plot_data = data() @@ -183,7 +183,7 @@ def test_live_plot(mock: MagicMock) -> None: assert mock.call_args_list[2].args[4] == 1 -@patch("RATapi.utils.plotting.plot_ref_sld_helper") +@patch("ratapi.utils.plotting.plot_ref_sld_helper") def test_plot_ref_sld(mock: MagicMock, input_project, reflectivity_calculation_results) -> None: RATplot.plot_ref_sld(input_project, reflectivity_calculation_results) mock.assert_called_once() @@ -216,7 +216,7 @@ def test_ref_sld_subplot_correction(): assert len(ref_sld_fig.axes) == 2 -@patch("RATapi.utils.plotting.plot_ref_sld_helper") +@patch("ratapi.utils.plotting.plot_ref_sld_helper") def test_plot_ref_sld_bayes_validation(mock, input_project, reflectivity_calculation_results, dream_results): """Test that plot_ref_sld correctly throws errors for bad Bayesian input.""" RATplot.plot_ref_sld(input_project, dream_results) @@ -388,7 +388,7 @@ def test_corner(dream_results, params): @pytest.mark.parametrize( "params", [None, [2, 3], [1, 5, "D2O"], ["Bilayer Heads Thickness", "Bilayer Heads Hydration", "D2O"]] ) -@patch("RATapi.plotting.panel_plot_helper") +@patch("ratapi.plotting.panel_plot_helper") def test_hist_panel(mock_panel_helper: MagicMock, params, dream_results): """Test chain panel name-to-index (panel helper has already been tested)""" fig = RATplot.plot_hists(dream_results, params, return_fig=True) @@ -412,7 +412,7 @@ def test_hist_panel(mock_panel_helper: MagicMock, params, dream_results): ({"default": "normal", 1: "kernel"}, "DEFAULT_WITH_1CHANGE_DICT"), ], ) -@patch("RATapi.plotting.plot_one_hist") +@patch("ratapi.plotting.plot_one_hist") def test_standardise_est_dens(mock_plot_hist: MagicMock, input, expected_dict, dream_results): """Test estimated density is correctly standardised.""" _ = RATplot.plot_hists(dream_results, estimated_density=input, return_fig=True) @@ -445,7 +445,7 @@ def test_est_dens_error(dream_results, input): @pytest.mark.parametrize( "params", [None, [2, 3], [1, 5, "D2O"], ["Bilayer Heads Thickness", "Bilayer Heads Hydration", "D2O"]] ) -@patch("RATapi.plotting.panel_plot_helper") +@patch("ratapi.plotting.panel_plot_helper") def test_chain_panel(mock_panel_helper: MagicMock, params, dream_results): """Test chain panel name-to-index (panel helper has already been tested)""" # return fig just to avoid plt.show() being called @@ -458,9 +458,9 @@ def test_chain_panel(mock_panel_helper: MagicMock, params, dream_results): assert param == (dream_results.fitNames.index(param) if isinstance(param, str) else param) -@patch("RATapi.plotting.plot_ref_sld") -@patch("RATapi.plotting.plot_hists") -@patch("RATapi.plotting.plot_corner") +@patch("ratapi.plotting.plot_ref_sld") +@patch("ratapi.plotting.plot_hists") +@patch("ratapi.plotting.plot_corner") def test_bayes_calls( mock_corner: MagicMock, mock_hists: MagicMock, mock_ref_sld: MagicMock, input_project, dream_results ): @@ -486,7 +486,7 @@ def test_extract_plot_data(data) -> None: assert len(plot_data["sld"]) == len(data.shiftedData) -@patch("RATapi.utils.plotting.plot_ref_sld_helper") +@patch("ratapi.utils.plotting.plot_ref_sld_helper") def test_blit_plot(plot_helper, fig: plt.figure) -> None: plot_helper.return_value = fig event_data = data() diff --git a/tests/test_project.py b/tests/test_project.py index 2cdd5ead..c2ea92a2 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -12,8 +12,8 @@ import pytest from typing_extensions import get_args, get_origin -import RATapi -from RATapi.utils.enums import Calculations, LayerModels, TypeOptions +import ratapi +from ratapi.utils.enums import Calculations, LayerModels, TypeOptions layer_params = {"thickness": "Test Thickness", "SLD": "Test SLD", "roughness": "Test Roughness"} absorption_layer_params = { @@ -24,28 +24,28 @@ } model_classes = { - "parameters": RATapi.models.Parameter, - "bulk_in": RATapi.models.Parameter, - "bulk_out": RATapi.models.Parameter, - "scalefactors": RATapi.models.Parameter, - "domain_ratios": RATapi.models.Parameter, - "background_parameters": RATapi.models.Parameter, - "resolution_parameters": RATapi.models.Parameter, - "backgrounds": RATapi.models.Background, - "resolutions": RATapi.models.Resolution, - "custom_files": RATapi.models.CustomFile, - "data": RATapi.models.Data, - "layers": RATapi.models.Layer, - "domain_contrasts": RATapi.models.DomainContrast, - "contrasts": RATapi.models.Contrast, + "parameters": ratapi.models.Parameter, + "bulk_in": ratapi.models.Parameter, + "bulk_out": ratapi.models.Parameter, + "scalefactors": ratapi.models.Parameter, + "domain_ratios": ratapi.models.Parameter, + "background_parameters": ratapi.models.Parameter, + "resolution_parameters": ratapi.models.Parameter, + "backgrounds": ratapi.models.Background, + "resolutions": ratapi.models.Resolution, + "custom_files": ratapi.models.CustomFile, + "data": ratapi.models.Data, + "layers": ratapi.models.Layer, + "domain_contrasts": ratapi.models.DomainContrast, + "contrasts": ratapi.models.Contrast, } @pytest.fixture def test_project(): """Add parameters to the default project, so each ClassList can be tested properly.""" - test_project = RATapi.Project( - data=RATapi.ClassList([RATapi.models.Data(name="Simulation", data=np.array([[1.0, 1.0, 1.0]]))]), + test_project = ratapi.Project( + data=ratapi.ClassList([ratapi.models.Data(name="Simulation", data=np.array([[1.0, 1.0, 1.0]]))]), ) test_project.parameters.append(name="Test Thickness") test_project.parameters.append(name="Test SLD") @@ -141,8 +141,8 @@ def test_classlists(test_project) -> None: """The ClassLists in the "Project" model should contain instances of the models given by the dictionary "model_in_classlist". """ - for model in (fields := RATapi.Project.model_fields): - if get_origin(fields[model].annotation) == RATapi.ClassList: + for model in (fields := ratapi.Project.model_fields): + if get_origin(fields[model].annotation) == ratapi.ClassList: class_list = getattr(test_project, model) assert class_list._class_handle == get_args(fields[model].annotation)[0] @@ -151,7 +151,7 @@ def test_classlists_specific_cases() -> None: """The ClassLists in the "Project" model should contain instances of specific models given various non-default options. """ - project = RATapi.Project(calculation=Calculations.Domains, absorption=True) + project = ratapi.Project(calculation=Calculations.Domains, absorption=True) assert project.layers._class_handle.__name__ == "AbsorptionLayer" assert project.contrasts._class_handle.__name__ == "ContrastWithRatio" @@ -159,15 +159,15 @@ def test_classlists_specific_cases() -> None: @pytest.mark.parametrize( ["input_model", "model_params"], [ - (RATapi.models.Background, {}), - (RATapi.models.Contrast, {}), - (RATapi.models.ContrastWithRatio, {}), - (RATapi.models.CustomFile, {}), - (RATapi.models.Data, {}), - (RATapi.models.DomainContrast, {}), - (RATapi.models.Layer, layer_params), - (RATapi.models.AbsorptionLayer, absorption_layer_params), - (RATapi.models.Resolution, {}), + (ratapi.models.Background, {}), + (ratapi.models.Contrast, {}), + (ratapi.models.ContrastWithRatio, {}), + (ratapi.models.CustomFile, {}), + (ratapi.models.Data, {}), + (ratapi.models.DomainContrast, {}), + (ratapi.models.Layer, layer_params), + (ratapi.models.AbsorptionLayer, absorption_layer_params), + (ratapi.models.Resolution, {}), ], ) def test_initialise_wrong_classes(input_model: Callable, model_params: dict) -> None: @@ -178,14 +178,14 @@ def test_initialise_wrong_classes(input_model: Callable, model_params: dict) -> "Value error, This ClassList only supports elements of type Parameter. In the input list:\n" f" index 0 is of type {input_model.__name__}", ): - RATapi.Project(parameters=RATapi.ClassList(input_model(**model_params))) + ratapi.Project(parameters=ratapi.ClassList(input_model(**model_params))) @pytest.mark.parametrize( ["input_model", "model_params", "absorption", "actual_model_name"], [ - (RATapi.models.Layer, layer_params, True, "AbsorptionLayer"), - (RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"), + (ratapi.models.Layer, layer_params, True, "AbsorptionLayer"), + (ratapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"), ], ) def test_initialise_wrong_layers( @@ -203,18 +203,18 @@ def test_initialise_wrong_layers( f'"The layers attribute contains {input_model.__name__}s, but the absorption parameter is ' f'{absorption}. The attribute should be a ClassList of {actual_model_name} instead."', ): - RATapi.Project(absorption=absorption, layers=RATapi.ClassList(input_model(**model_params))) + ratapi.Project(absorption=absorption, layers=ratapi.ClassList(input_model(**model_params))) @pytest.mark.parametrize( ["input_model", "calculation", "actual_model_name"], [ - (RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"), - (RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"), + (ratapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"), + (ratapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"), ], ) def test_initialise_wrong_contrasts( - input_model: RATapi.models.RATModel, calculation: Calculations, actual_model_name: str + input_model: ratapi.models.RATModel, calculation: Calculations, actual_model_name: str ) -> None: """If the "Project" model is initialised with the incorrect contrast model given the value of calculation, we should raise a ValidationError. @@ -226,16 +226,16 @@ def test_initialise_wrong_contrasts( f' Value error, "The contrasts attribute contains contrasts {word} ratio, ' f'but the calculation is {calculation}"', ): - RATapi.Project(calculation=calculation, contrasts=RATapi.ClassList(input_model())) + ratapi.Project(calculation=calculation, contrasts=ratapi.ClassList(input_model())) @pytest.mark.parametrize( "calculation, model", - [(Calculations.Domains, RATapi.models.ContrastWithRatio), (Calculations.Normal, RATapi.models.Contrast)], + [(Calculations.Domains, ratapi.models.ContrastWithRatio), (Calculations.Normal, ratapi.models.Contrast)], ) -def test_initialise_ambiguous_contrasts(calculation: Calculations, model: RATapi.models.RATModel): +def test_initialise_ambiguous_contrasts(calculation: Calculations, model: ratapi.models.RATModel): """If a sequence of dictionaries is passed to 'contrasts', convert them to the correct model for the calculation.""" - proj = RATapi.Project(calculation=calculation, contrasts=RATapi.ClassList([{"name": "Contrast 1"}])) + proj = ratapi.Project(calculation=calculation, contrasts=ratapi.ClassList([{"name": "Contrast 1"}])) assert proj.contrasts._class_handle == model @@ -243,14 +243,14 @@ def test_initialise_without_substrate_roughness() -> None: """If the "Project" model is initialised without "Substrate Roughness" as a parameter, add it as a protected parameter to the front of the "parameters" ClassList. """ - project = RATapi.Project(parameters=RATapi.ClassList(RATapi.models.Parameter(name="Test Parameter"))) - assert project.parameters[0] == RATapi.models.ProtectedParameter( + project = ratapi.Project(parameters=ratapi.ClassList(ratapi.models.Parameter(name="Test Parameter"))) + assert project.parameters[0] == ratapi.models.ProtectedParameter( name="Substrate Roughness", min=1.0, value=3.0, max=5.0, fit=True, - prior_type=RATapi.models.Priors.Uniform, + prior_type=ratapi.models.Priors.Uniform, mu=0.0, sigma=np.inf, ) @@ -259,38 +259,38 @@ def test_initialise_without_substrate_roughness() -> None: @pytest.mark.parametrize( "input_parameter", [ - RATapi.models.Parameter(name="Substrate Roughness"), - RATapi.models.Parameter(name="SUBSTRATE ROUGHNESS"), - RATapi.models.Parameter(name="substrate roughness"), + ratapi.models.Parameter(name="Substrate Roughness"), + ratapi.models.Parameter(name="SUBSTRATE ROUGHNESS"), + ratapi.models.Parameter(name="substrate roughness"), ], ) -def test_initialise_without_protected_substrate_roughness(input_parameter: RATapi.models.Parameter) -> None: +def test_initialise_without_protected_substrate_roughness(input_parameter: ratapi.models.Parameter) -> None: """If the "Project" model is initialised without "Substrate Roughness" as a protected parameter, add it to the front of the "parameters" ClassList. """ - project = RATapi.Project(parameters=RATapi.ClassList(input_parameter)) - assert project.parameters[0] == RATapi.models.ProtectedParameter(name=input_parameter.name) + project = ratapi.Project(parameters=ratapi.ClassList(input_parameter)) + assert project.parameters[0] == ratapi.models.ProtectedParameter(name=input_parameter.name) def test_initialise_without_simulation() -> None: """If the "Project" model is initialised without "Simulation" in the "data" ClassList, add it to the front of the "data" ClassList. """ - project = RATapi.Project(parameters=RATapi.ClassList(RATapi.models.Parameter(name="Test Parameter"))) - assert project.data[0] == RATapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7]) + project = ratapi.Project(parameters=ratapi.ClassList(ratapi.models.Parameter(name="Test Parameter"))) + assert project.data[0] == ratapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7]) @pytest.mark.parametrize( ["field", "model_type", "wrong_input_model", "model_params"], [ - ("backgrounds", "Background", RATapi.models.Resolution, {}), - ("contrasts", "Contrast", RATapi.models.Layer, layer_params), - ("domain_contrasts", "DomainContrast", RATapi.models.Parameter, {}), - ("custom_files", "CustomFile", RATapi.models.Data, {}), - ("data", "Data", RATapi.models.Contrast, {}), - ("layers", "Layer", RATapi.models.DomainContrast, {}), - ("parameters", "Parameter", RATapi.models.CustomFile, {}), - ("resolutions", "Resolution", RATapi.models.Background, {}), + ("backgrounds", "Background", ratapi.models.Resolution, {}), + ("contrasts", "Contrast", ratapi.models.Layer, layer_params), + ("domain_contrasts", "DomainContrast", ratapi.models.Parameter, {}), + ("custom_files", "CustomFile", ratapi.models.Data, {}), + ("data", "Data", ratapi.models.Contrast, {}), + ("layers", "Layer", ratapi.models.DomainContrast, {}), + ("parameters", "Parameter", ratapi.models.CustomFile, {}), + ("resolutions", "Resolution", ratapi.models.Background, {}), ], ) def test_assign_wrong_classes( @@ -312,14 +312,14 @@ def test_assign_wrong_classes( f" index 0 is of type {wrong_input_model.__name__}" ), ): - setattr(test_project, field, RATapi.ClassList(wrong_input_model(**model_params))) + setattr(test_project, field, ratapi.ClassList(wrong_input_model(**model_params))) @pytest.mark.parametrize( ["wrong_input_model", "model_params", "absorption", "actual_model_name"], [ - (RATapi.models.Layer, layer_params, True, "AbsorptionLayer"), - (RATapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"), + (ratapi.models.Layer, layer_params, True, "AbsorptionLayer"), + (ratapi.models.AbsorptionLayer, absorption_layer_params, False, "Layer"), ], ) def test_assign_wrong_layers( @@ -329,26 +329,26 @@ def test_assign_wrong_layers( actual_model_name: str, ) -> None: """If we assign incorrect classes to the "Project" model, we should raise a ValidationError.""" - project = RATapi.Project(absorption=absorption) + project = ratapi.Project(absorption=absorption) with pytest.raises( pydantic.ValidationError, match=f"1 validation error for Project\nlayers\n Value error, " f'"The layers attribute contains {wrong_input_model.__name__}s, but the absorption parameter is ' f'{absorption}. The attribute should be a ClassList of {actual_model_name} instead."', ): - project.layers = RATapi.ClassList(wrong_input_model(**model_params)) + project.layers = ratapi.ClassList(wrong_input_model(**model_params)) @pytest.mark.parametrize( ["wrong_input_model", "calculation", "actual_model_name"], [ - (RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"), - (RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"), + (ratapi.models.Contrast, Calculations.Domains, "ContrastWithRatio"), + (ratapi.models.ContrastWithRatio, Calculations.Normal, "Contrast"), ], ) def test_assign_wrong_contrasts(wrong_input_model: Callable, calculation: Calculations, actual_model_name: str) -> None: """If we assign incorrect classes to the "Project" model, we should raise a ValidationError.""" - project = RATapi.Project(calculation=calculation) + project = ratapi.Project(calculation=calculation) word = "without" if calculation == Calculations.Domains else "with" with pytest.raises( pydantic.ValidationError, @@ -356,7 +356,7 @@ def test_assign_wrong_contrasts(wrong_input_model: Callable, calculation: Calcul f' Value error, "The contrasts attribute contains contrasts {word} ratio, but the calculation is ' f'{calculation}"', ): - project.contrasts = RATapi.ClassList(wrong_input_model()) + project.contrasts = ratapi.ClassList(wrong_input_model()) @pytest.mark.parametrize( @@ -395,7 +395,7 @@ def test_wrapped_routines(test_project) -> None: "extend", "set_fields", ] - for class_list in RATapi.project.class_lists: + for class_list in ratapi.project.class_lists: attribute = getattr(test_project, class_list) for methodName in wrapped_methods: assert hasattr(getattr(attribute, methodName), "__wrapped__") @@ -422,7 +422,7 @@ def test_set_domain_contrasts(project_parameters: dict) -> None: """If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model should always be empty. """ - project = RATapi.Project(**project_parameters) + project = ratapi.Project(**project_parameters) assert project.domain_contrasts == [] project.domain_contrasts.append(name="New Domain Contrast") assert project.domain_contrasts == [] @@ -437,7 +437,7 @@ def test_set_domain_contrasts(project_parameters: dict) -> None: ) def test_set_layers(project_parameters: dict) -> None: """If we are not using a standard layers model, the "layers" field of the model should always be empty.""" - project = RATapi.Project(**project_parameters) + project = ratapi.Project(**project_parameters) assert project.layers == [] project.layers.append(name="New Layer", thickness="Test Thickness", SLD="Test SLD", roughness="Test Roughness") assert project.layers == [] @@ -446,8 +446,8 @@ def test_set_layers(project_parameters: dict) -> None: @pytest.mark.parametrize( ["input_calculation", "input_contrast", "new_calculation", "new_contrast_model", "num_domain_ratios"], [ - (Calculations.Normal, RATapi.models.Contrast, Calculations.Domains, "ContrastWithRatio", 1), - (Calculations.Domains, RATapi.models.ContrastWithRatio, Calculations.Normal, "Contrast", 0), + (Calculations.Normal, ratapi.models.Contrast, Calculations.Domains, "ContrastWithRatio", 1), + (Calculations.Domains, ratapi.models.ContrastWithRatio, Calculations.Normal, "Contrast", 0), ], ) def test_set_calculation( @@ -460,7 +460,7 @@ def test_set_calculation( """When changing the value of the calculation option, the "contrasts" ClassList should switch to using the appropriate Contrast model. """ - project = RATapi.Project(calculation=input_calculation, contrasts=RATapi.ClassList(input_contrast())) + project = ratapi.Project(calculation=input_calculation, contrasts=ratapi.ClassList(input_contrast())) project.calculation = new_calculation assert project.calculation is new_calculation @@ -525,13 +525,13 @@ def test_check_contrast_model_length( """If we are not running a domains calculation with standard layers, the "domain_contrasts" field of the model should always be empty. """ - test_domain_ratios = RATapi.ClassList(RATapi.models.Parameter(name="Test Domain Ratio")) - test_contrasts = RATapi.ClassList(RATapi.models.ContrastWithRatio(model=test_contrast_model)) + test_domain_ratios = ratapi.ClassList(ratapi.models.Parameter(name="Test Domain Ratio")) + test_contrasts = ratapi.ClassList(ratapi.models.ContrastWithRatio(model=test_contrast_model)) with pytest.raises( pydantic.ValidationError, match=f"1 validation error for Project\n Value error, {error_message}", ): - RATapi.Project( + ratapi.Project( calculation=Calculations.Domains, model=input_model, domain_ratios=test_domain_ratios, @@ -542,8 +542,8 @@ def test_check_contrast_model_length( @pytest.mark.parametrize( ["input_layer", "model_params", "input_absorption", "new_layer_model"], [ - (RATapi.models.Layer, layer_params, False, "AbsorptionLayer"), - (RATapi.models.AbsorptionLayer, absorption_layer_params, True, "Layer"), + (ratapi.models.Layer, layer_params, False, "AbsorptionLayer"), + (ratapi.models.AbsorptionLayer, absorption_layer_params, True, "Layer"), ], ) def test_set_absorption( @@ -555,16 +555,16 @@ def test_set_absorption( """When changing the value of the absorption option, the "layers" ClassList should switch to using the appropriate Layer model. """ - project = RATapi.Project( + project = ratapi.Project( absorption=input_absorption, - parameters=RATapi.ClassList( + parameters=ratapi.ClassList( [ - RATapi.models.Parameter(name="Test Thickness"), - RATapi.models.Parameter(name="Test SLD"), - RATapi.models.Parameter(name="Test Roughness"), + ratapi.models.Parameter(name="Test Thickness"), + ratapi.models.Parameter(name="Test SLD"), + ratapi.models.Parameter(name="Test Roughness"), ], ), - layers=RATapi.ClassList(input_layer(**model_params)), + layers=ratapi.ClassList(input_layer(**model_params)), ) project.absorption = not input_absorption @@ -584,7 +584,7 @@ def test_set_absorption( ) def test_check_protected_parameters(delete_operation) -> None: """If we try to remove a protected parameter, we should raise an error.""" - project = RATapi.Project() + project = ratapi.Project() with pytest.raises( pydantic.ValidationError, @@ -617,16 +617,16 @@ def test_rename_models(test_project, model: str, fields: list[str]) -> None: in the project. """ if model == "data": - test_project.backgrounds[0] = RATapi.models.Background(type="data", source="Simulation") + test_project.backgrounds[0] = ratapi.models.Background(type="data", source="Simulation") if model == "custom_files": - test_project.backgrounds[0] = RATapi.models.Background(type="function", source="Test Custom File") + test_project.backgrounds[0] = ratapi.models.Background(type="function", source="Test Custom File") # workaround until function resolutions are added - # test_project.resolutions[0] = RATapi.models.Resolution(type="function", source="Test Custom File") - test_project.resolution_parameters.append(RATapi.models.Parameter(name="New Name")) - test_project.resolutions[0] = RATapi.models.Resolution(type="constant", source="New Name") + # test_project.resolutions[0] = ratapi.models.Resolution(type="function", source="Test Custom File") + test_project.resolution_parameters.append(ratapi.models.Parameter(name="New Name")) + test_project.resolutions[0] = ratapi.models.Resolution(type="constant", source="New Name") getattr(test_project, model).set_fields(-1, name="New Name") - model_name_lists = RATapi.project.model_names_used_in[model] + model_name_lists = ratapi.project.model_names_used_in[model] for model_name_list, field in zip(model_name_lists, fields): attribute = model_name_list.attribute assert getattr(getattr(test_project, attribute)[-1], field) == "New Name" @@ -645,7 +645,7 @@ def test_allowed_backgrounds(background_type, expected_field) -> None: If the source field of the Background model is set to a value that is not specified in the appropriate ClassList, we should raise a ValidationError. """ - test_background = RATapi.models.Background(type=background_type, source="undefined") + test_background = ratapi.models.Background(type=background_type, source="undefined") with pytest.raises( pydantic.ValidationError, match=re.escape( @@ -654,7 +654,7 @@ def test_allowed_backgrounds(background_type, expected_field) -> None: f'before including it in "backgrounds".' ), ): - RATapi.Project(backgrounds=RATapi.ClassList(test_background)) + ratapi.Project(backgrounds=ratapi.ClassList(test_background)) @pytest.mark.parametrize( @@ -669,7 +669,7 @@ def test_allowed_layers(field: str) -> None: """If the "thickness", "SLD", or "roughness" fields of the Layer model are set to values that are not specified in the parameters, we should raise a ValidationError. """ - test_layer = RATapi.models.Layer(**{**layer_params, field: "undefined"}) + test_layer = ratapi.models.Layer(**{**layer_params, field: "undefined"}) with pytest.raises( pydantic.ValidationError, @@ -679,16 +679,16 @@ def test_allowed_layers(field: str) -> None: f'before including it in "layers".' ), ): - RATapi.Project( + ratapi.Project( absorption=False, - parameters=RATapi.ClassList( + parameters=ratapi.ClassList( [ - RATapi.models.Parameter(name="Test Thickness"), - RATapi.models.Parameter(name="Test SLD"), - RATapi.models.Parameter(name="Test Roughness"), + ratapi.models.Parameter(name="Test Thickness"), + ratapi.models.Parameter(name="Test SLD"), + ratapi.models.Parameter(name="Test Roughness"), ], ), - layers=RATapi.ClassList(test_layer), + layers=ratapi.ClassList(test_layer), ) @@ -705,7 +705,7 @@ def test_allowed_absorption_layers(field: str) -> None: """If the "thickness", "SLD_real", "SLD_imaginary", or "roughness" fields of the AbsorptionLayer model are set to values that are not specified in the parameters, we should raise a ValidationError. """ - test_layer = RATapi.models.AbsorptionLayer(**{**absorption_layer_params, field: "undefined"}) + test_layer = ratapi.models.AbsorptionLayer(**{**absorption_layer_params, field: "undefined"}) with pytest.raises( pydantic.ValidationError, @@ -715,16 +715,16 @@ def test_allowed_absorption_layers(field: str) -> None: f'in "layers".' ), ): - RATapi.Project( + ratapi.Project( absorption=True, - parameters=RATapi.ClassList( + parameters=ratapi.ClassList( [ - RATapi.models.Parameter(name="Test Thickness"), - RATapi.models.Parameter(name="Test SLD"), - RATapi.models.Parameter(name="Test Roughness"), + ratapi.models.Parameter(name="Test Thickness"), + ratapi.models.Parameter(name="Test SLD"), + ratapi.models.Parameter(name="Test Roughness"), ], ), - layers=RATapi.ClassList(test_layer), + layers=ratapi.ClassList(test_layer), ) @@ -740,7 +740,7 @@ def test_allowed_resolutions(resolution_type, expected_field) -> None: """If the "value" fields of the Resolution model are set to values that are not specified in the resolution parameters, we should raise a ValidationError. """ - test_resolution = RATapi.models.Resolution(type=resolution_type, source="undefined") + test_resolution = ratapi.models.Resolution(type=resolution_type, source="undefined") with pytest.raises( pydantic.ValidationError, match=re.escape( @@ -749,7 +749,7 @@ def test_allowed_resolutions(resolution_type, expected_field) -> None: f'before including it in "resolutions".' ), ): - RATapi.Project(resolutions=RATapi.ClassList(test_resolution)) + ratapi.Project(resolutions=ratapi.ClassList(test_resolution)) @pytest.mark.parametrize( @@ -767,7 +767,7 @@ def test_allowed_contrasts(field: str, model_name: str) -> None: """If the fields of the Contrast model are set to values not specified in the other respective models of the project, we should raise a ValidationError. """ - test_contrast = RATapi.models.Contrast(**{field: "undefined"}) + test_contrast = ratapi.models.Contrast(**{field: "undefined"}) with pytest.raises( pydantic.ValidationError, match=re.escape( @@ -776,7 +776,7 @@ def test_allowed_contrasts(field: str, model_name: str) -> None: f'including it in "contrasts".' ), ): - RATapi.Project(calculation=Calculations.Normal, contrasts=RATapi.ClassList(test_contrast)) + ratapi.Project(calculation=Calculations.Normal, contrasts=ratapi.ClassList(test_contrast)) @pytest.mark.parametrize( @@ -795,7 +795,7 @@ def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None: """If the fields of the ContrastWithRatio model are set to values not specified in the other respective models of the project, we should raise a ValidationError. """ - test_contrast = RATapi.models.ContrastWithRatio(**{field: "undefined"}) + test_contrast = ratapi.models.ContrastWithRatio(**{field: "undefined"}) with pytest.raises( pydantic.ValidationError, match=re.escape( @@ -804,7 +804,7 @@ def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None: f'including it in "contrasts".' ), ): - RATapi.Project(calculation=Calculations.Domains, contrasts=RATapi.ClassList(test_contrast)) + ratapi.Project(calculation=Calculations.Domains, contrasts=ratapi.ClassList(test_contrast)) @pytest.mark.parametrize( @@ -813,37 +813,37 @@ def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None: ( Calculations.Domains, LayerModels.StandardLayers, - RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined", "undefined"]), + ratapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined", "undefined"]), "domain_contrasts", ), ( Calculations.Domains, LayerModels.CustomLayers, - RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]), + ratapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]), "custom_files", ), ( Calculations.Domains, LayerModels.CustomXY, - RATapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]), + ratapi.models.ContrastWithRatio(name="Test Contrast", model=["undefined"]), "custom_files", ), ( Calculations.Normal, LayerModels.StandardLayers, - RATapi.models.Contrast(name="Test Contrast", model=["undefined", "undefined", "undefined"]), + ratapi.models.Contrast(name="Test Contrast", model=["undefined", "undefined", "undefined"]), "layers", ), ( Calculations.Normal, LayerModels.CustomLayers, - RATapi.models.Contrast(name="Test Contrast", model=["undefined"]), + ratapi.models.Contrast(name="Test Contrast", model=["undefined"]), "custom_files", ), ( Calculations.Normal, LayerModels.CustomXY, - RATapi.models.Contrast(name="Test Contrast", model=["undefined"]), + ratapi.models.Contrast(name="Test Contrast", model=["undefined"]), "custom_files", ), ], @@ -851,7 +851,7 @@ def test_allowed_contrasts_with_ratio(field: str, model_name: str) -> None: def test_allowed_contrast_models( input_calc: Calculations, input_model: LayerModels, - test_contrast: "RATapi.models", + test_contrast: "ratapi.models", field_name: str, ) -> None: """If any value in the model field of the contrasts is set to a value not specified in the appropriate part of the @@ -866,14 +866,14 @@ def test_allowed_contrast_models( f'"{field_name}". Please add all required values to "{field_name}" before including them in "contrasts".' ), ): - RATapi.Project(calculation=input_calc, model=input_model, contrasts=RATapi.ClassList(test_contrast)) + ratapi.Project(calculation=input_calc, model=input_model, contrasts=ratapi.ClassList(test_contrast)) def test_allowed_domain_contrast_models() -> None: """If any value in the model field of the domain_contrasts is set to a value not specified in the "layers" field of the project, we should raise a ValidationError. """ - test_contrast = RATapi.models.DomainContrast(name="Test Domain Contrast", model=["undefined"]) + test_contrast = ratapi.models.DomainContrast(name="Test Domain Contrast", model=["undefined"]) with pytest.raises( pydantic.ValidationError, match=re.escape( @@ -882,12 +882,12 @@ def test_allowed_domain_contrast_models() -> None: 'including them in "domain_contrasts".' ), ): - RATapi.Project(calculation=Calculations.Domains, domain_contrasts=RATapi.ClassList(test_contrast)) + ratapi.Project(calculation=Calculations.Domains, domain_contrasts=ratapi.ClassList(test_contrast)) def test_str(default_project_str: str) -> None: """We should be able to print the "Project" model as a formatted list of the fields.""" - assert str(RATapi.Project()) == default_project_str + assert str(ratapi.Project()) == default_project_str def test_get_all_names(test_project) -> None: @@ -933,8 +933,8 @@ def test_get_all_protected_parameters(test_project) -> None: def test_check_allowed_values(test_value: str) -> None: """We should not raise an error if string values are defined and on the list of allowed values.""" allowed_values = ["Substrate Roughness"] - project = RATapi.Project.model_construct( - layers=RATapi.ClassList(RATapi.models.Layer(**dict(layer_params, roughness=test_value))) + project = ratapi.Project.model_construct( + layers=ratapi.ClassList(ratapi.models.Layer(**dict(layer_params, roughness=test_value))) ) assert project.check_allowed_values("layers", ["roughness"], allowed_values, allowed_values) is None @@ -947,8 +947,8 @@ def test_check_allowed_values(test_value: str) -> None: ) def test_check_allowed_values_not_on_list(test_value: str) -> None: """If string values are defined and are not included on the list of allowed values we should raise a ValueError.""" - project = RATapi.Project.model_construct( - layers=RATapi.ClassList(RATapi.models.Layer(**dict(layer_params, roughness=test_value))) + project = ratapi.Project.model_construct( + layers=ratapi.ClassList(ratapi.models.Layer(**dict(layer_params, roughness=test_value))) ) allowed_values = ["Substrate Roughness"] with pytest.raises( @@ -970,9 +970,9 @@ def test_check_allowed_values_not_on_list(test_value: str) -> None: ) def test_check_allowed_background_resolution_values_constant(test_value: str) -> None: """We should not raise an error if string values are defined and on the appropriate list of allowed values.""" - project = RATapi.Project.model_construct( - background_parameters=RATapi.ClassList(RATapi.models.Parameter(name="Background Param 1")), - backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Constant, source=test_value)), + project = ratapi.Project.model_construct( + background_parameters=ratapi.ClassList(ratapi.models.Parameter(name="Background Param 1")), + backgrounds=ratapi.ClassList(ratapi.models.Background(type=TypeOptions.Constant, source=test_value)), ) assert project.check_allowed_source("backgrounds") is None @@ -986,8 +986,8 @@ def test_check_allowed_background_resolution_values_constant(test_value: str) -> ) def test_check_allowed_background_resolution_values_data(test_value: str) -> None: """We should not raise an error if string values are defined and on the appropriate list of allowed values.""" - project = RATapi.Project.model_construct( - backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Data, source=test_value)) + project = ratapi.Project.model_construct( + backgrounds=ratapi.ClassList(ratapi.models.Background(type=TypeOptions.Data, source=test_value)) ) assert project.check_allowed_source("backgrounds") is None @@ -1000,8 +1000,8 @@ def test_check_allowed_background_resolution_values_not_on_constant_list(test_va """If string values are defined and are not included on the correct list of allowed values we should raise a ValueError. """ - project = RATapi.Project.model_construct( - backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Constant, source=test_value)) + project = ratapi.Project.model_construct( + backgrounds=ratapi.ClassList(ratapi.models.Background(type=TypeOptions.Constant, source=test_value)) ) with pytest.raises( ValueError, @@ -1027,8 +1027,8 @@ def test_check_allowed_background_resolution_values_on_data_list(test_value: str """If string values are defined and are not included on the correct list of allowed values we should raise a ValueError. """ - project = RATapi.Project.model_construct( - backgrounds=RATapi.ClassList(RATapi.models.Background(type=TypeOptions.Data, source=test_value)) + project = ratapi.Project.model_construct( + backgrounds=ratapi.ClassList(ratapi.models.Background(type=TypeOptions.Data, source=test_value)) ) with pytest.raises( ValueError, @@ -1051,8 +1051,8 @@ def test_check_contrast_model_allowed_values(test_values: list[str]) -> None: """We should not raise an error if values are defined in a non-empty list and all are on the list of allowed values. """ - project = RATapi.Project.model_construct( - contrasts=RATapi.ClassList(RATapi.models.Contrast(name="Test Contrast", model=test_values)), + project = ratapi.Project.model_construct( + contrasts=ratapi.ClassList(ratapi.models.Contrast(name="Test Contrast", model=test_values)), ) assert project.check_contrast_model_allowed_values("contrasts", ["Test Layer"], ["Test Layer"], "layers") is None @@ -1069,8 +1069,8 @@ def test_check_allowed_contrast_model_not_on_list(test_values: list[str]) -> Non """If string values are defined in a non-empty list and any of them are not included on the list of allowed values we should raise a ValueError. """ - project = RATapi.Project.model_construct( - contrasts=RATapi.ClassList(RATapi.models.Contrast(name="Test Contrast", model=test_values)), + project = ratapi.Project.model_construct( + contrasts=ratapi.ClassList(ratapi.models.Contrast(name="Test Contrast", model=test_values)), ) allowed_values = ["Test Layer"] missing_values = list(set(test_values) - set(allowed_values)) @@ -1097,8 +1097,8 @@ def test_check_allowed_contrast_model_removed_from_list(test_values: list[str]) """If string values are defined in a non-empty list and any of them have been removed from the list of allowed values we should raise a ValueError. """ - project = RATapi.Project.model_construct( - contrasts=RATapi.ClassList(RATapi.models.Contrast(name="Test Contrast", model=test_values)), + project = ratapi.Project.model_construct( + contrasts=ratapi.ClassList(ratapi.models.Contrast(name="Test Contrast", model=test_values)), ) previous_values = ["Test Layer", "Undefined Param 1", "Undefined Param 2"] allowed_values = ["Test Layer"] @@ -1129,7 +1129,7 @@ def test_get_contrast_model_field(input_calc: Calculations, input_model: LayerMo """Each combination of calculation and model determines the field where the values of "model" field of "contrasts" are defined. """ - project = RATapi.Project(calculation=input_calc, model=input_model) + project = ratapi.Project(calculation=input_calc, model=input_model) assert project.get_contrast_model_field() == expected_field_name @@ -1158,7 +1158,7 @@ def test_write_script(project, request, temp_dir, input_filename: str) -> None: exec(script_path.read_text(), globals(), local_dict) new_project = local_dict["problem"] - for class_list in RATapi.project.class_lists: + for class_list in ratapi.project.class_lists: assert getattr(new_project, class_list) == getattr(test_project, class_list) @@ -1205,8 +1205,8 @@ def test_wrap_set(test_project, class_list: str, model_type: str, field: str) -> pydantic.ValidationError, match=re.escape( f'1 validation error for Project\n Value error, The value "undefined" used in the "{field}" field of ' - f'{class_list}[{index}] must be defined in "{RATapi.project.values_defined_in[class_list_str]}". Please ' - f'add "undefined" to "{RATapi.project.values_defined_in[class_list_str]}" before including it in ' + f'{class_list}[{index}] must be defined in "{ratapi.project.values_defined_in[class_list_str]}". Please ' + f'add "undefined" to "{ratapi.project.values_defined_in[class_list_str]}" before including it in ' f'"{class_list}".' ), ): @@ -1236,7 +1236,7 @@ def test_wrap_del(test_project, class_list: str, parameter: str, field: str) -> orig_class_list = copy.deepcopy(test_attribute) index = test_attribute.index(parameter) - sub_attribute_name = RATapi.project.model_names_used_in[class_list][0].attribute + sub_attribute_name = ratapi.project.model_names_used_in[class_list][0].attribute sub_attribute = getattr(test_project, sub_attribute_name) sub_index = [i for i, _ in enumerate(sub_attribute) if getattr(sub_attribute[i], field) == parameter][0] @@ -1283,8 +1283,8 @@ def test_wrap_iadd(test_project, class_list: str, model_type: str, field: str, m match=re.escape( f'1 validation error for Project\n Value error, The value "undefined" used in the "{field}" ' f"field of {class_list}[{len(test_attribute)}] must be defined in " - f'"{RATapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' - f'"{RATapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' + f'"{ratapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' + f'"{ratapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' ), ): test_attribute += [input_model(**{**model_params, field: "undefined"})] @@ -1323,8 +1323,8 @@ def test_wrap_append(test_project, class_list: str, model_type: str, field: str, match=re.escape( f'1 validation error for Project\n Value error, The value "undefined" used in the "{field}" ' f"field of {class_list}[{len(test_attribute)}] must be defined in " - f'"{RATapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' - f'"{RATapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' + f'"{ratapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' + f'"{ratapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' ), ): test_attribute.append(input_model(**{**model_params, field: "undefined"})) @@ -1363,8 +1363,8 @@ def test_wrap_insert(test_project, class_list: str, model_type: str, field: str, match=re.escape( f'1 validation error for Project\n Value error, The value "undefined" used in the "{field}" ' f"field of {class_list}[{index}] must be defined in " - f'"{RATapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' - f'"{RATapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' + f'"{ratapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' + f'"{ratapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' ), ): test_attribute.insert(index, input_model(**{**model_params, field: "undefined"})) @@ -1430,7 +1430,7 @@ def test_wrap_pop(test_project, class_list: str, parameter: str, field: str) -> orig_class_list = copy.deepcopy(test_attribute) index = test_attribute.index(parameter) - sub_attribute_name = RATapi.project.model_names_used_in[class_list][0].attribute + sub_attribute_name = ratapi.project.model_names_used_in[class_list][0].attribute sub_attribute = getattr(test_project, sub_attribute_name) sub_index = [i for i, _ in enumerate(sub_attribute) if getattr(sub_attribute[i], field) == parameter][0] @@ -1467,7 +1467,7 @@ def test_wrap_remove(test_project, class_list: str, parameter: str, field: str) test_attribute = getattr(test_project, class_list) orig_class_list = copy.deepcopy(test_attribute) - sub_attribute_name = RATapi.project.model_names_used_in[class_list][0].attribute + sub_attribute_name = ratapi.project.model_names_used_in[class_list][0].attribute sub_attribute = getattr(test_project, sub_attribute_name) sub_index = [i for i, _ in enumerate(sub_attribute) if getattr(sub_attribute[i], field) == parameter][0] @@ -1504,7 +1504,7 @@ def test_wrap_clear(test_project, class_list: str, parameter: str, field: str) - test_attribute = getattr(test_project, class_list) orig_class_list = copy.deepcopy(test_attribute) - sub_attribute_name = RATapi.project.model_names_used_in[class_list][0].attribute + sub_attribute_name = ratapi.project.model_names_used_in[class_list][0].attribute sub_attribute = getattr(test_project, sub_attribute_name) sub_index = [i for i, _ in enumerate(sub_attribute) if getattr(sub_attribute[i], field) == parameter][0] @@ -1551,8 +1551,8 @@ def test_wrap_extend(test_project, class_list: str, model_type: str, field: str, match=re.escape( f'1 validation error for Project\n Value error, The value "undefined" used in the "{field}" ' f"field of {class_list}[{len(test_attribute)}] must be defined in " - f'"{RATapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' - f'"{RATapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' + f'"{ratapi.project.values_defined_in[class_list_str]}". Please add "undefined" to ' + f'"{ratapi.project.values_defined_in[class_list_str]}" before including it in "{class_list}".' ), ): test_attribute.extend([input_model(**{**model_params, field: "undefined"})]) @@ -1588,9 +1588,9 @@ def test_save_load(project, request): with warnings.catch_warnings(): warnings.simplefilter("ignore") original_project.save(path) - converted_project = RATapi.Project.load(path) + converted_project = ratapi.Project.load(path) - for field in RATapi.Project.model_fields: + for field in ratapi.Project.model_fields: assert getattr(converted_project, field) == getattr(original_project, field) @@ -1600,7 +1600,7 @@ def test_relative_paths(): with tempfile.TemporaryDirectory() as tmp: data_path = Path(tmp, "data/myfile.dat") - assert Path(RATapi.project.try_relative_to(data_path, tmp)) == Path("data/myfile.dat") + assert Path(ratapi.project.try_relative_to(data_path, tmp)) == Path("data/myfile.dat") def test_relative_paths_warning(): @@ -1615,6 +1615,6 @@ def test_relative_paths_warning(): "make sure your custom files are in a subfolder of the project save location.", ): assert ( - Path(RATapi.project.try_relative_to(data_path, relative_path)) + Path(ratapi.project.try_relative_to(data_path, relative_path)) == Path("/tmp/project/data/mydata.dat").resolve() ) diff --git a/tests/test_run.py b/tests/test_run.py index a3242d45..3c85fbcd 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -10,12 +10,12 @@ import numpy as np import pytest -import RATapi -import RATapi.outputs -import RATapi.rat_core -from RATapi.events import EventTypes, ProgressEventData, notify -from RATapi.run import ProgressBar, TextOutput -from RATapi.utils.enums import Calculations, Geometries, LayerModels, Procedures +import ratapi +import ratapi.outputs +import ratapi.rat_core +from ratapi.events import EventTypes, ProgressEventData, notify +from ratapi.run import ProgressBar, TextOutput +from ratapi.utils.enums import Calculations, Geometries, LayerModels, Procedures from tests.utils import check_results_equal @@ -24,7 +24,7 @@ def reflectivity_calculation_problem(): """The output C++ ProblemDefinition object for a reflectivity calculation of the project set out in "DSPC_standard_layers.py". """ - problem = RATapi.rat_core.ProblemDefinition() + problem = ratapi.rat_core.ProblemDefinition() problem.TF = Calculations.Normal problem.modelType = LayerModels.StandardLayers problem.geometry = Geometries.SubstrateLiquid @@ -185,7 +185,7 @@ def dream_problem(): This optimisation used the parameters: nSamples=50000, nChains=10. """ - problem = RATapi.rat_core.ProblemDefinition() + problem = ratapi.rat_core.ProblemDefinition() problem.TF = Calculations.Normal problem.modelType = LayerModels.StandardLayers problem.geometry = Geometries.SubstrateLiquid @@ -362,12 +362,12 @@ def test_run(test_procedure, test_output_problem, test_output_results, test_baye test_results = request.getfixturevalue(test_results) with mock.patch.object( - RATapi.rat_core, + ratapi.rat_core, "RATMain", mock.MagicMock(return_value=(test_output_problem, test_output_results, test_bayes)), ): # Use default project as we patch RATMain to give the desired outputs - project, results = RATapi.run(input_project, RATapi.Controls(procedure=test_procedure)) + project, results = ratapi.run(input_project, ratapi.Controls(procedure=test_procedure)) check_results_equal(test_results, results) diff --git a/tests/test_wrappers.py b/tests/test_wrappers.py index 2ced5ad0..680b198b 100644 --- a/tests/test_wrappers.py +++ b/tests/test_wrappers.py @@ -3,21 +3,21 @@ import pytest -import RATapi.wrappers +import ratapi.wrappers def test_matlab_wrapper() -> None: with ( - mock.patch.object(RATapi.wrappers.MatlabWrapper, "loader", None), + mock.patch.object(ratapi.wrappers.MatlabWrapper, "loader", None), pytest.raises(ImportError), ): - RATapi.wrappers.MatlabWrapper("demo.m") + ratapi.wrappers.MatlabWrapper("demo.m") mocked_matlab_future = mock.MagicMock() mocked_engine = mock.MagicMock() mocked_matlab_future.result.return_value = mocked_engine - with mock.patch.object(RATapi.wrappers.MatlabWrapper, "loader", mocked_matlab_future): - wrapper = RATapi.wrappers.MatlabWrapper("demo.m") + with mock.patch.object(ratapi.wrappers.MatlabWrapper, "loader", mocked_matlab_future): + wrapper = ratapi.wrappers.MatlabWrapper("demo.m") assert wrapper.function_name == "demo" mocked_engine.cd.assert_called_once() assert pathlib.Path(mocked_engine.cd.call_args[0][0]).samefile(".") @@ -45,8 +45,8 @@ def test_matlab_wrapper() -> None: def test_dylib_wrapper() -> None: mocked_engine = mock.MagicMock() - with mock.patch("RATapi.wrappers.RATapi.rat_core.DylibEngine", mocked_engine): - wrapper = RATapi.wrappers.DylibWrapper("demo.dylib", "demo") + with mock.patch("ratapi.wrappers.ratapi.rat_core.DylibEngine", mocked_engine): + wrapper = ratapi.wrappers.DylibWrapper("demo.dylib", "demo") mocked_engine.assert_called_once_with("demo.dylib", "demo") wrapper.engine.invoke.return_value = ([2], 5) diff --git a/tests/utils.py b/tests/utils.py index d293d7b1..91b5b9ae 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,6 +1,6 @@ import numpy as np -import RATapi.outputs +import ratapi.outputs class InputAttributes: @@ -39,19 +39,19 @@ def check_results_equal(actual_results, expected_results) -> None: ] assert ( - isinstance(actual_results, RATapi.outputs.Results) and isinstance(expected_results, RATapi.outputs.Results) + isinstance(actual_results, ratapi.outputs.Results) and isinstance(expected_results, ratapi.outputs.Results) ) or ( - isinstance(actual_results, RATapi.outputs.BayesResults) - and isinstance(expected_results, RATapi.outputs.BayesResults) + isinstance(actual_results, ratapi.outputs.BayesResults) + and isinstance(expected_results, ratapi.outputs.BayesResults) ) # The first set of fields are either 1D or 2D python lists containing numpy arrays. # Hence, we need to compare them element-wise. - for list_field in RATapi.outputs.results_fields["list_fields"]: + for list_field in ratapi.outputs.results_fields["list_fields"]: for a, b in zip(getattr(actual_results, list_field), getattr(expected_results, list_field)): assert (a == b).all() - for list_field in RATapi.outputs.results_fields["double_list_fields"]: + for list_field in ratapi.outputs.results_fields["double_list_fields"]: actual_list = getattr(actual_results, list_field) expected_list = getattr(expected_results, list_field) assert len(actual_list) == len(expected_list) @@ -70,8 +70,8 @@ def check_results_equal(actual_results, expected_results) -> None: for field in contrast_param_fields: assert (getattr(actual_results.contrastParams, field) == getattr(expected_results.contrastParams, field)).all() - if isinstance(actual_results, RATapi.outputs.BayesResults) and isinstance( - expected_results, RATapi.outputs.BayesResults + if isinstance(actual_results, ratapi.outputs.BayesResults) and isinstance( + expected_results, ratapi.outputs.BayesResults ): check_bayes_fields_equal(actual_results, expected_results) @@ -82,18 +82,18 @@ def check_bayes_fields_equal(actual_results, expected_results) -> None: We focus here on the fields and subclasses specific to the Bayesian optimisation. """ # The BayesResults object consists of a number of subclasses, each containing fields of differing formats. - for subclass in RATapi.outputs.bayes_results_subclasses: + for subclass in ratapi.outputs.bayes_results_subclasses: actual_subclass = getattr(actual_results, subclass) expected_subclass = getattr(expected_results, subclass) - for field in RATapi.outputs.bayes_results_fields["param_fields"][subclass]: + for field in ratapi.outputs.bayes_results_fields["param_fields"][subclass]: assert getattr(actual_subclass, field) == getattr(expected_subclass, field) - for field in RATapi.outputs.bayes_results_fields["list_fields"][subclass]: + for field in ratapi.outputs.bayes_results_fields["list_fields"][subclass]: for a, b in zip(getattr(actual_subclass, field), getattr(expected_subclass, field)): assert (a == b).all() - for field in RATapi.outputs.bayes_results_fields["double_list_fields"][subclass]: + for field in ratapi.outputs.bayes_results_fields["double_list_fields"][subclass]: actual_list = getattr(actual_subclass, field) expected_list = getattr(expected_subclass, field) assert len(actual_list) == len(expected_list) @@ -102,7 +102,7 @@ def check_bayes_fields_equal(actual_results, expected_results) -> None: assert (a == b).all() # Need to account for the arrays that are initialised as "NaN" in the compiled code - for array in RATapi.outputs.bayes_results_fields["array_fields"][subclass]: + for array in ratapi.outputs.bayes_results_fields["array_fields"][subclass]: actual_array = getattr(actual_subclass, array) expected_array = getattr(expected_subclass, array) for i in range(len(actual_array)):