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
ratapi/project.py ADDED
@@ -0,0 +1,1091 @@
1
+ """The project module. Defines and stores all the input data required for reflectivity calculations in RAT."""
2
+
3
+ import collections
4
+ import copy
5
+ import functools
6
+ import json
7
+ import warnings
8
+ from collections.abc import Callable
9
+ from enum import Enum
10
+ from pathlib import Path
11
+ from textwrap import indent
12
+ from typing import Annotated, Any, get_args, get_origin
13
+
14
+ import numpy as np
15
+ from pydantic import (
16
+ BaseModel,
17
+ Discriminator,
18
+ Field,
19
+ Tag,
20
+ ValidationError,
21
+ ValidationInfo,
22
+ field_validator,
23
+ model_validator,
24
+ )
25
+
26
+ import ratapi.models
27
+ from ratapi.classlist import ClassList
28
+ from ratapi.utils.custom_errors import custom_pydantic_validation_error
29
+ from ratapi.utils.enums import Calculations, Geometries, LayerModels, Priors, TypeOptions
30
+
31
+
32
+ # note for these discriminators that the before-validator discriminate_ambiguous_dicts
33
+ # guarantees we don't run into the ambiguous case of a sequence of dicts
34
+ def discriminate_layers(layer_input):
35
+ """Union discriminator for layers."""
36
+ if isinstance(layer_input, collections.abc.Sequence):
37
+ # if classlist is empty, just label it as no absorption and it'll get fixed in post_init
38
+ if len(layer_input) > 0 and isinstance(layer_input[0], ratapi.models.AbsorptionLayer):
39
+ return "abs"
40
+ return "no_abs"
41
+
42
+
43
+ def discriminate_contrasts(contrast_input):
44
+ """Union discriminator for contrasts."""
45
+ if isinstance(contrast_input, collections.abc.Sequence):
46
+ # if classlist is empty, just label it as no ratio and it'll get fixed in post_init
47
+ if len(contrast_input) > 0 and isinstance(contrast_input[0], ratapi.models.ContrastWithRatio):
48
+ return "ratio"
49
+ return "no_ratio"
50
+
51
+
52
+ values_defined_in = {
53
+ "backgrounds.value_1": "background_parameters",
54
+ "backgrounds.value_2": "background_parameters",
55
+ "backgrounds.value_3": "background_parameters",
56
+ "backgrounds.value_4": "background_parameters",
57
+ "backgrounds.value_5": "background_parameters",
58
+ "backgrounds.constant.source": "background_parameters",
59
+ "backgrounds.data.source": "data",
60
+ "backgrounds.function.source": "custom_files",
61
+ "resolutions.value_1": "resolution_parameters",
62
+ "resolutions.value_2": "resolution_parameters",
63
+ "resolutions.value_3": "resolution_parameters",
64
+ "resolutions.value_4": "resolution_parameters",
65
+ "resolutions.value_5": "resolution_parameters",
66
+ "resolutions.constant.source": "resolution_parameters",
67
+ "resolutions.function.source": "custom_files",
68
+ "layers.thickness": "parameters",
69
+ "layers.SLD": "parameters",
70
+ "layers.SLD_real": "parameters",
71
+ "layers.SLD_imaginary": "parameters",
72
+ "layers.roughness": "parameters",
73
+ "contrasts.data": "data",
74
+ "contrasts.background": "backgrounds",
75
+ "contrasts.bulk_in": "bulk_in",
76
+ "contrasts.bulk_out": "bulk_out",
77
+ "contrasts.scalefactor": "scalefactors",
78
+ "contrasts.resolution": "resolutions",
79
+ "contrasts.domain_ratio": "domain_ratios",
80
+ }
81
+
82
+ AllFields = collections.namedtuple("AllFields", ["attribute", "fields"])
83
+ model_names_used_in = {
84
+ "background_parameters": [
85
+ AllFields("backgrounds", ["source", "value_1", "value_2", "value_3", "value_4", "value_5"])
86
+ ],
87
+ "resolution_parameters": [
88
+ AllFields("resolutions", ["source", "value_1", "value_2", "value_3", "value_4", "value_5"])
89
+ ],
90
+ "parameters": [AllFields("layers", ["thickness", "SLD", "SLD_real", "SLD_imaginary", "roughness", "hydration"])],
91
+ "data": [
92
+ AllFields("contrasts", ["data"]),
93
+ AllFields("backgrounds", ["source"]),
94
+ ],
95
+ "custom_files": [AllFields("backgrounds", ["source"]), AllFields("resolutions", ["source"])],
96
+ "backgrounds": [AllFields("contrasts", ["background"])],
97
+ "bulk_in": [AllFields("contrasts", ["bulk_in"])],
98
+ "bulk_out": [AllFields("contrasts", ["bulk_out"])],
99
+ "scalefactors": [AllFields("contrasts", ["scalefactor"])],
100
+ "domain_ratios": [AllFields("contrasts", ["domain_ratio"])],
101
+ "resolutions": [AllFields("contrasts", ["resolution"])],
102
+ }
103
+
104
+ # Note that the order of these parameters is hard-coded into RAT
105
+ parameter_class_lists = [
106
+ "parameters",
107
+ "background_parameters",
108
+ "scalefactors",
109
+ "bulk_in",
110
+ "bulk_out",
111
+ "resolution_parameters",
112
+ "domain_ratios",
113
+ ]
114
+ class_lists = [
115
+ *parameter_class_lists,
116
+ "backgrounds",
117
+ "resolutions",
118
+ "custom_files",
119
+ "data",
120
+ "layers",
121
+ "domain_contrasts",
122
+ "contrasts",
123
+ ]
124
+
125
+
126
+ class Project(BaseModel, validate_assignment=True, extra="forbid", use_attribute_docstrings=True):
127
+ """Defines the input data for a reflectivity calculation in RAT.
128
+
129
+ This class combines the data defined in each of the pydantic models included in "models.py" into the full set of
130
+ inputs required for a reflectivity calculation.
131
+ """
132
+
133
+ name: str = ""
134
+ """The name of the project."""
135
+
136
+ calculation: Calculations = Calculations.Normal
137
+ """What calculation type should be used. Can be 'normal' or 'domains'."""
138
+
139
+ model: LayerModels = LayerModels.StandardLayers
140
+ """What layer model should be used. Can be 'standard layers', 'custom layers', or 'custom xy'."""
141
+
142
+ geometry: Geometries = Geometries.AirSubstrate
143
+ """What geometry should be used. Can be 'air/substrate' or 'substrate/liquid'"""
144
+
145
+ absorption: bool = False
146
+ """Whether imaginary SLD (absorption) should be accounted for."""
147
+
148
+ parameters: ClassList[ratapi.models.Parameter] = ClassList()
149
+ """The list of parameters used in the layers of a model."""
150
+
151
+ bulk_in: ClassList[ratapi.models.Parameter] = ClassList(
152
+ ratapi.models.Parameter(
153
+ name="SLD Air",
154
+ min=0.0,
155
+ value=0.0,
156
+ max=0.0,
157
+ fit=False,
158
+ prior_type=Priors.Uniform,
159
+ mu=0.0,
160
+ sigma=np.inf,
161
+ ),
162
+ )
163
+ """The list of parameters for SLD of the entry interfaces of a model."""
164
+
165
+ bulk_out: ClassList[ratapi.models.Parameter] = ClassList(
166
+ ratapi.models.Parameter(
167
+ name="SLD D2O",
168
+ min=6.2e-6,
169
+ value=6.35e-6,
170
+ max=6.35e-6,
171
+ fit=False,
172
+ prior_type=Priors.Uniform,
173
+ mu=0.0,
174
+ sigma=np.inf,
175
+ ),
176
+ )
177
+ """The list of parameters for SLD of the exit interfaces of a model."""
178
+
179
+ scalefactors: ClassList[ratapi.models.Parameter] = ClassList(
180
+ ratapi.models.Parameter(
181
+ name="Scalefactor 1",
182
+ min=0.02,
183
+ value=0.23,
184
+ max=0.25,
185
+ fit=False,
186
+ prior_type=Priors.Uniform,
187
+ mu=0.0,
188
+ sigma=np.inf,
189
+ ),
190
+ )
191
+ """The list of parameters for scale factors to handle systematic error in model data."""
192
+
193
+ domain_ratios: ClassList[ratapi.models.Parameter] = ClassList(
194
+ ratapi.models.Parameter(
195
+ name="Domain Ratio 1",
196
+ min=0.4,
197
+ value=0.5,
198
+ max=0.6,
199
+ fit=False,
200
+ prior_type=Priors.Uniform,
201
+ mu=0.0,
202
+ sigma=np.inf,
203
+ ),
204
+ )
205
+ """The list of parameters for weighting between domains of a domains model."""
206
+
207
+ background_parameters: ClassList[ratapi.models.Parameter] = ClassList(
208
+ ratapi.models.Parameter(
209
+ name="Background Param 1",
210
+ min=1e-7,
211
+ value=1e-6,
212
+ max=1e-5,
213
+ fit=False,
214
+ prior_type=Priors.Uniform,
215
+ mu=0.0,
216
+ sigma=np.inf,
217
+ ),
218
+ )
219
+ """The list of parameters for models of backgrounds."""
220
+
221
+ backgrounds: ClassList[ratapi.models.Background] = ClassList(
222
+ ratapi.models.Background(name="Background 1", type=TypeOptions.Constant, source="Background Param 1"),
223
+ )
224
+ """The list of models for background noise in the project."""
225
+
226
+ resolution_parameters: ClassList[ratapi.models.Parameter] = ClassList(
227
+ ratapi.models.Parameter(
228
+ name="Resolution Param 1",
229
+ min=0.01,
230
+ value=0.03,
231
+ max=0.05,
232
+ fit=False,
233
+ prior_type=Priors.Uniform,
234
+ mu=0.0,
235
+ sigma=np.inf,
236
+ ),
237
+ )
238
+ """The list of parameters for models of resolutions."""
239
+
240
+ resolutions: ClassList[ratapi.models.Resolution] = ClassList(
241
+ ratapi.models.Resolution(name="Resolution 1", type=TypeOptions.Constant, source="Resolution Param 1"),
242
+ )
243
+ """The list of models for instrument resolution in the project."""
244
+
245
+ custom_files: ClassList[ratapi.models.CustomFile] = ClassList()
246
+ """Handles for custom files used by the project."""
247
+
248
+ data: ClassList[ratapi.models.Data] = ClassList()
249
+ """Experimental data for a model."""
250
+
251
+ layers: (
252
+ Annotated[ClassList[ratapi.models.Layer], Tag("no_abs")]
253
+ | Annotated[ClassList[ratapi.models.AbsorptionLayer], Tag("abs")]
254
+ ) = Field(
255
+ default=ClassList(),
256
+ discriminator=Discriminator(
257
+ discriminate_layers,
258
+ custom_error_type="invalid_union_member",
259
+ custom_error_message="Input should be an instance of ClassList",
260
+ custom_error_context={"discriminator": "absorption_or_no"},
261
+ ),
262
+ )
263
+ """The layers of a standard layer model."""
264
+
265
+ domain_contrasts: ClassList[ratapi.models.DomainContrast] = ClassList()
266
+ """The groups of layers required by each domain in a domains model."""
267
+
268
+ contrasts: (
269
+ Annotated[ClassList[ratapi.models.Contrast], Tag("no_ratio")]
270
+ | Annotated[ClassList[ratapi.models.ContrastWithRatio], Tag("ratio")]
271
+ ) = Field(
272
+ default=ClassList(),
273
+ discriminator=Discriminator(
274
+ discriminate_contrasts,
275
+ custom_error_type="invalid_union_member",
276
+ custom_error_message="Input should be an instance of ClassList.",
277
+ custom_error_context={"discriminator": "ratio_or_no_ratio"},
278
+ ),
279
+ )
280
+ """All groups of components used to define each model in the project."""
281
+
282
+ _all_names: dict
283
+ _contrast_model_field: str
284
+ _protected_parameters: dict
285
+
286
+ @model_validator(mode="before")
287
+ @classmethod
288
+ def discriminate_ambiguous_dicts(cls, data: Any) -> Any:
289
+ """If layers or contrasts contain a dict, convert it to the relevant model."""
290
+ # pydantic docs says data can be anything, but i can't see anywhere where it isn't a dict.
291
+ # if it's not a dict, just return and let the library handle it
292
+ if isinstance(data, dict):
293
+ layer_model = ratapi.models.AbsorptionLayer if data.get("absorption", False) else ratapi.models.Layer
294
+ if data.get("calculation", Calculations.Normal) == Calculations.Domains:
295
+ contrast_model = ratapi.models.ContrastWithRatio
296
+ else:
297
+ contrast_model = ratapi.models.Contrast
298
+
299
+ # note we aren't modifying the layers and contrasts in-place:
300
+ # if a ClassList of dicts is passed, in-place conversion would make the ClassList heterogenous
301
+ # & it'd throw an error
302
+ if layers := data.get("layers", False):
303
+ new_layers = ClassList()
304
+ for layer in layers:
305
+ if isinstance(layer, dict):
306
+ layer = layer_model.model_validate(layer)
307
+ new_layers.append(layer)
308
+ data["layers"] = new_layers
309
+
310
+ if contrasts := data.get("contrasts", False):
311
+ new_contrasts = ClassList()
312
+ for contrast in contrasts:
313
+ if isinstance(contrast, dict):
314
+ contrast = contrast_model.model_validate(contrast)
315
+ new_contrasts.append(contrast)
316
+ data["contrasts"] = new_contrasts
317
+
318
+ return data
319
+
320
+ @field_validator("layers")
321
+ @classmethod
322
+ def check_layers(cls, value: ClassList, info: ValidationInfo):
323
+ """Check that layers are AbsorptionLayers if doing absorption, and Layers otherwise."""
324
+ if info.data["absorption"]:
325
+ model_name = "AbsorptionLayer"
326
+ other_model = "Layer"
327
+ else:
328
+ model_name = "Layer"
329
+ other_model = "AbsorptionLayer"
330
+ model = getattr(ratapi.models, model_name)
331
+ if not all(isinstance(element, model) for element in value):
332
+ raise ValueError(
333
+ f'"The layers attribute contains {other_model}s, '
334
+ f"but the absorption parameter is {info.data['absorption']}. "
335
+ f'The attribute should be a ClassList of {model_name} instead."'
336
+ )
337
+
338
+ return value
339
+
340
+ @field_validator("contrasts")
341
+ @classmethod
342
+ def check_contrasts(cls, value: ClassList, info: ValidationInfo):
343
+ """Check that contrasts are with ratio if calculating domains, and without otherwise."""
344
+ if info.data["calculation"] == Calculations.Domains:
345
+ model_name = "ContrastWithRatio"
346
+ error_word = "without"
347
+ else:
348
+ model_name = "Contrast"
349
+ error_word = "with"
350
+ model = getattr(ratapi.models, model_name)
351
+ if not all(isinstance(element, model) for element in value):
352
+ raise ValueError(
353
+ f'"The contrasts attribute contains contrasts {error_word} ratio, '
354
+ f'but the calculation is {str(info.data["calculation"])}", '
355
+ f"The attribute should be a ClassList of {model_name} instead."
356
+ )
357
+
358
+ return value
359
+
360
+ def model_post_init(self, __context: Any) -> None:
361
+ """Set up the Class to protect against disallowed modification.
362
+
363
+ We initialise the class handle in the ClassLists for empty data fields, set protected parameters, get names of
364
+ all defined parameters, determine the contents of the "model" field in contrasts, and wrap ClassList routines
365
+ to control revalidation.
366
+ """
367
+ # Ensure all ClassLists have the correct _class_handle defined
368
+ for field in (fields := Project.model_fields):
369
+ annotation = fields[field].annotation
370
+ if get_origin(annotation) == ClassList:
371
+ classlist = getattr(self, field)
372
+ if not hasattr(field, "_class_handle"):
373
+ classlist._class_handle = get_args(annotation)[0]
374
+
375
+ layers_field = self.layers
376
+ if not hasattr(layers_field, "_class_handle"):
377
+ if self.absorption:
378
+ layers_field._class_handle = ratapi.models.AbsorptionLayer
379
+ else:
380
+ layers_field._class_handle = ratapi.models.Layer
381
+
382
+ contrast_field = self.contrasts
383
+ if not hasattr(contrast_field, "_class_handle"):
384
+ if self.calculation == Calculations.Domains:
385
+ contrast_field._class_handle = ratapi.models.ContrastWithRatio
386
+ else:
387
+ contrast_field._class_handle = ratapi.models.Contrast
388
+
389
+ if "Substrate Roughness" not in [name.title() for name in self.parameters.get_names()]:
390
+ self.parameters.insert(
391
+ 0,
392
+ ratapi.models.ProtectedParameter(
393
+ name="Substrate Roughness",
394
+ min=1.0,
395
+ value=3.0,
396
+ max=5.0,
397
+ fit=True,
398
+ prior_type=ratapi.models.Priors.Uniform,
399
+ mu=0.0,
400
+ sigma=np.inf,
401
+ ),
402
+ )
403
+ elif "Substrate Roughness" not in [name.title() for name in self.get_all_protected_parameters()["parameters"]]:
404
+ # If substrate roughness is included as a standard parameter replace it with a protected parameter
405
+ substrate_roughness_values = self.parameters["Substrate Roughness"].model_dump()
406
+ self.parameters.remove("Substrate Roughness")
407
+ self.parameters.insert(0, ratapi.models.ProtectedParameter(**substrate_roughness_values))
408
+
409
+ if "Simulation" not in [name.title() for name in self.data.get_names()]:
410
+ self.data.insert(0, ratapi.models.Data(name="Simulation", simulation_range=[0.005, 0.7]))
411
+
412
+ self._all_names = self.get_all_names()
413
+ self._contrast_model_field = self.get_contrast_model_field()
414
+ self._protected_parameters = self.get_all_protected_parameters()
415
+
416
+ # Wrap ClassList routines - when any of these routines are called, the wrapper will force revalidation of the
417
+ # model, handle errors and reset previous values if necessary.
418
+ methods_to_wrap = [
419
+ "_setitem",
420
+ "_delitem",
421
+ "_iadd",
422
+ "append",
423
+ "insert",
424
+ "pop",
425
+ "remove",
426
+ "clear",
427
+ "extend",
428
+ "set_fields",
429
+ ]
430
+
431
+ for class_list in class_lists:
432
+ attribute = getattr(self, class_list)
433
+ for methodName in methods_to_wrap:
434
+ setattr(attribute, methodName, self._classlist_wrapper(attribute, getattr(attribute, methodName)))
435
+
436
+ @model_validator(mode="after")
437
+ def set_domain_ratios(self) -> "Project":
438
+ """If we are not running a domains calculation, ensure the domain_ratios component of the model is empty."""
439
+ if self.calculation != Calculations.Domains:
440
+ self.domain_ratios.data = []
441
+ return self
442
+
443
+ @model_validator(mode="after")
444
+ def set_domain_contrasts(self) -> "Project":
445
+ """Ensure ``domain_contrasts`` is empty if we are not running a standard layer domains calculation."""
446
+ if not (self.calculation == Calculations.Domains and self.model == LayerModels.StandardLayers):
447
+ self.domain_contrasts.data = []
448
+ return self
449
+
450
+ @model_validator(mode="after")
451
+ def set_layers(self) -> "Project":
452
+ """If we are not using a standard layers model, ensure the layers component of the model is empty."""
453
+ if self.model != LayerModels.StandardLayers:
454
+ self.layers.data = []
455
+ return self
456
+
457
+ @model_validator(mode="after")
458
+ def set_repeat_layers(self) -> "Project":
459
+ """If we are not using a standard layers model, warn that the repeat layers setting is not valid."""
460
+ if self.model != LayerModels.StandardLayers:
461
+ for contrast in self.contrasts:
462
+ if "repeat_layers" in contrast.model_fields_set and contrast.repeat_layers != 1:
463
+ warnings.warn(
464
+ 'For a custom layers or custom XY calculation, the "repeat_layers" setting for each '
465
+ "contrast is not valid - resetting to 1.",
466
+ stacklevel=2,
467
+ )
468
+ contrast.repeat_layers = 1
469
+ return self
470
+
471
+ @model_validator(mode="after")
472
+ def set_resample(self) -> "Project":
473
+ """If we are using a custom XY model, warn that the resample setting for each contrast must always be True."""
474
+ if self.model == LayerModels.CustomXY:
475
+ for contrast in self.contrasts:
476
+ if "resample" in contrast.model_fields_set and contrast.resample is False:
477
+ warnings.warn(
478
+ 'For a custom XY calculation, "resample" must be True for each contrast - resetting to True.',
479
+ stacklevel=2,
480
+ )
481
+ contrast.resample = True
482
+ return self
483
+
484
+ @model_validator(mode="after")
485
+ def set_calculation(self) -> "Project":
486
+ """Apply the calc setting to the project."""
487
+ contrast_list = []
488
+ handle = self.contrasts._class_handle.__name__
489
+ if self.calculation == Calculations.Domains and handle == "Contrast":
490
+ for contrast in self.contrasts:
491
+ contrast_list.append(ratapi.models.ContrastWithRatio(**contrast.model_dump()))
492
+ self.contrasts.data = contrast_list
493
+ self.domain_ratios.data = [
494
+ ratapi.models.Parameter(
495
+ name="Domain Ratio 1",
496
+ min=0.4,
497
+ value=0.5,
498
+ max=0.6,
499
+ fit=False,
500
+ prior_type=ratapi.models.Priors.Uniform,
501
+ mu=0.0,
502
+ sigma=np.inf,
503
+ ),
504
+ ]
505
+ self.contrasts._class_handle = ratapi.models.ContrastWithRatio
506
+ elif self.calculation != Calculations.Domains and handle == "ContrastWithRatio":
507
+ for contrast in self.contrasts:
508
+ contrast_params = contrast.model_dump()
509
+ del contrast_params["domain_ratio"]
510
+ contrast_list.append(ratapi.models.Contrast(**contrast_params))
511
+ self.contrasts.data = contrast_list
512
+ self.contrasts._class_handle = ratapi.models.Contrast
513
+ return self
514
+
515
+ @model_validator(mode="after")
516
+ def set_contrast_model_field(self) -> "Project":
517
+ """Clear the contrast models if ``calculation`` or ``model_type`` has changed.
518
+
519
+ The contents of the "model" field of "contrasts" depend on the values of the "calculation" and "model_type"
520
+ defined in the project.
521
+ """
522
+ model_field = self.get_contrast_model_field()
523
+ if model_field != self._contrast_model_field:
524
+ for contrast in self.contrasts:
525
+ contrast.model = []
526
+ self._contrast_model_field = model_field
527
+ return self
528
+
529
+ @model_validator(mode="after")
530
+ def check_contrast_model_length(self) -> "Project":
531
+ """Ensure the contrast model isn't too long for a domains, custom layers, or custom XY calculation.
532
+
533
+ If a custom model is used, the ``model`` field of the contrast should just be one item long. For
534
+ a standard layers domain calculation, it should be exactly two items long.
535
+ """
536
+ if self.model == LayerModels.StandardLayers and self.calculation == Calculations.Domains:
537
+ for contrast in self.contrasts:
538
+ if contrast.model and len(contrast.model) != 2:
539
+ raise ValueError(
540
+ 'For a standard layers domains calculation the "model" field of "contrasts" must '
541
+ "contain exactly two values.",
542
+ )
543
+ elif self.model != LayerModels.StandardLayers:
544
+ for contrast in self.contrasts:
545
+ if len(contrast.model) > 1:
546
+ raise ValueError(
547
+ 'For a custom model calculation the "model" field of "contrasts" cannot contain '
548
+ "more than one value.",
549
+ )
550
+ return self
551
+
552
+ @model_validator(mode="after")
553
+ def set_absorption(self) -> "Project":
554
+ """Apply the absorption setting to the project."""
555
+ layer_list = []
556
+ handle = self.layers._class_handle.__name__
557
+ if self.absorption and handle == "Layer":
558
+ for layer in self.layers:
559
+ layer_params = layer.model_dump()
560
+ layer_params["SLD_imaginary"] = ""
561
+ layer_list.append(ratapi.models.AbsorptionLayer(**layer_params))
562
+ self.layers.data = layer_list
563
+ self.layers._class_handle = ratapi.models.AbsorptionLayer
564
+ elif not self.absorption and handle == "AbsorptionLayer":
565
+ for layer in self.layers:
566
+ layer_params = layer.model_dump()
567
+ del layer_params["SLD_imaginary"]
568
+ layer_list.append(ratapi.models.Layer(**layer_params))
569
+ self.layers.data = layer_list
570
+ self.layers._class_handle = ratapi.models.Layer
571
+ return self
572
+
573
+ @model_validator(mode="after")
574
+ def update_renamed_models(self) -> "Project":
575
+ """When models defined in the ClassLists are renamed, we need to update that name elsewhere in the project."""
576
+ for class_list, fields_to_update in model_names_used_in.items():
577
+ old_names = self._all_names[class_list]
578
+ new_names = getattr(self, class_list).get_names()
579
+ if len(old_names) == len(new_names):
580
+ name_diff = [(old, new) for (old, new) in zip(old_names, new_names, strict=False) if old != new]
581
+ for old_name, new_name in name_diff:
582
+ for field in fields_to_update:
583
+ project_field = getattr(self, field.attribute)
584
+ all_matches = project_field.get_all_matches(old_name)
585
+ params = field.fields
586
+ for index, param in all_matches:
587
+ if param in params:
588
+ setattr(project_field[index], param, new_name)
589
+ return self
590
+
591
+ @model_validator(mode="after")
592
+ def cross_check_model_values(self) -> "Project":
593
+ """Certain model fields should contain values defined elsewhere in the project."""
594
+ values = ["value_1", "value_2", "value_3", "value_4", "value_5"]
595
+ for field in ["backgrounds", "resolutions"]:
596
+ self.check_allowed_source(field)
597
+ self.check_allowed_values(
598
+ field,
599
+ values,
600
+ getattr(self, f"{field[:-1]}_parameters").get_names(),
601
+ self._all_names[f"{field[:-1]}_parameters"],
602
+ )
603
+
604
+ self.check_allowed_values(
605
+ "layers",
606
+ ["thickness", "SLD", "SLD_real", "SLD_imaginary", "roughness"],
607
+ self.parameters.get_names(),
608
+ self._all_names["parameters"],
609
+ )
610
+
611
+ self.check_allowed_values("contrasts", ["data"], self.data.get_names(), self._all_names["data"])
612
+ self.check_allowed_values(
613
+ "contrasts", ["background"], self.backgrounds.get_names(), self._all_names["backgrounds"]
614
+ )
615
+ self.check_allowed_values("contrasts", ["bulk_in"], self.bulk_in.get_names(), self._all_names["bulk_in"])
616
+ self.check_allowed_values("contrasts", ["bulk_out"], self.bulk_out.get_names(), self._all_names["bulk_out"])
617
+ self.check_allowed_values(
618
+ "contrasts", ["scalefactor"], self.scalefactors.get_names(), self._all_names["scalefactors"]
619
+ )
620
+ self.check_allowed_values(
621
+ "contrasts", ["resolution"], self.resolutions.get_names(), self._all_names["resolutions"]
622
+ )
623
+ self.check_allowed_values(
624
+ "contrasts", ["domain_ratio"], self.domain_ratios.get_names(), self._all_names["domain_ratios"]
625
+ )
626
+
627
+ self.check_contrast_model_allowed_values(
628
+ "contrasts",
629
+ getattr(self, self._contrast_model_field).get_names(),
630
+ self._all_names[self._contrast_model_field],
631
+ self._contrast_model_field,
632
+ )
633
+ self.check_contrast_model_allowed_values(
634
+ "domain_contrasts", self.layers.get_names(), self._all_names["layers"], "layers"
635
+ )
636
+ return self
637
+
638
+ @model_validator(mode="after")
639
+ def check_protected_parameters(self) -> "Project":
640
+ """Protected parameters should not be deleted. If this is attempted, raise an error."""
641
+ for class_list in parameter_class_lists:
642
+ protected_parameters = [
643
+ param.name for param in getattr(self, class_list) if isinstance(param, ratapi.models.ProtectedParameter)
644
+ ]
645
+ # All previously existing protected parameters should be present in new list
646
+ if not all(element in protected_parameters for element in self._protected_parameters[class_list]):
647
+ removed_params = [
648
+ param for param in self._protected_parameters[class_list] if param not in protected_parameters
649
+ ]
650
+ raise ValueError(f"Can't delete the protected parameters: {', '.join(str(i) for i in removed_params)}")
651
+ self._protected_parameters = self.get_all_protected_parameters()
652
+ return self
653
+
654
+ @model_validator(mode="after")
655
+ def update_names(self) -> "Project":
656
+ """Following validation, update the list of all parameter names."""
657
+ self._all_names = self.get_all_names()
658
+ return self
659
+
660
+ def __str__(self):
661
+ output = ""
662
+ for key, value in self.__dict__.items():
663
+ if value:
664
+ output += f"{key.replace('_', ' ').title() + ': ':-<100}\n\n"
665
+ try:
666
+ output += value.value + "\n\n" # For enums
667
+ except AttributeError:
668
+ output += str(value) + "\n\n"
669
+ return output
670
+
671
+ def get_all_names(self):
672
+ """Record the names of all models defined in the project."""
673
+ return {class_list: getattr(self, class_list).get_names() for class_list in class_lists}
674
+
675
+ def get_all_protected_parameters(self):
676
+ """Record the protected parameters defined in the project."""
677
+ return {
678
+ class_list: [
679
+ param.name for param in getattr(self, class_list) if isinstance(param, ratapi.models.ProtectedParameter)
680
+ ]
681
+ for class_list in parameter_class_lists
682
+ }
683
+
684
+ def check_allowed_values(
685
+ self, attribute: str, field_list: list[str], allowed_values: list[str], previous_values: list[str]
686
+ ) -> None:
687
+ """Check the values of the given fields in the given model are in the supplied list of allowed values.
688
+
689
+ Parameters
690
+ ----------
691
+ attribute : str
692
+ The attribute of Project being validated.
693
+ field_list : list [str]
694
+ The fields of the attribute to be checked for valid values.
695
+ allowed_values : list [str]
696
+ The list of allowed values for the fields given in field_list.
697
+ previous_values : list [str]
698
+ The list of allowed values for the fields given in field_list after the previous validation.
699
+
700
+ Raises
701
+ ------
702
+ ValueError
703
+ Raised if any field in field_list has a value not specified in allowed_values.
704
+
705
+ """
706
+ class_list = getattr(self, attribute)
707
+ for index, model in enumerate(class_list):
708
+ for field in field_list:
709
+ value = getattr(model, field, "")
710
+ if value and value not in allowed_values:
711
+ if value in previous_values:
712
+ raise ValueError(
713
+ f'The value "{value}" used in the "{field}" field of {attribute}[{index}] must be defined '
714
+ f'in "{values_defined_in[f"{attribute}.{field}"]}". Please remove "{value}" from '
715
+ f'"{attribute}[{index}].{field}" before attempting to delete it.',
716
+ )
717
+ else:
718
+ raise ValueError(
719
+ f'The value "{value}" used in the "{field}" field of {attribute}[{index}] must be defined '
720
+ f'in "{values_defined_in[f"{attribute}.{field}"]}". Please add "{value}" to '
721
+ f'"{values_defined_in[f"{attribute}.{field}"]}" before including it in "{attribute}".',
722
+ )
723
+
724
+ def check_allowed_source(self, attribute: str) -> None:
725
+ """Check that the source of a background or resolution is defined in the relevant field for its type.
726
+
727
+ - A constant background or resolution source should be defined in
728
+ `background_parameters` or `resolution_parameters` respectively;
729
+ - A data background source should be defined in `data`
730
+ - A function background source should be defined in `custom_files`
731
+
732
+ Parameters
733
+ ----------
734
+ attribute : str
735
+ The attribute of Project being validated.
736
+
737
+ Raises
738
+ ------
739
+ ValueError
740
+ Raised if any field in field_list has a value not specified in allowed_constants or allowed_data as
741
+ appropriate.
742
+
743
+ """
744
+ class_list = getattr(self, attribute)
745
+ for index, model in enumerate(class_list):
746
+ if model.type == TypeOptions.Constant:
747
+ allowed_values = getattr(self, f"{attribute[:-1]}_parameters").get_names()
748
+ previous_values = self._all_names[f"{attribute[:-1]}_parameters"]
749
+ elif model.type == TypeOptions.Data:
750
+ allowed_values = self.data.get_names()
751
+ previous_values = self._all_names["data"]
752
+ else:
753
+ allowed_values = self.custom_files.get_names()
754
+ previous_values = self._all_names["custom_files"]
755
+
756
+ if (value := model.source) != "" and value not in allowed_values:
757
+ if value in previous_values:
758
+ raise ValueError(
759
+ f'The value "{value}" used in the "source" field of {attribute}[{index}] must be defined in '
760
+ f'"{values_defined_in[f"{attribute}.{model.type}.source"]}". Please remove "{value}" from '
761
+ f'"{attribute}[{index}].source" before attempting to delete it.',
762
+ )
763
+ else:
764
+ raise ValueError(
765
+ f'The value "{value}" used in the "source" field of {attribute}[{index}] must be defined in '
766
+ f'"{values_defined_in[f"{attribute}.{model.type}.source"]}". Please add "{value}" to '
767
+ f'"{values_defined_in[f"{attribute}.{model.type}.source"]}" before including it in '
768
+ f'"{attribute}".',
769
+ )
770
+
771
+ def check_contrast_model_allowed_values(
772
+ self,
773
+ contrast_attribute: str,
774
+ allowed_values: list[str],
775
+ previous_values: list[str],
776
+ allowed_field: str,
777
+ ) -> None:
778
+ """Ensure the contents of the ``model`` for a contrast or domain contrast exist in the required project fields.
779
+
780
+ Parameters
781
+ ----------
782
+ contrast_attribute : str
783
+ The specific contrast attribute of Project being validated (either "contrasts" or "domain_contrasts").
784
+ allowed_values : list [str]
785
+ The list of allowed values for the model of the contrast_attribute.
786
+ previous_values : list [str]
787
+ The list of allowed values for the model of the contrast_attribute after the previous validation.
788
+ allowed_field : str
789
+ The name of the field in the project in which the allowed_values are defined.
790
+
791
+ Raises
792
+ ------
793
+ ValueError
794
+ Raised if any model in contrast_attribute has a value not specified in allowed_values.
795
+
796
+ """
797
+ class_list = getattr(self, contrast_attribute)
798
+ for index, contrast in enumerate(class_list):
799
+ if (model_values := contrast.model) and (missing_values := list(set(model_values) - set(allowed_values))):
800
+ if all(value in previous_values for value in model_values):
801
+ raise ValueError(
802
+ f"The value{'s' if len(missing_values) > 1 else ''}: "
803
+ f'"{", ".join(str(i) for i in missing_values)}" used in the "model" field of '
804
+ f'{contrast_attribute}[{index}] must be defined in "{allowed_field}". Please remove all '
805
+ f'unnecessary values from "model" before attempting to delete them.',
806
+ )
807
+ else:
808
+ raise ValueError(
809
+ f"The value{'s' if len(missing_values) > 1 else ''}: "
810
+ f'"{", ".join(str(i) for i in missing_values)}" used in the "model" field of '
811
+ f'{contrast_attribute}[{index}] must be defined in "{allowed_field}". Please add all '
812
+ f'required values to "{allowed_field}" before including them in "{contrast_attribute}".',
813
+ )
814
+
815
+ def get_contrast_model_field(self):
816
+ """Get the field used to define the contents of the "model" field in contrasts.
817
+
818
+ Returns
819
+ -------
820
+ model_field : str
821
+ The name of the field used to define the contrasts' model field.
822
+
823
+ """
824
+ if self.model == LayerModels.StandardLayers:
825
+ if self.calculation == Calculations.Domains:
826
+ model_field = "domain_contrasts"
827
+ else:
828
+ model_field = "layers"
829
+ else:
830
+ model_field = "custom_files"
831
+ return model_field
832
+
833
+ def set_prior_visibility(self, priors_visible: bool):
834
+ """Set whether priors are visible or invisible for all parameters.
835
+
836
+ Parameters
837
+ ----------
838
+ priors_visible : bool
839
+ Whether priors should be shown.
840
+
841
+ """
842
+ for classlist_name in parameter_class_lists:
843
+ classlist = getattr(self, classlist_name)
844
+ for i in range(0, len(classlist)):
845
+ classlist[i].show_priors = priors_visible
846
+
847
+ def show_priors(self):
848
+ """Show priors for all parameters in the model."""
849
+ # convenience function from set_prior_visibility
850
+ self.set_prior_visibility(True)
851
+
852
+ def hide_priors(self):
853
+ """Hide priors for all parameters in the model."""
854
+ # convenience function from set_prior_visibility
855
+ self.set_prior_visibility(False)
856
+
857
+ def write_script(self, obj_name: str = "problem", script: str = "project_script.py"):
858
+ """Write a python script that can be run to reproduce this project object.
859
+
860
+ Parameters
861
+ ----------
862
+ obj_name : str, optional
863
+ The name given to the project object under construction (default is "problem").
864
+ script : str, optional
865
+ The filepath of the generated script (default is "project_script.py").
866
+
867
+ """
868
+ # Need to ensure correct format for script name
869
+ script_path = Path(script)
870
+ if script_path.suffix == "":
871
+ script_path = script_path.with_suffix(".py")
872
+ elif script_path.suffix != ".py":
873
+ raise ValueError('The script name provided to "write_script" must use the ".py" format')
874
+
875
+ def write_item(item):
876
+ """Write a model item as a string of a dictionary."""
877
+ if isinstance(item, ratapi.models.Data):
878
+ item_str = "{" + f"'name': '{item.name}',"
879
+ if not np.any(item.data): # if array is empty, e.g. in simulation data
880
+ item_str += "'data': empty([0, 3]), "
881
+ else:
882
+ item_str += f"'data': {repr(item.data)}, "
883
+ if len(item.data_range) != 0:
884
+ item_str += f"'data_range': {item.data_range}, "
885
+ if len(item.simulation_range) != 0:
886
+ item_str += f"'simulation_range': {item.simulation_range}"
887
+ item_str += "}"
888
+ return item_str
889
+
890
+ if isinstance(item, ratapi.models.CustomFile):
891
+ # convert file paths to strings because pathlib gets too specific
892
+ item_str = (
893
+ "{"
894
+ + f"'name': '{item.name}', "
895
+ + f"'filename': '{item.filename}', "
896
+ + f"'function_name': '{item.function_name}', "
897
+ + f"'language': '{str(item.language)}', "
898
+ # Raw string to ensure backslash is not interpreted as escape
899
+ + f"'path': r'{str(try_relative_to(item.path, script_path.parent))}'"
900
+ + "}"
901
+ )
902
+ return item_str
903
+ # converting a dict to a string doesn't automatically convert StrEnums to str :(
904
+ return str({key: str(value) if isinstance(value, Enum) else value for key, value in dict(item).items()})
905
+
906
+ def classlist_script(name, classlist):
907
+ """Write a classlist as a script."""
908
+ return f"{name}=[\n " + "\n ".join([write_item(item) + "," for item in classlist.data]) + "],"
909
+
910
+ script_path.write_text(
911
+ f"""# THIS FILE IS GENERATED FROM RAT VIA THE "WRITE_SCRIPT" ROUTINE. IT IS NOT PART OF THE RAT CODE.
912
+
913
+ import ratapi
914
+ from numpy import array, empty, inf
915
+
916
+ {obj_name} = ratapi.Project(
917
+ name="{self.name}",
918
+ calculation="{self.calculation}",
919
+ model="{self.model}",
920
+ geometry="{self.geometry}",
921
+ absorption="{self.absorption}",
922
+ """
923
+ + indent(
924
+ "\n".join([classlist_script(class_list, getattr(self, class_list)) for class_list in class_lists]),
925
+ " " * 4,
926
+ )
927
+ + "\n)"
928
+ )
929
+
930
+ def to_dict(self):
931
+ """Generate a dictionary representation of the model.
932
+
933
+ Returns
934
+ -------
935
+ model_dict : dict
936
+ A dict containing the model information.
937
+ """
938
+ model_dict = {}
939
+ for field in self.model_fields:
940
+ attr = getattr(self, field)
941
+
942
+ if field == "data":
943
+
944
+ def make_data_dict(item):
945
+ return {
946
+ "name": item.name,
947
+ "data": item.data.tolist(),
948
+ "data_range": item.data_range,
949
+ "simulation_range": item.simulation_range,
950
+ }
951
+
952
+ model_dict["data"] = [make_data_dict(data) for data in attr]
953
+
954
+ elif field == "custom_files":
955
+
956
+ def make_custom_file_dict(item):
957
+ file_dict = {
958
+ "name": item.name,
959
+ "filename": item.filename,
960
+ "language": item.language,
961
+ "path": str(item.path),
962
+ }
963
+ if item.name != item.function_name:
964
+ file_dict["function_name"] = item.function_name
965
+
966
+ return file_dict
967
+
968
+ model_dict["custom_files"] = [make_custom_file_dict(file) for file in attr]
969
+
970
+ elif isinstance(attr, ClassList):
971
+ model_dict[field] = [item.model_dump() for item in attr]
972
+ else:
973
+ model_dict[field] = attr
974
+ return model_dict
975
+
976
+ def save(self, filepath: str | Path = "./project.json"):
977
+ """Save a project to a JSON file.
978
+
979
+ Parameters
980
+ ----------
981
+ filepath : str or Path
982
+ The path to where the project file will be written.
983
+ """
984
+ filepath = Path(filepath).with_suffix(".json")
985
+ json_dict = self.to_dict()
986
+ for file in json_dict["custom_files"]:
987
+ file["path"] = try_relative_to(file["path"], filepath.parent)
988
+ filepath.write_text(json.dumps(json_dict))
989
+
990
+ @classmethod
991
+ def load(cls, path: str | Path) -> "Project":
992
+ """Load a project from file.
993
+
994
+ Parameters
995
+ ----------
996
+ path : str or Path
997
+ The path to the project file.
998
+
999
+ """
1000
+ path = Path(path)
1001
+ input_data = path.read_text()
1002
+ model_dict = json.loads(input_data)
1003
+ for dataset in model_dict["data"]:
1004
+ if dataset["name"] == "Simulation":
1005
+ dataset["data"] = np.empty([0, 3])
1006
+ del dataset["data_range"]
1007
+ else:
1008
+ data = dataset["data"]
1009
+ dataset["data"] = np.array(data)
1010
+
1011
+ # file paths are saved as relative to the project directory
1012
+ for file in model_dict["custom_files"]:
1013
+ if not Path(file["path"]).is_absolute():
1014
+ file["path"] = Path(path.parent, file["path"]).resolve()
1015
+
1016
+ return cls.model_validate(model_dict)
1017
+
1018
+ def _classlist_wrapper(self, class_list: ClassList, func: Callable):
1019
+ """Define the function used to wrap around ClassList routines to force revalidation.
1020
+
1021
+ Parameters
1022
+ ----------
1023
+ class_list : ClassList
1024
+ The ClassList defined in the "Project" model that is being modified.
1025
+ func : Callable
1026
+ The routine being wrapped.
1027
+
1028
+ Returns
1029
+ -------
1030
+ wrapped_func : Callable
1031
+ The wrapped routine.
1032
+
1033
+ """
1034
+
1035
+ @functools.wraps(func)
1036
+ def wrapped_func(*args, **kwargs):
1037
+ """Run the given function and then revalidate the "Project" model.
1038
+
1039
+ If any exception is raised, restore the previous state of the given ClassList
1040
+ and report details of the exception.
1041
+
1042
+ """
1043
+ previous_state = copy.deepcopy(class_list.data)
1044
+ return_value = None
1045
+ try:
1046
+ return_value = func(*args, **kwargs)
1047
+ Project.model_validate(self)
1048
+ except ValidationError as exc:
1049
+ class_list.data = previous_state
1050
+ custom_error_list = custom_pydantic_validation_error(exc.errors(include_url=False))
1051
+ raise ValidationError.from_exception_data(exc.title, custom_error_list, hide_input=True) from None
1052
+ except (TypeError, ValueError):
1053
+ class_list.data = previous_state
1054
+ raise
1055
+ finally:
1056
+ del previous_state
1057
+ return return_value
1058
+
1059
+ return wrapped_func
1060
+
1061
+
1062
+ def try_relative_to(path: Path, relative_to: Path) -> str:
1063
+ """Attempt to create a relative path and warn the user if it isn't possible.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ path : Path
1068
+ The path to try to find a relative path for.
1069
+ relative_to: Path
1070
+ The path to which we find a relative path for ``path``.
1071
+
1072
+ Returns
1073
+ -------
1074
+ str
1075
+ The relative path if successful, else the absolute path.
1076
+
1077
+ """
1078
+ path = Path(path)
1079
+ relative_to = Path(relative_to)
1080
+ if not path.is_absolute():
1081
+ return str(path)
1082
+ elif path.is_relative_to(relative_to):
1083
+ return str(path.relative_to(relative_to))
1084
+ else:
1085
+ warnings.warn(
1086
+ "Could not write custom file path as relative to the project directory, "
1087
+ "which means that it may not work on other devices. If you would like to share your project, "
1088
+ "make sure your custom files are in a subfolder of the project save location.",
1089
+ stacklevel=2,
1090
+ )
1091
+ return str(path.resolve())