forked from diffpy/diffpy.utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiffraction_objects.py
959 lines (826 loc) · 35.4 KB
/
diffraction_objects.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
import datetime
import warnings
from copy import deepcopy
import numpy as np
from diffpy.utils.tools import get_package_info
QQUANTITIES = ["q"]
ANGLEQUANTITIES = ["angle", "tth", "twotheta", "2theta"]
DQUANTITIES = ["d", "dspace"]
XQUANTITIES = ANGLEQUANTITIES + DQUANTITIES + QQUANTITIES
XUNITS = ["degrees", "radians", "rad", "deg", "inv_angs", "inv_nm", "nm-1", "A-1"]
x_grid_emsg = (
"objects are not on the same x-grid. You may add them using the self.add method "
"and specifying how to handle the mismatch."
)
wavelength_warning_emsg = (
"INFO: no wavelength has been specified. You can continue "
"to use the DiffractionObject but some of its powerful features "
"will not be available. To specify a wavelength, set "
"diffraction_object.wavelength = [number], "
"where diffraction_object is the variable name of you Diffraction Object, "
"and number is the wavelength in angstroms."
)
length_mismatch_emsg = "Please ensure {array_name} array and intensity array are of the same length."
non_numeric_value_emsg = "Invalid value found in {array_name} array. Please ensure all values are numeric."
invalid_tth_emsg = "Two theta exceeds 180 degrees. Please check the input values for errors."
invalid_q_or_wavelength_emsg = (
"The supplied q-array and wavelength will result in an impossible two-theta. "
"Please check these values and re-instantiate the DiffractionObject with correct values."
)
class Diffraction_object:
"""A class to represent and manipulate data associated with diffraction experiments.
.. deprecated:: 3.5.1
`Diffraction_object` is deprecated and will be removed in diffpy.utils 3.6.0. It is replaced by
`DiffractionObject` to follow the class naming convention.
"""
warnings.warn(
"Diffraction_object` is deprecated and will be removed in diffpy.utils 3.6.0, It is replaced by "
"DiffractionObject` to follow the class naming convention.",
DeprecationWarning,
stacklevel=2,
)
def __init__(self, name="", wavelength=None):
self.name = name
self.wavelength = wavelength
self.scat_quantity = ""
self.on_q = [np.empty(0), np.empty(0)]
self.on_tth = [np.empty(0), np.empty(0)]
self.on_d = [np.empty(0), np.empty(0)]
self._all_arrays = [self.on_q, self.on_tth]
self.metadata = {}
def __eq__(self, other):
if not isinstance(other, Diffraction_object):
return NotImplemented
self_attributes = [key for key in self.__dict__ if not key.startswith("_")]
other_attributes = [key for key in other.__dict__ if not key.startswith("_")]
if not sorted(self_attributes) == sorted(other_attributes):
return False
for key in self_attributes:
value = getattr(self, key)
other_value = getattr(other, key)
if isinstance(value, float):
if (
not (value is None and other_value is None)
and (value is None)
or (other_value is None)
or not np.isclose(value, other_value, rtol=1e-5)
):
return False
elif isinstance(value, list) and all(isinstance(i, np.ndarray) for i in value):
if not all(np.allclose(i, j, rtol=1e-5) for i, j in zip(value, other_value)):
return False
else:
if value != other_value:
return False
return True
def __add__(self, other):
summed = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
summed.on_tth[1] = self.on_tth[1] + other
summed.on_q[1] = self.on_q[1] + other
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to sum two Diffraction_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
summed.on_tth[1] = self.on_tth[1] + other.on_tth[1]
summed.on_q[1] = self.on_q[1] + other.on_q[1]
return summed
def __radd__(self, other):
summed = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
summed.on_tth[1] = self.on_tth[1] + other
summed.on_q[1] = self.on_q[1] + other
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to sum two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
summed.on_tth[1] = self.on_tth[1] + other.on_tth[1]
summed.on_q[1] = self.on_q[1] + other.on_q[1]
return summed
def __sub__(self, other):
subtracted = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
subtracted.on_tth[1] = self.on_tth[1] - other
subtracted.on_q[1] = self.on_q[1] - other
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to subtract two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
subtracted.on_tth[1] = self.on_tth[1] - other.on_tth[1]
subtracted.on_q[1] = self.on_q[1] - other.on_q[1]
return subtracted
def __rsub__(self, other):
subtracted = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
subtracted.on_tth[1] = other - self.on_tth[1]
subtracted.on_q[1] = other - self.on_q[1]
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to subtract two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
subtracted.on_tth[1] = other.on_tth[1] - self.on_tth[1]
subtracted.on_q[1] = other.on_q[1] - self.on_q[1]
return subtracted
def __mul__(self, other):
multiplied = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
multiplied.on_tth[1] = other * self.on_tth[1]
multiplied.on_q[1] = other * self.on_q[1]
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to multiply two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
multiplied.on_tth[1] = self.on_tth[1] * other.on_tth[1]
multiplied.on_q[1] = self.on_q[1] * other.on_q[1]
return multiplied
def __rmul__(self, other):
multiplied = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
multiplied.on_tth[1] = other * self.on_tth[1]
multiplied.on_q[1] = other * self.on_q[1]
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
multiplied.on_tth[1] = self.on_tth[1] * other.on_tth[1]
multiplied.on_q[1] = self.on_q[1] * other.on_q[1]
return multiplied
def __truediv__(self, other):
divided = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
divided.on_tth[1] = other / self.on_tth[1]
divided.on_q[1] = other / self.on_q[1]
elif not isinstance(other, Diffraction_object):
raise TypeError("I only know how to multiply two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
divided.on_tth[1] = self.on_tth[1] / other.on_tth[1]
divided.on_q[1] = self.on_q[1] / other.on_q[1]
return divided
def __rtruediv__(self, other):
divided = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
divided.on_tth[1] = other / self.on_tth[1]
divided.on_q[1] = other / self.on_q[1]
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
divided.on_tth[1] = other.on_tth[1] / self.on_tth[1]
divided.on_q[1] = other.on_q[1] / self.on_q[1]
return divided
def set_angles_from_list(self, angles_list):
self.angles = angles_list
self.n_steps = len(angles_list) - 1.0
self.begin_angle = self.angles[0]
self.end_angle = self.angles[-1]
def set_qs_from_range(self, begin_q, end_q, step_size=None, n_steps=None):
"""
create an array of linear spaced Q-values
Parameters
----------
begin_q float
the beginning angle
end_q float
the ending angle
step_size float
the size of the step between points. Only specify step_size or n_steps, not both
n_steps integer
the number of steps. Odd numbers are preferred. Only specify step_size or n_steps, not both
Returns
-------
Sets self.qs
self.qs array of floats
the q values in the independent array
"""
self.qs = self._set_array_from_range(begin_q, end_q, step_size=step_size, n_steps=n_steps)
def set_angles_from_range(self, begin_angle, end_angle, step_size=None, n_steps=None):
"""
create an array of linear spaced angle-values
Parameters
----------
begin_angle float
the beginning angle
end_angle float
the ending angle
step_size float
the size of the step between points. Only specify step_size or n_steps, not both
n_steps integer
the number of steps. Odd numbers are preferred. Only specify step_size or n_steps, not both
Returns
-------
Sets self.angles
self.angles array of floats
the q values in the independent array
"""
self.angles = self._set_array_from_range(begin_angle, end_angle, step_size=step_size, n_steps=n_steps)
def _set_array_from_range(self, begin, end, step_size=None, n_steps=None):
if step_size is not None and n_steps is not None:
print(
"WARNING: both step_size and n_steps have been given. n_steps will be used and step_size will be "
"reset."
)
array = np.linspace(begin, end, n_steps)
elif step_size is not None:
array = np.arange(begin, end, step_size)
elif n_steps is not None:
array = np.linspace(begin, end, n_steps)
return array
def get_angle_index(self, angle):
count = 0
for i, target in enumerate(self.angles):
if angle == target:
return i
else:
count += 1
if count >= len(self.angles):
raise IndexError(f"WARNING: no angle {angle} found in angles list")
def insert_scattering_quantity(
self,
xarray,
yarray,
xtype,
metadata={},
scat_quantity=None,
name=None,
wavelength=None,
):
f"""
insert a new scattering quantity into the scattering object
Parameters
----------
xarray array-like of floats
the independent variable array
yarray array-like of floats
the dependent variable array
xtype string
the type of quantity for the independent variable from {*XQUANTITIES, }
metadata: dict
the metadata in the form of a dictionary of user-supplied key:value pairs
Returns
-------
"""
self.input_xtype = xtype
# empty attributes have been defined in the __init__ method so only
# set the attributes that are not empty to avoid emptying them by mistake
if metadata:
self.metadata = metadata
if scat_quantity is not None:
self.scat_quantity = scat_quantity
if name is not None:
self.name = name
if wavelength is not None:
self.wavelength = wavelength
if xtype.lower() in QQUANTITIES:
self.on_q = [np.array(xarray), np.array(yarray)]
elif xtype.lower() in ANGLEQUANTITIES:
self.on_tth = [np.array(xarray), np.array(yarray)]
elif xtype.lower() in DQUANTITIES:
self.on_tth = [np.array(xarray), np.array(yarray)]
self.set_all_arrays()
def q_to_tth(self):
r"""
Helper function to convert q to two-theta.
By definition the relationship is:
.. math::
\sin\left(\frac{2\theta}{2}\right) = \frac{\lambda q}{4 \pi}
thus
.. math::
2\theta_n = 2 \arcsin\left(\frac{\lambda q}{4 \pi}\right)
Parameters
----------
q : array
An array of :math:`q` values
wavelength : float
Wavelength of the incoming x-rays
Function adapted from scikit-beam. Thanks to those developers
Returns
-------
two_theta : array
An array of :math:`2\theta` values in radians
"""
q = self.on_q[0]
q = np.asarray(q)
wavelength = float(self.wavelength)
pre_factor = wavelength / (4 * np.pi)
return np.rad2deg(2.0 * np.arcsin(q * pre_factor))
def tth_to_q(self):
r"""
Helper function to convert two-theta to q
By definition the relationship is
.. math::
\sin\left(\frac{2\theta}{2}\right) = \frac{\lambda q}{4 \pi}
thus
.. math::
q = \frac{4 \pi \sin\left(\frac{2\theta}{2}\right)}{\lambda}
Parameters
----------
two_theta : array
An array of :math:`2\theta` values in units of degrees
wavelength : float
Wavelength of the incoming x-rays
Function adapted from scikit-beam. Thanks to those developers.
Returns
-------
q : array
An array of :math:`q` values in the inverse of the units
of ``wavelength``
"""
two_theta = np.asarray(np.deg2rad(self.on_tth[0]))
wavelength = float(self.wavelength)
pre_factor = (4 * np.pi) / wavelength
return pre_factor * np.sin(two_theta / 2)
def set_all_arrays(self):
master_array, xtype = self._get_original_array()
if xtype == "q":
self.on_tth[0] = self.q_to_tth()
self.on_tth[1] = master_array[1]
if xtype == "tth":
self.on_q[0] = self.tth_to_q()
self.on_q[1] = master_array[1]
self.tthmin = self.on_tth[0][0]
self.tthmax = self.on_tth[0][-1]
self.qmin = self.on_q[0][0]
self.qmax = self.on_q[0][-1]
def _get_original_array(self):
if self.input_xtype in QQUANTITIES:
return self.on_q, "q"
elif self.input_xtype in ANGLEQUANTITIES:
return self.on_tth, "tth"
elif self.input_xtype in DQUANTITIES:
return self.on_d, "d"
def scale_to(self, target_diff_object, xtype=None, xvalue=None):
f"""
returns a new diffraction object which is the current object but recaled in y to the target
Parameters
----------
target_diff_object: Diffraction_object
the diffractoin object you want to scale the current one on to
xtype: string, optional. Default is Q
the xtype, from {XQUANTITIES}, that you will specify a point from to scale to
xvalue: float. Default is the midpoint of the array
the y-value in the target at this x-value will be used as the factor to scale to.
The entire array is scaled be the factor that places on on top of the other at that point.
xvalue does not have to be in the x-array, the point closest to this point will be used for the scaling.
Returns
-------
the rescaled Diffraction_object as a new object
"""
scaled = deepcopy(self)
if xtype is None:
xtype = "q"
data = self.on_xtype(xtype)
target = target_diff_object.on_xtype(xtype)
if xvalue is None:
xvalue = data[0][0] + (data[0][-1] - data[0][0]) / 2.0
xindex = (np.abs(data[0] - xvalue)).argmin()
ytarget = target[1][xindex]
yself = data[1][xindex]
scaled.on_tth[1] = data[1] * ytarget / yself
scaled.on_q[1] = data[1] * ytarget / yself
return scaled
def on_xtype(self, xtype):
"""
return a 2D np array with x in the first column and y in the second for x of type type
Parameters
----------
xtype
Returns
-------
"""
if xtype.lower() in ANGLEQUANTITIES:
return self.on_tth
elif xtype.lower() in QQUANTITIES:
return self.on_q
elif xtype.lower() in DQUANTITIES:
return self.on_d
pass
def dump(self, filepath, xtype=None):
if xtype is None:
xtype = " q"
if xtype == "q":
data_to_save = np.column_stack((self.on_q[0], self.on_q[1]))
elif xtype == "tth":
data_to_save = np.column_stack((self.on_tth[0], self.on_tth[1]))
elif xtype == "d":
data_to_save = np.column_stack((self.on_d[0], self.on_d[1]))
else:
print(f"WARNING: cannot handle the xtype '{xtype}'")
self.metadata.update(get_package_info("diffpy.utils", metadata=self.metadata))
self.metadata["creation_time"] = datetime.datetime.now()
with open(filepath, "w") as f:
f.write(
f"[Diffraction_object]\nname = {self.name}\nwavelength = {self.wavelength}\n"
f"scat_quantity = {self.scat_quantity}\n"
)
for key, value in self.metadata.items():
f.write(f"{key} = {value}\n")
f.write("\n#### start data\n")
np.savetxt(f, data_to_save, delimiter=" ")
class DiffractionObject:
def __init__(self, name="", wavelength=None):
self.name = name
self.wavelength = wavelength
self.scat_quantity = ""
self.on_q = [np.empty(0), np.empty(0)]
self.on_tth = [np.empty(0), np.empty(0)]
self.on_d = [np.empty(0), np.empty(0)]
self._all_arrays = [self.on_q, self.on_tth]
self.metadata = {}
def __eq__(self, other):
if not isinstance(other, DiffractionObject):
return NotImplemented
self_attributes = [key for key in self.__dict__ if not key.startswith("_")]
other_attributes = [key for key in other.__dict__ if not key.startswith("_")]
if not sorted(self_attributes) == sorted(other_attributes):
return False
for key in self_attributes:
value = getattr(self, key)
other_value = getattr(other, key)
if isinstance(value, float):
if (
not (value is None and other_value is None)
and (value is None)
or (other_value is None)
or not np.isclose(value, other_value, rtol=1e-5)
):
return False
elif isinstance(value, list) and all(isinstance(i, np.ndarray) for i in value):
if not all(np.allclose(i, j, rtol=1e-5) for i, j in zip(value, other_value)):
return False
else:
if value != other_value:
return False
return True
def __add__(self, other):
summed = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
summed.on_tth[1] = self.on_tth[1] + other
summed.on_q[1] = self.on_q[1] + other
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to sum two DiffractionObject objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
summed.on_tth[1] = self.on_tth[1] + other.on_tth[1]
summed.on_q[1] = self.on_q[1] + other.on_q[1]
return summed
def __radd__(self, other):
summed = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
summed.on_tth[1] = self.on_tth[1] + other
summed.on_q[1] = self.on_q[1] + other
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to sum two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
summed.on_tth[1] = self.on_tth[1] + other.on_tth[1]
summed.on_q[1] = self.on_q[1] + other.on_q[1]
return summed
def __sub__(self, other):
subtracted = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
subtracted.on_tth[1] = self.on_tth[1] - other
subtracted.on_q[1] = self.on_q[1] - other
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to subtract two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
subtracted.on_tth[1] = self.on_tth[1] - other.on_tth[1]
subtracted.on_q[1] = self.on_q[1] - other.on_q[1]
return subtracted
def __rsub__(self, other):
subtracted = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
subtracted.on_tth[1] = other - self.on_tth[1]
subtracted.on_q[1] = other - self.on_q[1]
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to subtract two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
subtracted.on_tth[1] = other.on_tth[1] - self.on_tth[1]
subtracted.on_q[1] = other.on_q[1] - self.on_q[1]
return subtracted
def __mul__(self, other):
multiplied = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
multiplied.on_tth[1] = other * self.on_tth[1]
multiplied.on_q[1] = other * self.on_q[1]
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to multiply two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
multiplied.on_tth[1] = self.on_tth[1] * other.on_tth[1]
multiplied.on_q[1] = self.on_q[1] * other.on_q[1]
return multiplied
def __rmul__(self, other):
multiplied = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
multiplied.on_tth[1] = other * self.on_tth[1]
multiplied.on_q[1] = other * self.on_q[1]
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
multiplied.on_tth[1] = self.on_tth[1] * other.on_tth[1]
multiplied.on_q[1] = self.on_q[1] * other.on_q[1]
return multiplied
def __truediv__(self, other):
divided = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
divided.on_tth[1] = other / self.on_tth[1]
divided.on_q[1] = other / self.on_q[1]
elif not isinstance(other, DiffractionObject):
raise TypeError("I only know how to multiply two Scattering_object objects")
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
divided.on_tth[1] = self.on_tth[1] / other.on_tth[1]
divided.on_q[1] = self.on_q[1] / other.on_q[1]
return divided
def __rtruediv__(self, other):
divided = deepcopy(self)
if isinstance(other, int) or isinstance(other, float) or isinstance(other, np.ndarray):
divided.on_tth[1] = other / self.on_tth[1]
divided.on_q[1] = other / self.on_q[1]
elif self.on_tth[0].all() != other.on_tth[0].all():
raise RuntimeError(x_grid_emsg)
else:
divided.on_tth[1] = other.on_tth[1] / self.on_tth[1]
divided.on_q[1] = other.on_q[1] / self.on_q[1]
return divided
def set_angles_from_list(self, angles_list):
self.angles = angles_list
self.n_steps = len(angles_list) - 1.0
self.begin_angle = self.angles[0]
self.end_angle = self.angles[-1]
def set_qs_from_range(self, begin_q, end_q, step_size=None, n_steps=None):
"""
create an array of linear spaced Q-values
Parameters
----------
begin_q float
the beginning angle
end_q float
the ending angle
step_size float
the size of the step between points. Only specify step_size or n_steps, not both
n_steps integer
the number of steps. Odd numbers are preferred. Only specify step_size or n_steps, not both
Returns
-------
Sets self.qs
self.qs array of floats
the q values in the independent array
"""
self.qs = self._set_array_from_range(begin_q, end_q, step_size=step_size, n_steps=n_steps)
def set_angles_from_range(self, begin_angle, end_angle, step_size=None, n_steps=None):
"""
create an array of linear spaced angle-values
Parameters
----------
begin_angle float
the beginning angle
end_angle float
the ending angle
step_size float
the size of the step between points. Only specify step_size or n_steps, not both
n_steps integer
the number of steps. Odd numbers are preferred. Only specify step_size or n_steps, not both
Returns
-------
Sets self.angles
self.angles array of floats
the q values in the independent array
"""
self.angles = self._set_array_from_range(begin_angle, end_angle, step_size=step_size, n_steps=n_steps)
def _set_array_from_range(self, begin, end, step_size=None, n_steps=None):
if step_size is not None and n_steps is not None:
print(
"WARNING: both step_size and n_steps have been given. n_steps will be used and step_size will be "
"reset."
)
array = np.linspace(begin, end, n_steps)
elif step_size is not None:
array = np.arange(begin, end, step_size)
elif n_steps is not None:
array = np.linspace(begin, end, n_steps)
return array
def get_angle_index(self, angle):
count = 0
for i, target in enumerate(self.angles):
if angle == target:
return i
else:
count += 1
if count >= len(self.angles):
raise IndexError(f"WARNING: no angle {angle} found in angles list")
def insert_scattering_quantity(
self,
xarray,
yarray,
xtype,
metadata={},
scat_quantity=None,
name=None,
wavelength=None,
):
f"""
insert a new scattering quantity into the scattering object
Parameters
----------
xarray array-like of floats
the independent variable array
yarray array-like of floats
the dependent variable array
xtype string
the type of quantity for the independent variable from {*XQUANTITIES, }
metadata: dict
the metadata in the form of a dictionary of user-supplied key:value pairs
Returns
-------
"""
self.input_xtype = xtype
# empty attributes have been defined in the __init__ method so only
# set the attributes that are not empty to avoid emptying them by mistake
if metadata:
self.metadata = metadata
if scat_quantity is not None:
self.scat_quantity = scat_quantity
if name is not None:
self.name = name
if wavelength is not None:
self.wavelength = wavelength
if xtype.lower() in QQUANTITIES:
self.on_q = [np.array(xarray), np.array(yarray)]
elif xtype.lower() in ANGLEQUANTITIES:
self.on_tth = [np.array(xarray), np.array(yarray)]
elif xtype.lower() in DQUANTITIES:
self.on_tth = [np.array(xarray), np.array(yarray)]
self.set_all_arrays()
def q_to_tth(self):
r"""
Helper function to convert q to two-theta.
By definition the relationship is:
.. math::
\sin\left(\frac{2\theta}{2}\right) = \frac{\lambda q}{4 \pi}
thus
.. math::
2\theta_n = 2 \arcsin\left(\frac{\lambda q}{4 \pi}\right)
Function adapted from scikit-beam. Thanks to those developers
Parameters
----------
q : array
The array of :math:`q` values
wavelength : float
Wavelength of the incoming x-rays
Returns
-------
two_theta : array
The array of :math:`2\theta` values in radians
"""
for i, value in enumerate(self.on_q[0]):
if not isinstance(value, (int, float)):
raise TypeError(non_numeric_value_emsg.format(array_name="q"))
if len(self.on_q[0]) != len(self.on_q[1]):
raise RuntimeError(length_mismatch_emsg.format(array_name="q"))
if self.wavelength is None:
warnings.warn(wavelength_warning_emsg, UserWarning)
return np.empty(0)
q = self.on_q[0]
q = np.asarray(q)
wavelength = float(self.wavelength)
pre_factor = wavelength / (4 * np.pi)
if np.any(np.abs(q * pre_factor) > 1):
raise ValueError(invalid_q_or_wavelength_emsg)
return np.rad2deg(2.0 * np.arcsin(q * pre_factor))
def tth_to_q(self):
r"""
Helper function to convert two-theta to q
By definition the relationship is
.. math::
\sin\left(\frac{2\theta}{2}\right) = \frac{\lambda q}{4 \pi}
thus
.. math::
q = \frac{4 \pi \sin\left(\frac{2\theta}{2}\right)}{\lambda}
Function adapted from scikit-beam. Thanks to those developers.
Parameters
----------
two_theta : array
The array of :math:`2\theta` values in units of degrees
wavelength : float
Wavelength of the incoming x-rays
Returns
-------
q : array
The array of :math:`q` values in the inverse of the units
of ``wavelength``
"""
for i, value in enumerate(self.on_tth[0]):
if not isinstance(value, (int, float)):
raise TypeError(non_numeric_value_emsg.format(array_name="two theta"))
if len(self.on_tth[0]) != len(self.on_tth[1]):
raise RuntimeError(length_mismatch_emsg.format(array_name="two theta"))
two_theta = np.asarray(np.deg2rad(self.on_tth[0]))
if np.any(two_theta > np.pi):
raise ValueError(invalid_tth_emsg)
if self.wavelength is None:
warnings.warn(wavelength_warning_emsg, UserWarning)
return np.empty(0)
wavelength = float(self.wavelength)
pre_factor = (4 * np.pi) / wavelength
return pre_factor * np.sin(two_theta / 2)
def set_all_arrays(self):
master_array, xtype = self._get_original_array()
if xtype == "q":
self.on_tth[0] = self.q_to_tth()
self.on_tth[1] = master_array[1]
if xtype == "tth":
self.on_q[0] = self.tth_to_q()
self.on_q[1] = master_array[1]
self.tthmin = self.on_tth[0][0]
self.tthmax = self.on_tth[0][-1]
self.qmin = self.on_q[0][0]
self.qmax = self.on_q[0][-1]
def _get_original_array(self):
if self.input_xtype in QQUANTITIES:
return self.on_q, "q"
elif self.input_xtype in ANGLEQUANTITIES:
return self.on_tth, "tth"
elif self.input_xtype in DQUANTITIES:
return self.on_d, "d"
def scale_to(self, target_diff_object, xtype=None, xvalue=None):
f"""
returns a new diffraction object which is the current object but recaled in y to the target
Parameters
----------
target_diff_object: DiffractionObject
the diffractoin object you want to scale the current one on to
xtype: string, optional. Default is Q
the xtype, from {XQUANTITIES}, that you will specify a point from to scale to
xvalue: float. Default is the midpoint of the array
the y-value in the target at this x-value will be used as the factor to scale to.
The entire array is scaled be the factor that places on on top of the other at that point.
xvalue does not have to be in the x-array, the point closest to this point will be used for the scaling.
Returns
-------
the rescaled DiffractionObject as a new object
"""
scaled = deepcopy(self)
if xtype is None:
xtype = "q"
data = self.on_xtype(xtype)
target = target_diff_object.on_xtype(xtype)
if xvalue is None:
xvalue = data[0][0] + (data[0][-1] - data[0][0]) / 2.0
xindex = (np.abs(data[0] - xvalue)).argmin()
ytarget = target[1][xindex]
yself = data[1][xindex]
scaled.on_tth[1] = data[1] * ytarget / yself
scaled.on_q[1] = data[1] * ytarget / yself
return scaled
def on_xtype(self, xtype):
"""
return a 2D np array with x in the first column and y in the second for x of type type
Parameters
----------
xtype
Returns
-------
"""
if xtype.lower() in ANGLEQUANTITIES:
return self.on_tth
elif xtype.lower() in QQUANTITIES:
return self.on_q
elif xtype.lower() in DQUANTITIES:
return self.on_d
pass
def dump(self, filepath, xtype=None):
if xtype is None:
xtype = " q"
if xtype == "q":
data_to_save = np.column_stack((self.on_q[0], self.on_q[1]))
elif xtype == "tth":
data_to_save = np.column_stack((self.on_tth[0], self.on_tth[1]))
elif xtype == "d":
data_to_save = np.column_stack((self.on_d[0], self.on_d[1]))
else:
print(f"WARNING: cannot handle the xtype '{xtype}'")
self.metadata.update(get_package_info("diffpy.utils", metadata=self.metadata))
self.metadata["creation_time"] = datetime.datetime.now()
with open(filepath, "w") as f:
f.write(
f"[DiffractionObject]\nname = {self.name}\nwavelength = {self.wavelength}\n"
f"scat_quantity = {self.scat_quantity}\n"
)
for key, value in self.metadata.items():
f.write(f"{key} = {value}\n")
f.write("\n#### start data\n")
np.savetxt(f, data_to_save, delimiter=" ")