Skip to content

Commit d295afe

Browse files
authored
Updates submodule (#146)
* Renames "BayesResults" as "OutputBayesResult" in "rat_core" * Updates submodule * Fixes matlab import error * Refactors matlab save in "project_to_r1"
1 parent b92118a commit d295afe

File tree

13 files changed

+72
-74
lines changed

13 files changed

+72
-74
lines changed

RATapi/examples/convert_rascal_project/convert_rascal.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def convert_rascal(mat_filename="lipid_bilayer.mat"):
2626
2727
"""
2828
project_path = pathlib.Path(__file__).parent / "R1monolayerVolumeModel.mat"
29-
project = RAT.utils.convert.r1_to_project_class(project_path)
29+
project = RAT.utils.convert.r1_to_project(project_path)
3030

3131
# change values if you like, including ones not supported by R1
3232
project.parameters["Head Thickness"].prior_type = "gaussian"
@@ -35,10 +35,10 @@ def convert_rascal(mat_filename="lipid_bilayer.mat"):
3535

3636
# convert DSPC standard layers example to a struct and save as file
3737
lipid_bilayer_project = RAT.examples.DSPC_standard_layers()[0]
38-
RAT.utils.convert.project_class_to_r1(lipid_bilayer_project, filename=mat_filename)
38+
RAT.utils.convert.project_to_r1(lipid_bilayer_project, filename=mat_filename)
3939

4040
# convert and return as a Python dictionary
41-
struct = RAT.utils.convert.project_class_to_r1(lipid_bilayer_project, return_struct=True)
41+
struct = RAT.utils.convert.project_to_r1(lipid_bilayer_project, return_struct=True)
4242

4343
return project, struct
4444

RATapi/inputs.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ def make_problem(project: RATapi.Project) -> ProblemDefinition:
284284
problem.numberOfContrasts = len(project.contrasts)
285285
problem.geometry = project.geometry
286286
problem.useImaginary = project.absorption
287-
problem.repeatLayers = [[0, 1]] * len(project.contrasts) # This is marked as "to do" in RAT
287+
problem.repeatLayers = [1] * len(project.contrasts)
288288
problem.contrastBackgroundParams = contrast_background_params
289289
problem.contrastBackgroundTypes = contrast_background_types
290290
problem.contrastBackgroundActions = [contrast.background_action for contrast in project.contrasts]

RATapi/outputs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ class BayesResults(Results):
409409
def make_results(
410410
procedure: Procedures,
411411
output_results: RATapi.rat_core.OutputResult,
412-
bayes_results: Optional[RATapi.rat_core.BayesResults] = None,
412+
bayes_results: Optional[RATapi.rat_core.OutputBayesResult] = None,
413413
) -> Union[Results, BayesResults]:
414414
"""Initialise a python Results or BayesResults object using the outputs from a RAT calculation.
415415
@@ -419,7 +419,7 @@ def make_results(
419419
The procedure used by the calculation.
420420
output_results : RATapi.rat_core.OutputResult
421421
The C++ output results from the calculation.
422-
bayes_results : Optional[RATapi.rat_core.BayesResults]
422+
bayes_results : Optional[RATapi.rat_core.OutputBayesResult]
423423
The optional extra C++ Bayesian output results from a Bayesian calculation.
424424
425425
Returns

RATapi/utils/convert.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from RATapi.utils.enums import Geometries, Languages, LayerModels
1616

1717

18-
def r1_to_project_class(filename: Union[str, PathLike]) -> Project:
18+
def r1_to_project(filename: Union[str, PathLike]) -> Project:
1919
"""Read a RasCAL1 project struct as a Python `Project`.
2020
2121
Parameters
@@ -318,7 +318,7 @@ def fix_invalid_constraints(name: str, constrs: tuple[float, float], value: floa
318318
return project
319319

320320

321-
def project_class_to_r1(
321+
def project_to_r1(
322322
project: Project, filename: Union[str, PathLike] = "RAT_project", return_struct: bool = False
323323
) -> Union[dict, None]:
324324
"""Convert a RAT Project to a RasCAL1 project struct.
@@ -549,10 +549,10 @@ def convert_parameters(
549549
# scipy.io.savemat doesn't do cells properly:
550550
# https://github.com/scipy/scipy/issues/3756
551551
# rather than fiddling we just use matlab
552-
eng = wrappers.start_matlab().result()
553-
if eng is None:
552+
loader = wrappers.MatlabWrapper.loader
553+
if loader is None:
554554
raise ImportError("matlabengine is not installed.")
555+
eng = loader.result()
555556
eng.workspace["problem"] = r1
556557
eng.save(str(filename), "problem", nargout=0)
557-
eng.exit()
558558
return None

RATapi/utils/plotting.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import RATapi
1818
import RATapi.inputs
1919
import RATapi.outputs
20-
from RATapi.rat_core import PlotEventData, makeSLDProfileXY
20+
from RATapi.rat_core import PlotEventData, makeSLDProfile
2121

2222

2323
def plot_errorbars(ax: Axes, x: np.ndarray, y: np.ndarray, err: np.ndarray, one_sided: bool, color: str):
@@ -154,11 +154,11 @@ def plot_ref_sld_helper(
154154
layer = data.resampledLayers[i][j]
155155
if layers.shape[1] == 4:
156156
layer = np.delete(layer, 2, 1)
157-
new_profile = makeSLDProfileXY(
157+
new_profile = makeSLDProfile(
158158
layers[0, 1], # Bulk In
159159
layers[-1, 1], # Bulk Out
160-
data.subRoughs[i], # roughness
161160
layer,
161+
data.subRoughs[i], # roughness
162162
1,
163163
)
164164

cpp/includes/defines.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,12 +262,12 @@ struct DreamOutput
262262
py::array_t<real_T> CR;
263263
};
264264

265-
const std::string docsBayesResults = R"(The Python binding for the C++ bayesResults struct.
265+
const std::string docsOutputBayesResult = R"(The Python binding for the C++ bayesResults struct.
266266
The results of a Bayesian RAT calculation.
267267
268268
Parameters
269269
----------
270-
predictionIntervals : RATapi.rat_core.orePredictionIntervals
270+
predictionIntervals : RATapi.rat_core.PredictionIntervals
271271
The prediction intervals.
272272
confidenceIntervals : RATapi.rat_core.ConfidenceIntervals
273273
The 65% and 95% confidence intervals for the best fit results.
@@ -282,7 +282,7 @@ chain : np.ndarray
282282
The ``i``'th column of the array contains the chain for parameter ``fitNames[i]``.
283283
)";
284284

285-
struct BayesResults
285+
struct OutputBayesResult
286286
{
287287
PredictionIntervals predictionIntervals;
288288
ConfidenceIntervals confidenceIntervals;

cpp/rat.cpp

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ setup_pybind11(cfg)
1616
#include "RAT/RATMain_initialize.h"
1717
#include "RAT/RATMain_terminate.h"
1818
#include "RAT/RATMain_types.h"
19-
#include "RAT/makeSLDProfileXY.h"
19+
#include "RAT/makeSLDProfile.h"
2020
#include "RAT/dylib.hpp"
2121
#include "RAT/events/eventManager.h"
2222
#include "includes/defines.h"
@@ -263,7 +263,7 @@ RAT::b_ProblemDefinition createProblemDefinitionStruct(const ProblemDefinition&
263263
problem_struct.numberOfContrasts = problem.numberOfContrasts;
264264
stringToRatBoundedArray(problem.geometry, problem_struct.geometry.data, problem_struct.geometry.size);
265265
problem_struct.useImaginary = problem.useImaginary;
266-
problem_struct.repeatLayers = customCaller("Problem.repeatLayers", pyListToRatCellWrap2, problem.repeatLayers);
266+
problem_struct.repeatLayers = customCaller("Problem.repeatLayers", pyArrayToRatRowArray1d, problem.repeatLayers);
267267
problem_struct.contrastBackgroundParams = customCaller("Problem.contrastBackgroundParams", pyListToRatCellWrap3, problem.contrastBackgroundParams);
268268
problem_struct.contrastBackgroundTypes = customCaller("Problem.contrastBackgroundTypes", pyListToRatCellWrap02d, problem.contrastBackgroundTypes);
269269
problem_struct.contrastBackgroundActions = customCaller("Problem.contrastBackgroundActions", pyListToRatCellWrap02d, problem.contrastBackgroundActions);
@@ -460,7 +460,7 @@ ProblemDefinition problemDefinitionFromStruct(const RAT::b_ProblemDefinition pro
460460
problem_def.numberOfContrasts = problem.numberOfContrasts;
461461
stringFromRatBoundedArray(problem.geometry.data, problem.geometry.size, problem_def.geometry);
462462
problem_def.useImaginary = problem.useImaginary;
463-
problem_def.repeatLayers = pyListFromRatCellWrap2(problem.repeatLayers);
463+
problem_def.repeatLayers = pyArrayFromRatArray1d<coder::array<real_T, 2U>>(problem.repeatLayers);
464464
problem_def.contrastBackgroundParams = pyListFromBoundedCellWrap<coder::array<RAT::cell_wrap_3, 2U>>(problem.contrastBackgroundParams);
465465
problem_def.contrastBackgroundTypes = pyListFromRatCellWrap02d(problem.contrastBackgroundTypes);
466466
problem_def.contrastBackgroundActions = pyListFromRatCellWrap02d(problem.contrastBackgroundActions);
@@ -510,9 +510,9 @@ ProblemDefinition problemDefinitionFromStruct(const RAT::b_ProblemDefinition pro
510510
return problem_def;
511511
}
512512

513-
BayesResults bayesResultsFromStruct(const RAT::BayesResults results)
513+
OutputBayesResult OutputBayesResultsFromStruct(const RAT::BayesResults results)
514514
{
515-
BayesResults bayesResults;
515+
OutputBayesResult bayesResults;
516516

517517
bayesResults.chain = pyArrayFromRatArray2d(results.chain);
518518

@@ -575,7 +575,7 @@ out_problem_def : Rat.rat_core.ProblemDefinition
575575
The project input with the updated fit values.
576576
results : Rat.rat_core.OutputResult
577577
The results from a RAT calculation.
578-
bayes_result : Rat.rat_core.BayesResults
578+
bayes_result : Rat.rat_core.OutputBayesResult
579579
The extra results if RAT calculation is Bayesian.
580580
)";
581581

@@ -593,21 +593,21 @@ py::tuple RATMain(const ProblemDefinition& problem_def, const Control& control)
593593
out_problem_def.customFiles = problem_def.customFiles.attr("copy")();
594594
return py::make_tuple(out_problem_def,
595595
OutputResultFromStruct(results),
596-
bayesResultsFromStruct(bayesResults));
596+
OutputBayesResultsFromStruct(bayesResults));
597597
}
598598

599-
const std::string docsMakeSLDProfileXY = R"(Creates the profiles for the SLD plots
599+
const std::string docsMakeSLDProfile = R"(Creates the profiles for the SLD plots
600600
601601
Parameters
602602
----------
603603
bulk_in : float
604604
Bulk in value for contrast.
605605
bulk_out : float
606606
Bulk out value for contrast.
607-
ssub : float
608-
Substrate roughness.
609607
layers : np.ndarray[np.float]
610608
Array of parameters for each layer in the contrast.
609+
ssub : float
610+
Substrate roughness.
611611
number_of_repeats : int, default: 1
612612
Number of times the layers are repeated.
613613
@@ -617,22 +617,20 @@ sld_profile : np.ndarray[np.float]
617617
Computed SLD profile
618618
)";
619619

620-
py::array_t<real_T> makeSLDProfileXY(real_T bulk_in,
621-
real_T bulk_out,
622-
real_T ssub,
623-
const py::array_t<real_T> &layers,
624-
int number_of_repeats=DEFAULT_NREPEATS)
620+
py::array_t<real_T> makeSLDProfile(real_T bulk_in,
621+
real_T bulk_out,
622+
const py::array_t<real_T> &layers,
623+
real_T ssub,
624+
int number_of_repeats=DEFAULT_NREPEATS)
625625
{
626626
coder::array<real_T, 2U> out;
627627
coder::array<real_T, 2U> layers_array = pyArrayToRatArray2d(layers);
628-
py::buffer_info buffer_info = layers.request();
629-
RAT::makeSLDProfileXY(bulk_in,
630-
bulk_out,
631-
ssub,
632-
layers_array,
633-
buffer_info.shape[0],
634-
number_of_repeats,
635-
out);
628+
RAT::makeSLDProfile(bulk_in,
629+
bulk_out,
630+
layers_array,
631+
ssub,
632+
number_of_repeats,
633+
out);
636634

637635
return pyArrayFromRatArray2d(out);
638636

@@ -787,14 +785,14 @@ PYBIND11_MODULE(rat_core, m) {
787785
.def_readwrite("R_stat", &DreamOutput::R_stat)
788786
.def_readwrite("CR", &DreamOutput::CR);
789787

790-
py::class_<BayesResults>(m, "BayesResults", docsBayesResults.c_str())
788+
py::class_<OutputBayesResult>(m, "OutputBayesResult", docsOutputBayesResult.c_str())
791789
.def(py::init<>())
792-
.def_readwrite("predictionIntervals", &BayesResults::predictionIntervals)
793-
.def_readwrite("confidenceIntervals", &BayesResults::confidenceIntervals)
794-
.def_readwrite("dreamParams", &BayesResults::dreamParams)
795-
.def_readwrite("dreamOutput", &BayesResults::dreamOutput)
796-
.def_readwrite("nestedSamplerOutput", &BayesResults::nestedSamplerOutput)
797-
.def_readwrite("chain", &BayesResults::chain);
790+
.def_readwrite("predictionIntervals", &OutputBayesResult::predictionIntervals)
791+
.def_readwrite("confidenceIntervals", &OutputBayesResult::confidenceIntervals)
792+
.def_readwrite("dreamParams", &OutputBayesResult::dreamParams)
793+
.def_readwrite("dreamOutput", &OutputBayesResult::dreamOutput)
794+
.def_readwrite("nestedSamplerOutput", &OutputBayesResult::nestedSamplerOutput)
795+
.def_readwrite("chain", &OutputBayesResult::chain);
798796

799797
py::class_<Calculation>(m, "Calculation", docsCalculation.c_str())
800798
.def(py::init<>())
@@ -1047,7 +1045,7 @@ PYBIND11_MODULE(rat_core, m) {
10471045
p.numberOfContrasts = t[6].cast<real_T>();
10481046
p.geometry = t[7].cast<std::string>();
10491047
p.useImaginary = t[8].cast<bool>();
1050-
p.repeatLayers = t[9].cast<py::list>();
1048+
p.repeatLayers = t[9].cast<py::array_t<real_T>>();
10511049
p.contrastBackgroundParams = t[10].cast<py::list>();
10521050
p.contrastBackgroundTypes = t[11].cast<py::list>();
10531051
p.contrastBackgroundActions = t[12].cast<py::list>();
@@ -1099,6 +1097,6 @@ PYBIND11_MODULE(rat_core, m) {
10991097

11001098
m.def("RATMain", &RATMain, docsRATMain.c_str(), py::arg("problem_def"), py::arg("control"));
11011099

1102-
m.def("makeSLDProfileXY", &makeSLDProfileXY, docsMakeSLDProfileXY.c_str(),
1103-
py::arg("bulk_in"), py::arg("bulk_out"), py::arg("ssub"), py::arg("layers"), py::arg("number_of_repeats") = DEFAULT_NREPEATS);
1100+
m.def("makeSLDProfile", &makeSLDProfile, docsMakeSLDProfile.c_str(),
1101+
py::arg("bulk_in"), py::arg("bulk_out"), py::arg("layers"), py::arg("ssub"), py::arg("number_of_repeats") = DEFAULT_NREPEATS);
11041102
}

tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2253,7 +2253,7 @@ def dream_bayes():
22532253
22542254
This optimisation used the parameters: nSamples=1, nChains=1.
22552255
"""
2256-
bayes = RATapi.rat_core.BayesResults()
2256+
bayes = RATapi.rat_core.OutputBayesResult()
22572257
bayes.predictionIntervals = RATapi.rat_core.PredictionIntervals()
22582258
bayes.predictionIntervals.reflectivity = [
22592259
np.array(

tests/test_convert.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest
99

1010
import RATapi
11-
from RATapi.utils.convert import project_class_to_r1, r1_to_project_class
11+
from RATapi.utils.convert import project_to_r1, r1_to_project
1212

1313
TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data")
1414

@@ -58,9 +58,9 @@ def dspc_bilayer():
5858
],
5959
)
6060
@pytest.mark.parametrize("path_type", [os.path.join, pathlib.Path])
61-
def test_r1_to_project_class(file, project, path_type, request):
61+
def test_r1_to_project(file, project, path_type, request):
6262
"""Test that R1 to Project class conversion returns the expected Project."""
63-
output_project = r1_to_project_class(path_type(TEST_DIR_PATH, file))
63+
output_project = r1_to_project(path_type(TEST_DIR_PATH, file))
6464
expected_project = request.getfixturevalue(project)
6565

6666
# assert statements have to be more careful due to R1 missing features
@@ -83,7 +83,7 @@ def test_r1_to_project_class(file, project, path_type, request):
8383
def test_r1_involution(project, request, monkeypatch):
8484
"""Test that converting a Project to an R1 struct and back returns the same project."""
8585
original_project = request.getfixturevalue(project)
86-
r1_struct = project_class_to_r1(original_project, return_struct=True)
86+
r1_struct = project_to_r1(original_project, return_struct=True)
8787

8888
# rather than writing the struct to a file and reading the file, just directly
8989
# hand the struct over
@@ -93,7 +93,7 @@ def mock_load(ignored_filename, **ignored_settings):
9393

9494
monkeypatch.setattr("RATapi.utils.convert.loadmat", mock_load, raising=True)
9595

96-
converted_project = r1_to_project_class(project)
96+
converted_project = r1_to_project(project)
9797

9898
for class_list in RATapi.project.class_lists:
9999
assert getattr(converted_project, class_list) == getattr(original_project, class_list)
@@ -105,7 +105,7 @@ def test_invalid_constraints():
105105
match=r"The parameter (.+) has invalid constraints,"
106106
" these have been adjusted to satisfy the current value of the parameter."
107107
):
108-
output_project = r1_to_project_class(pathlib.Path(TEST_DIR_PATH, "R1DoubleBilayerVolumeModel.mat"))
108+
output_project = r1_to_project(pathlib.Path(TEST_DIR_PATH, "R1DoubleBilayerVolumeModel.mat"))
109109

110110
assert output_project.background_parameters[0].min == output_project.background_parameters[0].value
111111

@@ -117,7 +117,7 @@ def test_matlab_save(path_type, request):
117117
project = request.getfixturevalue("r1_default_project")
118118
with tempfile.TemporaryDirectory() as temp:
119119
matfile = path_type(temp, "testfile.mat")
120-
project_class_to_r1(project, filename=matfile)
121-
converted_project = r1_to_project_class(matfile)
120+
project_to_r1(project, filename=matfile)
121+
converted_project = r1_to_project(matfile)
122122

123123
assert project == converted_project

0 commit comments

Comments
 (0)