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