/
sparky.py
1317 lines (1025 loc) · 35.5 KB
/
sparky.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Functions for reading and writing Sparky (.ucsf) files.
"""
__developer_info__ = """
Sparky file format information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Information on the Sparky file format can be found online at:
`http://www.cgl.ucsf.edu/home/sparky/manual/files.html`_
and in the Sparky source file ucsffile.cc.
"""
import os
import struct
import datetime
import numpy as np
from . import fileiobase
# unit conversion function
def make_uc(dic, data, dim=-1):
"""
Create a unit conversion object.
Parameters
----------
dic : dict
Dictionary of Sparky parameters.
data : ndarray
Array of NMR data.
dim : int, optional
Dimension number to create unit conversion object for. Default is for
last dimension.
Returns
-------
uc : unit conversion object.
Unit conversion object for given dimension.
"""
if dim == -1:
dim = data.ndim - 1 # last dimention
wdic = dic["w" + str(int(1 + dim))]
size = float(wdic["npoints"])
cplx = False
sw = wdic["spectral_width"]
obs = wdic["spectrometer_freq"]
car = wdic["xmtr_freq"] * obs
return fileiobase.unit_conversion(size, cplx, sw, obs, car)
# dictionary/data creation
def create_data(data):
"""
Create a Sparky data array (recast into float32 array)
"""
return np.array(data, dtype="float32")
def guess_udic(dic, data):
"""
Guess parameter of universal dictionary from dic,data pair.
Parameters
----------
dic : dict
Dictionary of Sparky parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Universal dictionary of spectral parameter.
"""
# create an empty universal dictionary
udic = fileiobase.create_blank_udic(data.ndim)
# update default values
for i in xrange(data.ndim):
adic = dic["w" + str(i + 1)]
udic[i]["size"] = data.shape[i]
udic[i]["sw"] = adic['spectral_width']
udic[i]["obs"] = adic['spectrometer_freq']
udic[i]["car"] = adic['xmtr_freq'] * adic['spectrometer_freq']
udic[i]["label"] = adic['nucleus']
udic[i]["complex"] = False
udic[i]["time"] = False
udic[i]["freq"] = True
return udic
def create_dic(udic, datetimeobj=datetime.datetime.now(), user='user'):
"""
Create a Sparky parameter dictionary from universal dictionary.
Parameters
----------
udic : dict
Universal dictionary of spectral parameters.
datatimeobj : datetime object, optional
Datetime to record in Sparky dictionary
user : str, optional
Username to record in Sparky dictionary. Default is 'user'
Returns
-------
dic : dict
Dictionary of Sparky parameters.
"""
dic = dict()
# determind shape of array
shape = [udic[k]["size"] for k in xrange(udic["ndim"])]
# populate the dictionary
dic["ident"] = 'UCSF NMR'
dic["naxis"] = udic["ndim"]
dic["ncomponents"] = 1
dic["encoding"] = 0
dic["version"] = 2
dic["owner"] = user
dic["date"] = datetimeobj.ctime()
dic["comment"] = ''
dic["scratch"] = ''
# calc a good tile shape
tshape = calc_tshape(shape)
# total number of tiles
ntiles = 1
for tlen, slen in zip(tshape, shape):
ntiles *= np.ceil(float(slen) / tlen)
# points in tile
tpoints = np.array(tshape).prod()
# data bytes
dbytes = tpoints * ntiles * 4
# total file size if data size plus leaders
dic["seek_pos"] = int(dbytes + 180 + 128 * len(shape))
# populate the dictionary with axis dictionaries
for i, (tlen, dlen) in enumerate(zip(tshape, shape)):
dic["w" + str(i + 1)] = create_axisdic(udic[i], tlen, dlen)
return dic
def create_axisdic(adic, tlen, dlen):
"""
Make an Sparky axis dictionary from a universal axis dictionary.
Parameters
----------
adic : dict
Axis dictionary from a universal dictionary.
tlen : int
Tile length of axis.
dlen : int
Data length of axis.
Returns
-------
sdic : dict
Sparky axis dictionary
"""
dic = dict()
dic["nucleus"] = adic["label"]
dic["spectral_shift"] = 0
dic["npoints"] = int(dlen)
dic["size"] = int(dlen)
dic["bsize"] = int(tlen)
dic["spectrometer_freq"] = float(adic["obs"])
dic["spectral_width"] = float(adic["sw"])
dic["xmtr_freq"] = float(adic["car"]) / dic["spectrometer_freq"]
dic["zero_order"] = 0.0
dic["first_order"] = 0.0
dic["first_pt_scale"] = 0.0
dic["extended"] = '\x80' # transform bit set
return dic
def datetime2dic(datetimeobj, dic):
"""
Add datetime object to dictionary
"""
dic["date"] = datetimeobj.ctime()
return dic
def dic2datetime(dic):
"""
Create a datetime object from a Sparky dictionary
"""
return datetime.datetime.strptime(dic["date"], "%a %b %d %H:%M:%S %Y")
def calc_tshape(shape, kbyte_max=128):
"""
Calculate a tile shape from data shape.
Parameters
----------
shape : tuple
Shape of NMR data (data.shape).
kbyte_max : float or int
Maximum tile size in Kilobytes.
Returns
-------
tshape : tuple
Shape of tile.
"""
# Algorithm divides each dimention by 2 until under kbyte_max tile size.
s = np.array(shape, dtype="int")
i = 0
while (s.prod() * 4. / 1024. > kbyte_max):
s[i] = np.floor(s[i] / 2.)
i = i + 1
if i == len(s):
i = 0
return tuple(s)
# global read/write functions
def read(filename):
"""
Read a Sparky file.
Parameters
----------
filename : str
Filename of Sparky file to read.
Returns
-------
dic : dict
Dictionary of Sparky parameters.
data : ndarray
Array of NMR data.
See Also
--------
read_lowmem : Sparky file reading with minimal memory usage.
write : Write a Sparky file.
"""
# open the file
f = open(filename, 'rb')
# determind the dimentionality
n = fileheader2dic(get_fileheader(f))["naxis"]
f.close()
if n == 2:
return read_2D(filename)
if n == 3:
return read_3D(filename)
raise ValueError("unknown dimentionality: %s" % n)
def read_lowmem(filename):
"""
Read a Sparky file using minimal memory.
Parameters
----------
filename : str
Filename of Sparky file to read.
Returns
-------
dic : dict
Dictionary of Sparky parameters.
data : array_like
Low memory object which can access NMR data on demand.
See Also
--------
read : Read a Sparky file.
write_lowmem : Write a Sparky file using mimimal memory.
"""
# open the file
f = open(filename, 'rb')
# determind the dimentionality
n = fileheader2dic(get_fileheader(f))["naxis"]
f.close()
if n == 2:
return read_lowmem_2D(filename)
if n == 3:
return read_lowmem_3D(filename)
raise ValueError("unknown dimentionality: %s" % n)
def write(filename, dic, data, overwrite=False):
"""
Write a Sparky file.
Parameters
----------
filename : str
Filename of Sparky file to write to.
dic : dict
Dictionary of Sparky parameters.
data : array_like
Array of NMR data.
overwrite : bool, optional
Set True to overwrite files, False will raise a Warning if the file
exists.
See Also
--------
write_lowmem : Write a Sparky file using minimal amounts of memory.
read : Read a Sparky file.
"""
n = dic["naxis"]
if n == 2:
return write_2D(filename, dic, data, overwrite=overwrite)
if n == 3:
return write_3D(filename, dic, data, overwrite=overwrite)
raise ValueError("unknown dimentionality: %s" % n)
def write_lowmem(filename, dic, data, overwrite=False):
"""
Write a Sparky using minimum amounts of memory (tile by tile)
Parameters
----------
filename : str
Filename of Sparky file to write to.
dic : dict
Dictionary of Sparky parameters.
data : array_like.
Array of NMR data.
overwrite : bool, optional
Set True to overwrite files, False will raise a Warning if the file
exists.
See Also
--------
write : Write a Sparky file.
read_lowmem : Read a Sparky file using mimimal amounts of memory.
"""
# write also writes tile by tile...
return write(filename, dic, data, overwrite)
# dimension specific reading/writing functions
def read_2D(filename):
"""
Read a 2D sparky file. See :py:func:`read` for documentation.
"""
seek_pos = os.stat(filename).st_size
f = open(filename, 'rb')
# read the file header
dic = fileheader2dic(get_fileheader(f))
# check for file size mismatch
if seek_pos != dic["seek_pos"]:
raise IOError("Bad file size %s vs %s", (seek_pos, dic["seek_pos"]))
# read the axis headers...
for i in xrange(dic['naxis']):
dic["w" + str(i + 1)] = axisheader2dic(get_axisheader(f))
# read the data and untile
lenY = dic["w1"]["npoints"]
lenX = dic["w2"]["npoints"]
lentY = dic["w1"]["bsize"]
lentX = dic["w2"]["bsize"]
data = get_data(f)
data = untile_data2D(data, (lentY, lentX), (lenY, lenX))
return dic, data
def write_2D(filename, dic, data, overwrite=False):
"""
Write a 2D Sparky file. See :py:func:`write` for documentation.
"""
# open the file for writing
f = fileiobase.open_towrite(filename, overwrite)
# write the file header
put_fileheader(f, dic2fileheader(dic))
# write the axis headers
put_axisheader(f, dic2axisheader(dic["w1"]))
put_axisheader(f, dic2axisheader(dic["w2"]))
lentX = dic["w2"]["bsize"]
lentY = dic["w1"]["bsize"]
t_tup = (lentY, lentX)
ttX = np.ceil(data.shape[1] / float(lentX)) # total tiles in X dim
ttY = np.ceil(data.shape[0] / float(lentY)) # total tiles in Y dim
tt = ttX * ttY
for i in xrange(int(tt)):
put_data(f, find_tilen_2d(data, i, (t_tup)))
f.close()
return
def read_3D(filename):
"""
Read a 3D Sparky file. See :py:func:`read` for documentation.
"""
seek_pos = os.stat(filename).st_size
f = open(filename, 'rb')
# read the file header
dic = fileheader2dic(get_fileheader(f))
# check for file size mismatch
if seek_pos != dic["seek_pos"]:
raise IOError("Bad file size %s vs %s", (seek_pos, dic["seek_pos"]))
# read the axis headers...
for i in xrange(dic['naxis']):
dic["w" + str(i + 1)] = axisheader2dic(get_axisheader(f))
# read the data and untile
lenZ = dic["w1"]["npoints"]
lenY = dic["w2"]["npoints"]
lenX = dic["w3"]["npoints"]
lentZ = dic["w1"]["bsize"]
lentY = dic["w2"]["bsize"]
lentX = dic["w3"]["bsize"]
data = get_data(f)
data = untile_data3D(data, (lentZ, lentY, lentX), (lenZ, lenY, lenX))
return dic, data
def write_3D(filename, dic, data, overwrite=False):
"""
Write a 3D Sparky file. See :py:func:`write` for documentation.
"""
# open the file for writing
f = fileiobase.open_towrite(filename, overwrite)
# write the file header
put_fileheader(f, dic2fileheader(dic))
# write the axis headers
put_axisheader(f, dic2axisheader(dic["w1"]))
put_axisheader(f, dic2axisheader(dic["w2"]))
put_axisheader(f, dic2axisheader(dic["w3"]))
lentX = dic["w3"]["bsize"]
lentY = dic["w2"]["bsize"]
lentZ = dic["w1"]["bsize"]
t_tup = (lentZ, lentY, lentX)
ttX = np.ceil(data.shape[2] / float(lentX)) # total tiles in X dim
ttY = np.ceil(data.shape[1] / float(lentY)) # total tiles in Y dim
ttZ = np.ceil(data.shape[0] / float(lentZ)) # total tiles in Z dim
tt = ttX * ttY * ttZ
for i in xrange(int(tt)):
put_data(f, find_tilen_3d(data, i, (t_tup)))
f.close()
return
# read_lowmem functions
def read_lowmem_2D(filename):
"""
Read a 2D Sparky file using minimal memory. See :py:func:`read_lowmem`.
"""
seek_pos = os.stat(filename).st_size
# create the sparky_2d file
data = sparky_2d(filename)
dic = dict(data.dic)
# check for file size mismatch
if seek_pos != dic["seek_pos"]:
raise IOError("Bad file size %s vs %s", (seek_pos, dic["seek_pos"]))
return dic, data
def read_lowmem_3D(filename):
"""
Read a 3D sparky file using minimal memory. See :py:func:`read_lowmem`.
"""
seek_pos = os.stat(filename).st_size
# create the sparky_3d file
data = sparky_3d(filename)
dic = dict(data.dic)
# check for file size mismatch
if seek_pos != dic["seek_pos"]:
raise IOError("Bad file size %s vs %s", (seek_pos, dic["seek_pos"]))
return dic, data
# sparky_ low memory objects
class sparky_2d(fileiobase.data_nd):
"""
Emulates a ndarray object without loading data into memory for low memory
reading of 2D Sparky files.
* slicing operations return ndarray objects.
* can iterate over with expected results.
* transpose and swapaxes methods create a new objects with correct axes
ordering.
* has ndim, shape, and dtype attributes.
Parameters
----------
filename : str
Filename of 2D Sparky file.
order : tuple, optional
Order of axes against file. None is equivelent to (0, 1).
"""
def __init__(self, filename, order=None):
"""
Create and set up object
"""
# open the file
self.filename = filename
f = open(filename, 'rb')
# read the fileheader
self.dic = fileheader2dic(get_fileheader(f))
if self.dic["naxis"] != 2:
raise StandardError("file is not a 2D Sparky file")
# read in the axisheaders
self.dic["w1"] = axisheader2dic(get_axisheader(f))
self.dic["w2"] = axisheader2dic(get_axisheader(f))
f.close()
# sizes
self.lenY = self.dic["w1"]["npoints"]
self.lenX = self.dic["w2"]["npoints"]
# tile sizes
self.lentY = self.dic["w1"]["bsize"]
self.lentX = self.dic["w2"]["bsize"]
# check order
if order == None:
order = (0, 1)
# finalize
self.dtype = np.dtype("float32")
self.order = order
self.fshape = (self.lenY, self.lenX)
self.__setdimandshape__()
def __fcopy__(self, order):
"""
Create a copy
"""
n = sparky_2d(self.filename, order)
return n
def __fgetitem__(self, (sY, sX)):
"""
Returns ndarray of selected values.
(sY, sX) is a well formatted tuple of slices
"""
f = open(self.filename, 'rb')
#print sY,sX
gY = range(self.lenY)[sY] # list of values to take in Y
gX = range(self.lenX)[sX] # list of values to take in X
# tiles to get in each dim to read
gtY = set([np.floor(i / self.lentY) for i in gY]) # Y tile to read
gtX = set([np.floor(i / self.lentX) for i in gX]) # X tile to read
# create a empty output directory
out = np.empty((len(gY), len(gX)), dtype=self.dtype)
for iY in gtY: # loop over Y tiles to get
for iX in gtX: # loop over X tiles to get
# get the tile and reshape it
ntile = iY * np.ceil(self.lenX / self.lentX) + iX
tile = get_tilen(f, ntile, (self.lentX, self.lentY))
tile = tile.reshape(self.lentY, self.lentX)
# tile minimum and max values for each dim
minX = iX * self.lentX
maxX = (iX + 1) * self.lentX
minY = iY * self.lentY
maxY = (iY + 1) * self.lentY
# determind what elements are needed from this tile
XinX = [i for i in gX if maxX > i >= minX] # values in gX
XinT = [i - minX for i in XinX] # tile index values
XinO = [gX.index(i) for i in XinX] # output indexes
YinY = [i for i in gY if maxY > i >= minY] # values in gX
YinT = [i - minY for i in YinY] # tile index values
YinO = [gY.index(i) for i in YinY] # output indexes
# take elements from the tile
ctile = tile.take(XinT, axis=1).take(YinT, axis=0)
# DEBUGGING info
#print "-------------------------------"
#print "iX:",iX,"iY:",iY,"ntile:",ntile
#print "tile.shape",tile.shape
#print "minX:",minX,"maxX",maxX
#print "minY:",minY,"maxY",maxY
#print "XinX",XinX
#print "XinT",XinT
#print "XinO",XinO
#print "YinY",YinY
#print "YinT",YinT
#print "YinO",YinO
# put the cut tile to the out array (uses some fancy indexing)
out[np.ix_(YinO, XinO)] = ctile
f.close()
return out
class sparky_3d(fileiobase.data_nd):
"""
Emulates a ndarray object without loading data into memory for low memory
read of 3D Sparky files.
* slicing operations return ndarray objects.
* can iterate over with expected results.
* transpose and swapaxes methods create a new objects with correct axes
ordering.
* has ndim, shape, and dtype attributes.
Parameters
----------
filename : str
Filename of 3D Sparky file.
order : tuple
Ordering of axes against file. None is equilent to (0, 1, 2)
"""
def __init__(self, filename, order=None):
"""
Create and set up object
"""
# open the file
self.filename = filename
f = open(filename, 'rb')
# read the fileheader
self.dic = fileheader2dic(get_fileheader(f))
if self.dic["naxis"] != 3:
raise StandardError("file not 3D Sparky file")
# read in the axisheaders
self.dic["w1"] = axisheader2dic(get_axisheader(f))
self.dic["w2"] = axisheader2dic(get_axisheader(f))
self.dic["w3"] = axisheader2dic(get_axisheader(f))
f.close()
# sizes
self.lenZ = self.dic["w1"]["npoints"]
self.lenY = self.dic["w2"]["npoints"]
self.lenX = self.dic["w3"]["npoints"]
# tile sizes
self.lentZ = self.dic["w1"]["bsize"]
self.lentY = self.dic["w2"]["bsize"]
self.lentX = self.dic["w3"]["bsize"]
# check order
if order == None:
order = (0, 1, 2)
# finalize
self.dtype = np.dtype("float32")
self.order = order
self.fshape = (self.lenZ, self.lenY, self.lenX)
self.__setdimandshape__()
def __fcopy__(self, order):
"""
Create a copy
"""
n = sparky_3d(self.filename, order)
return n
def __fgetitem__(self, (sZ, sY, sX)):
"""
Returns ndarray of selected values.
(sZ, sY, sX) is a well formateed tuple of slices
"""
f = open(self.filename, 'rb')
gZ = range(self.lenZ)[sZ] # list of values to take in Z
gY = range(self.lenY)[sY] # list of values to take in Y
gX = range(self.lenX)[sX] # list of values to take in X
# tiles to get in each dim to read
gtZ = set([np.floor(float(i) / self.lentZ) for i in gZ]) # Z tiles
gtY = set([np.floor(float(i) / self.lentY) for i in gY]) # Y tiles
gtX = set([np.floor(float(i) / self.lentX) for i in gX]) # X tiles
# total tiles in each dim
ttX = np.ceil(self.lenX / float(self.lentX)) # total tiles in X
ttY = np.ceil(self.lenY / float(self.lentY)) # total tiles in Y
ttZ = np.ceil(self.lenZ / float(self.lentZ)) # total tiles in Z
tile_tup = (self.lentZ, self.lentY, self.lentX)
# create a empty output array
out = np.empty((len(gZ), len(gY), len(gX)), dtype=self.dtype)
for iZ in gtZ: # loop over Z tiles to get
for iY in gtY: # loop over Y tiles to get
for iX in gtX: # loop over X tiles to get
# get the tile and reshape it
ntile = iZ * ttX * ttY + iY * ttX + iX
tile = get_tilen(f, ntile, tile_tup)
tile = tile.reshape(tile_tup)
# tile minimum and max values for each dim
minX = iX * self.lentX
maxX = (iX + 1) * self.lentX
minY = iY * self.lentY
maxY = (iY + 1) * self.lentY
minZ = iZ * self.lentZ
maxZ = (iZ + 1) * self.lentZ
# determind what elements are needed from this tile
XinX = [i for i in gX if maxX > i >= minX] # values in gX
XinT = [i - minX for i in XinX] # tile index values
XinO = [gX.index(i) for i in XinX] # output indexes
YinY = [i for i in gY if maxY > i >= minY] # values in gX
YinT = [i - minY for i in YinY] # tile index values
YinO = [gY.index(i) for i in YinY] # output indexes
ZinZ = [i for i in gZ if maxZ > i >= minZ] # values in gX
ZinT = [i - minZ for i in ZinZ] # tile index values
ZinO = [gZ.index(i) for i in ZinZ] # output indexes
# take elements from the tile
ctile = tile.take(XinT, axis=2).take(YinT, axis=1)
ctile = ctile.take(ZinT, axis=0)
# DEBUGGING info
#print "-------------------------------"
#print "iX:",iX,"iY:",iY,"iZ:",iZ,"ntile:",ntile
#print "ttX:",ttX,"ttY:",ttY,"ttZ",ttZ
#print "tile.shape",tile.shape
#print "minX:",minX,"maxX",maxX
#print "minY:",minY,"maxY",maxY
#print "minZ:",minZ,"maxZ",maxZ
#print "XinX",XinX
#print "XinT",XinT
#print "XinO",XinO
#print "YinY",YinY
#print "YinT",YinT
#print "YinO",YinO
#print "ZinZ",ZinZ
#print "ZinT",ZinT
#print "ZinO",ZinO
# put the cut tile to the out array
out[np.ix_(ZinO, YinO, XinO)] = ctile
f.close()
return out
# tile and data get/put functions
def get_tilen(f, n_tile, tw_tuple):
"""
Read a tile from a Sparky file object.
Parameters
----------
f : file object
Open file object pointing to a Sparky file.
n_tile : int
Tile number to read
tw_tuple : tuple of ints
Tile size
Returns
-------
tile : ndarray
Tile of NMR data. Data is returned as a 1D array.
Notes
-----
Current file position is loss. In can be stored before calling if the
position is later needed.
"""
# determind the size of the tile in bytes
tsize = 4
for i in tw_tuple:
tsize = tsize * i
# seek to the beginning of the tile
f.seek(int(180 + 128 * len(tw_tuple) + n_tile * tsize))
return np.frombuffer(f.read(tsize), dtype='>f4')
def get_tile(f, num_points):
"""
Read the next tile from a Sparky file object.
Parameters
----------
f : file object
Open file object pointing to a Sparky file.
num_points : int
Number of points in the tile.
Returns
-------
tile : ndarray
Tile of NMR data. Data is returned as a 1D array.
"""
bsize = num_points * 4 # size in bytes
return np.frombuffer(f.read(bsize), dtype='>f4')
def put_tile(f, tile):
"""
Put a tile to a Sparky file object.
Parameters
----------
f : file object
Open file object pointing to a Sparky file, to be written to.
tile : ndarray
Tile of NMR data to be written.
"""
f.write(tile.astype('>f4').tostring())
return
def get_data(f):
"""
Read all data from sparky file object.
"""
return np.frombuffer(f.read(), dtype='>f4')
def put_data(f, data):
"""
Put data to a Sparky file object.
This function does not untile data. This should be done before calling
this function
"""
f.write(data.astype('>f4').tostring())
return
# tiling/untiling functions
def find_tilen_2d(data, ntile, (lentY, lentX)):
"""
Return a tile from a 2D NMR data set.
Parameters
----------
data : 2D ndarray
NMR data, untiled/standard format.
ntile : int
Tile number to extract.
(lentY, lentX) : tuple of ints
Tile size (w1, w2).
Returns
-------
tile : 1D ndarray
Tile of NMR data, returned as 1D array.
Notes
-----
Edge tiles are zero filled to the indicated tile size.
"""
ttX = np.ceil(data.shape[1] / float(lentX)) # total tiles in X dim
ttY = np.ceil(data.shape[0] / float(lentY)) # total tiles in Y dim
# tile number in each dim
Xt = ntile % ttX
Yt = int(np.floor(ntile / ttX))
# dimention limits
Xmin = int(Xt * lentX)
Xmax = int((Xt + 1) * lentX)
Ymin = int(Yt * lentY)
Ymax = int((Yt + 1) * lentY)
tile = data[Ymin:Ymax, Xmin:Xmax]
# some edge tiles might need zero filling
# see if this is the case
if tile.shape == (lentY, lentX): # well sized tile
return tile.flatten()
else:
new_tile = np.zeros((lentY, lentX), dtype="float32")
new_tile[:tile.shape[0], :tile.shape[1]] = tile
return new_tile.flatten()
def tile_data2d(data, (lentY, lentX)):
"""
Tile 2D data into a 1D array.
Parameters
----------
data : 2D ndarray
NMR data, untiled/standard format.
(lentY, lentX) : tuple of ints
Tile size.
Returns
-------
tdata : 1D ndarray
Tiled/Sparky formatted NMR data, returned as 1D array.
"""
# determind the number of tiles in data
ttX = np.ceil(data.shape[1] / float(lentX)) # total tiles in X dim
ttY = np.ceil(data.shape[0] / float(lentY)) # total tiles in Y dim
tt = ttX * ttY # total number of tiles
# calc some basic parameter
tsize = lentX * lentY # number of points in one tile
t_tup = (lentY, lentX) # tile size tuple
# create an empty array to store file data
out = np.empty((tt * tsize), dtype="float32")
for i in xrange(int(tt)):
out[i * tsize:(i + 1) * tsize] = find_tilen_2d(data, i, t_tup)
return out
def untile_data2D(data, (lentY, lentX), (lenY, lenX)):
"""
Rearrange 2D Tiled/Sparky formatted data into standard format.
Parameters
----------
data : 1D ndarray
Tiled/Sparky formatted 2D NMR data.
(lentY, lenX) : tuple of ints
Size of tile.
(lenY, lenX) : tuple of ints
Size of NMR data.