-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspectragen4.py
1532 lines (1320 loc) · 61 KB
/
spectragen4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
r"""Package for spectrum generation via crispy 0.7.4 and Quanty.
Usage
1) Download the latest version (right now, this is 0.7.4 - 2024-05-27) from GitHub
https://github.com/mretegan/crispy, unzip it.
2) Download Quanty for Windows https://www.quanty.org/index.html
3) Import this file in your python script
>>> import sys
>>> sys.path.append(r'<path-to-spectragen>\spectragen4')
>>> import spectragen4 as sg4
4) set quanty and crispy filepaths
>>> sg4.settings.QUANTY_FILEPATH = r'C:\Users\galdin_c\github\quanty\quanty_win\QuantyWin64.exe'
>>> sg4.settings.CRISPY_FILEPATH = r'C:\Users\galdin_c\github\crispy-0.7.4'
5) if you want to use it with brixs, set USE_BRIXS to True
>>> sg4.settings.USE_BRIXS = True
6) basic calculation
TO DO:
( ) Check if broaden works with non-monotonic data.
( ) Not sure if broaden works fine. Compare with crispy.
"""
# %% Imports ===================================================================
# standard libraries
from pathlib import Path
import numpy as np
import copy
import sys
import os
import subprocess
# specific libraries
from collections.abc import MutableMapping
import tempfile
import shutil
import gzip
import json
# %% broadening functions ======================================================
def _broaden(self, value):
"""Apply gaussian broadening to spectrum.
Args:
value (number): fwhm value of the gaussian broadening.
Returns:
None
"""
# xScale = np.abs(self.x.min() - self.x.max()) / self.x.shape[0]
# fwhm = float(value)/float(xScale)
self.y = broaden(self.x, self.y, value)
def broaden(x, y, value):
"""Apply gaussian broadening to spectrum.
Args:
value (number): fwhm value of the gaussian broadening.
Returns:
Broadened y
"""
fwhm = value
xScale = np.abs(min(x) - max(x)) / x.shape[0]
fwhm = float(value)/float(xScale)
y = settings.broaden1(y, fwhm, 'gaussian') # broaden1 is loaded with crispy down below
return y
# %% support functions =========================================================
def _normalize(vector):
"""Returns normalized vector."""
if np.linalg.norm(vector) != 1:
return vector/np.linalg.norm(vector)
else:
return vector
# %% settings ==================================================================
class _settings():
def __init__(self):
self._QUANTY_FILEPATH = ''
self._CRISPY_FILEPATH = ''
self._CRISPY_PATH_INDEX = 0
self.default = ''
self._USE_BRIXS = False
@property
def QUANTY_FILEPATH(self):
return self._QUANTY_FILEPATH
@QUANTY_FILEPATH.setter
def QUANTY_FILEPATH(self, value):
value = Path(value)
assert value.exists(), 'Cannot find filepath'
assert value.is_file(), 'filepath does not point to a file'
self._QUANTY_FILEPATH = value
@QUANTY_FILEPATH.deleter
def QUANTY_FILEPATH(self):
raise AttributeError('Cannot delete object.')
@property
def CRISPY_FILEPATH(self):
return self._CRISPY_FILEPATH
@CRISPY_FILEPATH.setter
def CRISPY_FILEPATH(self, value):
# inside <folderpath2crispy> one must find the folders 'crispy', 'docs', 'scripts', etc...
value = Path(value)
assert value.exists(), 'Cannot find filepath'
assert value.is_dir(), 'filepath does not point to a folder'
# delete previously loaded functions
try:
del QuantyCalculation
del broaden1
sys.path.pop(self._CRISPY_PATH_INDEX)
except NameError:
pass
# load crispy functions
self._CRISPY_PATH_INDEX = len(sys.path)
sys.path.append(str(value))
from crispy.gui.quanty import QuantyCalculation
from crispy.gui.quanty import broaden as broaden1
# load crispy settings.default parameters
f = gzip.open(value/r'crispy\modules\quanty\parameters\parameters.json.gz', 'r')
temp = json.load(f)
self.default = temp['elements']
del temp
# save
self.QuantyCalculation = QuantyCalculation
self.broaden1 = broaden1
self._CRISPY_FILEPATH = value
@CRISPY_FILEPATH.deleter
def CRISPY_FILEPATH(self):
raise AttributeError('Cannot delete object.')
@property
def USE_BRIXS(self):
return self._USE_BRIXS
@USE_BRIXS.setter
def USE_BRIXS(self, value):
assert isinstance(value, bool), 'USE_BRIXS must be True or False'
if value:
import brixs as _br
settings._br = _br
settings._br.Spectrum.broaden = _broaden
# save
self._USE_BRIXS = value
@USE_BRIXS.deleter
def USE_BRIXS(self):
raise AttributeError('Cannot delete object.')
settings = _settings()
# %% Operating system ==========================================================
import platform
system = platform.system().lower()
is_windows = system == 'windows'
is_linux = system == 'linux'
is_mac = system == 'darwin'
# %% support classes ===========================================================
class _hamiltonianState(MutableMapping):
def __init__(self, initial):
self.store = dict(initial)
# change from int to bool
for name in self.store:
if self.store[name]:
self.store[name] = True
else:
self.store[name] = False
def __str__(self):
return str(self.store).replace(', ', '\n ')
def __repr__(self):
# return str(self.store)
return str(self.store).replace(', ', '\n ')
def __getitem__(self, name):
return self.store[name]
def __setitem__(self, name, value):
if name not in self:
raise ValueError(f'New terms cannot be created.\nInvalid term: {name}\nValid terms are: {list(self.keys())}')
if value:
self.store[name] = True
else:
self.store[name] = False
self.check_hybridization()
def __delitem__(self, key):
raise AttributeError('Items cannot be deleted')
def __iter__(self):
return iter(self.store)
def __len__(self):
return len({name:self.store[name] for name in self.store if self.store[name] is not None})
def check_hybridization(self):
lmct = False
mlct = False
for item in self.store:
if item.endswith('(LMCT)'):
lmct = self.store[item]
elif item.endswith('(MLCT)'):
mlct = self.store[item]
if lmct and mlct:
for item in self.store:
if item.endswith('(LMCT)') or item.endswith('(MLCT)'):
self.store[item] = False
raise ValueError('Ligands Hybridization LMCT and MLCT cannot be both True.\nSwitching both to False.')
def export(self):
temp = {}
for item in self.store:
if self.store[item]:
temp[item] = 2
else:
temp[item] = 0
return temp
class _hamiltonianData(MutableMapping):
def __init__(self, initial):
self.store = dict(copy.deepcopy(initial))
for key in self.store:
if type(self.store[key]) != float and type(self.store[key]) != list:
self.store[key] = _hamiltonianData(self.store[key])
self.initial = dict(copy.deepcopy(initial))
self.sync = False
def __str__(self):
# toprint = str(self.store).replace('\':', '\':\n'+' '*10).replace(', \'', ', \n'+' '*0+'\'')
# toprint = toprint.replace('(\'Final', '\n'+' '*11+'\'Final').replace('), (\'', ',\n'+' '*20+'\'')
# toprint = toprint.replace('odict([(', '').replace('Hamiltonian\', \'', 'Hamiltonian\',\n'+' '*20+'\'')
# toprint = toprint.replace(')]))])', '')
# toprint = toprint.replace(')]))', '')
# return toprint
i = 8
toprint = str(self.store).replace('\': {\'Initial', '\':\n'+' '*i+'{\'Initial') # initial
toprint = toprint.replace('}, \'Intermediate', '\':\n'+' '*i+'\'Intermediate') # Intermediate
toprint = toprint.replace('}, \'Final', '},\n'+' '*(i+1)+'\'Final') # final
toprint = toprint.replace('}}, \'', '\n \'') # terms
toprint = toprint.replace(', \'', '\n'+' '*i*2 +'\'') # values
toprint = toprint.replace('\': {\'', '\':\n'+' '*i*2 +'\'') # values from the first line
return toprint
def __repr__(self):
return str(self.store)
def __getitem__(self, name):
return self.store[name]
def __setitem__(self, name, value):
if name not in self:
raise ValueError(f'New terms cannot be created.\nInvalid term: {name}\nValid terms are: {list(self.keys())}')
if type(self.store[name]) != type(value):
if (type(self.store[name]) == float and type(value) == int) or (type(self.store[name]) == int and type(value) == float):
pass
else:
raise ValueError(f'New value does not have a valid type.\nOld value: {self.store[name]}\nOld type: {type(self.store[name])}\nNew value: {value}\nNew type: {type(value)}')
self.store[name] = value
def __delitem__(self, key):
raise AttributeError('Itens cannot be deleted')
def __iter__(self):
return iter(self.store)
def __len__(self):
return len({name:self.store[name] for name in self.store if self.store[name] is not None})
def reset(self):
self.store = copy.deepcopy(self.initial)
# %% Main class ================================================================
class Calculation():
"""Initialize a Crispy/Quanty calculation object.
Args:
element (string, optional): transition metals, lanthanides and actinides.
default is 'Ni'.
charge (string, optional): suitable oxidation state of the element as
'1+', '2+' and so on. default depends on the element.
symmetry (string, optional): local symmetry. Possible values are 'Oh',
'D4h', 'Td', 'C3v', and 'D3h'. default depends on the element.
experiment (string, optional): experiment to simulate spectrum. Possible
values are 'XAS', 'XES', 'XPS', and 'RIXS'. default is 'XAS'.
edge (string, optional): investigated edge.
* For 'XAS' and 'XPS', possible values are 'K (1s)', 'L1 (2s)', 'L2,3 (2p)', 'M1 (3s)', and 'M2,3 (3p)'.
* For 'XES', possible values are 'Ka (1s2p)' and 'Kb (1s3p)'.
* For 'RIXS', possible values are 'K-L2,3 (1s2p)', 'K-M2,3 (1s3p)', and 'L2,3-M4,5 (2p3d)'
default is depends on the experiment type and element.
toCalculate (list, optional): type of spectrum to calculate. default is ['Isotropic']
* For 'XAS', possible values are 'Circular Dichroism' (cir, cd),
'Isotropic' (i, iso), 'Linear Dichroism' (lin, ld).
* For 'XES' and 'XPS', possible value is 'Isotropic'.
* For 'RIXS', possible values are 'Isotropic', 'Linear Dichroism'.
Note: 'Linear Dichroism' for RIXS is not a crispy feature and is
implemented by this object.
nPsis (number, optional): number of states to calculate. If None,
nPsiAuto will be set to 1 and a suitable value will be calculated.
Default is None.
nPsisAuto (int, optional): If 1, a suitable value will be picked for
nPsis. Default is 1.
nConfigurations (int, optional): number of configurations. If None,
a suitable value will be calculated. default is None.
APPARENTLY THIS IS ALWAYS 1.
filepath_lua (str or pathlib.Path, optional): filepath to save .lua file.
If extension .lua is not present, extension .lua is added.
default depends on element, charge, etc... example: Cr3+_Oh_2p3d_RIXS.lua
filepath_spec (str or pathlib.Path, optional): filepath to save spectrum.
This filepath will be written in the .lua file.
If extension .spec is not present, extension .spec is added.
default depends on element, charge, etc...
example: Cr3+_Oh_2p3d_RIXS_iso.spec
filepath_par (str or pathlib.Path, optional): filepath to save parameter
file (parameter list file).
If extension .par is not present, extension .par is added.
default depends on element, charge, etc...
example: Cr3+_Oh_2p3d_RIXS_iso.spec
magneticField (number, optional): Magnetic field value in Tesla. If zero
or None, a very small magnetic field (0.002 T) will be used to
have nice expected values for observables. To force a zero magnetic
field you have to turn it off via the ``hamiltonianState``. default
is 0.002 T. The direction of the magnetic quantization axis is
defined by k1.
temperature (number, optional): temperature in Kelvin. default is 10 K.
If temperature is zero, nPsi is set to 1 and nPsiAuto to 0.
xLorentzian (number, tuple, or list, optional):
* For 'XAS', it is the spectral broadening for the first and second
half of the spectrum. default depends on the element, oxidation
state, etc. WARNING: as for now, the second number in the xLorentzian
applies to both edges.
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', n.a.
yLorentzian (tuple or list, optional):
* For 'XAS', n.a.
* For 'XES' and 'XPS', n.a. (check)
* For 'RIXS', the first value is the broadening of the energy transfer
axis of the RIXS spectrum. The second value is the broadening of
the incident photon energy axis (equivalent to the XAS broadening).
default depends on the element, oxidation state, etc. The second
value is not implemented in the crispy interface.
k1 (tuple, optional): magnetic quantization axis. default is (0, 0, 1).
eps11 (tuple, optional): vertical incoming photon polarization vector.
default is (0, 1, 0).
eps12 (tuple, optional): horizontal incoming photon polarization vector.
It should be perpendicular to eps11. default is (1, 0, 0)
circular polarization vectors are calculated based on eps11 and eps12:
er = {sqrt(1/2) * (eps12[1] - I * eps11[1]),
sqrt(1/2) * (eps12[2] - I * eps11[2]),
sqrt(1/2) * (eps12[3] - I * eps11[3])}
el = {-sqrt(1/2) * (eps12[1] + I * eps11[1]),
-sqrt(1/2) * (eps12[2] + I * eps11[2]),
-sqrt(1/2) * (eps12[3] + I * eps11[3])}
k2 (tuple, optional): scattered wavevector. default is (0, 0, 1).
I'm not sure if this is used ever (check)
eps21 (tuple, optional): Only for RIXS. Sigma scattered photon polarization vector.
default is (0, 1, 0).
eps22 (tuple, optional): Only for RIXS. Pi scattered photon polarization vector.
It should be perpendicular to eps21. default is (1, 0, 0)
xMin (number, optional):
* For 'XAS', incident photon energy minimum value (in eV).
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', incident photon energy minimum value (in eV).
If None, a suitable value depending on the element will
be chosen. default is None.
xMax (number, optional):
* For 'XAS', incident photon energy maximum value (in eV).
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', incident photon energy maximum value (in eV).
If None, a suitable value depending on the element will
be chosen. default is None.
xNPoints (number, optional):
* For 'XAS', number of incident photon energy between xMin and
Xmax (number of data points in the XAS spectrum).
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', number of incident photon energies between xMin and
Xmax.
If None, a suitable value depending on the element will
be chosen. default is None.
yMin (number, optional):
* For 'XAS', n.a.
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', energy transfer minimum value (in eV).
If None, a suitable value depending on the element will
be chosen. default is None.
yMax (number, optional):
* For 'XAS', n.a.
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', energy transfer maximum value (in eV).
If None, a suitable value depending on the element will
be chosen. default is None.
yNPoints (number, optional):
* For 'XAS', n.a.
* For 'XES' and 'XPS', not sure. Need to check!
* For 'RIXS', number of energy transfer data points.
If None, a suitable value depending on the element will
be chosen. default is None.
Attributes:
All initial args are also attributes.
hamiltonianState (dict, optional): a dictionary that turns on or off the
different contributions to the hamiltonian. default is such that
'Atomic', 'Crystal Field', and 'Magnetic Field' terms will be True.
hamiltonianData (dict, optional): dictionary with values for the strength
of each different contributions to the hamiltonian. The default value
ise different for each element and charge stat. Values are in eV.
Methods:
save_input(): Create input file for Quanty.
run(): Create quanty calculation.
load_spectrum(): Load calculated spectrum from file.
get_parameters(): Returns a dictionary with all calculation parameters.
save_parameters(): Save calculation parameters to a file.
load_parameters(): Load calculation parameters from file.
"""
def __init__(self, element = 'Ni',
charge = '2+',
symmetry = None,
experiment = None,
edge = None,
#
toCalculate = 'Isotropic',
nPsis = None,
nPsisAuto = 1,
nConfigurations = 1,
filepath_lua = None,
filepath_spec = None,
filepath_par = None,
#
magneticField = 0,
temperature = 10,
#
xLorentzian = None,
yLorentzian = None,
#
k1 = (0, 0, 1),
eps11 = (0, 1, 0),
eps12 = (1, 0, 0),
k2 = (0, 0, 1),
eps21 = (0, 1, 0),
eps22 = (1, 0, 0),
#
xMin = None,
xMax = None,
xNPoints = None,
yMin = None,
yMax = None,
yNPoints = None
):
# crispy attributes
self.verbosity = '0x0000'
self.denseBorder = '2000'
# primary attributes
self._set_primary_attributes(element, charge, symmetry, experiment, edge)
# # hamiltonian
self.hamiltonianState = _hamiltonianState(self.q.hamiltonianState)
self.hamiltonianData = _hamiltonianData(self.q.hamiltonianData)
# calculation attributes
self.toCalculate = toCalculate
self.nPsis = nPsis
self.nPsisAuto = nPsisAuto
self.nConfigurations = nConfigurations # this is always 1 in Crispy.
self.filepath_lua = filepath_lua
self.filepath_spec = filepath_spec
self.filepath_par = filepath_par
# experiment attributes
self.temperature = temperature
self.magneticField = magneticField
# spectrum attributes
self.xMin = xMin
self.xMax = xMax
self.xNPoints = xNPoints
self.yMin = yMin
self.yMax = yMax
self.yNPoints = yNPoints
# orientation attributes
self.k1 = k1
self.eps11 = eps11
self.eps12 = eps12
self.k2 = k2
self.eps21 = eps21
self.eps22 = eps22
# broadening attributes
self.xLorentzian = xLorentzian
self.yLorentzian = yLorentzian
def _set_primary_attributes(self, element, charge, symmetry, experiment, edge):
"""Validate and set primary attributes."""
# validation
if element is None:
element = 'Ni'
assert element in settings.default, f'Not a valid element.\nValid elements are: {tuple(settings.default.keys())}'
valid_charges = tuple(settings.default[element]['charges'].keys())
if charge is None:
charge = valid_charges[0]
assert charge in valid_charges, f'Not a valid oxidation state for {element}\nValid oxidation states are: {valid_charges}'
valid_symmetries = tuple(settings.default[element]['charges'][charge]['symmetries'].keys())
if symmetry is None:
symmetry = valid_symmetries[0]
assert symmetry in valid_symmetries, f'Not a valid symmetry for {element} {charge}\nValid symmetries are: {valid_symmetries}'
valid_experiments = tuple(settings.default[element]['charges'][charge]['symmetries'][symmetry]['experiments'].keys())
if experiment is None:
experiment = valid_experiments[0]
assert experiment in valid_experiments, f'Not a valid experiment for {element} {charge} {symmetry}\nValid experiments are: {valid_experiments}'
valid_edges = tuple(settings.default[element]['charges'][charge]['symmetries'][symmetry]['experiments'][experiment]['edges'].keys())
if edge is None:
edge = valid_edges[0]
assert edge in valid_edges, f'Not a valid edge for {element} {charge} {symmetry} {experiment}\nValid edges are: {valid_edges}'
# initialize calculation object
self.q = settings.QuantyCalculation(element=element,
charge=charge,
symmetry=symmetry,
experiment=experiment,
edge=edge)
# set verbosity (this is set the same as in crispy)
self.q.verbosity = self.verbosity
# set border (this is set the same as in crispy)
self.q.denseBorder = self.denseBorder
# %% primary attributes
@property
def element(self):
return self.q.element
@element.setter
def element(self, value):
raise AttributeError('Primary attributes cannot be changed (element, charge, symmetry, experiment, edge).\nPlease, start a new Calculation() object')
@element.deleter
def element(self):
raise AttributeError('Cannot delete object.')
@property
def charge(self):
return self.q.charge
@charge.setter
def charge(self, value):
raise AttributeError('Primary attributes cannot be changed (element, charge, symmetry, experiment, edge).\nPlease, start a new Calculation() object')
@charge.deleter
def charge(self):
raise AttributeError('Cannot delete object.')
@property
def symmetry(self):
return self.q.symmetry
@symmetry.setter
def symmetry(self, value):
raise AttributeError('Primary attributes cannot be changed (element, charge, symmetry, experiment, edge).\nPlease, start a new Calculation() object')
@symmetry.deleter
def symmetry(self):
raise AttributeError('Cannot delete object.')
@property
def experiment(self):
return self.q.experiment
@experiment.setter
def experiment(self, value):
raise AttributeError('Primary attributes cannot be changed (element, charge, symmetry, experiment, edge).\nPlease, start a new Calculation() object')
@experiment.deleter
def experiment(self):
raise AttributeError('Cannot delete object.')
@property
def edge(self):
return self.q.edge
@edge.setter
def edge(self, value):
raise AttributeError('Primary attributes cannot be changed (element, charge, symmetry, experiment, edge).\nPlease, start a new Calculation() object')
@edge.deleter
def edge(self):
raise AttributeError('Cannot delete object.')
# %% calculation attributes
@property
def toCalculate(self):
return self.q.spectra.toCalculate[0]
@toCalculate.setter
def toCalculate(self, value):
# validation
error = "Invalid value for toCalculate\nValid values are:\nXAS: 'Circular Dichroism', 'Isotropic', 'Linear Dichroism'\nXES: 'Isotropic'\nXPS: 'Isotropic'\nRIXS: 'Isotropic', 'Linear Dichroism', 'Polarimeter'"
assert type(value) == str, error
assert value.lower().startswith(("cir", "cd", "lin", "ld", "iso", 'i', 'pol', 'polarimeter')), error
if self.experiment == 'RIXS':
assert value.lower().startswith(("lin", "ld", "iso", 'i', 'pol', 'polarimeter')), error
if self.experiment == 'XES' or self.experiment == 'XPS':
assert value.lower().startswith(("iso", 'i')), error
# convert value to crispy syntax
if value.lower().startswith(("cir", "cd")):
value = 'Circular Dichroism'
elif value.lower().startswith(("lin", "ld")):
value = 'Linear Dichroism'
elif value.lower().startswith(("i", "iso")):
value = 'Isotropic'
elif value.lower().startswith(("pol", "pola")):
value = 'Polarimeter'
# set value
self.q.spectra.toCalculate = [value]
self.q.spectra.toCalculateChecked = [value]
@toCalculate.deleter
def toCalculate(self):
raise AttributeError('Cannot delete object.')
@property
def nPsis(self):
return self.q.nPsis
@nPsis.setter
def nPsis(self, value):
if value is None:
self.q.nPsisAuto = 1
value = self.q.nPsisMax
else:
assert value > 0, 'The number of states must be larger than zero.'
assert value <= self.q.nPsisMax, f'The selected number of states exceeds the maximum.\nMaximum {self.q.nPsisMax}'
self.q.nPsis = value
self.q.nPsisAuto = 0
@nPsis.deleter
def nPsis(self):
raise AttributeError('Cannot delete object.')
@property
def nPsisAuto(self):
return self.q.nPsisAuto
@nPsisAuto.setter
def nPsisAuto(self, value):
if value == 0:
self.q.nPsisAuto = 0
elif value == 1:
self.q.nPsisAuto = 1
else:
raise ValueError('nPsiAuto can only be 0 or 1')
@nPsisAuto.deleter
def nPsisAuto(self):
raise AttributeError('Cannot delete object.')
@property
def nConfigurations(self):
return self.q.nConfigurations
@nConfigurations.setter
def nConfigurations(self, value):
if value is None:
value = self.q.nConfigurationsMax
else:
assert value <= self.q.nConfigurationsMax, f'The maximum number of configurations is {self.q.nConfigurationsMax}.'
self.q.nConfigurations = value
@nConfigurations.deleter
def nConfigurations(self):
raise AttributeError('Cannot delete object.')
@property
def filepath_lua(self):
return self._filepath_lua
@filepath_lua.setter
def filepath_lua(self, value):
if value is None:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['template name']
value = Path(value).with_suffix('.lua')
assert type(value) == str or isinstance(value, Path), 'filepath_lua must be a string or pathlib.Path.'
self._filepath_lua = value
@filepath_lua.deleter
def filepath_lua(self):
raise AttributeError('Cannot delete object.')
@property
def filepath_spec(self):
return self._filepath_spec
@filepath_spec.setter
def filepath_spec(self, value):
if value is None:
value = Path(self.filepath_lua).with_suffix('.spec')
assert type(value) == str or isinstance(value, Path), 'filepath_lua must be a string or pathlib.Path.'
self._filepath_spec = value
@filepath_spec.deleter
def filepath_spec(self):
raise AttributeError('Cannot delete object.')
@property
def filepath_par(self):
return self._filepath_par
@filepath_par.setter
def filepath_par(self, value):
if value is None:
value = Path(self.filepath_lua).with_suffix('.par')
assert type(value) == str or isinstance(value, Path), 'filepath_par must be a string or pathlib.Path.'
self._filepath_par = value
@filepath_par.deleter
def filepath_par(self):
raise AttributeError('Cannot delete object.')
# %% spectrum attributes
@property
def xMin(self):
return self.q.xMin
@xMin.setter
def xMin(self, value):
if value is None:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][1]
assert value > 0, 'xMin cannot be negative'
self.q.xMin = value
@xMin.deleter
def xMin(self):
raise AttributeError('Cannot delete object.')
@property
def xMax(self):
return self.q.xMax
@xMax.setter
def xMax(self, value):
if value is None:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][2]
assert value > 0, 'xMax cannot be negative'
self.q.xMax = value
@xMax.deleter
def xMax(self):
raise AttributeError('Cannot delete object.')
@property
def xNPoints(self):
return self.q.xNPoints + 1
@xNPoints.setter
def xNPoints(self, value):
if value is None:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][3]
assert value >= 2, 'xNPoints cannot be less than 2.\nThe CreateResonantSpectra() function from Quanty prevents xNPoints to be less than 2.'
value = int(value - 1)
self.q.xNPoints = value
@xNPoints.deleter
def xNPoints(self):
raise AttributeError('Cannot delete object.')
@property
def yMin(self):
return self.q.yMin
@yMin.setter
def yMin(self, value):
if value is None:
if self.experiment != 'RIXS':
value = None
else:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][1][1]
self.q.yMin = value
@yMin.deleter
def yMin(self):
raise AttributeError('Cannot delete object.')
@property
def yMax(self):
return self.q.yMax
@yMax.setter
def yMax(self, value):
if value is None:
if self.experiment != 'RIXS':
value = None
else:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][1][2]
self.q.yMax = value
@yMax.deleter
def yMax(self):
raise AttributeError('Cannot delete object.')
@property
def yNPoints(self):
try:
return self.q.yNPoints + 1
except TypeError:
return self.q.yNPoints
@yNPoints.setter
def yNPoints(self, value):
if value is None:
if self.experiment != 'RIXS':
value = None
self.q.yNPoints = None
return
else:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][1][3]
assert value >= 2, 'yNPoints cannot be less than 2.\nThe CreateResonantSpectra() function from Quanty prevents yNPoints to be less than 2.'
value = int(value - 1)
self.q.yNPoints = value
@yNPoints.deleter
def yNPoints(self):
raise AttributeError('Cannot delete object.')
# %% broadening attributes
@property
def xLorentzian(self):
return self.q.xLorentzian
@xLorentzian.setter
def xLorentzian(self, value):
if value is None:
if self.experiment == 'RIXS':
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][5]
else:
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][5]
try:
if value < 0:
raise ValueError('Broadening cannot be negative.')
value = (value, value)
except TypeError:
if any([v < 0 for v in value]):
raise ValueError('Broadening cannot be negative.')
self.q.xLorentzian = value
@xLorentzian.deleter
def xLorentzian(self):
raise AttributeError('Cannot delete object.')
@property
def yLorentzian(self):
return self.q.yLorentzian
@yLorentzian.setter
def yLorentzian(self, value):
if value is None:
if self.experiment == 'RIXS':
value = settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][1][5]
else:
value = (0, 0)
try:
if value < 0:
raise ValueError('Broadening cannot be negative.')
value = (value, settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][2][5][1])
except TypeError:
if any([v < 0 for v in value]):
raise ValueError('Broadening cannot be negative.')
self.q.yLorentzian = value
@yLorentzian.deleter
def yLorentzian(self):
raise AttributeError('Cannot delete object.')
# %% experiment attributes
@property
def temperature(self):
return self.q.temperature
@temperature.setter
def temperature(self, value):
assert value >= 0, 'Temperature cannot be negative.'
if value == 0:
print('Temperature = 0\nnPsi set to 1.')
self.nPsis = 1
self.nPsisAuto = 0
self.q.temperature = value
@temperature.deleter
def temperature(self):
raise AttributeError('Cannot delete object.')
@property
def magneticField(self):
return self.q.magneticField
@magneticField.setter
def magneticField(self, value):
# print(value)
# small = np.finfo(np.float32).eps # ~1.19e-7
if value is None or value == 0:
value = 0.002
elif value < 0:
raise ValueError('Magnetic field value must be positive.')
elif value < 0.002:
raise ValueError('Magnetic field cannot be smaller than 0.002 T.\nTurn off the magnetic field hamiltonian using hamiltonianState["Magnetic Field"]')
self.q.magneticField = value
self._update_magnetic_field_hamiltonian_data()
@magneticField.deleter
def magneticField(self):
raise AttributeError('Cannot delete object.')
# %% orientation attributes
@property
def k1(self):
return self.q.k1
@k1.setter
def k1(self, value):
assert len(value) == 3, 'k1 must be a vector, like [0, 1, 0].'
self.q.k1 = _normalize(value)
self._update_magnetic_field_hamiltonian_data()
@k1.deleter
def k1(self):
raise AttributeError('Cannot delete object.')
@property
def eps11(self):
return self.q.eps11
@eps11.setter
def eps11(self, value):
assert len(value) == 3, 'eps11 must be a vector, like [0, 1, 0].'
self.q.eps11 = _normalize(value)
@eps11.deleter
def eps11(self):
raise AttributeError('Cannot delete object.')
@property
def eps12(self):
return self.q.eps12
@eps12.setter
def eps12(self, value):
assert len(value) == 3, 'eps12 must be a vector, like [0, 1, 0].'
self.q.eps12 = _normalize(value)
# raise ValueError('Cannot edit eps12.\nIts value is perpendicular to k1 and eps11.')
@eps12.deleter
def eps12(self):
raise AttributeError('Cannot delete object.')
@property
def k2(self):
return self.q.k2
@k2.setter
def k2(self, value):
assert len(value) == 3, 'k2 must be a vector, like [0, 1, 0].'
self.q.k2 = _normalize(value)
@k2.deleter
def k2(self):
raise AttributeError('Cannot delete object.')
@property
def eps21(self):
return self.q.eps21
@eps21.setter
def eps21(self, value):
assert len(value) == 3, 'eps21 must be a vector, like [0, 1, 0].'
self.q.eps21 = _normalize(value)
@eps21.deleter
def eps21(self):
raise AttributeError('Cannot delete object.')
@property
def eps22(self):
return self.q.eps22
@eps22.setter
def eps22(self, value):
assert len(value) == 3, 'eps22 must be a vector, like [0, 1, 0].'
self.q.eps22 = _normalize(value)
# raise ValueError('Cannot edit eps22.\nIts value is perpendicular to k1 and eps11.')
@eps22.deleter
def eps22(self):
raise AttributeError('Cannot delete object.')
# %% extra attr
@property
def configurations(self):
return settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['configurations']
@configurations.setter
def configurations(self, value):
raise AttributeError('Attribute is read-only.')
@configurations.deleter
def configurations(self):
raise AttributeError('Cannot delete object.')
@property
def resonance(self):
return settings.default[self.element]['charges'][self.charge]['symmetries'][self.symmetry]['experiments'][self.experiment]['edges'][self.edge]['axes'][0][4]
@resonance.setter