orGUI 1.0.1__py3-none-any.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 (83) hide show
  1. orGUI-1.0.1.dist-info/LICENSE +21 -0
  2. orGUI-1.0.1.dist-info/METADATA +147 -0
  3. orGUI-1.0.1.dist-info/RECORD +83 -0
  4. orGUI-1.0.1.dist-info/WHEEL +5 -0
  5. orGUI-1.0.1.dist-info/entry_points.txt +2 -0
  6. orGUI-1.0.1.dist-info/top_level.txt +1 -0
  7. orgui/__init__.py +36 -0
  8. orgui/app/ArrayTableDialog.py +433 -0
  9. orgui/app/QReflectionSelector.py +538 -0
  10. orgui/app/QScanSelector.py +692 -0
  11. orgui/app/QUBCalculator.py +1210 -0
  12. orgui/app/__init__.py +36 -0
  13. orgui/app/database.py +487 -0
  14. orgui/app/orGUI.py +2613 -0
  15. orgui/app/qutils.py +51 -0
  16. orgui/backend/__init__.py +32 -0
  17. orgui/backend/backends.py +157 -0
  18. orgui/backend/beamline/ID31DiffractLinTilt.py +77 -0
  19. orgui/backend/beamline/P212_tools.py +577 -0
  20. orgui/backend/beamline/__init__.py +36 -0
  21. orgui/backend/beamline/fio_reader.py +110 -0
  22. orgui/backend/beamline/id31_tools.py +651 -0
  23. orgui/backend/scans.py +95 -0
  24. orgui/backend/udefaults.py +163 -0
  25. orgui/backend/universalScanLoader.py +105 -0
  26. orgui/datautils/__init__.py +32 -0
  27. orgui/datautils/util.py +705 -0
  28. orgui/datautils/xrayutils/CTRcalc.py +3022 -0
  29. orgui/datautils/xrayutils/CTRopt.py +623 -0
  30. orgui/datautils/xrayutils/CTRplotutil.py +904 -0
  31. orgui/datautils/xrayutils/DetectorCalibration.py +685 -0
  32. orgui/datautils/xrayutils/HKLVlieg.py +1360 -0
  33. orgui/datautils/xrayutils/ReciprocalNavigation.py +401 -0
  34. orgui/datautils/xrayutils/_CTRcalc_accel.py +181 -0
  35. orgui/datautils/xrayutils/__init__.py +46 -0
  36. orgui/datautils/xrayutils/element_data.py +213 -0
  37. orgui/datautils/xrayutils/test/__init__.py +57 -0
  38. orgui/datautils/xrayutils/test/test_CTRcalc.py +152 -0
  39. orgui/datautils/xrayutils/test/test_DetectorCalibration.py +336 -0
  40. orgui/datautils/xrayutils/test/test_HKLcalc.py +88 -0
  41. orgui/datautils/xrayutils/unitcells/Fe3O4(100).bul +59 -0
  42. orgui/datautils/xrayutils/unitcells/Pt100.bul +7 -0
  43. orgui/datautils/xrayutils/unitcells/Pt100_small.bul +5 -0
  44. orgui/datautils/xrayutils/unitcells/Pt110.bul +5 -0
  45. orgui/datautils/xrayutils/unitcells/Pt111.bul +6 -0
  46. orgui/datautils/xrayutils/unitcells/Pt310.bul +13 -0
  47. orgui/datautils/xrayutils/unitcells/Pt3O4(100).bul +19 -0
  48. orgui/datautils/xrayutils/unitcells/PtO(001).bul +9 -0
  49. orgui/datautils/xrayutils/unitcells/PtO(010).bul +9 -0
  50. orgui/datautils/xrayutils/unitcells/PtO(100).bul +9 -0
  51. orgui/datautils/xrayutils/unitcells/__init__.py +67 -0
  52. orgui/datautils/xrayutils/unitcells/a-PtO2(0001).bul +6 -0
  53. orgui/main.py +101 -0
  54. orgui/resources/__init__.py +40 -0
  55. orgui/resources/icons/alpha.png +0 -0
  56. orgui/resources/icons/alpha.svg +67 -0
  57. orgui/resources/icons/diffractometer_v3.png +0 -0
  58. orgui/resources/icons/disable-image.png +0 -0
  59. orgui/resources/icons/disable-image.svg +68 -0
  60. orgui/resources/icons/document-nx-open.png +0 -0
  61. orgui/resources/icons/document-nx-open.svg +152 -0
  62. orgui/resources/icons/document-nx-save.png +0 -0
  63. orgui/resources/icons/document-nx-save.svg +73 -0
  64. orgui/resources/icons/logo.png +0 -0
  65. orgui/resources/icons/logo.svg +808 -0
  66. orgui/resources/icons/max_image.png +0 -0
  67. orgui/resources/icons/max_image.svg +77 -0
  68. orgui/resources/icons/max_image2.png +0 -0
  69. orgui/resources/icons/max_image2.svg +83 -0
  70. orgui/resources/icons/search-image.png +0 -0
  71. orgui/resources/icons/search-image.svg +94 -0
  72. orgui/resources/icons/search-reflection.png +0 -0
  73. orgui/resources/icons/search-reflection.svg +126 -0
  74. orgui/resources/icons/search.png +0 -0
  75. orgui/resources/icons/search.svg +91 -0
  76. orgui/resources/icons/select-image.png +0 -0
  77. orgui/resources/icons/select-image.svg +60 -0
  78. orgui/resources/icons/set-reflection.png +0 -0
  79. orgui/resources/icons/set-reflection.svg +91 -0
  80. orgui/resources/icons/sum_image.png +0 -0
  81. orgui/resources/icons/sum_image.svg +63 -0
  82. orgui/resources/icons/sum_image2.png +0 -0
  83. orgui/resources/icons/sum_image2.svg +75 -0
@@ -0,0 +1,904 @@
1
+ # -*- coding: utf-8 -*-
2
+ # /*##########################################################################
3
+ #
4
+ # Copyright (c) 2020-2024 Timo Fuchs
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in
14
+ # all copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ # THE SOFTWARE.
23
+ #
24
+ # ###########################################################################*/
25
+ __author__ = "Timo Fuchs"
26
+ __copyright__ = "Copyright 2020-2024 Timo Fuchs"
27
+ __license__ = "MIT License"
28
+ __version__ = "1.0.0"
29
+ __maintainer__ = "Timo Fuchs"
30
+ __email__ = "fuchs@physik.uni-kiel.de"
31
+
32
+
33
+ import os
34
+ import matplotlib
35
+ import matplotlib.pyplot as plt
36
+ import matplotlib.figure as mplfig
37
+ import matplotlib.transforms as mtransforms
38
+ import scipy.interpolate as interp
39
+ from scipy.stats.mstats import gmean
40
+ import numpy as np
41
+ from matplotlib import rc
42
+ import matplotlib.ticker
43
+ import matplotlib.pyplot as plt
44
+ from matplotlib import colors as mcolors
45
+ import math
46
+ import json
47
+ import warnings
48
+ from collections import OrderedDict
49
+ from .CTRcalc import SXRDCrystal
50
+ from .HKLVlieg import VliegAngles
51
+ from .. import util
52
+
53
+ # don't init CTRFigure directly, use ctrfigure instead
54
+ class CTRFigure(mplfig.Figure):
55
+
56
+ def __init__(self,**figargs):
57
+ super(CTRFigure, self).__init__(**figargs)
58
+ self.data = OrderedDict()
59
+ self.xlabels = "L / r.l.u."
60
+ self.ylabels = "Structure factor / arb. units"
61
+ self.xlim = None #[0,5]
62
+ self.ylim = None #[3e1,2e3]
63
+ self.wspace = 0
64
+ self.hspace = 0.05
65
+
66
+
67
+ def settings(self,**settings):
68
+ self.__dict__.update(settings)
69
+
70
+
71
+ def addCTR(self,ctr,*plotargs,**keyargs):
72
+ if ctr.ctr_id in self.data:
73
+ self.data[ctr.ctr_id].append([ctr,plotargs,keyargs])
74
+ else:
75
+ self.data[ctr.ctr_id] = [[ctr,plotargs,keyargs]]
76
+
77
+ def addCollection(self,collection):
78
+ for rod in collection:
79
+ self.addCTR(rod,*collection.plotsett,**collection.plotkeyargs)
80
+
81
+
82
+ def generateCTRplot(self,cols=2,maxrelerr=None,**keyargs):
83
+ rows = math.ceil(float(len(self.data))/float(cols))
84
+ ax1 = self.add_subplot( rows,cols,1 )
85
+ [self.add_subplot( rows,cols,i ) for i in range(2,rows*cols+1)]
86
+ self.axes_ctr_id = []
87
+ self.axes_ctr_hk = []
88
+ share = keyargs.get('share_axes', True)
89
+ self.to_sharex = np.array([share for i in range(len(self.axes))])
90
+ self.to_sharey = np.array([share for i in range(len(self.axes))])
91
+ if keyargs.get('sort_hk', False):
92
+ data = sorted(self.data,key=lambda x : np.sum(np.abs(x[0])))
93
+ else:
94
+ data = self.data
95
+ offset = 0
96
+ for i,ctrkey in enumerate(data):
97
+ i += offset
98
+ while(i in keyargs.get('skip_panel', [])):
99
+ i += 1
100
+ offset += 1
101
+ self.axes_ctr_id.append(i)
102
+ self.axes_ctr_hk.append(i)
103
+ ax = self.axes[i]
104
+ ctrname, ctrid = ctrkey
105
+ self.axes_ctr_id.append(ctrkey)
106
+ self.axes_ctr_hk.append(ctrname)
107
+
108
+ def formatMillerName(h):
109
+ h = round(h, 3)
110
+ if not h % 1:
111
+ h = int(h)
112
+ if h < 0:
113
+ return r"\overline{%s}" % abs(h)
114
+ else:
115
+ return r"%s" % abs(h)
116
+
117
+ if 'rodLabelL' in keyargs:
118
+ ctrstr = r"$( \, %s \, %s \, \ell \, )$" % (formatMillerName(ctrname[0]),formatMillerName(ctrname[1]))
119
+ else:
120
+ ctrstr = r"$( \,%s \, %s \,)$" % (formatMillerName(ctrname[0]),formatMillerName(ctrname[1]) )
121
+
122
+ if hasattr(self,"rodlabelsize"):
123
+ size = self.rodlabelsize
124
+ else:
125
+ size = None
126
+
127
+ if hasattr(self,"rodlabelweight"):
128
+ weight = self.rodlabelweight
129
+ else:
130
+ weight = 'bold'
131
+
132
+ if 'rodlabel' in keyargs:
133
+ if keyargs['rodlabel'] == 'bottom':
134
+ txt = ax.text(keyargs.get('labelxpos',0.02),keyargs.get('labelypos',0.02),ctrstr,horizontalalignment='left',
135
+ verticalalignment='bottom' ,size=size,transform=ax.transAxes, weight=weight)
136
+ if keyargs['rodlabel'] == 'topright':
137
+ txt = ax.text(keyargs.get('labelxpos',0.95),keyargs.get('labelypos',0.95),ctrstr,horizontalalignment='right',
138
+ verticalalignment='top' ,size=size,transform=ax.transAxes, weight=weight)
139
+ else:
140
+ txt = ax.text(keyargs.get('labelxpos',0.05),keyargs.get('labelypos',0.95),ctrstr,horizontalalignment='left',
141
+ verticalalignment='top' ,size=size,transform=ax.transAxes, weight=weight)
142
+ #txt.set_bbox(dict(facecolor='white', alpha=1., edgecolor=))
143
+ xlim = None
144
+ ylim = None
145
+ for ctr,plotargs,keyargs_c in self.data[ctrkey]:
146
+ xlim = keyargs_c.pop('xlim', xlim)
147
+ ylim = keyargs_c.pop('ylim', ylim)
148
+ if ctr.isWithError:
149
+ if maxrelerr is not None:
150
+ relerr = ctr.err / ctr.sfI
151
+ mask = relerr > maxrelerr
152
+ ax.errorbar(ctr.l[~mask],ctr.sfI[~mask],yerr=ctr.err[~mask],**keyargs_c)
153
+ if 'plotcaps' in keyargs:
154
+ errbar = ax.errorbar(ctr.l[mask],ctr.sfI[mask],yerr=ctr.err[mask],**keyargs_c)
155
+ _,_,barlinecols = errbar.lines
156
+ barlinecols[0].set_visible(False)
157
+ else:
158
+ ax.errorbar(ctr.l,ctr.sfI,yerr=ctr.err,**keyargs_c) # ,fmt='.',elinewidth=0.5,capsize=1. ,errorevery=1,color='k',zorder=1
159
+ else:
160
+ ax.plot(ctr.l,ctr.sfI,*plotargs,**keyargs_c)
161
+ if self.data[ctrkey][0][0].difference:
162
+ ax.set_yscale('linear')
163
+ else:
164
+ ax.set_yscale('log')
165
+ if xlim is not None:
166
+ self.to_sharex[i] = False
167
+ ax.set_xlim(xlim)
168
+ elif self.xlim is not None:
169
+ ax.set_xlim(self.xlim)
170
+
171
+ if ylim is not None:
172
+ self.to_sharey[i] = False
173
+ ax.set_ylim(ylim)
174
+ elif self.xlim is not None:
175
+ ax.set_ylim(self.ylim)
176
+
177
+ if np.any(self.to_sharey):
178
+ shareyaxes = np.array(self.axes)[self.to_sharey]
179
+ for axy in shareyaxes:
180
+ if axy is shareyaxes[0]:
181
+ continue
182
+ axy.sharey(shareyaxes[0])
183
+
184
+ if np.any(self.to_sharex):
185
+ sharexaxes = np.array(self.axes)[self.to_sharex]
186
+ for axx in sharexaxes:
187
+ if axx is sharexaxes[0]:
188
+ continue
189
+ axx.sharex(sharexaxes[0])
190
+
191
+
192
+ axes = np.reshape(self.axes,(rows,cols))
193
+ [a.tick_params(axis='x', labelbottom=False) for a in axes[:-1, :].flat]
194
+ [a.tick_params(axis='y', labelleft=False) for a in axes[:, 1:].flat]
195
+ if isinstance(self.xlabels, list):
196
+ [a.set_ylabel(ylbl) for ylbl, a in zip(self.ylabels, axes[:, 0])]
197
+ [a.set_xlabel(xlbl) for xlbl,a in zip(self.xlabels, axes[-1, :])]
198
+ elif keyargs.get('sharexyLabels', False):
199
+ if keyargs.get('sharexyLabels') == 'x':
200
+ axes[-1,0].set_xlabel(self.xlabels)
201
+ [a.set_ylabel(self.ylabels) for a in axes[:, 0]]
202
+ xy_lablel = 'x'
203
+ elif keyargs.get('sharexyLabels') == 'y':
204
+ axes[0,0].set_ylabel(self.ylabels)
205
+ [a.set_xlabel(self.xlabels) for a in axes[-1, :]]
206
+ xy_lablel = 'y'
207
+ else:
208
+ axes[0,0].set_ylabel(self.ylabels) # create labels for the tight_layout() call below
209
+ axes[-1,0].set_xlabel(self.xlabels)
210
+ xy_lablel = 'xy'
211
+ else:
212
+ [a.set_ylabel(self.ylabels) for a in axes[:, 0]]
213
+ [a.set_xlabel(self.xlabels) for a in axes[-1, :]]
214
+
215
+ self.tight_layout()
216
+ self.subplots_adjust(wspace=self.wspace,hspace=self.hspace)
217
+
218
+ if keyargs.get('sharexyLabels', False):
219
+ if 'x' in xy_lablel:
220
+ avepos_width = 0.5 * (self.subplotpars.left + self.subplotpars.right)
221
+ transform_xlabel = mtransforms.blended_transform_factory(self.transFigure, mtransforms.IdentityTransform())
222
+ axes[-1,0].xaxis.label.set_transform(transform_xlabel)
223
+ axes[-1,0].xaxis.label.set_x(avepos_width)
224
+ if 'y' in xy_lablel:
225
+ avepos_height = 0.5 * (self.subplotpars.bottom + self.subplotpars.top)
226
+ transform_ylabel = mtransforms.blended_transform_factory(mtransforms.IdentityTransform(), self.transFigure)
227
+ axes[0,0].yaxis.label.set_transform(transform_ylabel)
228
+ axes[0,0].yaxis.label.set_y(avepos_height)
229
+
230
+
231
+ def get_ctr_ax(self, hk, ident=None):
232
+ hk = (float(hk[0]), float(hk[1]))
233
+ if ident is None:
234
+ idx = self.axes_ctr_hk.index(hk)
235
+ else:
236
+ idx = self.axes_ctr_id.index((hk,ident))
237
+ return self.axes[idx]
238
+
239
+ def set_ctr_xlim(self, hk, xlim, ident=None):
240
+ hk = (float(hk[0]), float(hk[1]))
241
+ if self.axes:
242
+ ax = self.get_ctr_ax(hk, ident)
243
+ if len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
244
+ raise RuntimeError("CTR axes limits must be set before plot creation.")
245
+ else:
246
+ ax.set_xlim(xlim)
247
+ else:
248
+ if ident is None:
249
+ for ids in self.data:
250
+ if ids[0] == hk:
251
+ self.data[ids][0][2]['xlim'] = xlim
252
+ break
253
+ else:
254
+ raise KeyError("CTR %s not found in figure data" % str(hk))
255
+ else:
256
+ self.data[(hk, ident)][0][2]['xlim'] = xlim
257
+
258
+
259
+ def set_ctr_ylim(self, hk, ylim, ident=None):
260
+ hk = (float(hk[0]), float(hk[1]))
261
+ if self.axes:
262
+ ax = self.get_ctr_ax(hk, ident)
263
+ if len(ax.get_shared_y_axes().get_siblings(ax)) > 1:
264
+ raise RuntimeError("CTR axes limits must be set before plot creation.")
265
+ else:
266
+ ax.set_ylim(ylim)
267
+ else:
268
+ if ident is None:
269
+ for ids in self.data:
270
+ if ids[0] == hk:
271
+ self.data[ids][0][2]['ylim'] = ylim
272
+ break
273
+ else:
274
+ raise KeyError("CTR %s not found in figure data" % str(hk))
275
+ else:
276
+ self.data[(hk, ident)][0][2]['ylim'] = ylim
277
+
278
+
279
+ class CTR(object):
280
+
281
+ ctrtype = 100
282
+
283
+ optional_counters = ['bgI', 'ctrI', 'croi_pix', 'bgroi_pix', 'weight']
284
+
285
+ def __init__(self,hk,l=None,sfI=None,err=None,phi=None,**keyargs):
286
+ self.hk = tuple(hk)
287
+ h,k = hk
288
+ self.l = np.ascontiguousarray(l)
289
+ self.sfI = np.ascontiguousarray(sfI)
290
+ if err is not None:
291
+ self.err = np.ascontiguousarray(err)
292
+ else:
293
+ self.err = None
294
+ self.ctrtype = CTR.ctrtype
295
+ CTR.ctrtype += 1
296
+ self.withErr = True
297
+ self.phi = phi
298
+ self.difference = False
299
+ self.weight = 1
300
+ if 'name' in keyargs:
301
+ self.name = keyargs['name']
302
+ else:
303
+ self.name = 'default'
304
+ self.harr = np.full_like(self.l,h)
305
+ self.karr = np.full_like(self.l,k)
306
+
307
+ def toNXdict(self):
308
+ nxdict = {
309
+ "@NX_class": u"NXdata",
310
+ "sixc_angles": {
311
+ "@NX_class": u"NXpositioner",
312
+ "@unit" : u"deg"
313
+ },
314
+ "hkl": {
315
+ "@NX_class": u"NXcollection",
316
+ "h" : self.harr,
317
+ "k" : self.harr,
318
+ "l" : self.l,
319
+ "@unit" : u"r.l.u."
320
+ },
321
+ "counters":{
322
+ "@NX_class": u"NXdetector",
323
+ "structurefactor" : self.sfI
324
+ },
325
+ "@signal" : u"counters/structurefactor",
326
+ "@axes": u"hkl/l",
327
+ "@title" : repr(self),
328
+ "@name" : self.name,
329
+ "@difference" : self.difference
330
+ }
331
+ for cnter in CTR.optional_counters:
332
+ if hasattr(self, cnter):
333
+ nxdict["counters"][cnter] = getattr(self, cnter)
334
+
335
+ if self.err is not None:
336
+ nxdict["counters"]["structurefactor_errors"] = self.err
337
+
338
+ if self.phi is not None:
339
+ nxdict["counters"]["phase"] = self.phi
340
+
341
+ if hasattr(self, 'angles'):
342
+ for ang in self.angles.dtype.fields:
343
+ nxdict["sixc_angles"][ang] = self.angles[ang]
344
+
345
+ return nxdict
346
+
347
+ @classmethod
348
+ def fromNXdict(cls, nxdict):
349
+ h = nxdict['hkl']['h']
350
+ k = nxdict['hkl']['k']
351
+ l = nxdict['hkl']['l']
352
+ sfI = nxdict['counters']['structurefactor']
353
+ err = nxdict['counters'].get('structurefactor_errors', None)
354
+ phi = nxdict['counters'].get('phase', None)
355
+ name = nxdict.get('@name', 'default')
356
+
357
+ ctr = cls((h[0], k[0]), l, sfI, err, phi, name=name)
358
+ ctr.harr = h
359
+ ctr.karr = k
360
+
361
+ if '@difference' in nxdict:
362
+ ctr.difference = nxdict['@difference']
363
+
364
+ for cnter in CTR.optional_counters:
365
+ if hasattr(nxdict['counters'], cnter):
366
+ setattr(ctr, cnter, nxdict["counters"][cnter])
367
+
368
+ angles = []
369
+ angles_names = []
370
+ for ang in nxdict['sixc_angles']:
371
+ if not ang.startswith("@"):
372
+ angles.append(nxdict['sixc_angles'][ang])
373
+ angles_names.append(ang)
374
+ if angles:
375
+ dt = np.dtype([(ang, 'f8') for ang in angles_names])
376
+ angles = np.vstack(angles).T
377
+ angles = np.core.records.fromarrays(angles,dtype=dt)
378
+ ctr.angles = angles
379
+ return ctr
380
+
381
+
382
+ def getPlotLabel(self):
383
+ if self.plotlabel in self:
384
+ return self.plotlabel
385
+ else:
386
+ return self.name
387
+
388
+ def convertToF(self,excludeInvalid=True):
389
+ self.sfI = np.sqrt(self.sfI)
390
+ if excludeInvalid:
391
+ mask = ~np.isnan(self.sfI)
392
+ else:
393
+ mask = np.ones_like(self.sfI,dtype=np.bool_)
394
+
395
+ if self.isWithError:
396
+ self.err = 0.5*(self.err/self.sfI)[mask]
397
+ if hasattr(self,'bgI'):
398
+ self.bgI = np.sqrt(self.bgI)[mask]
399
+ if hasattr(self,'ctrI'):
400
+ self.ctrI = np.sqrt(self.ctrI)[mask]
401
+ self.sfI = self.sfI[mask]
402
+ self.l = self.l[mask]
403
+ self.harr = self.harr[mask]
404
+ self.karr = self.karr[mask]
405
+ if self.isWithPhase:
406
+ self.phi = self.phi[mask]
407
+
408
+ # in degrees
409
+ def setPhase(self,phi):
410
+ self.phi = phi
411
+
412
+ def setWithError(self,err):
413
+ self.withErr = err
414
+
415
+ @property
416
+ def isWithPhase(self):
417
+ if not isinstance(self.phi,np.ndarray):
418
+ return False
419
+ else:
420
+ return True
421
+
422
+ @property
423
+ def isWithError(self):
424
+ if not isinstance(self.err,np.ndarray):
425
+ return False
426
+ return self.withErr
427
+
428
+ def getComplexSF(self):
429
+ if not self.isWithPhase:
430
+ raise Exception("%s:\nNo phase informaion available." % repr(self))
431
+ return self.sfI*np.exp(1j*np.deg2rad(self.phi))
432
+
433
+ @property
434
+ def ctr_id(self):
435
+ return tuple(np.around(self.hk,2)),self.ctrtype
436
+
437
+ def setToDefaultID(self):
438
+ self.ctrtype = 0
439
+
440
+ def generateDifference(self,other):
441
+ otherinter = interp.interp1d(other.l,other.sfI)
442
+ self.sfI -= otherinter(self.l)
443
+ self.difference = True
444
+ return self
445
+
446
+ def meanSF(self,lowerL,upperL):
447
+ upper = np.nanargmin(np.abs(self.l - upperL))
448
+ lower = np.nanargmin(np.abs(self.l - lowerL))
449
+ return np.nanmean(self.sfI[lower:upper])
450
+
451
+ def __imul__(self,valOrArray):
452
+ self.sfI *= valOrArray
453
+ if isinstance(self.err,np.ndarray):
454
+ self.err *= valOrArray
455
+ return self
456
+
457
+ def __iadd__(self,valOrArray):
458
+ self.sfI += valOrArray
459
+ #raise NotImplementedError()
460
+ #if isinstance(self.err,np.ndarray):
461
+ # self.err += valOrArray
462
+ return self
463
+
464
+ def cut(self,lower,upper, invert=False):
465
+ """Restricts the CTR to the selected lower and upper index
466
+
467
+ If invert is True, will remove the data within the selected range.
468
+
469
+ If invert is set to 'insertNAN', the sfI of the lower index will be set to nan.
470
+ This is useful for CTR plotting to interrupt the lines at this point.
471
+ But should never be used for any CTR that is supposed to be used for
472
+ further computations!
473
+
474
+ """
475
+ if invert:
476
+ mask = np.ones_like(self.l,dtype=np.bool_)
477
+ if invert=='insertNAN':
478
+ mask[lower+1:upper] = False
479
+ self.sfI[lower] = np.nan
480
+ else:
481
+ mask[lower:upper] = False
482
+
483
+ else:
484
+ mask = slice(lower,upper)
485
+ self.l = self.l[mask]
486
+ self.harr = self.harr[mask]
487
+ self.karr = self.karr[mask]
488
+ self.sfI = self.sfI[mask]
489
+ if self.isWithError:
490
+ self.err = self.err[mask]
491
+ if self.isWithPhase:
492
+ self.phi = self.phi[mask]
493
+ if hasattr(self,'bgI'):
494
+ self.bgI = self.bgI[mask]
495
+ if hasattr(self,'ctrI'):
496
+ self.ctrI = self.ctrI[mask]
497
+
498
+ def cutToL(self,lowerL,upperL, invert=False):
499
+ """Restricts the CTR to the selected lowerL and upperL.
500
+
501
+ If invert is True, will remove the data within the selected range.
502
+
503
+ If invert is set to 'insertNAN', the sfI of the lower index will be set to nan.
504
+ This is useful for CTR plotting to interrupt the lines at this point.
505
+ But should never be used for any CTR that is supposed to be used for
506
+ further computations!
507
+ """
508
+ upper = np.nanargmin(np.abs(self.l - upperL))
509
+ lower = np.nanargmin(np.abs(self.l - lowerL))
510
+ self.cut(lower,upper,invert)
511
+
512
+
513
+ def cutToROIfile(self,jsonfile):
514
+ with open(jsonfile,'r') as f:
515
+ udict = json.load(f)
516
+
517
+ rois = udict['ROI']['roidict']
518
+ del rois['ICR']
519
+ mask = np.zeros_like(self.l,dtype=np.bool_)
520
+
521
+ for roikey in rois:
522
+ fr = rois[roikey]['from']
523
+ to = rois[roikey]['to']
524
+ lower = np.nanargmin(np.abs(self.l - fr))
525
+ upper = np.nanargmin(np.abs(self.l - to))
526
+ mask[lower:upper] = 1.
527
+ self.l = self.l[mask]
528
+ self.harr = self.harr[mask]
529
+ self.karr = self.karr[mask]
530
+ self.sfI = self.sfI[mask]
531
+
532
+ if self.isWithError:
533
+ self.err = self.err[mask]
534
+ if self.isWithPhase:
535
+ self.phi = self.phi[mask]
536
+ if hasattr(self,'bgI'):
537
+ self.bgI = self.bgI[mask]
538
+ if hasattr(self,'ctrI'):
539
+ self.ctrI = self.ctrI[mask]
540
+
541
+ def get_scale(self, xtal, omitErrors=False ,lognorm=False):
542
+ if not hasattr(self,'err') or omitErrors:
543
+ err = None
544
+ else:
545
+ err = self.err
546
+ F_cryst = np.abs( xtal.F(self.harr,self.karr,self.l))
547
+ if lognorm:
548
+ return util.get_scale_logchi2(F_cryst, self.sfI)
549
+ else:
550
+ return util.get_scale_chi2(F_cryst, self.sfI, err)
551
+
552
+ def scaleToXtal(self,xtal, omitErrors=False, lognorm=False):
553
+ self.__imul__(self.get_scale(xtal,omitErrors,lognorm))
554
+
555
+
556
+ def calcAnglesZmode(self,vliegangles,fixedangle=np.deg2rad(0.1),
557
+ fixed='in', chi=0.,phi=0., **keyargs):
558
+ l = self.l
559
+ h = self.harr
560
+ k = self.karr
561
+ hkl = np.vstack((h,k,l))
562
+
563
+ pos = vliegangles.anglesZmode(hkl,fixedangle,fixed='in',chi=0,phi=0,**keyargs)
564
+ dt = np.dtype([('alpha', 'f8'), ('delta','f8'), ('gamma','f8'), ('omega','f8'), ('chi','f8'), ('phi','f8')])
565
+ self.angles = np.core.records.fromarrays(pos.T,dtype=dt)
566
+ return self.angles
567
+
568
+
569
+ def toArray(self,mode=None):
570
+ if mode is not None:
571
+ data = np.empty((6,self.l.size))
572
+ data[5] = mode
573
+ else:
574
+ data = np.empty((5,self.l.size))
575
+ data[0] = self.harr
576
+ data[1] = self.karr
577
+ data[2] = self.l
578
+ data[3] = self.sfI
579
+ if self.err is not None:
580
+ data[4] = self.err
581
+ elif self.phi is not None:
582
+ data[4] = self.phi
583
+ else:
584
+ data[4] = np.nan
585
+
586
+ return data.T
587
+
588
+ #returns a list of CTRs!!!
589
+ @staticmethod
590
+ def fromANAROD(filenameOrArray,RODexport=False):
591
+ warnings.warn("CTR.fromANAROD is deprecated, use CTRCollection.fromANAROD instead!", DeprecationWarning)
592
+ if not isinstance(filenameOrArray,np.ndarray):
593
+ filenameOrArray = np.loadtxt(filenameOrArray,skiprows=1)
594
+ rods = np.unique(filenameOrArray[:,:2],axis=0)
595
+ CTRs = []
596
+ for hk in rods:
597
+ rodmask = np.logical_and(filenameOrArray[:,0] == hk[0],filenameOrArray[:,1] == hk[1])
598
+ rod = filenameOrArray[rodmask]
599
+ l = rod[:,2]
600
+ sfI = rod[:,3]
601
+ if RODexport:
602
+ ctr = CTR(tuple(hk),l,sfI)
603
+ ctr.setPhase(rod[:,4])
604
+ CTRs.append(ctr)
605
+ else:
606
+ err = rod[:,4] if rod.shape[1] > 4 else None
607
+ CTRs.append(CTR(tuple(hk),l,sfI,err))
608
+
609
+ return CTRCollection(CTRs)
610
+
611
+ @classmethod
612
+ def fromArray(cls, array,RODexport=False):
613
+ h = array[:,0][0]
614
+ k = array[:,1][0]
615
+ l = array[:,2]
616
+ sfI = array[:,3]
617
+ if RODexport:
618
+ err = None
619
+ phase = array[:,4]
620
+ else:
621
+ err = array[:,4] if array.shape[1] > 4 else None
622
+ phase = None
623
+ return cls([h,k],l,sfI,err,phase)
624
+
625
+ def millerIdentifier(self):
626
+ h,k = self.hk
627
+ idstr = "%i_%02i_%i_%02i" % (round(h), round((h % 1) * 100),round(k), round((k % 1) * 100))
628
+ return idstr
629
+
630
+ def rollbackHK(self):
631
+ idstrsp = self.name.split('_')
632
+ h = float(idstrsp[0] + '.' + idstrsp[1])
633
+ k = float(idstrsp[2] + '.' + idstrsp[3])
634
+ self.hk = h,k
635
+
636
+
637
+ def __repr__(self):
638
+ #return "<CTR %s ctrtype %s at %016X>" % (tuple(np.around(self.hk,2)), self.ctrtype , id(self))
639
+ return "<CTR<%s> %s ctrtype %s>" % (self.name,tuple(np.around(self.hk,2)), self.ctrtype)
640
+
641
+
642
+ class CTRCollection(list):
643
+ def __init__(self,iterableCTRs=[], **kwargs):
644
+ super(CTRCollection, self).__init__(iterableCTRs)
645
+ self.plotsett = ()
646
+ self.plotkeyargs = {'linestyle':'-', 'marker':'.','color':'k','zorder':1}
647
+ #self._updaterodtypes()
648
+ self.name = kwargs.get('name', 'CTRs')
649
+
650
+ def setPlotSettings(self,*settings,**keyargs):
651
+ self.plotsett = settings
652
+ self.plotkeyargs = keyargs
653
+
654
+ def getReprList(self):
655
+ return [repr(rod) for rod in self]
656
+
657
+ def getHKList(self):
658
+ return [rod.hk for rod in self]
659
+
660
+ def setAllToDefaultID(self):
661
+ for rod in self:
662
+ rod.setToDefaultID()
663
+
664
+ def deleteRod(self,key):
665
+ if isinstance(key,tuple):
666
+ for rod in self:
667
+ if rod.hk == key:
668
+ self.remove(rod)
669
+
670
+ def __and__(self,other):
671
+ coll = CTRCollection()
672
+ for rod in self:
673
+ if repr(rod) in other.getReprList():
674
+ coll.append(rod)
675
+ #coll._updaterodtypes()
676
+ return coll
677
+
678
+ def convertToF(self):
679
+ for ctr in self:
680
+ ctr.convertToF()
681
+
682
+ def generateDifferenceCollection(self,other,sortby='repr'):
683
+ coll = CTRCollection()
684
+ if isinstance(other,CTRCollection):
685
+ for rod in self:
686
+ if sortby == 'repr':
687
+ try:
688
+ idx = other.getReprList().index(repr(rod))
689
+ except ValueError:
690
+ continue
691
+ else:
692
+ try:
693
+ idx = other.getHKList().index(rod.hk)
694
+ except ValueError:
695
+ continue
696
+ coll.append(rod.generateDifference(other[idx]))
697
+ return coll
698
+ elif isinstance(other,SXRDCrystal):
699
+ for ctr in self:
700
+ l = np.copy(ctr.l)
701
+ h,k = ctr.hk
702
+ harr = np.full_like(l,h)
703
+ karr = np.full_like(l,k)
704
+ F_theo = np.abs(other.F(harr,karr,l))
705
+ scale = np.prod(ctr.sfI/F_theo)**(1/ctr.l.size)
706
+ F_theo *= scale
707
+ diffCTR = CTR((h,k), l, ctr.sfI - F_theo,name=ctr.name)
708
+ diffCTR.difference = True
709
+ coll.append(diffCTR)
710
+ return coll
711
+ else:
712
+ raise NotImplementedError("Can not generate difference collection for type %s" % type(other))
713
+
714
+ def addScalar(self,scalar):
715
+ for rod in self:
716
+ rod += scalar
717
+ return self
718
+
719
+ def generateCollectionFromXtal(self,xtal,samples=None,lrange=None):
720
+ CTRs = CTRCollection()
721
+ if samples is not None or lrange is not None:
722
+ if lrange is not None:
723
+ for ctr in self:
724
+ h,k = ctr.hk
725
+ l = np.linspace(lrange[0],lrange[1],samples)
726
+ h = np.full_like(l,h)
727
+ k = np.full_like(l,k)
728
+ F = xtal.F(h,k,l)
729
+ CTRs.append( CTR( ctr.hk, l, np.abs(F),phi=np.angle(F)))
730
+ return CTRs
731
+ else:
732
+ for ctr in self:
733
+ h,k = ctr.hk
734
+ l = np.linspace(np.amin(ctr.l),np.amax(ctr.l),samples)
735
+ h = np.full_like(l,h)
736
+ k = np.full_like(l,k)
737
+ F = xtal.F(h,k,l)
738
+ CTRs.append( CTR(ctr.hk, l, np.abs(F),phi=np.angle(F)))
739
+ return CTRs
740
+ else:
741
+ for ctr in self:
742
+ F = xtal.F(ctr.harr,ctr.karr,ctr.l)
743
+ CTRs.append( CTR(ctr.hk, ctr.l, np.abs(F),phi=np.angle(F)))
744
+ return CTRs
745
+
746
+ def toANAROD(self,filename, mode=-3):
747
+ if self.__getitem__(0).isWithError:
748
+ header = "H K L F_HKL errorF mode"
749
+ else:
750
+ header = "H K L F_HKL phi"
751
+
752
+ data_combined = np.vstack([ctr.toArray(mode) for ctr in self])
753
+
754
+ np.savetxt(filename,data_combined,header=header,fmt='%.5f')
755
+
756
+
757
+ @staticmethod
758
+ def fromANAROD(filenameOrArray,RODexport=False, **kwargs):
759
+ if not isinstance(filenameOrArray,np.ndarray):
760
+ name = kwargs.get('name', os.path.basename(filenameOrArray))
761
+ filenameOrArray = np.loadtxt(filenameOrArray,skiprows=1)
762
+ else:
763
+ name = kwargs.get('name', 'Array_CTR_import')
764
+ rods = np.unique(filenameOrArray[:,:2],axis=0)
765
+ CTRs = []
766
+ for hk in rods:
767
+ rodmask = np.logical_and(filenameOrArray[:,0] == hk[0],filenameOrArray[:,1] == hk[1])
768
+ rod = filenameOrArray[rodmask]
769
+ l = rod[:,2]
770
+ sfI = rod[:,3]
771
+ if RODexport:
772
+ ctr = CTR(tuple(hk),l,sfI)
773
+ ctr.setPhase(rod[:,4])
774
+ CTRs.append(ctr)
775
+ else:
776
+ err = rod[:,4] if rod.shape[1] > 4 else None
777
+ CTRs.append(CTR(tuple(hk),l,sfI,err))
778
+
779
+ return CTRCollection(CTRs, name=name)
780
+
781
+ def toNXdict(self):
782
+
783
+ nxdict = {
784
+ "@title":u"%s" % self.name,
785
+ "@NX_class": u"NXentry",
786
+ "@name" : u"%s" % self.name
787
+ }
788
+ for ctr in self:
789
+ d = ctr.toNXdict()
790
+ nxdict[d['@title']] = d
791
+ nxdict["@default"] = d['@title']
792
+
793
+ return nxdict
794
+
795
+ @classmethod
796
+ def fromNXdict(cls, nxdict):
797
+ ctrs = []
798
+ for dt in nxdict:
799
+ if not dt.startswith("@"):
800
+ ctr = CTR.fromNXdict(nxdict[dt])
801
+ ctrs.append(ctr)
802
+ name = nxdict["@name"]
803
+
804
+ CTRs = cls(ctrs, name=name)
805
+ return CTRs
806
+
807
+
808
+ def get_flat(self):
809
+ h = []; k = []; l = []; F = []
810
+ for ctr in self:
811
+ h.append(ctr.harr)
812
+ k.append(ctr.karr)
813
+ l.append(ctr.l)
814
+ F.append(ctr.sfI)
815
+ return (np.concatenate(h),np.concatenate(k),np.concatenate(l)),np.concatenate(F)
816
+
817
+ def get_err_flat(self):
818
+ err = []
819
+ for ctr in self:
820
+ err.append(ctr.err)
821
+ return np.concatenate(err)
822
+
823
+ def get_scale(self, xtal, omitErrors=False ,lognorm=False):
824
+ hkl, F = self.get_flat()
825
+ F_cryst = np.abs( xtal.F(*hkl))
826
+ if omitErrors:
827
+ err = None
828
+ else:
829
+ err = self.get_err_flat()
830
+ if lognorm:
831
+ return util.get_scale_logchi2(F_cryst, F)
832
+ else:
833
+ return util.get_scale_chi2(F_cryst, F, err)
834
+
835
+
836
+ def scaleToXtal(self,xtal, individual=True, omitErrors=False, lognorm=False):
837
+ if individual:
838
+ for ctr in self:
839
+ ctr.scaleToXtal(xtal,lognorm, omitErrors)
840
+ else:
841
+ self.__imul__(self.get_scale(xtal,omitErrors,lognorm))
842
+
843
+ def __imul__(self,valOrArray):
844
+ for rod in self:
845
+ rod *= valOrArray
846
+ return self
847
+
848
+ def __getitem__(self,key):
849
+ if isinstance(key,tuple):
850
+ for rod in self:
851
+ if rod.hk == key:
852
+ return rod
853
+ return super(CTRCollection, self).__getitem__(key)
854
+
855
+ def __repr__(self):
856
+ s = "<%s: %s\n" % (type(self).__name__, self.name)
857
+ s += super().__repr__()
858
+ s += ">"
859
+ return s
860
+
861
+
862
+ def ctrfigure(**figargs):
863
+ figargs['FigureClass'] = CTRFigure
864
+ fig = plt.figure(**figargs)
865
+ return fig
866
+
867
+ if __name__ == "__main__":
868
+ fig = ctrfigure(figsize=(12,8))
869
+ ctrlist = CTR.fromANAROD("CTRfit/data_in/0V17/CH4977_0V17_0001.dat")
870
+ [ctr.setWithError(False) for ctr in ctrlist]
871
+ [ctr.setToDefaultID() for ctr in ctrlist]
872
+ [fig.addCTR(r,linestyle='', marker='.',color='k',zorder=1) for r in ctrlist]
873
+ ctrlist = CTR.fromANAROD("CTRfit/data_in/0V47/CH4977_0V47_0001.dat")
874
+ [ctr.setWithError(False) for ctr in ctrlist]
875
+ [ctr.setToDefaultID() for ctr in ctrlist]
876
+ [fig.addCTR(r,linestyle='', marker='.',color='g',zorder=1) for r in ctrlist]
877
+
878
+ ctrlist = CTR.fromANAROD("CTRfit/data_in/0V72/CH4977_0V72_0001.dat")
879
+ [ctr.setWithError(False) for ctr in ctrlist]
880
+ [ctr.setToDefaultID() for ctr in ctrlist]
881
+ [fig.addCTR(r,linestyle='', marker='.',color='b',zorder=1) for r in ctrlist]
882
+
883
+ ctrlist = CTR.fromANAROD("CTRfit/data_in/0V02/CH4977_0V02_0001.dat")
884
+ [ctr.setWithError(False) for ctr in ctrlist]
885
+ [ctr.setToDefaultID() for ctr in ctrlist]
886
+ [fig.addCTR(r,linestyle='', marker='.',color='y',zorder=1) for r in ctrlist]
887
+
888
+ fig.settings(wspace=0.05,hspace=0,ylabels='|F| / a.u.',ylim=[1e1,1e3])
889
+ fig.generateCTRplot()
890
+ fig.show()
891
+
892
+
893
+
894
+
895
+
896
+
897
+
898
+
899
+
900
+
901
+
902
+
903
+
904
+