/
pipe.py
2214 lines (1794 loc) · 67.1 KB
/
pipe.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 NMRPipe files and table (.tab) files
"""
__developer_info__ = """
NMRPipe file structure is described in the NMRPipe man pages and fdatap.h
"""
import struct
import datetime
import os
from StringIO import StringIO
from warnings import warn
import numpy as np
from . import fileiobase
from .table import pipe2glue, glue2pipe, guess_pformat
#########################
# table reading/writing #
#########################
def read_table(filename):
"""
Read a NMRPipe database table (.tab) file.
Parameters
----------
filename : str
Filename of NMRPipe table file to read.
Returns
-------
pcomments : list
List of NMRPipe comment lines
pformat: list
List of NMRPipe table column format strings.
rec : recarray
Records array with named fields.
See Also
--------
write_table : Write a NMRPipe table file.
"""
# divide up into comment lines and data lines
specials = ["VARS", "FORMAT", "NULLSTRING", "NULLVALUE", "REMARK", "DATA"]
f = open(filename, 'rb')
cl = []
dl = []
for line in f:
for k in specials:
if line[:len(k)] == k:
cl.append(line)
break
else:
dl.append(line)
f.close()
# pull out and parse the VARS line
vl = [i for i, l in enumerate(cl) if l[:4] == "VARS"]
if len(vl) != 1:
raise IOError("%s has no/more than one VARS line" % (filename))
dtd = {'names': cl.pop(vl[0]).split()[1:]}
# pull out and parse the FORMAT line
fl = [i for i, l in enumerate(cl) if l[:6] == "FORMAT"]
if len(fl) != 1:
raise IOError("%s has no/more than one FORMAT line" % (filename))
pformat = cl.pop(fl[0]).split()[1:]
p2f = {'d': 'i4', 'f': 'f8', 'e': 'f8', 's': 'S256'} # pipe -> format
dtd['formats'] = [p2f[i[-1]] for i in pformat]
# DEBUG
#print dtd['names'],dtd['formats']
s = StringIO("".join(dl))
rec = np.recfromtxt(s, dtype=dtd, comments='XXXXXXXXXXX')
return cl, pformat, np.atleast_1d(rec)
def write_table(filename, pcomments, pformats, rec, overwrite=False):
"""
Write a NMRPipe database table (.tab) file.
Parameters
----------
filename : str
Filename of file to write to.
pcomments: list
List of NMRPipe comment lines.
pformats :
List of NMRPipe table column formats strings.
rec : recarray
Records array of table.
overwrite: bool, optional
True to overwrite file if it exists, False will raise a Warning if the
file exists.
See Also
--------
read_table : Read a NMRPipe table file.
"""
if len(rec[0]) != len(pformats):
s = "number of rec columns %i and pformat elements %i do not match"
raise ValueError(s % (len(rec[0]), len(pformats)))
# open the file for writing
f = fileiobase.open_towrite(filename, overwrite)
# write out the VARS line
names = rec.dtype.names
s = "VARS " + " ".join(names) + "\n"
f.write(s)
# write out the FORMAT line
s = "FORMAT " + " ".join(pformats) + "\n"
f.write(s)
# write out any comment lines
for c in pcomments:
f.write(c)
# write out each line of the records array
s = " ".join(pformats) + "\n"
for row in rec:
f.write(s % tuple(row))
f.close()
return
###################
# unit conversion #
###################
def make_uc(dic, data, dim=-1):
"""
Create a unit conversion object
Parameters
----------
dic : dict
Dictionary of NMRPipe parameters.
data : ndarray
Array of NMR data.
dim : int, optional
Dimension number to create unit conversion object for. Default is for
last (direct) dimension.
Returns
-------
uc : unit conversion object
Unit conversion object for given dimension.
"""
if dim == -1:
dim = data.ndim - 1 # last dimention
fn = "FDF" + str(int(dic["FDDIMORDER"][data.ndim - 1 - dim]))
size = float(data.shape[dim])
# check for quadrature in indirect dimentions
if (dic[fn + "QUADFLAG"] != 1) and (dim != data.ndim - 1):
size = size / 2.
cplx = True
else:
cplx = False
sw = dic[fn + "SW"]
if sw == 0.0:
sw = 1.0
obs = dic[fn + "OBS"]
if obs == 0.0:
obs = 1.0
car = dic[fn + "CAR"] * obs
# NMRPipe keeps the carrier constant during extractions storing the
# location of this point as CENTER. This may not be the actual "center" of
# the spectrum and may not even be a valid index in that dimension. We need
# to re-center the carrier value so that actually represents the
# frequency of the central point in the dimension.
car = car + sw / size * (dic[fn + "CENTER"] - 1. - size / 2.)
return fileiobase.unit_conversion(size, cplx, sw, obs, car)
############################
# dictionary/data creation #
############################
fd2dphase_dic = {"magnitude": 0, "tppi": 1, "states": 2, "image": 3}
def create_data(data):
"""
Create a NMRPipe data array (recast into float32 or complex64)
"""
if np.iscomplexobj(data): # check quadrature
return np.array(data, dtype="complex64")
else:
return np.array(data, dtype="float32")
########################
# universal dictionary #
########################
def guess_udic(dic, data):
"""
Guess parameters of universal dictionary from dic, data pair.
Parameters
----------
dic : dict
Dictionary of NMRPipe parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Universal dictionary of spectral parameters.
"""
# create an empty universal dictionary
udic = fileiobase.create_blank_udic(data.ndim)
# update default values
for i in xrange(data.ndim):
udic[i]["size"] = data.shape[i] # size from data shape
# determind NMRPipe axis name
fn = ["FDF2", "FDF1", "FDF3", "FDF4"][(data.ndim - 1) - i]
# directly corresponding
udic[i]["sw"] = dic[fn + "SW"]
udic[i]["obs"] = dic[fn + "OBS"]
udic[i]["car"] = dic[fn + "CAR"] * dic[fn + "OBS"] # ppm->hz
udic[i]["label"] = dic[fn + "LABEL"]
if dic[fn + "QUADFLAG"] == 1: # real data
udic[i]["complex"] = False
else:
udic[i]["complex"] = True
if dic[fn + "FTFLAG"] == 0: # time domain
udic[i]["time"] = True
udic[i]["freq"] = False
else:
udic[i]["time"] = False
udic[i]["freq"] = True
if i != 0:
if dic["FD2DPHASE"] == 0:
udic[i]["encoding"] = "magnitude"
elif dic["FD2DPHASE"] == 1:
udic[i]["encoding"] = "tppi"
elif dic["FD2DPHASE"] == 2:
udic[i]["encoding"] = "states"
elif dic["FD2DPHASE"] == 2:
udic[i]["encoding"] = "image"
else:
udic[i]["encoding"] = "unknown"
return udic
def create_dic(udic, datetimeobj=datetime.datetime.now()):
"""
Crate a NMRPipe parameter dictionary from universal dictionary
This function does not update the dictionary keys that are unknown such as
MIN/MAX, apodization and processing parameters, and sizes in none-current
domain. Also rounding of parameter is different than NMRPipe.
Parameters
----------
udic : dict
Universal dictionary of spectral parameters.
datetimeobj : datetime object, optional
Datetime to record in NMRPipe dictionary
Returns
-------
dic : dict
Dictionary NMRPipe parameters.
"""
# create the blank dictionary
dic = create_empty_dic() # create the empty dictionary
dic = datetime2dic(datetimeobj, dic) # add the datetime to the dictionary
# fill global dictionary parameters
dic["FDDIMCOUNT"] = float(udic["ndim"])
# FD2DPHASE
if udic[0]["encoding"] == "tppi":
dic["FD2DPHASE"] = 1.0
elif udic[0]["encoding"] == "states":
dic["FD2DPHASE"] = 2.0
else:
dic["FD2DPHASE"] = 0.0
# fill in parameters for each dimension
for i, adic in enumerate([udic[k] for k in xrange(udic["ndim"])]):
n = int((dic["FDDIMCOUNT"] - 1) - i)
dic = add_axis_to_dic(dic, adic, n)
if dic["FDDIMCOUNT"] >= 3: # at least 3D
dic["FDFILECOUNT"] = dic["FDF3SIZE"] * dic["FDF4SIZE"]
if ((dic["FDF1QUADFLAG"] == dic["FDF2QUADFLAG"] == dic["FDF3QUADFLAG"]) and
(dic["FDF1QUADFLAG"] == dic["FDF4QUADFLAG"] == 1)):
dic["FDQUADFLAG"] = 1.0
return dic
def add_axis_to_dic(dic, adic, n):
"""
Add an axis dictionary (adic) to a NMRPipe dictionary (dic) as axis n.
"""
# determind F1,F2,F3,...
fn = ["FDF2", "FDF1", "FDF3", "FDF4"][n]
# parameter directly in dictionary
dic[fn + "SW"] = float(adic["sw"])
dic[fn + "OBS"] = float(adic["obs"])
dic[fn + "CAR"] = float(adic["car"] / adic["obs"])
dic[fn + "LABEL"] = adic["label"]
if adic["complex"]:
dic[fn + "QUADFLAG"] = 0.0
else:
dic[fn + "QUADFLAG"] = 1.0
# determine R|I size
if adic["complex"] and n != 0:
psize = adic["size"] / 2.
else:
psize = adic["size"] / 1.
# origin calculation size
osize = psize
# set FT/TD SIZE and FTFLAG depending on domain
if adic["time"]:
dic[fn + "TDSIZE"] = psize
dic[fn + "FTFLAG"] = 0.0
else:
dic[fn + "FTSIZE"] = psize
dic[fn + "FTFLAG"] = 1.0
# apodization and center
dic[fn + "APOD"] = dic[fn + "TDSIZE"]
if n == 0 or dic["FD2DPHASE"] != 1:
dic[fn + "CENTER"] = int(psize / 2.) + 1.
else: # TPPI requires division by 4
dic[fn + "CENTER"] = int(psize / 4.) + 1
osize = psize / 2.
# origin (last point) is CAR*OBS-SW*(N/2-1)/N
# see Fig 3.1 on p.36 of Hoch and Stern
#print "fn:",n
#print "CAR:",dic[fn+"CAR"]
#print "OBS:",dic[fn+"OBS"]
#print "SW:",dic[fn+"SW"]
#print "osize:",osize
#print "CENTER:",dic[fn+"CENTER"]
dic[fn + "ORIG"] = (dic[fn + "CAR"] * dic[fn + "OBS"] - dic[fn + "SW"] *
(osize - dic[fn + "CENTER"]) / osize)
if n == 0: # direct dim
dic["FDSIZE"] = psize
dic["FDREALSIZE"] = psize
if n == 1: # first indirect
dic["FDSPECNUM"] = float(adic["size"]) # R+I
if n == 2: # second indirect
if adic["complex"]:
dic["FDF3SIZE"] = psize * 2
else:
dic["FDF3SIZE"] = psize
if n == 3: # third indirect
if adic["complex"]:
dic["FDF4SIZE"] = psize * 2
else:
dic["FDF3SIZE"] = psize
return dic
def create_empty_dic():
"""
Creates a NMRPipe dictionary with default values
"""
dic = fdata2dic(np.zeros((512), dtype="float32"))
# parameters which are 1
dic["FDF1CENTER"] = 1.
dic["FDF2CENTER"] = 1.
dic["FDF3CENTER"] = 1.
dic["FDF4CENTER"] = 1.
dic["FDF3SIZE"] = 1.
dic["FDF4SIZE"] = 1.
dic["FDF1QUADFLAG"] = 1.
dic["FDF2QUADFLAG"] = 1.
dic["FDF3QUADFLAG"] = 1.
dic["FDF4QUADFLAG"] = 1.
dic["FDSPECNUM"] = 1.
dic["FDFILECOUNT"] = 1.
dic["FD2DVIRGIN"] = 1.
# dimention ordering
dic["FDDIMORDER1"] = 2.0
dic["FDDIMORDER2"] = 1.0
dic["FDDIMORDER3"] = 3.0
dic["FDDIMORDER4"] = 4.0
dic["FDDIMORDER"] = [2.0, 1.0, 3.0, 4.0]
# string and such
dic["FDF1LABEL"] = "Y"
dic["FDF2LABEL"] = "X"
dic["FDF3LABEL"] = "Z"
dic["FDF4LABEL"] = "A"
# misc values
dic["FDFLTFORMAT"] = struct.unpack('f', '\xef\xeenO')[0]
dic["FDFLTORDER"] = float(2.3450000286102295)
return dic
def datetime2dic(dt, dic):
"""
Add datatime object to a NMRPipe dictionary
"""
dic["FDYEAR"] = float(dt.year)
dic["FDMONTH"] = float(dt.month)
dic["FDDAY"] = float(dt.day)
dic["FDHOURS"] = float(dt.hour)
dic["FDMINS"] = float(dt.minute)
dic["FDSECS"] = float(dt.second)
return dic
def dic2datetime(dic):
"""
Create a datetime object from a NMRPipe dictionary
"""
year = int(dic["FDYEAR"])
month = int(dic["FDMONTH"])
day = int(dic["FDDAY"])
hour = int(dic["FDHOURS"])
minute = int(dic["FDMINS"])
second = int(dic["FDSECS"])
return datetime.datetime(year, month, day, hour, minute, second)
################
# file reading #
################
def read(filename):
"""
Read a NMRPipe file.
For standard multi-file 3D/4D NMRPipe data sets, filename should be a
filemask (for example "/ft/test%03d.ft3") with a "%" formatter. If only
one file of a 3D/4D data set is provided only that 2D slice of the data is
read (for example "/ft/test001.ft3" results in a 2D data set being read).
NMRPipe data streams stored as files (one file 3D/4D data sets made using
xyz2pipe) can be read by providing the file name of the stream. The entire
data set is read into memory.
Parameters
----------
filename : str
Filename or filemask of NMRPipe file(s) to read.
Returns
--------
dic : dict
Dictionary of NMRPipe parameters.
data : ndarray
Array of NMR data.
See Also
--------
read_lowmem : NMRPipe file reading with minimal memory usage.
write : Write a NMRPipe data to file(s).
"""
if filename.count("%") == 1:
filemask = filename
filename = filename % 1
elif filename.count("%") == 2:
filemask = filename
filename = filename % (1, 1)
else:
filemask = None
fdata = get_fdata(filename)
dic = fdata2dic(fdata)
order = dic["FDDIMCOUNT"]
if order == 1:
return read_1D(filename)
if order == 2:
return read_2D(filename)
if dic["FDPIPEFLAG"] != 0: # open streams
return read_stream(filename)
if filemask == None: # if no filemask open as 2D
return read_2D(filename)
if order == 3:
return read_3D(filemask)
if order == 4:
return read_4D(filemask)
raise ValueError('unknown dimensionality: %s' % order)
def read_lowmem(filename):
"""
Read a NMRPipe file with minimal memory usage.
See :py:func:`read` for Parameters and information.
Returns
-------
dic : dict
Dictionary of NMRPipe parameters.
data : array_like
Low memory object which can access NMR data on demand.
See Also
--------
read : Read NMRPipe files.
write_lowmem : Write NMRPipe files using minimal amounts of memory.
"""
if filename.count("%") == 1:
filemask = filename
filename = filename % 1
elif filename.count("%") == 2:
filemask = filename
filename = filename % (1, 1)
else:
filemask = None
fdata = get_fdata(filename)
dic = fdata2dic(fdata)
order = dic["FDDIMCOUNT"]
if order == 1:
return read_1D(filename) # there is no 1D low memory option
if order == 2:
return read_lowmem_2D(filename)
if dic["FDPIPEFLAG"] != 0: # open streams
return read_lowmem_stream(filename)
if filemask == None: # if no filemask open as 2D
return read_lowmem_2D(filename)
if order == 3:
return read_lowmem_3D(filemask)
if order == 4:
return read_lowmem_4D(filemask)
raise ValueError('unknown dimentionality: %s' % order)
# dimension specific reading
def read_1D(filename):
"""
Read a 1D NMRPipe file.
See :py:func:`read` for documentation.
"""
fdata, data = get_fdata_data(filename) # get the fdata and data arrays
dic = fdata2dic(fdata) # convert the fdata block to a python dictionary
data = reshape_data(data, find_shape(dic)) # reshape data
# unappend imaginary data if needed
if dic["FDF2QUADFLAG"] != 1:
data = unappend_data(data)
return (dic, data)
def read_2D(filename):
"""
Read a 2D NMRPipe file or NMRPipe data stream.
See :py:func:`read` for documentation.
"""
fdata, data = get_fdata_data(filename) # get the fdata and data arrays
dic = fdata2dic(fdata) # convert the fdata block to a python dictionary
data = reshape_data(data, find_shape(dic)) # reshape data
# unappend imaginary data if needed
if dic["FDTRANSPOSED"] == 1 and dic["FDF1QUADFLAG"] != 1:
data = unappend_data(data)
elif dic["FDTRANSPOSED"] == 0 and dic["FDF2QUADFLAG"] != 1:
data = unappend_data(data)
return (dic, data)
def read_lowmem_2D(filename):
"""
Read a 2D NMRPipe file or NMRPipe data stream using minimal memory.
See :py:func:`read_lowmem` for documentation
"""
dic = fdata2dic(get_fdata(filename))
order = dic["FDDIMCOUNT"]
if order == 2:
data = pipe_2d(filename)
if order == 3:
data = pipestream_3d(filename)
if order == 4:
data = pipestream_4d(filename)
return dic, data
def read_stream(filename):
"""
Read a NMRPipe data stream (one file 3D or 4D files).
See :py:func:`read` for documentation.
"""
return read_2D(filename)
def read_lowmem_stream(filename):
"""
Read a NMRPipe data stream using minimal memory.
See :py:func:`read_lowmem` for documentation.
"""
return read_lowmem_2D(filename)
def read_3D(filemask):
"""
Read a 3D NMRPipe file.
See :py:func:`read` for documentation.
"""
dic, data = read_lowmem_3D(filemask)
data = data[:, :, :] # read all the data
return dic, data
def read_lowmem_3D(filemask):
"""
Read a 3D NMRPipe file using minimal memory.
See :py:func:`read_lowmem` for documentation
"""
if '%' not in filemask: # data streams should be read with read_stream
return read_lowmem_stream(filemask)
data = pipe_3d(filemask) # create a new pipe_3d object
dic = fdata2dic(get_fdata(filemask % (1)))
return dic, data
def read_4D(filemask):
"""
Read a 3D NMRPipe file.
See :py:func:`read` for documentation.
Notes
-----
This function should not be used to read NMRPipe data streams stored in a
single file (one file 3D/4D data sets made using xyz2pipe),
:py:func:`read_2D` should be used.
"""
dic, data = read_lowmem_4D(filemask)
data = data[:, :, :, :] # read all the data
return dic, data
def read_lowmem_4D(filemask):
"""
Read a NMRPipe file using minimal memory.
See :py:func:`read_lowmem` for documentation
Notes
-----
This function should not be used to read NMRPipe data streams stored in a
single file (one file 3D/4D data sets made using xyz2pipe),
:py:func:`read_lowmem_2D` should be used.
"""
if '%' not in filemask: # data streams should be read with read_stream
return read_lowmem_stream(filemask)
data = pipe_4d(filemask) # create a new pipe_3d object
if data.singleindex:
dic = fdata2dic(get_fdata(filemask % (1)))
else:
dic = fdata2dic(get_fdata(filemask % (1, 1)))
return (dic, data)
#####################
# writing functions #
#####################
def write(filename, dic, data, overwrite=False):
"""
Write a NMRPipe file to disk.
Parameters
----------
filename : str
Filename of NMRPipe to write to. See Notes.
dic : dict
Dictionary of NMRPipe parameters.
data : array_like
Array of NMR data.
overwrite : bool, optional.
Set True to overwrite files, False will raise a Warning if file
exists.
Notes
-----
For 3D data if filename has no '%' formatter then the data is written as a
3D NMRPipe data stream. When the '%' formatter is provided the data is
written out as a standard NMRPipe 3D multi-file 3D.
For 4D data, filename can have one, two or no '%' formatters resulting in
a single index file (test%03d.ft), two index file(test%02d%03d.ft), or
one file data stream (test.ft4).
dic["FDPIPEFLAG"] is not changed or checked when writing, please check
that this value is 0.0 for standard non-data stream files, and 1.0 for data
stream files or an file may be written with an incorrect header.
Set overwrite to True to overwrite files that exist.
See Also
--------
write_lowmem : Write NMRPipe files using minimal amounts of memory.
read : Read NMRPipe files.
"""
# load all data if the data is not a numpy ndarray
if type(data) != np.ndarray:
data = data[:]
if filename.count("%") == 0:
return write_single(filename, dic, data, overwrite)
elif data.ndim == 3:
return write_3D(filename, dic, data, overwrite)
elif data.ndim == 4:
return write_4D(filename, dic, data, overwrite)
raise ValueError('unknown filename/dimension')
def write_single(filename, dic, data, overwrite=False):
"""
Write data to a single NMRPipe file from memory.
Write 1D and 2D files completely as well as NMRPipe data streams.
2D planes of 3D and 4D files should be written with this function.
See :py:func:`write` for documentation.
"""
# append imaginary and flatten
if data.dtype == "complex64":
data = append_data(data)
data = unshape_data(data)
# create the fdata array
fdata = dic2fdata(dic)
# write the file
put_data(filename, fdata, data, overwrite)
return
def write_3D(filemask, dic, data, overwrite=False):
"""
Write a standard multi-file 3D NMRPipe file
See :py:func:`write` for documentation.
"""
lenZ, lenY, lenX = data.shape
for zi in range(lenZ):
fn = filemask % (zi + 1)
plane = data[zi]
write_single(fn, dic, plane, overwrite)
return
def write_4D(filemask, dic, data, overwrite=False):
"""
Write a one or two index 4D NMRPipe file.
See :py:func:`write` for documentation.
"""
lenA, lenZ, lenY, lenX = data.shape
for ai in range(lenA):
for zi in range(lenZ):
if filemask.count("%") == 2:
fn = filemask % (ai + 1, zi + 1)
else:
fn = filemask % (ai * lenZ + zi + 1)
plane = data[ai, zi]
# update dictionary if needed
if dic["FDSCALEFLAG"] == 1:
dic["FDMAX"] = plane.max()
dic["FDDISPMAX"] = dic["FDMAX"]
dic["FDMIN"] = plane.min()
dic["FDDISPMIN"] = dic["FDMIN"]
write_single(fn, dic, plane, overwrite)
return
def write_lowmem(filename, dic, data, overwrite=False):
"""
Write a NMRPipe file to disk using minimal memory (trace by trace).
Parameters
----------
filename : str
Filename of NMRPipe to write to. See :py:func:`write` for details.
dic : dict
Dictionary of NMRPipe parameters.
data : array_like
Array of NMR data.
overwrite : bool, optional.
Set True to overwrite files, False will raise a Warning if file
exists.
See Also
--------
write : Write a NMRPipe file to disk.
read_lowmem : Read a NMRPipe file using minimal memory.
"""
if data.ndim == 1:
return write_single(filename, dic, data, overwrite)
if data.ndim == 2:
return write_lowmem_2D(filename, dic, data, overwrite)
if data.ndim == 3:
if "%" in filename:
return write_lowmem_3D(filename, dic, data, overwrite)
else:
return write_lowmem_3Ds(filename, dic, data, overwrite)
if data.ndim == 4:
if "%" in filename:
return write_lowmem_4D(filename, dic, data, overwrite)
else:
return write_lowmem_4Ds(filename, dic, data, overwrite)
raise ValueError('unknown dimensionality: %s' % data.ndim)
def write_lowmem_2D(filename, dic, data, overwrite=False):
"""
Write a 2D NMRPipe file using minimal memory (trace by trace)
See :py:func:`write_lowmem` for documentation.
"""
fh = fileiobase.open_towrite(filename, overwrite=overwrite)
# create the fdata array and put to disk
fdata = dic2fdata(dic)
put_fdata(fh, fdata)
# put data trace by trace
lenY, lenX = data.shape
for y in xrange(lenY):
put_trace(fh, data[y])
fh.close()
return
def write_lowmem_3D(filename, dic, data, overwrite=False):
"""
Write a standard multi-file 3D NMRPipe file using minimal memory.
See :py:func:`write_lowmem` for documentation.
Notes
-----
MIN/MAX parameters are not updated in the NMRPipe headers.
"""
# create the fdata array
fdata = dic2fdata(dic)
# put data trace by trace
lenZ, lenY, lenX = data.shape
for z in xrange(lenZ):
# open the file to store the 2D plane
fh = fileiobase.open_towrite(filename % (z + 1), overwrite=overwrite)
put_fdata(fh, fdata)
for y in xrange(lenY):
put_trace(fh, data[z, y])
fh.close()
return
def write_lowmem_3Ds(filename, dic, data, overwrite=False):
"""
Write 3D NMRPipe data stream file using minimal memory (trace by trace)
See :py:func:`write_lowmem` for documentation.
"""
fh = fileiobase.open_towrite(filename, overwrite=overwrite)
# create the fdata array and put to disk
fdata = dic2fdata(dic)
put_fdata(fh, fdata)
# put data trace by trace
lenZ, lenY, lenX = data.shape
for z in xrange(lenZ):
for y in xrange(lenY):
put_trace(fh, data[z, y])
fh.close()
return
def write_lowmem_4D(filename, dic, data, overwrite=False):
"""
Write a multi-file (single or double index) 4D NMRPipe file using
minimal memory.
See :py:func:`write_lowmem` for documentation.
Notes
-----
MIN/MAX parameters are not updated in the NMRPipe headers.
"""
# create the fdata array
fdata = dic2fdata(dic)
# put data trace by trace
lenA, lenZ, lenY, lenX = data.shape
for a in xrange(lenA):
for z in xrange(lenZ):
# open the file to store the 2D plane
if filename.count("%") == 1:
fname = filename % (a * lenZ + z + 1)
else:
fname = filename % (a + 1, z + 1)
fh = fileiobase.open_towrite(fname, overwrite=overwrite)
put_fdata(fh, fdata)
for y in xrange(lenY):
put_trace(fh, data[a, z, y])
fh.close()
return
def write_lowmem_4Ds(filename, dic, data, overwrite=False):
"""
Write 4D NMRPipe data stream file using minimal memory (trace by trace)
See :py:func:`write_lowmem` for documentation.
"""
fh = fileiobase.open_towrite(filename, overwrite=overwrite)
# create the fdata array and put to disk
fdata = dic2fdata(dic)
put_fdata(fh, fdata)
# put data trace by trace
lenA, lenZ, lenY, lenX = data.shape
for a in xrange(lenA):
for z in xrange(lenZ):
for y in xrange(lenY):
put_trace(fh, data[a, z, y])
fh.close()