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.
Files changed (63) hide show
  1. ratapi/__init__.py +42 -0
  2. ratapi/classlist.py +620 -0
  3. ratapi/controls.py +258 -0
  4. ratapi/eventManager.dll +0 -0
  5. ratapi/events.py +88 -0
  6. ratapi/examples/__init__.py +25 -0
  7. ratapi/examples/absorption/__init__.py +1 -0
  8. ratapi/examples/absorption/absorption.py +172 -0
  9. ratapi/examples/absorption/volume_thiol_bilayer.py +144 -0
  10. ratapi/examples/convert_rascal_project/Model_IIb.py +90 -0
  11. ratapi/examples/convert_rascal_project/__init__.py +1 -0
  12. ratapi/examples/convert_rascal_project/convert_rascal.py +49 -0
  13. ratapi/examples/data/D2O_spin_down.dat +100 -0
  14. ratapi/examples/data/D2O_spin_up.dat +101 -0
  15. ratapi/examples/data/DSPC_D2O.dat +82 -0
  16. ratapi/examples/data/DSPC_SMW.dat +82 -0
  17. ratapi/examples/data/H2O_spin_down.dat +102 -0
  18. ratapi/examples/data/H2O_spin_up.dat +102 -0
  19. ratapi/examples/data/__init__.py +1 -0
  20. ratapi/examples/data/c_PLP0016596.dat +146 -0
  21. ratapi/examples/data/c_PLP0016601.dat +97 -0
  22. ratapi/examples/data/c_PLP0016607.dat +104 -0
  23. ratapi/examples/data/d2o_background_data.dat +82 -0
  24. ratapi/examples/domains/__init__.py +1 -0
  25. ratapi/examples/domains/alloy_domains.py +34 -0
  26. ratapi/examples/domains/domains_XY_model.py +75 -0
  27. ratapi/examples/domains/domains_custom_XY.py +86 -0
  28. ratapi/examples/domains/domains_custom_layers.py +60 -0
  29. ratapi/examples/domains/domains_standard_layers.py +92 -0
  30. ratapi/examples/languages/__init__.py +1 -0
  31. ratapi/examples/languages/custom_bilayer.py +72 -0
  32. ratapi/examples/languages/run_custom_file_languages.py +41 -0
  33. ratapi/examples/languages/setup_problem.py +130 -0
  34. ratapi/examples/normal_reflectivity/DSPC_custom_XY.py +149 -0
  35. ratapi/examples/normal_reflectivity/DSPC_custom_layers.py +130 -0
  36. ratapi/examples/normal_reflectivity/DSPC_data_background.py +220 -0
  37. ratapi/examples/normal_reflectivity/DSPC_function_background.py +219 -0
  38. ratapi/examples/normal_reflectivity/DSPC_standard_layers.py +210 -0
  39. ratapi/examples/normal_reflectivity/__init__.py +1 -0
  40. ratapi/examples/normal_reflectivity/background_function.py +16 -0
  41. ratapi/examples/normal_reflectivity/custom_XY_DSPC.py +141 -0
  42. ratapi/examples/normal_reflectivity/custom_bilayer_DSPC.py +89 -0
  43. ratapi/inputs.py +603 -0
  44. ratapi/models.py +717 -0
  45. ratapi/outputs.py +821 -0
  46. ratapi/project.py +1091 -0
  47. ratapi/rat_core.cp315-win_amd64.pyd +0 -0
  48. ratapi/run.py +142 -0
  49. ratapi/utils/__init__.py +1 -0
  50. ratapi/utils/convert.py +597 -0
  51. ratapi/utils/custom_errors.py +40 -0
  52. ratapi/utils/enums.py +203 -0
  53. ratapi/utils/matlab.py +254 -0
  54. ratapi/utils/orso.py +247 -0
  55. ratapi/utils/plotting.py +1316 -0
  56. ratapi/wrappers.py +147 -0
  57. ratapi-0.0.0.dev16.dist-info/DELVEWHEEL +2 -0
  58. ratapi-0.0.0.dev16.dist-info/METADATA +61 -0
  59. ratapi-0.0.0.dev16.dist-info/RECORD +63 -0
  60. ratapi-0.0.0.dev16.dist-info/WHEEL +5 -0
  61. ratapi-0.0.0.dev16.dist-info/top_level.txt +1 -0
  62. ratapi.libs/msvcp140-a4c2229bdc2a2a630acdc095b4d86008.dll +0 -0
  63. ratapi.libs/vcomp140-f96f3a14d88d8846f31f3ab38a490304.dll +0 -0
@@ -0,0 +1,597 @@
1
+ """Utilities for converting input files to Python `Project`s."""
2
+
3
+ import warnings
4
+ from collections.abc import Iterable
5
+ from os import PathLike
6
+ from pathlib import Path
7
+
8
+ from numpy import array, empty, ndarray
9
+ from scipy.io.matlab import MatlabOpaque, loadmat
10
+
11
+ from ratapi import Project, wrappers
12
+ from ratapi.classlist import ClassList
13
+ from ratapi.models import Background, Contrast, CustomFile, Data, Layer, Parameter, Resolution
14
+ from ratapi.utils.enums import Geometries, Languages, LayerModels
15
+
16
+
17
+ def r1_to_project(filename: str | PathLike) -> Project:
18
+ """Read a RasCAL1 project struct as a Python `Project`.
19
+
20
+ Parameters
21
+ ----------
22
+ filename : str, PathLike
23
+ The path to a .mat file containing project data.
24
+
25
+ Returns
26
+ -------
27
+ Project
28
+ A RAT `Project` equivalent to the RasCAL1 project struct.
29
+
30
+ """
31
+ mat_project = loadmat(str(filename), simplify_cells=True)["problem"]
32
+
33
+ mat_module = mat_project["module"]
34
+ if mat_module["experiment_type"] == "Air / Liquid (or solid)":
35
+ geom = Geometries.AirSubstrate
36
+ else:
37
+ geom = Geometries.SubstrateLiquid
38
+
39
+ # R1 uses a different name for custom xy layer model
40
+ layer_model = mat_module["type"]
41
+ if layer_model.lower() == "custom xy profile":
42
+ layer_model = LayerModels.CustomXY
43
+ layer_model = LayerModels(layer_model)
44
+
45
+ def zip_if_several(*params) -> tuple | list[tuple]:
46
+ """Zips parameters if necessary, but can handle single-item parameters.
47
+
48
+ Examples
49
+ --------
50
+ zip_if_several([1, 2], [3, 4]) = [(1, 3), (2, 4)]
51
+ zip_if_several(1, 2, 3) = [(1, 2, 3)]
52
+
53
+ Parameters
54
+ ----------
55
+ *params
56
+ Any number of parameters.
57
+
58
+ Returns
59
+ -------
60
+ tuple or list of tuple
61
+ If any parameter is a single item, returns a list just containing the tuple of parameters.
62
+ Otherwise, returns the same as zip(*params).
63
+
64
+ """
65
+ if all(isinstance(param, Iterable) and not isinstance(param, str) for param in params):
66
+ return zip(*params, strict=False)
67
+ return [params]
68
+
69
+ def __opaque_to_string(opaque):
70
+ """Extract java string from MATLABOpaque object.
71
+
72
+ Parameters
73
+ ----------
74
+ opaque : MATLABOpaque
75
+ object containing java string.
76
+
77
+ Returns
78
+ -------
79
+ str
80
+ string extracted from object.
81
+
82
+ Raises
83
+ ------
84
+ ValueError
85
+ Raised if there is no java string array in the object.
86
+ """
87
+ entries = opaque[0]
88
+ for entry in entries:
89
+ if isinstance(entry, ndarray):
90
+ break
91
+ else:
92
+ raise ValueError("No array in MatlabOpaque")
93
+
94
+ return bytes(entry[7:]).decode("ascii")
95
+
96
+ def read_param(names, constrs, values, fits):
97
+ """Read in a parameter list from the relevant keys, and fix constraints for non-fit parameters.
98
+
99
+ Parameters
100
+ ----------
101
+ names, constrs, values, fits : str
102
+ The keys for names, constraints, values
103
+ and whether to fit for a type of parameter.
104
+
105
+ Returns
106
+ -------
107
+ ClassList
108
+ A list of all relevant parameters.
109
+
110
+ """
111
+
112
+ def fix_invalid_constraints(name: str, constrs: tuple[float, float], value: float) -> tuple[float, float]:
113
+ """Check that constraints are valid and fix them if they aren't.
114
+
115
+ RasCAL-1 allowed the constraints of non-fit parameters to be invalid, which means
116
+ we need to fix them here so that the project is valid.
117
+
118
+ Parameters
119
+ ----------
120
+ name: str
121
+ The name of the parameter.
122
+ constrs : tuple[float, float]
123
+ The constraints of the parameter (min and max, respectively)
124
+ value : float
125
+ The value of the parameter.
126
+
127
+ Returns
128
+ -------
129
+ tuple[float, float]
130
+ The adjusted constraints (identical to constrs if constraints were valid)
131
+
132
+ """
133
+ new_constrs = (min(constrs[0], value), max(constrs[1], value))
134
+ if new_constrs[0] != constrs[0] or new_constrs[1] != constrs[1]:
135
+ warnings.warn(
136
+ f"The parameter {name} has invalid constraints,"
137
+ " these have been adjusted to satisfy the current value of the parameter.",
138
+ stacklevel=2,
139
+ )
140
+ return new_constrs
141
+
142
+ # adjust invalid constraints
143
+ # if just one item in the classlist, these objects won't be in lists
144
+ if not isinstance(fit := mat_project[fits], Iterable):
145
+ if not fit:
146
+ mat_project[constrs] = fix_invalid_constraints(
147
+ mat_project[names], mat_project[constrs], mat_project[values]
148
+ )
149
+ # else they will be iterable
150
+ else:
151
+ for i, fit in enumerate(mat_project[fits]):
152
+ if not fit:
153
+ mat_project[constrs][i] = fix_invalid_constraints(
154
+ mat_project[names][i], mat_project[constrs][i], mat_project[values][i]
155
+ )
156
+
157
+ return ClassList(
158
+ [
159
+ Parameter(
160
+ name=name,
161
+ min=constr[0],
162
+ value=val,
163
+ max=constr[1],
164
+ fit=fitbool,
165
+ )
166
+ for name, constr, val, fitbool in zip_if_several(
167
+ mat_project[names],
168
+ mat_project[constrs],
169
+ mat_project[values],
170
+ mat_project[fits],
171
+ )
172
+ ]
173
+ )
174
+
175
+ # we add these as new attributes of the mat project dict so we can feed them into read_param better
176
+ if mat_project["numberOfBacks"] == 1:
177
+ mat_project["back_param_names"] = "Background parameter 1"
178
+ else:
179
+ mat_project["back_param_names"] = [
180
+ f"Background parameter {i}" for i in range(1, mat_project["numberOfBacks"] + 1)
181
+ ]
182
+
183
+ # sometimes numberOfResolutions isn't defined: in all these cases there's only one resolution
184
+ # maybe from before multiple resolutions were possible?
185
+ if getattr(mat_project, "numberOfResolutions", 1) == 1:
186
+ mat_project["res_param_names"] = "Resolution parameter 1"
187
+ else:
188
+ mat_project["res_param_names"] = [
189
+ f"Resolution parameter {i}" for i in range(1, mat_project["numberOfBacks"] + 1)
190
+ ]
191
+
192
+ params = read_param("paramnames", "constr", "params", "fityesno")
193
+ back_params = read_param("back_param_names", "backs_constr", "backs", "backgrounds_fityesno")
194
+ res_params = read_param("res_param_names", "resolution_constr", "resolution", "resolution_fityesno")
195
+ bulk_ins = read_param("nbaNames", "nbairs_constr", "nba", "nbairs_fityesno")
196
+ bulk_outs = read_param("nbsNames", "nbsubs_constr", "nbs", "nbsubs_fityesno")
197
+ scale_facs = read_param("scalesNames", "scale_constr", "scalefac", "scalefac_fityesno")
198
+
199
+ # if just one background, backsNames and back_param_names are strings; fix that here
200
+ # and mutatis mutandis for resolution
201
+ if isinstance(mat_project["back_param_names"], str):
202
+ mat_project["back_param_names"] = [mat_project["back_param_names"]]
203
+ if isinstance(mat_project["backsNames"], str):
204
+ mat_project["backsNames"] = [mat_project["backsNames"]]
205
+ if isinstance(mat_project["res_param_names"], str):
206
+ mat_project["res_param_names"] = [mat_project["res_param_names"]]
207
+ if isinstance(mat_project["resolNames"], str):
208
+ mat_project["resolNames"] = [mat_project["resolNames"]]
209
+
210
+ # create backgrounds and resolutions from parameters
211
+ backs = ClassList(
212
+ [
213
+ Background(name=back_name, type="constant", source=mat_project["back_param_names"][i])
214
+ for i, back_name in enumerate(mat_project["backsNames"])
215
+ ]
216
+ )
217
+ res = ClassList(
218
+ [
219
+ Resolution(name=res_name, type="constant", source=mat_project["res_param_names"][i])
220
+ for i, res_name in enumerate(mat_project["resolNames"])
221
+ ]
222
+ )
223
+
224
+ data = ClassList(
225
+ [
226
+ Data(
227
+ name=Path(name).stem,
228
+ data=data,
229
+ data_range=data_range,
230
+ simulation_range=sim_range,
231
+ )
232
+ for name, data, data_range, sim_range in zip_if_several(
233
+ mat_project["contrastFiles"],
234
+ mat_project["data"],
235
+ mat_project["dataLimits"],
236
+ mat_project["simLimits"],
237
+ )
238
+ ]
239
+ )
240
+
241
+ # contrast names may be java strings (unsure why, maybe GUI input?): convert to Python str
242
+ # the java string is presented in Python as a MatlabOpaque object in a 1-item array (hence index [0])
243
+ # which are given as a 1-item array with 4 entries. the fourth is the actual data (index [3]),
244
+ # which is given as the byte data of a Java string; this consists of 7 metadata bytes (ignored)
245
+ # and then the actual string characters (index [7:]) in ascii format (.decode("ascii"))
246
+ if len(mat_project["contrastNames"]) == 1 and isinstance(mat_project["contrastNames"], MatlabOpaque):
247
+ mat_project["contrastNames"] = __opaque_to_string(mat_project["contrastNames"])
248
+ else:
249
+ for i, contrast_name in enumerate(mat_project["contrastNames"]):
250
+ if isinstance(contrast_name, MatlabOpaque):
251
+ mat_project["contrastNames"][i] = __opaque_to_string(contrast_name)
252
+
253
+ # if just one contrast, resolNames is a string; fix that here
254
+ if isinstance(mat_project["resolNames"], str):
255
+ mat_project["resolNames"] = [mat_project["resolNames"]]
256
+
257
+ if isinstance(mat_project["contrastNames"], (ndarray, list)) and len(
258
+ dict.fromkeys(mat_project["contrastNames"])
259
+ ) != len(mat_project["contrastNames"]):
260
+ # contrast names are not unique so create unique ones
261
+ mat_project["contrastNames"] = [f"Contrast {i + 1}" for i in range(len(mat_project["contrastNames"]))]
262
+
263
+ contrasts = ClassList(
264
+ [
265
+ Contrast(
266
+ name=name,
267
+ background=backs[int(back) - 1].name,
268
+ resolution=mat_project["resolNames"][int(res) - 1],
269
+ scalefactor=scale_facs[int(scale) - 1].name,
270
+ bulk_in=bulk_ins[int(bulk_in) - 1].name,
271
+ bulk_out=bulk_outs[int(bulk_out) - 1].name,
272
+ data=data[i].name,
273
+ )
274
+ for i, (name, back, res, scale, bulk_in, bulk_out) in enumerate(
275
+ zip_if_several(
276
+ mat_project["contrastNames"],
277
+ mat_project["contrastBacks"],
278
+ mat_project["contrastResolutions"],
279
+ mat_project["contrastScales"],
280
+ mat_project["contrastNbas"],
281
+ mat_project["contrastNbss"],
282
+ )
283
+ )
284
+ ]
285
+ )
286
+
287
+ # set model for each contrast and add custom files
288
+ if layer_model == LayerModels.StandardLayers:
289
+ custom_file = ClassList()
290
+ layers = ClassList(
291
+ [
292
+ Layer(
293
+ name=name,
294
+ thickness=params[int(thickness) - 1].name,
295
+ SLD=params[int(sld) - 1].name,
296
+ roughness=params[int(roughness) - 1].name,
297
+ # if hydration is not set, it is an empty numpy array, else it is a string representing a number
298
+ hydration=params[int(hydration) - 1].name if getattr(hydration, "size", 1) > 0 else "",
299
+ hydrate_with=hydrate_with,
300
+ )
301
+ # R1 layers are 6-item arrays, unpack into a Layer object
302
+ for thickness, sld, roughness, hydration, name, hydrate_with in mat_project["layersDetails"]
303
+ ]
304
+ )
305
+
306
+ for i, contrast in enumerate(contrasts):
307
+ # if there is only one layer, contrastsNumberOfLayers is an int; otherwise it is a list
308
+ if (
309
+ isinstance(mat_project["contrastsNumberOfLayers"], int)
310
+ and mat_project["contrastsNumberOfLayers"] == 0
311
+ or isinstance(mat_project["contrastsNumberOfLayers"], list)
312
+ and mat_project["contrastsNumberOfLayers"][i] == 0
313
+ ):
314
+ continue
315
+ # contrastLayers is not an array, but rather a string with commas between entries
316
+ contrast_layers = mat_project["contrastLayers"][i].split(",")
317
+ contrast_layers = [
318
+ int(x) - 1 for x in contrast_layers if x != ""
319
+ ] # remove empty string from hanging commas
320
+ contrast.model = [layers[i].name for i in contrast_layers]
321
+
322
+ else:
323
+ custom_filepath = mat_module["name"]
324
+ if Path(custom_filepath).suffix != ".m":
325
+ custom_filepath += ".m"
326
+ model_name = Path(custom_filepath).stem
327
+ # Assume the custom file is in the same directory as the mat file
328
+ custom_file = ClassList(
329
+ [
330
+ CustomFile(
331
+ name=model_name, filename=custom_filepath, language=Languages.Matlab, path=Path(filename).parent
332
+ )
333
+ ]
334
+ )
335
+ layers = ClassList()
336
+ for contrast in contrasts:
337
+ contrast.model = [model_name]
338
+
339
+ project = Project(
340
+ name=mat_project.get("name", ""),
341
+ model=layer_model,
342
+ geometry=geom,
343
+ parameters=params,
344
+ backgrounds=backs,
345
+ background_parameters=back_params,
346
+ resolutions=res,
347
+ resolution_parameters=res_params,
348
+ bulk_in=bulk_ins,
349
+ bulk_out=bulk_outs,
350
+ scalefactors=scale_facs,
351
+ data=data,
352
+ layers=layers,
353
+ contrasts=contrasts,
354
+ custom_files=custom_file,
355
+ )
356
+
357
+ return project
358
+
359
+
360
+ def project_to_r1(
361
+ project: Project, filename: str | PathLike = "RAT_project", return_struct: bool = False
362
+ ) -> dict | None:
363
+ """Convert a RAT Project to a RasCAL1 project struct.
364
+
365
+ Parameters
366
+ ----------
367
+ project : Project
368
+ The RAT Project to convert.
369
+ filename : str or PathLike, default "RAT_project"
370
+ If given, saves as a .mat file with the given filename.
371
+ return_struct : bool, default False
372
+ If True, do not save and instead return the R1 struct.
373
+
374
+ Returns
375
+ -------
376
+ dict or None
377
+ If `return_struct` is True, return the r1 struct. Else, return nothing.
378
+
379
+ """
380
+
381
+ def convert_parameters(
382
+ params: ClassList[Parameter], name: str, value: str, constr: str, fit: str, number: str = ""
383
+ ):
384
+ """Convert a list of parameters to r1 data fields.
385
+
386
+ Parameters
387
+ ----------
388
+ params: ClassList
389
+ A list of parameter type from the Project.
390
+ name, constr, value, fit : str
391
+ The keys for names, constraints, values
392
+ and whether to fit for a type of parameter.
393
+ number : str, optional, default ""
394
+ Key for the length of the parameter list if not blank.
395
+
396
+ Returns
397
+ -------
398
+ dict
399
+ A dict of the relevant struct fields.
400
+
401
+ """
402
+ output = {
403
+ name: [p.name for p in params],
404
+ value: [p.value for p in params],
405
+ constr: [[p.min, p.max] for p in params],
406
+ fit: [int(p.fit) for p in params],
407
+ }
408
+ if number:
409
+ output[number] = len(params)
410
+
411
+ return output
412
+
413
+ # translate RAT geometries into R1 experiment types
414
+ r1_geoms_dict = {Geometries.AirSubstrate: "Air / Liquid (or solid)", Geometries.SubstrateLiquid: "Solid / Liquid"}
415
+
416
+ r1 = {
417
+ # set name, type, experiment type
418
+ "name": project.name,
419
+ "module": {
420
+ "type": str(project.model),
421
+ "experiment_type": r1_geoms_dict[project.geometry],
422
+ },
423
+ }
424
+ # parameter names, values, constraints, fits
425
+ r1.update(
426
+ convert_parameters(
427
+ project.parameters,
428
+ "paramnames",
429
+ "params",
430
+ "constr",
431
+ "fityesno",
432
+ )
433
+ )
434
+ # scalefactors names, values, constraints, fit, and number
435
+ r1.update(
436
+ convert_parameters(
437
+ project.scalefactors,
438
+ "scalesNames",
439
+ "scalefac",
440
+ "scale_constr",
441
+ "scalefac_fityesno",
442
+ "numberOfScales",
443
+ )
444
+ )
445
+ # bulk in names, values, constraints, fit, and number
446
+ r1.update(
447
+ convert_parameters(
448
+ project.bulk_in,
449
+ "nbaNames",
450
+ "nba",
451
+ "nbairs_constr",
452
+ "nbairs_fityesno",
453
+ "numberOfNbas",
454
+ )
455
+ )
456
+ # bulk out names, values, constraints, fit, and number
457
+ r1.update(
458
+ convert_parameters(
459
+ project.bulk_out,
460
+ "nbsNames",
461
+ "nbs",
462
+ "nbsubs_constr",
463
+ "nbsubs_fityesno",
464
+ "numberOfNbss",
465
+ )
466
+ )
467
+
468
+ shifts = {
469
+ "numberOfShifts": 1,
470
+ "shiftsNames": "Shift 1",
471
+ "shifts_horisontal": 0,
472
+ "shifts_fityesno": 0,
473
+ "shifts_constr": [-1e-4, 1e-4],
474
+ }
475
+ r1.update(shifts)
476
+
477
+ resolutions = {
478
+ "resolNames": [r.name for r in project.resolutions],
479
+ "resolution": [project.resolution_parameters[r.source].value for r in project.resolutions],
480
+ "resolution_constr": [
481
+ [project.resolution_parameters[r.source].min, project.resolution_parameters[r.source].max]
482
+ for r in project.resolutions
483
+ ],
484
+ "resolution_fityesno": [int(project.resolution_parameters[r.source].fit) for r in project.resolutions],
485
+ "numberOfResolutions": len(project.resolutions),
486
+ }
487
+ r1.update(resolutions)
488
+
489
+ backgrounds = {
490
+ "backsNames": [b.name for b in project.backgrounds],
491
+ "backs": [project.background_parameters[b.source].value for b in project.backgrounds],
492
+ "backs_constr": [
493
+ [project.background_parameters[b.source].min, project.background_parameters[b.source].max]
494
+ for b in project.backgrounds
495
+ ],
496
+ "backgrounds_fityesno": [int(project.background_parameters[b.source].fit) for b in project.backgrounds],
497
+ "numberOfBacks": len(project.backgrounds),
498
+ }
499
+ r1.update(backgrounds)
500
+
501
+ if project.model == LayerModels.StandardLayers:
502
+ layer_info = {
503
+ "numberOfLayers": len(project.layers),
504
+ "layersDetails": [
505
+ [
506
+ project.parameters.index(layer.thickness, True),
507
+ project.parameters.index(layer.SLD, True),
508
+ project.parameters.index(layer.roughness, True),
509
+ project.parameters.index(layer.hydration, True) if layer.hydration else empty(shape=(0, 0)),
510
+ layer.name,
511
+ str(layer.hydrate_with),
512
+ ]
513
+ for layer in project.layers
514
+ ],
515
+ }
516
+ r1["module"]["name"] = ""
517
+ else:
518
+ layer_info = {"numberOfLayers": 0, "layersDetails": []}
519
+ # note R1 only supports one custom file!
520
+ r1["module"]["name"] = project.custom_files[0].name
521
+ r1.update(layer_info)
522
+
523
+ contrasts = {
524
+ "contrastNames": [c.name for c in project.contrasts],
525
+ "contrastNbas": [project.bulk_in.index(c.bulk_in, True) for c in project.contrasts],
526
+ "contrastNbss": [project.bulk_out.index(c.bulk_out, True) for c in project.contrasts],
527
+ "contrastScales": [project.scalefactors.index(c.scalefactor, True) for c in project.contrasts],
528
+ "data": [project.data[c.data].data for c in project.contrasts],
529
+ "simLimits": [project.data[c.data].simulation_range for c in project.contrasts],
530
+ "dataLimits": [project.data[c.data].data_range for c in project.contrasts],
531
+ "fitlowrange": [project.data[c.data].data_range[0] for c in project.contrasts],
532
+ "fithirange": [project.data[c.data].data_range[1] for c in project.contrasts],
533
+ "contrastRepeatSLDs": [[0, 1] for _ in project.contrasts],
534
+ "contrastFiles": [project.data[c.data].name for c in project.contrasts],
535
+ # some of the data is a bit complex for a (readable) list comp; create empty lists and append below
536
+ "contrastResolutions": [],
537
+ "contrastBacks": [],
538
+ "dataPresent": [],
539
+ "include_data": [],
540
+ "dataTypes": [],
541
+ "contrastLayers": [],
542
+ "contrastsNumberOfLayers": [],
543
+ }
544
+ for contrast in project.contrasts:
545
+ # R1 stores contrast resolutions and background by the index of the relevant parameter
546
+ resolution = project.resolutions[contrast.resolution]
547
+ contrasts["contrastResolutions"].append(project.resolution_parameters.index(resolution.source, True))
548
+
549
+ background = project.backgrounds[contrast.background]
550
+ contrasts["contrastBacks"].append(project.background_parameters.index(background.source, True))
551
+
552
+ data = project.data[contrast.data]
553
+ if "simulation" in data.name:
554
+ contrasts["dataPresent"].append(0)
555
+ contrasts["include_data"].append(0)
556
+ contrasts["dataTypes"].append("Simulation")
557
+ else:
558
+ contrasts["dataPresent"].append(1)
559
+ contrasts["include_data"].append(1)
560
+ contrasts["dataTypes"].append("Ascii File")
561
+
562
+ if project.model == LayerModels.StandardLayers:
563
+ model = contrast.model
564
+ contrasts["contrastsNumberOfLayers"].append(len(model))
565
+ contrasts["contrastLayers"].append(",".join(str(project.layers.index(layer) + 1) for layer in model))
566
+ else:
567
+ contrasts["contrastsNumberOfLayers"].append(0)
568
+ contrasts["contrastLayers"].append("")
569
+
570
+ r1.update(contrasts)
571
+
572
+ # some final processing:
573
+ # .mat files just contain the item for any single-item list, so process and fix that
574
+ # also, `savemat` will only write cells instead of matrices for object-type ndarrays. convert lists to those
575
+ for key, value in r1.items():
576
+ if isinstance(value, list):
577
+ if len(value) == 1:
578
+ r1[key] = value[0]
579
+ else:
580
+ if not all(isinstance(x, type(r1[key][0])) for x in r1[key]):
581
+ r1[key] = array(value, dtype="object")
582
+
583
+ if return_struct:
584
+ return r1
585
+
586
+ if Path(filename).suffix != ".mat":
587
+ filename += ".mat"
588
+ # scipy.io.savemat doesn't do cells properly:
589
+ # https://github.com/scipy/scipy/issues/3756
590
+ # rather than fiddling we just use matlab
591
+ loader = wrappers.MatlabWrapper.loader
592
+ if loader is None:
593
+ raise ImportError("matlabengine is not installed.")
594
+ eng = loader.result()
595
+ eng.workspace["problem"] = r1
596
+ eng.save(str(filename), "problem", nargout=0)
597
+ return None
@@ -0,0 +1,40 @@
1
+ """Defines routines for custom error handling in RAT."""
2
+
3
+ import pydantic_core
4
+
5
+
6
+ def custom_pydantic_validation_error(
7
+ error_list: list[pydantic_core.ErrorDetails],
8
+ custom_error_msgs: dict[str, str] | None = None,
9
+ ) -> list[pydantic_core.ErrorDetails]:
10
+ """Give Pydantic errors a better custom message with extraneous information removed.
11
+
12
+ We substitute the standard error for a PydanticCustomError for a given set of error types.
13
+ For errors that do not have a custom error message defined,
14
+ we redefine them using a PydanticCustomError to remove the url from the error message.
15
+
16
+ Parameters
17
+ ----------
18
+ error_list : list[pydantic_core.ErrorDetails]
19
+ A list of errors produced by pydantic.ValidationError.errors().
20
+ custom_error_msgs: dict[str, str], optional
21
+ A dict of custom error messages for given error types.
22
+
23
+ Returns
24
+ -------
25
+ new_error : list[pydantic_core.ErrorDetails]
26
+ A list of errors including PydanticCustomErrors in place of the error types in custom_errors.
27
+
28
+ """
29
+ if custom_error_msgs is None:
30
+ custom_error_msgs = {}
31
+ custom_error_list = []
32
+ for error in error_list:
33
+ if error["type"] in custom_error_msgs:
34
+ custom_error = pydantic_core.PydanticCustomError(error["type"], custom_error_msgs[error["type"]])
35
+ else:
36
+ custom_error = pydantic_core.PydanticCustomError(error["type"], error["msg"])
37
+ error["type"] = custom_error
38
+ custom_error_list.append(error)
39
+
40
+ return custom_error_list