-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNPKData.py
More file actions
2962 lines (2824 loc) · 114 KB
/
Copy pathNPKData.py
File metadata and controls
2962 lines (2824 loc) · 114 KB
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 python
# encoding: utf-8
"""
NPKData.py
Implement the basic mechanisms for spectral data-sets
Created by Marc-André and Marie-Aude on 2010-03-17.
"""
from __future__ import print_function, division
import os
import numpy as np
import numpy.fft as npfft
import copy
import itertools as it
import unittest
import math
import re
import time
import warnings
import version
from NPKError import NPKError
import sys #
if sys.version_info[0] < 3:
pass
else:
xrange = range
########################################################################
# series of utilities
def hypercomplex_modulus(arr, size1, size2):
"""
Calculates the modulus of an array of hypercomplex numbers.
input:
arr : hypercomplex array
size1 : size counting horizontally each half quadrant.
size2 : siez counting vertically each half quadrant.
eg:
arr = np.array([[1, 4],[3, 7],[1, 9],[5, 7]])
is an hypercomplex with size1 = 2 and size2 = 2
"""
b = np.zeros((size1//2, size2//2))
brr = arr[::2, ::2]
bri = arr[::2, 1::2]
bir = arr[1::2, ::2]
bii = arr[1::2, 1::2]
b = np.sqrt(brr**2 + bri**2 + bir**2 + bii**2 )
return b
def as_cpx(arr):
"""
interpret arr as a complex array
useful to move between complex and real arrays (see as_float)
>>> print as_cpx(np.arange(4.0))
[ 0.+1.j 2.+3.j]
"""
# return np.frombuffer(arr,dtype = "complex
return arr.view(dtype = "complex")
def as_float(arr):
"""
interpret arr as a float array
useful to move between complex and real arrays (see as_float)
>>> print as_float(np.arange(4)*(1+1j))
[ 0. 0. 1. 1. 2. 2. 3. 3.]
"""
# return np.frombuffer(arr,dtype = "float")
return arr.view(dtype = "float")
def conj_ip(a):
"""
computes conjugate() in-place
>>> conj_ip(np.arange(4)*(1+1j))
[ 0.-0.j 1.-1.j 2.-2.j 3.-3.j]
"""
if a.dtype == np.complex:
b = as_float(a)[1::2] # create a view of the imaginary part of a
np.multiply(b,-1.0,b) # and inverse it on-place
# b *= -1.0 # is equivalent
return a
def _conj_ip_from_float(a):
return np.conjugate(a.view(dtype = "complex"))
def _conj_ip_to_float(a):
return np.conjugate(a).view(dtype = "float")
def _base_fft(a):
"""
should not be used for regular use - called by wrapper routines
computes the complex Fourier transform, the NMR way
built as the conjugate of the fft found in numpy
WARNING - destroy the buffer given as parameter
test :
>> print _base_fft(np.arange(4.0))
[ 2. 4. -2. -2.]
"""
return _conj_ip_to_float( npfft.fft( _conj_ip_from_float(a) ) ) # reverse,
# v = npfft.fft( conj_ip( as_cpx(a) )) # creates a new buffer
# return as_float( conj_ip(v) ) # reverse,
def _base_ifft(a):
"""
should not be used for regular use - called by wrapper routines
computes the inverse complex Fourier transform, the NMR way
built as the conjugate of the ifft found in numpy
WARNING - destroy the buffer given as parameter
test :
>> print _base_ifft(np.arange(4.0))
array([ 1., 2., -1., -1.])
"""
v = npfft.ifft( conj_ip( as_cpx(a) )) # creates a new buffer
return as_float( conj_ip(v) ) # reverse,
def _base_rfft(a):
"""
should not be used for regular use - called by wrapper routines
imaginary parts of first and last freq is zero ( [1] and [-1]) so they are dropped and rfft is inplace.
This works only if self.size2 is even !!!
test :
>> print _base_rfft(np.arange(4.0))
[ 3. 1. -2. -2.]
"""
v = as_float(npfft.rfft(as_float(a)))
# print "dropped:",v[1],v[-1]
v[1] = 0.5*v[-2] # 0.5 ??? c'est peut-etre un bug dans NPK
v[0] *= 0.5
return as_float(conj_ip(as_cpx(v[:-2])))
def _base_irfft(a):
"""
should not be used for regular use - called by wrapper routines
inverse of _base_rfft
This works only if self.size2 is even !!!
test :
>> print _base_irfft(np.arange(4.0))
[ 0.5, 2. , -1.5, -1. ]
"""
v = np.zeros(len(a)+2)
v[:-2] = as_float((conj_ip(as_cpx(a[:]))))
v[0] = 2*v[0]
v[-2] = 2*v[1]
v[1] = 0.0
return npfft.irfft(as_cpx(v))
def _base_fftr(a):
"""
should not be used for regular use - called by wrapper routines
complex to real direct FT
This works only if self.size2 is even !!!
test :
>> print _base_fftr(np.arange(4.0))
[ 2.0, -3.0, -2.0, 3.0 ]
>> print _base_fftr(np.arange(8.0)+1.0)
[16.0, -16.31, 0.0, 1.34, -4.0, 6.313, -8.0, 12.65]
"""
v = np.zeros(len(a)+2)
# v[:-2] = as_float((conj_ip(as_cpx(a[:]))))
v[:-2] = a[:]
v[0] = 2*v[0]
v[-2] = 2*v[1]
v[-2] = 0.0
v = npfft.irfft(as_cpx(v))
return v*(len(v)/2)
def _base_ifftr(a):
"""
should not be used for regular use - called by wrapper routines
inverse of fftr
test :
>> print _base_ifftr(np.arange(4.0))
[ 1.5, 0.5, -1.0, -1.0 ]
>> print _base_ifftr(np.arange(8.0)+1.0)
[4.5, 0.5, -1.0, 2.41, -1.0, 1.0, -1.0, 0.414]
"""
v = as_float(npfft.rfft(as_float(a)))
v[1] = 0.5*v[-2] # 0.5 ??? c'est peut-être un bug dans NPK
v[0] *= 0.5
return v[:-2]*(2.0/(len(v)-2))
def flatten(*arg):
"""
flatten recursively a list of lists
>>>print flatten( ( (1,2), 3, (4, (5,), (6,7) ) ) )
[1, 2, 3, 4, 5, 6, 7]
"""
import collections
r = []
for i in arg:
if isinstance(i, collections.Sequence):
#print i
for j in i:
r += flatten(j)
else:
r += [i]
return r
def warning(msg):
"""issue a warning message to the user"""
print("WARNING")
print(msg)
########################################################################
def ident(v):
"a identity function used by default converter"
return v
class Unit(object):
"""
a small class to hold parameters for units
name: the name of the "unit"
converter: a function converting from points to "unit"
bconverter: a function converting from "unit" to points
reverse: direction in which axis are displayed (True means right to left)
scale: scale along this axis, possible values are 'linear' or 'log'
"""
def __init__(self, name="points", converter=ident, bconverter=ident, reverse=False, scale='linear'):
"creates an 'points' methods - to be extended"
self.name = name
self.converter = converter
self.bconverter = bconverter
self.reverse = reverse
self.scale = scale
########################################################################
class Axis(object):
"""
hold information for one spectral axis
used internally
"""
def __init__(self, size = 64, itype = 0, currentunit = "points"):
"""
size number of points along axis
itype 0 == real, 1 == complex
currentunit string which hold the unit name (defaut is "points", also called index)
"""
self.size = size # number of ponts along axis
self.itype = itype # 0 == real, 1 == complex
self.units = {"points": Unit()} # units dico contains possible units indexs by name,
# here create default units
self.currentunit = currentunit
self.sampling = None # index list of sampled points if instantiated
self.sampling_info = {}
self.attributes = ["itype", "sampling"] # storable attributes
@property
def cpxsize(self):
"""returns size of complex entries
this is different from size,
size == cpxsize if axis is real
size == 2*cpxsize if axis is complex
"""
return self.size//(self.itype+1)
def report(self):
if self.sampling:
return "size : %d sampled from %d itype %d unit %s"%(self.size, max(self.sampling), self.itype, self.currentunit)
else:
return "size : %d itype %d currentunit %s"%(self.size, self.itype, self.currentunit)
def _report(self):
"low level full-report"
st = ["Stored attributes:\n"] + [" %s: %s\n"%(att,getattr(self,att)) for att in self.attributes]
st += ["other attributes:\n"] + [" %s: %s\n"%(att,getattr(self,att)) for att in self.__dict__ if att not in self.attributes + ["attributes","units"] ]
st += [" units: "] + [" %s"%k for k in self.units.keys()]
return "".join(st)
def typestr(self):
" returns its type (real or complex) as a string"
if self.itype == 1:
tt = "complex"
else:
tt = "real"
return tt
def copy(self):
return copy.deepcopy(self)
def getslice(self, zoom):
"""
given a zoom window (or any slice), given as (low,high) in CURRENT UNIT,
returns the value pair in index, as (star,end)
which insures that
- low<high and within axis size
- that it starts on a real index if itype is complex
raise error if not possible
"""
if len(zoom) != 2:
raise NPKError("slice should be defined as coordinate pair (left,right) in axis' current unit %s"%self.currentunit)
a = int( round( self.ctoi(zoom[0]) ) )
b = int( round( self.ctoi(zoom[1]) ) )
if self.itype == 1: # complex axis
a = 2*(a//2) # int( 2*round( (self.ctoi(zoom[0])-0.5)/2 ) ) # insure real (a%2==0)
b = 2*(b//2) # int( 2*round( (self.ctoi(zoom[1])-0.5)/2 ) )
left, right = min(a,b), max(a,b)
if self.itype == 1: # complex axis
right += 1 # insure imaginary
if not self.check_zoom( (left,right) ):
raise NPKError("%d-%d (points) slice probably outside current axis"%(left,right))
return (left,right)
def check_zoom(self, zoom):
"""
check whether a zoom window (or any slice), given as (low,high) is valid
- check low<high and within axis size
- check that it starts on a real index if itype is complex
return a boolean
"""
test = zoom[0] >= 0 and zoom[0] <= (self.size)
test = test and zoom[1] >= 0 and zoom[1] <= (self.size)
test = test and zoom[0] <= zoom[1]
if self.itype == 1:
test = test and zoom[0]%2 == 0 and zoom[1]%2 == 1
return test
def extract(self, zoom):
"""
redefines the axis parameters so that the new axis is extracted for the points [start:end]
zoom is given in current unit - does not modify the Data, only the axis definition
This definition should be overloaded for each new axis, as the calibration system, associated to unit should be updated.
"""
start, end = self.getslice(zoom)
self.size = end-start
return (start, end)
def load_sampling(self, filename):
"""
loads the sampling scheme contained in an external file
file should contain index values, one per line, comment lines start with a #
complex axes should be sampled by complex pairs, and indices go up to self.size1/2
sampling is loaded into self.sampling and self.sampling_info is a dictionnary with information
"""
from .Algo import CS_transformations as cstr
S = cstr.sampling_load(filename)
self.sampling = S[0]
#print 'self.sampling ', self.sampling
self.sampling_info = S[1]
def get_sampling(self):
"""returns the sampling scheme contained in current axis"""
return self.sampling
def set_sampling(self, sampling):
"""sets the sampling scheme contained in current axis"""
self.sampling = sampling
return self.sampling
#--------------------------------
@property
def sampled(self):
"""true is sampled axis"""
return self.sampling is not None
#---------------------------------
def _gcurunits(self):
"get the current unit for this axis, to be chosen in axis.units.keys()"
return self._currentunit
def _scurunits(self, currentunit):
"set the current unit for this axis, to be chosen in axis.units.keys()"
if currentunit not in self.units.keys():
raise NPKError("Wrong unit type: %s - valid units are : %s" % (currentunit, str(self.units.keys())))
self._currentunit = currentunit
currentunit = property(_gcurunits, _scurunits)
#-----------------------------------
def points_axis(self):
"""return axis in points currentunit, actually 0..size-1"""
return np.arange(self.size)
def unit_axis(self):
"""returns an axis in the unit defined in self.currentunit"""
# u = self.currentunit
# uu = "".join(re.findall("[\w]*",u))
# return getattr(self, uu+"_axis")()
return self.itoc( self.points_axis() )
def itoc(self,val):
"""
converts point value (i) to currentunit (c)
"""
f = self.units[self.currentunit].converter
return f(val)
def ctoi(self,val):
"""
converts into point value (i) from currentunit (c)
"""
f = self.units[self.currentunit].bconverter
return f(val)
class NMRAxis(Axis):
"""
hold information for one NMR axis
used internally
"""
def __init__(self,size = 64, specwidth = 2000.0*math.pi, offset = 0.0, frequency = 400.0, itype = 0, currentunit = "points"):
"""
all parameters from Axis, plus
specwidth spectral width, in Hz
offset position in Hz of the rightmost point
frequency carrier frequency, in MHz
zerotime position (in points) on the time zero
"""
super(NMRAxis, self).__init__(size = size, itype = itype)
self.specwidth = specwidth # spectral width, in Hz
self.offset = offset # position in Hz of the rightmost point
self.frequency = frequency # carrier frequency, in MHz
self.zerotime = 0.0 # position (in points) on the time zero
self.NMR = "NMR"
self.units["ppm"] = Unit(name="ppm", converter=self.itop, bconverter=self.ptoi, reverse=True)
self.units["Hz"]= Unit(name="Hz", converter=self.itoh, bconverter=self.htoi, reverse=True)
self.units["sec"]= Unit(name="Hz", converter=self.itos, bconverter=self.stoi) # for FID
for i in ("specwidth", "offset", "frequency", "NMR"): # updates storable attributes
self.attributes.insert(0, i)
self.currentunit = currentunit
def report(self):
"high level reporting"
if self.itype == 0:
return "NMR axis at %f MHz, %d real points, from %f ppm (%f Hz) to %f ppm (%f Hz)"% \
(self.frequency, self.size, self.itop(self.size-1), self.itoh(self.size-1), self.itop(0), self.itoh(0))
else:
return "NMR axis at %f MHz, %d complex pairs, from %f ppm (%f Hz) to %f ppm (%f Hz)"% \
(self.frequency, self.cpxsize, self.itop(self.size-1), self.itoh(self.size-1), self.itop(0), self.itoh(0))
#-------------------------------------------------------------------------------
def extract(self, zoom):
"""
redefines the axis parameters so that the new axis is extracted for the points [start:end]
zoom is given in current unit - does not modify the Data, only the axis definition
"""
start, end = self.getslice(zoom)
self.specwidth = (self.specwidth * (end - start)) /self.size
self.offset = self.offset + self.specwidth * (self.size - end)/self.size
self.size = end-start
return (start, end)
#-------------------------------------------------------------------------------
def itos(self,value):
"""
returns time value (s) from point value
"""
return 0.5*value/self.specwidth
def stoi(self,value):
"""
returns point value (i) from time value (s)
"""
return 2.0*value*self.specwidth
#-------------------------------------------------------------------------------
def itop(self,value):
"""
returns ppm value (p) from point value (i)
"""
ppm_value = self.itoh(value) / self.frequency
return ppm_value
#-------------------------------------------------------------------------------
def htop(self,value):
"""
returns ppm value (p) from Hz value (h)
"""
ppm_value = value / self.frequency
return ppm_value
#-------------------------------------------------------------------------------
def htoi(self,value):
"""
returns point value (i) from Hz value (h)
"""
pt_value = (self.size -1)*(self.offset - value)/self.specwidth + self.size-1
return pt_value
#-------------------------------------------------------------------------------
def ptoh(self,value):
"""
returns Hz value (h) from ppm value (p)
"""
Hz_value = value * self.frequency
return Hz_value
#-------------------------------------------------------------------------------
def ptoi(self,value):
"""
returns point value (i) from ppm value (p)
"""
pt_value = self.htoi((value*self.frequency))
return pt_value
#-------------------------------------------------------------------------------
def itoh(self,value):
"""
returns Hz value (h) from point value (i)
"""
hz_value = (self.size-value-1)*self.specwidth / (self.size-1) + self.offset
return hz_value
def freq_axis(self):
"""return axis containing Hz values, can be used for display"""
return self.itoh(self.points_axis())
Hz_axis = freq_axis # two names for this function
def ppm_axis(self):
"""return axis containing ppm values, can be used for display"""
return self.itop( self.points_axis() )
########################################################################
class LaplaceAxis(Axis):
"""
hold information for one Laplace axis (DOSY)
used internally
"""
def __init__(self, size = 64, dmin = 1.0, dmax = 10.0, dfactor = 1.0, currentunit = "damping"):
super(LaplaceAxis, self).__init__(size = size, itype = 0)
self.dmin = dmin
self.dmax = dmax
self.dfactor = dfactor
self.Laplace = "Laplace"
self.units["damping"] = Unit(name="damping", converter=self.itod, bconverter=self.dtoi, scale='log')
self.units["Diff"] = self.units["damping"]
for i in ("dmin", "dmax", "dfactor", "Laplace"): # updates storable attributes
self.attributes.append(i)
self.currentunit = currentunit
self.qvalues = None
def itod(self, value):
"""
returns damping value (d) from point value (i)
"""
# print("itod might have to be checked")
cst = (math.log(self.dmax)-math.log(self.dmin)) / (float(self.size)-1)
d = (self.dmin )* np.exp(cst*value)
return d
def dtoi(self, value):
"""
returns point value (i) from damping value (d)
"""
# print("dtoi might have to be checked")
cst = (math.log(self.dmax)-math.log(self.dmin)) / (float(self.size)-1)
i = (np.log(value/self.dmin)) / cst
return i
def D_axis(self):
"""return axis containing Diffusion values, can be used for display"""
return self.itod(self.points_axis())
def report(self):
"hight level report"
return "Laplace axis of %d points, from %f to %f using a scaling factor of %f"% \
(self.size, self.itod(0.0), self.itod(self.size-1), self.dfactor)
def load_qvalues(self, fname):
"""
doc
"""
with open(fname,'r') as F:
self.qvalues = np.array([float(l) for l in F.readlines() if not l.startswith('#')])
return self.qvalues
########################################################################
def copyaxes(inp,out):
"""
copy axes values from NPKDAta in to out.
internal use
"""
for ii in range(inp.dim):
i = ii + 1 # 1 2 3
setattr(out, "axis%1d"%(i), inp.axes(i).copy() )
#----------------------------------------------------------
def parsezoom(npkd, zoom):
"""
takes zoom (in currentunit) for NPKData npkd, and return either
in 1D : zlo, zup
in 2D : z1lo, z1up, z2lo, z2up
if zoom is None, it returns the full zone
"""
if npkd.dim == 1:
if zoom is not None:
z1lo, z1up = npkd.axis1.getslice(zoom)
else:
z1lo = 0
z1up = npkd.size1-1
return (z1lo, z1up)
elif npkd.dim == 2:
if zoom is not None: # should ((F1_limits),(F2_limits))
zz = flatten(zoom)
z1lo, z1up = npkd.axis1.getslice((zz[0],zz[1]))
z2lo, z2up = npkd.axis2.getslice((zz[2],zz[3]))
else:
z1lo=0
z1up=npkd.size1-1
z2lo=0
z2up=npkd.size2-1
#print("z1lo, z1up, z2lo, z2up in parsezoom", z1lo, z1up, z2lo, z2up)
return (z1lo, z1up, z2lo, z2up)
else:
raise Exception("this code is not done yet")
########################################################################
def NPKData_plugin(name, method, verbose=False):
"""
This function allows to register a new method inside the NPKData class.
for instance - define myfunc() anywhere in your code :
def myfunc(npkdata, args):
"myfunc doc"
...do whatever, assuming npkdata is a NPKData
return npkdata # THIS is important, that is the standard NPKData mechanism
then elsewhere do :
NPKData_plugin("mymeth", myfunc)
then all NPKData created will have the method .mymeth()
look at ..plugins for details
"""
import inspect
from . import plugins
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 1)
callerfile = calframe[1][1]
pluginfile = os.path.splitext(os.path.basename(callerfile))[0]
if not callable(method):
raise Exception("method should be callable")
if not isinstance(name, str):
raise Exception("method name should be a string")
setattr(NPKData, name, method)
if verbose:
print(" - successfully added .%s() method to NPKData"%name)
plugins.codes[pluginfile].append(name)
class NPKData(object):
"""
a working data used by the NPK package
The data is a numpy array, found in self.buffer can also be accessed directly d[i], d[i,j], ...
1D 2D and 3D are handled, 3 axes are defined : axis1 axis2 axis3
axes are defined as in NMR
in 1D, every is in axis1
in 2D, the fastest varying dimension is in axis2, the slowest in axis1
in 3D, the fastest varying dimension is in axis3, the slowest in axis1
see axis_index
typical properties and methods are :
utilities:
.display()
.check()
properties
.itype
.dim .size1, .size2, .size3 ...
moving data :
.row(i) .col(i) .set_row(i) .set_col(i)
.copy()
.load() .save()
processing :
.fft() .rfft() .modulus() .apod_xxx() sg() transpose() ...
arithmetics :
.fill() .mult .add()
also direct arithmetics : f = 2*d+e
all methods return self, so computation can be piped
etc...
"""
def __init__(self, dim = 1, shape = None, buffer = None, name = None, debug = 0):
"""
data initialisation,
four alternative posibilities :
- name : file-name is given, the file is read and loaded
- buffer : numpy buffer is given - used as is, not copied !
- shape eg : (si1,si2) is given
- dim is given (default is dim=1)
the first found takes over the others which are not used
"""
from GifaFile import GifaFile
self.debug = debug
self.frequency = 400.0
self.absmax = 0.0
self.noise = 0.0
self.name = None
self.level = None
if buffer is not None:
dim = len(buffer.shape)
if name is not None:
Go = GifaFile(name,"r")
Go.load()
Go.close()
B = Go.get_data()
del(Go)
self.buffer = B.buffer
copyaxes(B,self)
self.name = name
elif shape is not None:
self.buffer = np.zeros(shape)
self.axis1 = NMRAxis()
if (len(shape) == 2):
self.axis1 = NMRAxis()
self.axis2 = NMRAxis()
elif (len(shape) == 3):
self.axis1 = NMRAxis()
self.axis2 = NMRAxis()
self.axis3 = NMRAxis()
else:
if dim == 1:
self.buffer = np.zeros((64,))
self.axis1 = NMRAxis()
elif dim == 2:
self.buffer = np.zeros((64,64))
self.axis1 = NMRAxis()
self.axis2 = NMRAxis()
elif dim == 3:
self.buffer = np.zeros((64,64,64))
self.axis1 = NMRAxis()
self.axis2 = NMRAxis()
self.axis3 = NMRAxis()
else:
raise NPKError("invalid dimension")
if buffer is not None:
self.set_buffer(buffer)
self.adapt_size()
self.check()
#----------------------------------------------
def get_buffer(self, copy=False):
"""
returns a view or a copy of the numpy buffer containing the NPKData values
dtype is either real or complex if axis is complex.
remarks :
- default is a view, if you want a copy, simply do d.get_buffer(copy=True)
- if you use a view, do not modify the size, nor the dtype
- see set_buffer()
WARNING
- In nD with n>1 and if NPKData is hypercomplex, only the fastest (n) axis is considered, all other imaginary parts are left as real.
"""
if self.axes(self.dim).itype == 1:
buf = as_cpx(self.buffer)
else:
buf = self.buffer
if copy:
return buf.copy()
else:
return buf
def set_buffer(self, buff):
"""
modify the internal buffer of the NPKData.
allows real or complex arrays to be used
remarks
- see get_buffer()
"""
t = buff.shape # will raise exception if not an array
#print "buff.shape ",buff.shape
#print "self.dim ", self.dim
if len(t) != self.dim:
raise NPKError("set_buffer() cannot change the data dimension", data=self)
try: # pbs may appear with pytables buffer
dt = buff.dtype
except:
dt = np.float
if dt == np.complex:
buff = as_float(buff)
self.axes(self.dim).itype = 1
elif dt == 'float':
self.axes(self.dim).itype = 0
self.buffer = buff
self.absmax = 0.0
self.adapt_size()
self.check()
return self
#----------------------------------------------
def axes(self,axis):
"""
returns the required axis : 1, 2 or 3
"""
return getattr(self,"axis%1d"%(axis))
@property
def dim(self):
"returns the dimension of data : 1 2 or 3 (for 1D 2D or 3D)"
return len(self.buffer.shape)
@property
def cpxsize1(self):
"""
returns the size of the F1 spectral axis in 1D 2D and 3D (number of entries, real or complex)
i.e. the unique axis in 1D, the slowest axis in 2D and 3D
"""
return self.axis1.cpxsize
@property
def cpxsize2(self):
"""
returns the size of the F2 spectral axis in 2D and 3D (number of entries, real or complex)
i.e. the slowest axis in 2D and the intermediate in 3D
"""
return self.axis2.cpxsize
@property
def cpxsize3(self):
"""
returns the size of the F3 spectral axis in 3D (number of entries, real or complex)
i.e. the slowest axis in 3D
"""
return self.axis3.cpxsize
@property
def size1(self):
"""
returns the size of the F1 spectral axis in 1D 2D and 3D
i.e. the unique axis in 1D, the slowest axis in 2D and 3D
warning, if data along axis is complex, the size is twice the number of complex pairs
i.e. this is the size of the underlying array
"""
return self.axis1.size
@property
def size2(self):
"""
returns the size of the F2 spectral axis in 2D and 3D
i.e. the slowest axis in 2D and the intermediate in 3D
warning, if data along axis is complex, the size is twice the number of complex pairs
i.e. this is the size of the underlying array
"""
return self.axis2.size
@property
def size3(self):
"""
returns the size of the F3 spectral axis in 3D
i.e. the slowest axis in 3D
warning, if data along axis is complex, the size is twice the number of complex pairs
i.e. this is the size of the underlying array
"""
return self.axis3.size
@property
def itype(self):
"returns complex type of each axes coded as single number, using NPKv1 code"
if self.dim == 1:
t = self.axis1.itype
elif self.dim == 2:
t = self.axis2.itype + 2*self.axis1.itype
elif self.dim == 3:
t = self.axis3.itype + 2*self.axis2.itype + 4*self.axis1.itype
return t
def __getitem__(self, key):
"""
allows d[i] where d is an NPKData
will always return as if data is real, independently of itype
"""
return self.buffer.__getitem__(key)
def __setitem__(self, key, value):
"""
allows d[i] where d is an NPKData
will always set as if data is real, independently of itype
"""
return self.buffer.__setitem__(key, value)
#----------------------------------------------
def _gunits(self):
"copy currentunit to all the axes"
return [ self.axes(i+1).currentunit for i in range(self.dim) ]
def _sunits(self, currentunit):
for i in range(self.dim):
ax = self.axes(i+1)
ax.currentunit = currentunit
unit = property(_gunits, _sunits)
#------------------------------------------------
def check(self, warn = False):
"""
check basic internal validity
raises exceptions unless warn is set to True - in which case, only warnings are issued
can be used in pipes as it returns self if everything is ok
"""
#----------------------------------------------
def check_msg(string):
if warn:
warning( "WARNING in NPKData.check() : "+string)
else:
print(self.report())
raise Exception(string)
#----------------------------------------------
try: # self.buffer might come from HDF5File and doesn't have flags
if not self.buffer.flags['OWNDATA']:
if self.debug >0:
warning("WARNING in NPKData.check() : NPKData does not own its buffer")
# print self.buffer.base.flags['UPDATEIFCOPY']
# I am not sure this is a concern...
except:
pass
try: # self.buffer might come from HDF5File and doesn't have flags
if not self.buffer.flags['C_CONTIGUOUS']:
if self.debug >0:
warning( "WARNING in NPKData.check() : NPKData does not own its buffer")
# print self.buffer.base.flags['UPDATEIFCOPY']
# I am not sure this is a concern...
except:
pass
try:
dt = self.buffer.dtype
except:
dt = np.float
if dt != np.float:
check_msg("wrong buffer type : %s"%str(dt))
if len(self.buffer.shape) != self.dim:
check_msg("wrong dim value : %d while buffer is %d"%(self.dim,len(self.buffer.shape)))
if self.dim == 1:
if self.buffer.shape[0] != self.axis1.size:
check_msg("wrong size value : %d while buffer is %d"%(self.axis1.size, self.buffer.size))
elif self.dim == 2:
if self.buffer.shape[0] != self.axis1.size or self.buffer.shape[1] != self.axis2.size:
check_msg("wrong size value : %d x %d while buffer is %d x %d" % \
(self.axis1.size, self.axis2.size, self.buffer.shape[0],self.buffer.shape[1]))
elif self.dim == 3:
if self.buffer.shape[0] != self.axis1.size or self.buffer.shape[1] != self.axis2.size or self.buffer.shape[2] != self.axis3.size:
check_msg("wrong size value : %d x %d x %d while buffer is %d x %d x %d" % \
(self.axis1.size, self.axis2.size, self.axis3.size, self.buffer.shape[0], self.buffer.shape[1], self.buffer.shape[2]))
for i in range(self.dim):
if (self.axes(i+1).itype == 1) and (self.axes(i+1).size%2 == 1):
check_msg("axis %d as size and type mismatch : %d - %d"%(i,self.axes(i+1).itype, self.axes(i+1).size))
return self
#----------------------------------------------
def checknD(self,n):
if self.dim != n:
raise NPKError("The dataset is not a %1dD experiment, as required"%n, data=self)
else:
return True
def check1D(self):
"true for a 1D"
self.checknD(1)
def check2D(self):
"true for a 2D"
self.checknD(2)
def check3D(self):
"true for a 3D"
self.checknD(3)
#=========================================
# begin of processing functions
def copy(self):
"""return a copy of itself"""
Data = type(self) # NPKData get subclassed, so subclass creator is to be used
c = Data(buffer = self.buffer.copy())
copyaxes(self,c)
try:
c.params = copy.deepcopy(self.params)
except AttributeError:
pass
# warning('params is missing')
return c
#---------------------------------------------------------------------------
def adapt_size(self):
"""
adapt the sizes held in the axis objects to the size of the buffer
TO BE CALLED each time the buffer size is modified
otherwise strange things will happen
"""
sizes = self.buffer.shape
for i in range (self.dim):
self.axes(i+1).size = sizes[i]
self.check()
#---------------------------------------------------------------------------
def _chsize1d(self,sz1=-1):
"""
Change size of data, zero-fill or truncate.
Only designed for time domain data.
DO NOT change the value of spectroscopic units, so EXTRACT should
always be preferred on spectra (unless you know exactly what your are doing).
"""
self.check1D()
if sz1 == -1:
sz1 = self.axis1.size
if sz1<= self.size1:
self.buffer = self.buffer[:sz1]
else:
b = np.zeros(sz1)
b[:self.size1] = self.buffer
self.buffer = b
self.adapt_size()
return self
#---------------------------------------------------------------------------
def _chsize2d(self,sz1=-1,sz2=-1):
"""
Change size of data, zero-fill or truncate.
DO NOT change the value of OFFSET and SPECW, so EXTRACT should
always be preferred on spectra (unless you know exactly what your are doing).
"""
self.check2D()
if sz1 == -1:
sz1 = self.axis1.size
if sz2 == -1:
sz2 = self.axis2.size
b = np.zeros((sz1,sz2))
s1 = min(sz1,self.size1)
s2 = min(sz2,self.size2)
b[:s1,:s2] = self.buffer[:s1,:s2]
self.buffer = b
self.adapt_size()
return self
#---------------------------------------------------------------------------
def _chsize3d(self,sz1=-1,sz2=-1,sz3=-1):
"""
Change size of data, zero-fill or truncate.
DO NOT change the value of OFFSET and SPECW, so EXTRACT should
always be preferred on spectra (unless you know exactly what your are doing).
"""
self.check3D()
if sz1 == -1:
sz1 = self.axis1.size
if sz2 == -1:
sz2 = self.axis2.size
if sz3 == -1:
sz3 = self.axis3.size