RATapi 0.0.0.dev16__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ratapi/__init__.py +42 -0
- ratapi/classlist.py +620 -0
- ratapi/controls.py +258 -0
- ratapi/eventManager.dll +0 -0
- ratapi/events.py +88 -0
- ratapi/examples/__init__.py +25 -0
- ratapi/examples/absorption/__init__.py +1 -0
- ratapi/examples/absorption/absorption.py +172 -0
- ratapi/examples/absorption/volume_thiol_bilayer.py +144 -0
- ratapi/examples/convert_rascal_project/Model_IIb.py +90 -0
- ratapi/examples/convert_rascal_project/__init__.py +1 -0
- ratapi/examples/convert_rascal_project/convert_rascal.py +49 -0
- ratapi/examples/data/D2O_spin_down.dat +100 -0
- ratapi/examples/data/D2O_spin_up.dat +101 -0
- ratapi/examples/data/DSPC_D2O.dat +82 -0
- ratapi/examples/data/DSPC_SMW.dat +82 -0
- ratapi/examples/data/H2O_spin_down.dat +102 -0
- ratapi/examples/data/H2O_spin_up.dat +102 -0
- ratapi/examples/data/__init__.py +1 -0
- ratapi/examples/data/c_PLP0016596.dat +146 -0
- ratapi/examples/data/c_PLP0016601.dat +97 -0
- ratapi/examples/data/c_PLP0016607.dat +104 -0
- ratapi/examples/data/d2o_background_data.dat +82 -0
- ratapi/examples/domains/__init__.py +1 -0
- ratapi/examples/domains/alloy_domains.py +34 -0
- ratapi/examples/domains/domains_XY_model.py +75 -0
- ratapi/examples/domains/domains_custom_XY.py +86 -0
- ratapi/examples/domains/domains_custom_layers.py +60 -0
- ratapi/examples/domains/domains_standard_layers.py +92 -0
- ratapi/examples/languages/__init__.py +1 -0
- ratapi/examples/languages/custom_bilayer.py +72 -0
- ratapi/examples/languages/run_custom_file_languages.py +41 -0
- ratapi/examples/languages/setup_problem.py +130 -0
- ratapi/examples/normal_reflectivity/DSPC_custom_XY.py +149 -0
- ratapi/examples/normal_reflectivity/DSPC_custom_layers.py +130 -0
- ratapi/examples/normal_reflectivity/DSPC_data_background.py +220 -0
- ratapi/examples/normal_reflectivity/DSPC_function_background.py +219 -0
- ratapi/examples/normal_reflectivity/DSPC_standard_layers.py +210 -0
- ratapi/examples/normal_reflectivity/__init__.py +1 -0
- ratapi/examples/normal_reflectivity/background_function.py +16 -0
- ratapi/examples/normal_reflectivity/custom_XY_DSPC.py +141 -0
- ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py +89 -0
- ratapi/inputs.py +603 -0
- ratapi/models.py +717 -0
- ratapi/outputs.py +821 -0
- ratapi/project.py +1091 -0
- ratapi/rat_core.cp315-win_amd64.pyd +0 -0
- ratapi/run.py +142 -0
- ratapi/utils/__init__.py +1 -0
- ratapi/utils/convert.py +597 -0
- ratapi/utils/custom_errors.py +40 -0
- ratapi/utils/enums.py +203 -0
- ratapi/utils/matlab.py +254 -0
- ratapi/utils/orso.py +247 -0
- ratapi/utils/plotting.py +1316 -0
- ratapi/wrappers.py +147 -0
- ratapi-0.0.0.dev16.dist-info/DELVEWHEEL +2 -0
- ratapi-0.0.0.dev16.dist-info/METADATA +61 -0
- ratapi-0.0.0.dev16.dist-info/RECORD +63 -0
- ratapi-0.0.0.dev16.dist-info/WHEEL +5 -0
- ratapi-0.0.0.dev16.dist-info/top_level.txt +1 -0
- ratapi.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll +0 -0
- ratapi.libs/vcomp140-f96f3a14d88d8846f31f3ab38a490304.dll +0 -0
ratapi/utils/enums.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""The Enum values used in the parameters of various ratapi classes and functions."""
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
except ImportError:
|
|
6
|
+
from strenum import StrEnum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class RATEnum(StrEnum):
|
|
10
|
+
"""A subclass of StrEnum with some adjustments for variable spellings."""
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
def _missing_(cls, value: str):
|
|
14
|
+
value = value.lower()
|
|
15
|
+
|
|
16
|
+
# Replace common alternative spellings
|
|
17
|
+
value = value.replace("-", " ").replace("_", " ").replace("++", "pp").replace("polarized", "polarised")
|
|
18
|
+
|
|
19
|
+
for member in cls:
|
|
20
|
+
if member.value.lower() == value:
|
|
21
|
+
return member
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Controls
|
|
26
|
+
class Procedures(RATEnum):
|
|
27
|
+
"""The available options for procedures."""
|
|
28
|
+
|
|
29
|
+
Calculate = "calculate"
|
|
30
|
+
"""Run an Abelès reflectivity calculation and calculate chi-squared to the data."""
|
|
31
|
+
|
|
32
|
+
Simplex = "simplex"
|
|
33
|
+
"""Run a Nelder-Mead simplex optimisation over the fit parameters."""
|
|
34
|
+
|
|
35
|
+
DE = "de"
|
|
36
|
+
"""Run a Differential Evolution optimisation over the fit parameters."""
|
|
37
|
+
|
|
38
|
+
NS = "ns"
|
|
39
|
+
"""Run Bayesian Nested Sampling over the fit parameters."""
|
|
40
|
+
|
|
41
|
+
DREAM = "dream"
|
|
42
|
+
"""Run the Bayesian DREAM algorithm over the fit parameters."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Parallel(RATEnum):
|
|
46
|
+
"""The available options for parallelisation."""
|
|
47
|
+
|
|
48
|
+
Single = "single"
|
|
49
|
+
"""Do not parallelise."""
|
|
50
|
+
|
|
51
|
+
Points = "points"
|
|
52
|
+
"""Split all contrasts into groups of points, and assign a process to each group."""
|
|
53
|
+
|
|
54
|
+
Contrasts = "contrasts"
|
|
55
|
+
"""Assign one process to each contrast."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Display(RATEnum):
|
|
59
|
+
"""The available options for terminal output."""
|
|
60
|
+
|
|
61
|
+
Off = "off"
|
|
62
|
+
Iter = "iter"
|
|
63
|
+
Final = "final"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Strategies(RATEnum):
|
|
67
|
+
"""The available strategies for generating base vectors in differential evolution."""
|
|
68
|
+
|
|
69
|
+
Random = "random"
|
|
70
|
+
"""The base vector is random."""
|
|
71
|
+
|
|
72
|
+
LocalToBest = "local to best"
|
|
73
|
+
"""The base vector is a combination of one randomly-selected local solution
|
|
74
|
+
and the best solution of the previous iteration."""
|
|
75
|
+
|
|
76
|
+
BestWithJitter = "best jitter"
|
|
77
|
+
"""The base vector is the best solution of the previous iteration, with a small random perturbation applied."""
|
|
78
|
+
|
|
79
|
+
RandomWithPerVectorDither = "vector dither"
|
|
80
|
+
"""The base vector is random, with a random scaling factor applied to each mutant.
|
|
81
|
+
This scaling factor is different for each mutant."""
|
|
82
|
+
|
|
83
|
+
RandomWithPerGenerationDither = "generation dither"
|
|
84
|
+
"""The base vector is random, with a random scaling factor applied to each mutant.
|
|
85
|
+
This scaling factor is the same for every mutant, and randomised every generation."""
|
|
86
|
+
|
|
87
|
+
RandomEitherOrAlgorithm = "either or"
|
|
88
|
+
"""The base vector is randomly chosen from either a pure random mutation,
|
|
89
|
+
or a pure recombination of parent parameter values."""
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def _missing_(cls, value: int | str):
|
|
93
|
+
# legacy compatibility with strategies being 1-indexed ints under the hood
|
|
94
|
+
if isinstance(value, int):
|
|
95
|
+
if value < 1 or value > 6:
|
|
96
|
+
raise IndexError("Strategy indices must be between 1 and 6.")
|
|
97
|
+
return list(cls)[value - 1]
|
|
98
|
+
return super()._missing_(value)
|
|
99
|
+
|
|
100
|
+
def __int__(self):
|
|
101
|
+
"""Convert the DE strategy to its hardcoded index in the internal code.
|
|
102
|
+
|
|
103
|
+
RAT core expects strategy to be an integer, as this is how it is given to
|
|
104
|
+
the internal DE algorithm.
|
|
105
|
+
"""
|
|
106
|
+
return list(Strategies).index(self) + 1
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class BoundHandling(RATEnum):
|
|
110
|
+
"""The available options for bound handling in DREAM."""
|
|
111
|
+
|
|
112
|
+
Off = "off"
|
|
113
|
+
"""Allow points to be sampled out of the parameter bounds."""
|
|
114
|
+
|
|
115
|
+
Reflect = "reflect"
|
|
116
|
+
"""If a step passes a boundary, reflect it back across the boundary."""
|
|
117
|
+
|
|
118
|
+
Bound = "bound"
|
|
119
|
+
"""If a step passes a boundary, set it equal to the nearest point on the boundary."""
|
|
120
|
+
|
|
121
|
+
Fold = "fold"
|
|
122
|
+
"""Treat the boundary as periodic and ‘wrap the step around’ to the other side of the space."""
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# Models
|
|
126
|
+
class TypeOptions(RATEnum):
|
|
127
|
+
"""The types of signal (``Background`` and ``Resolution``)."""
|
|
128
|
+
|
|
129
|
+
Constant = "constant"
|
|
130
|
+
"""A uniform constant signal given by a parameter."""
|
|
131
|
+
|
|
132
|
+
Data = "data"
|
|
133
|
+
"""A signal for each q-value given by a dataset."""
|
|
134
|
+
|
|
135
|
+
Function = "function"
|
|
136
|
+
"""A signal defined by a custom function."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class BackgroundActions(RATEnum):
|
|
140
|
+
"""Ways that the background can be applied to the model."""
|
|
141
|
+
|
|
142
|
+
Add = "add"
|
|
143
|
+
Subtract = "subtract"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class Languages(RATEnum):
|
|
147
|
+
"""Language options for custom files."""
|
|
148
|
+
|
|
149
|
+
Cpp = "cpp"
|
|
150
|
+
Python = "python"
|
|
151
|
+
Matlab = "matlab"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class Hydration(RATEnum):
|
|
155
|
+
"""Options for the 'hydrate with' parameter of a Layer."""
|
|
156
|
+
|
|
157
|
+
BulkIn = "bulk in"
|
|
158
|
+
BulkOut = "bulk out"
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class Priors(RATEnum):
|
|
162
|
+
"""Prior distributions for parameters."""
|
|
163
|
+
|
|
164
|
+
Uniform = "uniform"
|
|
165
|
+
"""A uniform distribution over the parameter range."""
|
|
166
|
+
|
|
167
|
+
Gaussian = "gaussian"
|
|
168
|
+
"""A Gaussian distribution centred on the parameter value,
|
|
169
|
+
with shape defined by ``mu`` and ``sigma`` for the parameter."""
|
|
170
|
+
|
|
171
|
+
Jeffreys = "jeffreys"
|
|
172
|
+
"""A Jeffreys' prior distribution over the parameter range."""
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# Project
|
|
176
|
+
class Calculations(RATEnum):
|
|
177
|
+
"""Types of calculations that can be performed by RAT."""
|
|
178
|
+
|
|
179
|
+
Normal = "normal"
|
|
180
|
+
Domains = "domains"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class LayerModels(RATEnum):
|
|
184
|
+
"""Types of layer model supported by RAT."""
|
|
185
|
+
|
|
186
|
+
CustomLayers = "custom layers"
|
|
187
|
+
"""The layer model is given by a custom function."""
|
|
188
|
+
|
|
189
|
+
CustomXY = "custom xy"
|
|
190
|
+
"""The continuous SLD of the layer model is given by a custom function."""
|
|
191
|
+
|
|
192
|
+
StandardLayers = "standard layers"
|
|
193
|
+
"""The layer model is given by a list of ``Layer``s or ``DomainContrast``s."""
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class Geometries(RATEnum):
|
|
197
|
+
"""Where the substrate roughness is placed."""
|
|
198
|
+
|
|
199
|
+
AirSubstrate = "air/substrate"
|
|
200
|
+
"""The substrate roughness is placed at the end of the stack."""
|
|
201
|
+
|
|
202
|
+
SubstrateLiquid = "substrate/liquid"
|
|
203
|
+
"""The substrate roughness is placed at the beginning of the stack."""
|
ratapi/utils/matlab.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Runs RAT from the MATLAB API."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import tempfile
|
|
5
|
+
import warnings
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from ..events import EventTypes, PlotEventData, ProgressEventData, notify
|
|
11
|
+
from ..outputs import Results
|
|
12
|
+
from ..project import Project
|
|
13
|
+
from ..wrappers import MatlabWrapper
|
|
14
|
+
|
|
15
|
+
RUNNER = """function executeRAT()
|
|
16
|
+
|
|
17
|
+
cur_dir = pwd;
|
|
18
|
+
cd('{rat_path}');
|
|
19
|
+
addPaths;
|
|
20
|
+
cd(cur_dir);
|
|
21
|
+
|
|
22
|
+
project = jsonToProject('{project}');
|
|
23
|
+
controls = jsonToControls('{control}');
|
|
24
|
+
customControls = customControl();
|
|
25
|
+
customControls.update(controls);
|
|
26
|
+
customControls.filePath = '{ipc_path}';
|
|
27
|
+
|
|
28
|
+
for i=1:project.customFile.rowCount
|
|
29
|
+
addpath(project.customFile.varTable{{i, 5}});
|
|
30
|
+
end
|
|
31
|
+
eventManager.register(eventTypes.Message, @(x) logger('{msg_log_path}', x));
|
|
32
|
+
eventManager.register(eventTypes.Progress, @(x) logger('{progress_log_path}', x));
|
|
33
|
+
eventManager.register(eventTypes.Plot, @(x) logger('{plot_log_path}', x));
|
|
34
|
+
global RAT_PROGRESS_UPDATE_FREQ RAT_PROGRESS_UPDATE_COUNT
|
|
35
|
+
RAT_PROGRESS_UPDATE_FREQ = {progress_event_freq};
|
|
36
|
+
RAT_PROGRESS_UPDATE_COUNT = -1;
|
|
37
|
+
|
|
38
|
+
[project, results] = RAT(project, customControls);
|
|
39
|
+
|
|
40
|
+
projectToJson(project, '{project}');
|
|
41
|
+
resultsToJson(results, '{result}');
|
|
42
|
+
eventManager.clear();
|
|
43
|
+
close all
|
|
44
|
+
end
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
CONTROL = """classdef customControl < controlsClass
|
|
49
|
+
properties(Hidden = true)
|
|
50
|
+
filePath = ''
|
|
51
|
+
end
|
|
52
|
+
methods
|
|
53
|
+
function update(obj, controls)
|
|
54
|
+
propNames = properties(controls);
|
|
55
|
+
for i = 1:length(propNames)
|
|
56
|
+
obj.(propNames{i}) = controls.(propNames{i});
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
function path = getIPCFilePath(obj)
|
|
60
|
+
path = obj.filePath;
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
LOGGER = """function logger(logPath, data)
|
|
67
|
+
|
|
68
|
+
if isstruct(data)
|
|
69
|
+
entry = plotDataToJson(data);
|
|
70
|
+
elseif iscell(data)
|
|
71
|
+
global RAT_PROGRESS_UPDATE_FREQ RAT_PROGRESS_UPDATE_COUNT;
|
|
72
|
+
RAT_PROGRESS_UPDATE_COUNT = RAT_PROGRESS_UPDATE_COUNT + 1;
|
|
73
|
+
if rem(RAT_PROGRESS_UPDATE_COUNT, RAT_PROGRESS_UPDATE_FREQ) ~= 0
|
|
74
|
+
return
|
|
75
|
+
end
|
|
76
|
+
entry = [data{1}, ',', num2str(data{2})];
|
|
77
|
+
else
|
|
78
|
+
entry = strip(data, 'right');
|
|
79
|
+
end
|
|
80
|
+
fid = fopen(logPath, "a");
|
|
81
|
+
cleanup = onCleanup(@() fclose(fid));
|
|
82
|
+
fprintf(fid, "%s\\n", entry);
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
function encoded = plotDataToJson(data)
|
|
86
|
+
% Encodes the results into a json file...
|
|
87
|
+
tmpResults = struct();
|
|
88
|
+
for fn = fieldnames(data)'
|
|
89
|
+
tmpResults.(fn{1}) = data.(fn{1});
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
tmpResults.reflectivity = correctCellArray(tmpResults.reflectivity);
|
|
93
|
+
tmpResults.shiftedData = correctCellArray(tmpResults.shiftedData);
|
|
94
|
+
tmpResults.sldProfiles = makeCellJson(tmpResults.sldProfiles);
|
|
95
|
+
tmpResults.resampledLayers = makeCellJson(tmpResults.resampledLayers);
|
|
96
|
+
|
|
97
|
+
encoded = jsonencode(tmpResults,ConvertInfAndNaN=false);
|
|
98
|
+
encoded = strrep(encoded, ']"', ']');
|
|
99
|
+
encoded = strrep(encoded, '"[', '[');
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
function outputArray = makeCellJson(cellArray)
|
|
103
|
+
% The jsonencode function flattens 2d cell arrays this is a workaround to
|
|
104
|
+
% avoid flattening by converting to a string array with is not flattened.
|
|
105
|
+
[row, col] = size(cellArray, [1, 2]);
|
|
106
|
+
outputArray = strings([row, col]);
|
|
107
|
+
for i=1:row
|
|
108
|
+
for j=1:col
|
|
109
|
+
entry = cellArray{i, j};
|
|
110
|
+
if size(entry, 1) == 1
|
|
111
|
+
entry = {entry};
|
|
112
|
+
end
|
|
113
|
+
if col == 1
|
|
114
|
+
entry = {entry};
|
|
115
|
+
end
|
|
116
|
+
outputArray(i, j) = jsonencode(entry);
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
if row == 1
|
|
120
|
+
outputArray = {outputArray};
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
function cellArray = correctCellArray(cellArray)
|
|
126
|
+
% Corrects array with single row so its written as 2D array in json
|
|
127
|
+
[row, col] = size(cellArray, [1, 2]);
|
|
128
|
+
for i=1:row
|
|
129
|
+
for j=1:col
|
|
130
|
+
if size(cellArray{i, j}, 1) == 1
|
|
131
|
+
cellArray{i, j} = {cellArray{i, j}};
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
end
|
|
135
|
+
end
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def run_matlab_directly(
|
|
140
|
+
project, controls, matlab_rat_path, ipc_path="", stdout=None, stderr=None, progress_event_freq=10
|
|
141
|
+
):
|
|
142
|
+
"""Run User provided MATLAB RAT for the given project and controls inputs.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
project : RAT.Project or dict
|
|
147
|
+
The project model (or equivalent json dict), which defines the physical system under study.
|
|
148
|
+
controls : RAT.Controls or dict
|
|
149
|
+
The controls model (or equivalent json dict), which defines algorithmic properties.
|
|
150
|
+
matlab_rat_path : str
|
|
151
|
+
The path to MATLAB RAT folder.
|
|
152
|
+
ipc_path : str, optional
|
|
153
|
+
IPC path for MATLAB to use.
|
|
154
|
+
stdout : io.TextIOBase, optional
|
|
155
|
+
Text stream for MATLAB console output.
|
|
156
|
+
stderr : io.TextIOBase, optional
|
|
157
|
+
Text stream for MATLAB console error output.
|
|
158
|
+
progress_event_freq : int, default: 10
|
|
159
|
+
Update frequency of the progress event.
|
|
160
|
+
"""
|
|
161
|
+
if MatlabWrapper.loader is None:
|
|
162
|
+
raise ImportError(MatlabWrapper.loader_error_message) from None
|
|
163
|
+
|
|
164
|
+
engine = MatlabWrapper.loader.result()
|
|
165
|
+
|
|
166
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
167
|
+
project_file = Path(tmp, "project.json")
|
|
168
|
+
control_file = Path(tmp, "controls.json")
|
|
169
|
+
result_file = Path(tmp, "results.json")
|
|
170
|
+
runner_file = Path(tmp, "executeRAT.m")
|
|
171
|
+
custom_controls_file = Path(tmp, "customControl.m")
|
|
172
|
+
msg_log_file = Path(tmp, "runner_msg_log.txt")
|
|
173
|
+
progress_log_file = Path(tmp, "runner_progress_log.txt")
|
|
174
|
+
plot_log_file = Path(tmp, "runner_plot_log.txt")
|
|
175
|
+
Path(tmp, "logger.m").write_text(LOGGER)
|
|
176
|
+
with open(custom_controls_file, "w") as f:
|
|
177
|
+
f.write(CONTROL)
|
|
178
|
+
|
|
179
|
+
with open(runner_file, "w") as f:
|
|
180
|
+
f.write(
|
|
181
|
+
RUNNER.format(
|
|
182
|
+
project=project_file,
|
|
183
|
+
control=control_file,
|
|
184
|
+
result=result_file,
|
|
185
|
+
rat_path=matlab_rat_path,
|
|
186
|
+
ipc_path=ipc_path,
|
|
187
|
+
msg_log_path=msg_log_file,
|
|
188
|
+
progress_log_path=progress_log_file,
|
|
189
|
+
plot_log_path=plot_log_file,
|
|
190
|
+
progress_event_freq=progress_event_freq,
|
|
191
|
+
)
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
controls.save(control_file) if not isinstance(controls, dict) else control_file.write_text(json.dumps(controls))
|
|
195
|
+
|
|
196
|
+
with warnings.catch_warnings(): # Avoid warning about relative paths
|
|
197
|
+
warnings.simplefilter("ignore")
|
|
198
|
+
project.save(project_file) if not isinstance(project, dict) else project_file.write_text(
|
|
199
|
+
json.dumps(project)
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
engine.addpath(tmp, nargout=0)
|
|
203
|
+
future = engine.executeRAT(nargout=0, stdout=stdout, stderr=stderr, background=True)
|
|
204
|
+
msg_cur_line = 0
|
|
205
|
+
plot_cur_line = 0
|
|
206
|
+
progress_cur_line = 0
|
|
207
|
+
while not future.done():
|
|
208
|
+
if msg_log_file.exists():
|
|
209
|
+
with open(msg_log_file, encoding="utf-8") as handle:
|
|
210
|
+
handle.seek(msg_cur_line)
|
|
211
|
+
text = handle.read()
|
|
212
|
+
msg_cur_line = handle.tell()
|
|
213
|
+
if text:
|
|
214
|
+
notify(EventTypes.Message, text)
|
|
215
|
+
if progress_log_file.exists():
|
|
216
|
+
with open(progress_log_file, encoding="utf-8") as handle:
|
|
217
|
+
handle.seek(progress_cur_line)
|
|
218
|
+
lines = handle.readlines()
|
|
219
|
+
progress_cur_line = handle.tell()
|
|
220
|
+
if lines:
|
|
221
|
+
msg, percent = lines[-1].strip().rsplit(",", 1)
|
|
222
|
+
progress_data = ProgressEventData()
|
|
223
|
+
progress_data.message = msg
|
|
224
|
+
progress_data.percent = float(percent)
|
|
225
|
+
notify(EventTypes.Progress, progress_data)
|
|
226
|
+
if plot_log_file.exists():
|
|
227
|
+
with open(plot_log_file, encoding="utf-8") as handle:
|
|
228
|
+
handle.seek(plot_cur_line)
|
|
229
|
+
lines = handle.readlines()
|
|
230
|
+
plot_cur_line = handle.tell()
|
|
231
|
+
if lines:
|
|
232
|
+
plot_data = PlotEventData()
|
|
233
|
+
plot_json = json.loads(lines[-1])
|
|
234
|
+
plot_data.modelType = plot_json["modelType"]
|
|
235
|
+
plot_data.reflectivity = [np.array(ref) for ref in plot_json["reflectivity"]]
|
|
236
|
+
plot_data.shiftedData = [np.array(sd) for sd in plot_json["shiftedData"]]
|
|
237
|
+
plot_data.sldProfiles = [
|
|
238
|
+
[np.array(prof) for prof in profiles] for profiles in plot_json["sldProfiles"]
|
|
239
|
+
]
|
|
240
|
+
plot_data.resampledLayers = [
|
|
241
|
+
[np.array(lay) for lay in layers] for layers in plot_json["resampledLayers"]
|
|
242
|
+
]
|
|
243
|
+
plot_data.dataPresent = plot_json["dataPresent"]
|
|
244
|
+
plot_data.subRoughs = plot_json["subRoughs"]
|
|
245
|
+
plot_data.resample = plot_json["resample"]
|
|
246
|
+
plot_data.contrastNames = plot_json["contrastNames"]
|
|
247
|
+
notify(EventTypes.Plot, plot_data)
|
|
248
|
+
engine.rmpath(tmp, nargout=0)
|
|
249
|
+
if future.result() is not None:
|
|
250
|
+
raise RuntimeError(future.result())
|
|
251
|
+
|
|
252
|
+
project = Project.load(project_file)
|
|
253
|
+
results = Results.load(result_file)
|
|
254
|
+
return project, results
|
ratapi/utils/orso.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Readers from file formats."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from itertools import count
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from textwrap import shorten
|
|
7
|
+
|
|
8
|
+
import orsopy
|
|
9
|
+
import prettytable
|
|
10
|
+
from orsopy.fileio import load_orso
|
|
11
|
+
|
|
12
|
+
from ratapi import ClassList
|
|
13
|
+
from ratapi.models import AbsorptionLayer, Data, Layer, Parameter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ORSOProject:
|
|
17
|
+
"""A class to encapsulate model information and data from an .ort file.
|
|
18
|
+
|
|
19
|
+
Parameters
|
|
20
|
+
----------
|
|
21
|
+
filepath : str or Path
|
|
22
|
+
The path to the .ort file.
|
|
23
|
+
absorption : bool, default None
|
|
24
|
+
Whether to account for absorption in the model data.
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, filepath: str | Path, absorption: bool = False):
|
|
29
|
+
ort_data = load_orso(filepath)
|
|
30
|
+
datasets = [Data(name=dataset.info.data_source.sample.name, data=dataset.data) for dataset in ort_data]
|
|
31
|
+
# orso datasets in the same file can have repeated names!
|
|
32
|
+
# but classlists do not allow this
|
|
33
|
+
# use this dict to keep track of counts for repeated names
|
|
34
|
+
name_counts = {d.name: count(1) for d in datasets}
|
|
35
|
+
names = [d.name for d in datasets]
|
|
36
|
+
if len(names) > len(list(set(names))):
|
|
37
|
+
for i, data in enumerate(datasets):
|
|
38
|
+
if data.name in names[:i]:
|
|
39
|
+
data.name += f"-{next(name_counts[data.name])}"
|
|
40
|
+
self.data = ClassList(datasets)
|
|
41
|
+
self.samples = [
|
|
42
|
+
orso_model_to_rat(dataset.info.data_source.sample.model, absorption=absorption) for dataset in ort_data
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
def __str__(self):
|
|
46
|
+
data_str = f"Data:\n{str(self.data)}\n\n"
|
|
47
|
+
if len(self.samples) == 1:
|
|
48
|
+
samples_str = f"Sample:\n{str(self.samples[0])}"
|
|
49
|
+
else:
|
|
50
|
+
table = prettytable.PrettyTable()
|
|
51
|
+
table.field_names = ["index", "bulk in", "bulk out", "parameters", "layers", "model"]
|
|
52
|
+
for index, sample in enumerate(self.samples):
|
|
53
|
+
if sample is None:
|
|
54
|
+
row = [index, "", "", "", "", ""]
|
|
55
|
+
else:
|
|
56
|
+
row = [
|
|
57
|
+
index,
|
|
58
|
+
sample.bulk_in.name,
|
|
59
|
+
sample.bulk_out.name,
|
|
60
|
+
shorten(", ".join([p.name for p in sample.parameters]), width=20, placeholder="..."),
|
|
61
|
+
shorten(", ".join([layer.name for layer in sample.layers]), width=20, placeholder="..."),
|
|
62
|
+
shorten(str(sample.model), width=20, placeholder="..."),
|
|
63
|
+
]
|
|
64
|
+
table.add_row(row)
|
|
65
|
+
samples_str = table.get_string()
|
|
66
|
+
|
|
67
|
+
return data_str + samples_str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class ORSOSample:
|
|
72
|
+
"""The stack data from an ORSO SampleModel, in RAT models."""
|
|
73
|
+
|
|
74
|
+
bulk_in: Parameter
|
|
75
|
+
bulk_out: Parameter
|
|
76
|
+
parameters: ClassList[Parameter]
|
|
77
|
+
layers: ClassList[Layer] | ClassList[AbsorptionLayer]
|
|
78
|
+
model: list[str]
|
|
79
|
+
|
|
80
|
+
def __str__(self):
|
|
81
|
+
return (
|
|
82
|
+
"Bulk in:\n"
|
|
83
|
+
f"{str(self.bulk_in)}\n\n"
|
|
84
|
+
"Bulk out:\n"
|
|
85
|
+
f"{str(self.bulk_out)}\n\n"
|
|
86
|
+
"Parameters:\n"
|
|
87
|
+
f"{str(self.parameters)}\n\n"
|
|
88
|
+
"Layers:\n"
|
|
89
|
+
f"{str(self.layers)}\n\n"
|
|
90
|
+
"Model:\n"
|
|
91
|
+
f"{self.model}"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def orso_model_to_rat(
|
|
96
|
+
model: orsopy.fileio.model_language.SampleModel | str, absorption: bool = False
|
|
97
|
+
) -> ORSOSample | None:
|
|
98
|
+
"""Get information from an ORSO SampleModel object.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
model : orsopy.fileio.model_language.SampleModel or str
|
|
103
|
+
The sample model to turn into a RAT data. If given as a string,
|
|
104
|
+
the string is interpreted as a layer stack in ORSO model language.
|
|
105
|
+
absorption : bool, default False
|
|
106
|
+
Whether to account for absorption in the model.
|
|
107
|
+
|
|
108
|
+
Returns
|
|
109
|
+
-------
|
|
110
|
+
ORSOSample
|
|
111
|
+
A dataclass containing the sample data, or None if the model is None.
|
|
112
|
+
|
|
113
|
+
"""
|
|
114
|
+
if model is None:
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
if isinstance(model, str):
|
|
118
|
+
model = orsopy.fileio.model_language.SampleModel(stack=model)
|
|
119
|
+
|
|
120
|
+
stack = model.resolve_to_layers()
|
|
121
|
+
# if bulk in or out is air, it has SLD predefined
|
|
122
|
+
# else we need to grab it from SLDDB
|
|
123
|
+
if bulk_in_sld := stack[0].material.sld is None:
|
|
124
|
+
bulk_in_sld = stack[0].material.get_sld()
|
|
125
|
+
|
|
126
|
+
# resolve_to_layers loses the name of bulk in and out
|
|
127
|
+
bulk_in_name = model.stack.split("|")[0].strip()
|
|
128
|
+
bulk_in = Parameter(
|
|
129
|
+
name=f"{bulk_in_name} SLD",
|
|
130
|
+
min=bulk_in_sld.real,
|
|
131
|
+
value=bulk_in_sld.real,
|
|
132
|
+
max=bulk_in_sld.real,
|
|
133
|
+
fit=False,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if bulk_out_sld := stack[-1].material.sld is None:
|
|
137
|
+
bulk_out_sld = stack[-1].material.get_sld()
|
|
138
|
+
|
|
139
|
+
bulk_out_name = model.stack.split("|")[-1].strip()
|
|
140
|
+
bulk_out = Parameter(
|
|
141
|
+
name=f"{bulk_out_name} SLD",
|
|
142
|
+
min=bulk_out_sld.real,
|
|
143
|
+
value=bulk_out_sld.real,
|
|
144
|
+
max=bulk_out_sld.real,
|
|
145
|
+
fit=False,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
parameters = ClassList()
|
|
149
|
+
layers = ClassList()
|
|
150
|
+
contrast_model = []
|
|
151
|
+
|
|
152
|
+
for orso_layer in stack[1:-1]:
|
|
153
|
+
name = get_material_name(orso_layer.material, model)
|
|
154
|
+
contrast_model.append(name)
|
|
155
|
+
layer_params, layer = orso_layer_to_rat_layer(orso_layer, name, absorption)
|
|
156
|
+
parameters.union(layer_params)
|
|
157
|
+
layers.union(layer)
|
|
158
|
+
|
|
159
|
+
return ORSOSample(
|
|
160
|
+
bulk_in=bulk_in,
|
|
161
|
+
bulk_out=bulk_out,
|
|
162
|
+
parameters=parameters,
|
|
163
|
+
layers=layers,
|
|
164
|
+
model=contrast_model,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def orso_layer_to_rat_layer(
|
|
169
|
+
layer: orsopy.fileio.model_language.Layer, name: str, absorption: bool = False
|
|
170
|
+
) -> tuple[ClassList[Parameter], Layer]:
|
|
171
|
+
"""Convert an ``orsopy`` layer to a RAT layer.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
layer : orsopy.fileio.model_language.Layer
|
|
176
|
+
An ``orsopy`` Layer.
|
|
177
|
+
name : str
|
|
178
|
+
The name of the material in the layer.
|
|
179
|
+
absorption : bool, default True
|
|
180
|
+
Whether absorption should be accounted for in the layer.
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
-------
|
|
184
|
+
ClassList[Parameter], Layer
|
|
185
|
+
The parameters required for the RAT layer and the layer itself.
|
|
186
|
+
|
|
187
|
+
"""
|
|
188
|
+
thickness = layer.thickness.as_unit("angstrom")
|
|
189
|
+
roughness = layer.roughness.as_unit("angstrom")
|
|
190
|
+
sld = layer.material.get_sld()
|
|
191
|
+
|
|
192
|
+
params = ClassList(
|
|
193
|
+
[
|
|
194
|
+
Parameter(name=f"{name} Thickness", min=thickness, value=thickness, max=thickness, fit=False),
|
|
195
|
+
Parameter(name=f"{name} Roughness", min=roughness, value=roughness, max=roughness, fit=False),
|
|
196
|
+
Parameter(name=f"{name} SLD", min=sld.real, value=sld.real, max=sld.real, fit=False),
|
|
197
|
+
]
|
|
198
|
+
)
|
|
199
|
+
if absorption:
|
|
200
|
+
params.append(Parameter(name=f"{name} SLD imaginary", min=sld.imag, value=sld.imag, max=sld.imag, fit=False))
|
|
201
|
+
layer = AbsorptionLayer(
|
|
202
|
+
name=name,
|
|
203
|
+
thickness=f"{name} Thickness",
|
|
204
|
+
roughness=f"{name} Roughness",
|
|
205
|
+
SLD_real=f"{name} SLD",
|
|
206
|
+
SLD_imaginary=f"{name} SLD imaginary",
|
|
207
|
+
)
|
|
208
|
+
else:
|
|
209
|
+
layer = Layer(
|
|
210
|
+
name=name,
|
|
211
|
+
thickness=f"{name} Thickness",
|
|
212
|
+
roughness=f"{name} Roughness",
|
|
213
|
+
SLD=f"{name} SLD",
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
return params, layer
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def get_material_name(
|
|
220
|
+
material: orsopy.fileio.model_language.Material, model: orsopy.fileio.model_language.SampleModel
|
|
221
|
+
) -> str:
|
|
222
|
+
"""Get the name of a material in the model.
|
|
223
|
+
|
|
224
|
+
Layers with custom property definitions may not have a formula, so this adjusts the name for that.
|
|
225
|
+
|
|
226
|
+
Parameters
|
|
227
|
+
----------
|
|
228
|
+
material : Material
|
|
229
|
+
The material to get the name of.
|
|
230
|
+
model : SampleModel
|
|
231
|
+
The sample model from which the material came.
|
|
232
|
+
|
|
233
|
+
Returns
|
|
234
|
+
-------
|
|
235
|
+
str
|
|
236
|
+
The name of the material.
|
|
237
|
+
|
|
238
|
+
"""
|
|
239
|
+
if material.formula is not None:
|
|
240
|
+
return material.formula
|
|
241
|
+
else:
|
|
242
|
+
matching_materials = [k for k, v in model.materials.items() if v == material]
|
|
243
|
+
if matching_materials:
|
|
244
|
+
return matching_materials[0]
|
|
245
|
+
else:
|
|
246
|
+
# orsopy should catch that this is the case before we get here, but just in case...
|
|
247
|
+
raise ValueError("ORSO model contains layers with undefined materials!")
|