/
bruker.py
1576 lines (1280 loc) · 47.7 KB
/
bruker.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 Bruker binary (ser/fid) files, Bruker
JCAMP-DX parameter (acqus) files, and Bruker pulse program (pulseprogram)
files.
"""
__developer_info__ = """
Bruker file format information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Bruker binary files (ser/fid) store data as an array of int32s whose endiness
is determinded by the parameter BYTORDA (1 = big endian, 0 = little endian).
Typically the direct dimension is digitally filtered. The exact method of
removing this filter is unknown but an approximation is avaliable.
Bruker JCAMP-DX files (acqus, etc) are text file which are described by the
`JCAMP-DX standard <http://www.jcamp-dx.org/>`_. Bruker parameters are
prefixed with a '$'.
Bruker pulseprogram files are text files described in various Bruker manuals.
Of special important are lines which describe external variable assignments
(surrounded by "'s), loops (begin with lo), phases (contain ip of dp) or
increments (contain id, dd, ipu or dpu). These lines are parsed when reading
the file with nmrglue.
"""
import os
import numpy as np
from . import fileiobase
from ..process import proc_base
# data creation
def create_data(data):
"""
Create a bruker data array (recast into a complex128 or int32)
"""
if np.iscomplexobj(data):
return np.array(data, dtype='complex128')
else:
return np.array(data, dtype='int32')
# universal dictionary functions
def guess_udic(dic, data):
"""
Guess parameters of universal dictionary from dic, data pair.
Parameters
----------
dic : dict
Dictionary of Bruker parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Universal dictionary of spectral parameters.
"""
# XXX if pprog, acqus are in dic use them
# 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]
return udic
def create_dic(udic):
"""
Create a Bruker parameter dictionary from a universal dictionary.
Parameters
----------
udic : dict
Universal dictionary of spectral parameters.
Returns
-------
dic : dict
Dictionary of Bruker parameters.
"""
ndim = udic['ndim']
# determind the size in bytes
if udic[ndim - 1]["complex"]:
bytes = 8
else:
bytes = 4
for k in xrange(ndim):
bytes *= udic[k]["size"]
dic = {"FILE_SIZE":bytes}
# create the pprog dictionary parameter
dic["pprog"] = {'incr': [[], [1]] * (ndim*2-2),
'loop': [2] * (ndim * 2 - 2),
'ph_extra': [[]] * (ndim * 2 - 2),
'phase': [[]] * (ndim * 2 - 2),
'var': {}}
# create acqus dictionary parameters and fill in loop sizes
dic['acqus'] = create_acqus_dic(udic[ndim - 1], direct=True)
if ndim >= 2:
dic["acqu2s"] = create_acqus_dic(udic[ndim - 2])
dic["pprog"]["loop"][1] = udic[ndim - 2]["size"] / 2
if ndim >= 3:
dic["acqu3s"] = create_acqus_dic(udic[ndim - 3])
dic["pprog"]["loop"][3] = udic[ndim - 3]["size"] / 2
if ndim >= 4:
dic["acqu4s"] = create_acqus_dic(udic[ndim - 4])
dic["pprog"]["loop"][5] = udic[ndim - 4]["size"] / 2
return dic
def create_acqus_dic(adic, direct=False):
"""
Create a Bruker acqus dictionary from an Universal axis dictionary.
Set direct=True for direct dimension.
"""
if adic["complex"]:
AQ_mod = 3
if direct:
TD = int(np.ceil(adic["size"] / 256.) * 256 ) * 2
else:
TD = adic["size"]
else:
AQ_mod = 1
if direct:
TD = int(np.ceil(adic["size"] / 256.) * 256)
else:
TD = adic["size"]
s = '##NMRGLUE automatically created parameter file'
return {'_comments':[], '_coreheader':[s], 'AQ_mod':AQ_mod, 'TD':TD}
# Global read/write function and related utilities
def read(dir=".", bin_file=None, acqus_files=None, pprog_file=None,
shape=None, cplex=None, big=None, read_prog=True, read_acqus=True):
"""
Read Bruker files from a directory.
Parameters
----------
dir : str
Directory to read from.
bin_file : str, optional
Filename of binary file in directory. None uses standard files.
acqus_files : list, optional
List of filename(s) of acqus parameter files in directory. None uses
standard files.
pprog_file : str, optional
Filename of pulse program in directory. None uses standard files.
shape : tuple, optional
Shape of resulting data. None will guess the shape from the spectral
parameters.
cplex : bool, optional
True is direct dimension is complex, False otherwise. None will guess
quadrature from spectral parameters.
big : bool or None, optional
Endiness of binary file. True of big-endian, False for little-endian,
None to determine endiness from acqus file(s).
read_pprog : bool, optional
True to read pulse program, False prevents reading.
read_acqus : bool, optional
True to read acqus files(s), False prevents reading.
Returns
-------
dic : dict
Dictionary of Bruker parameters.
data : ndarray
Array of NMR data.
See Also
--------
read_lowmem : Low memory reading of Bruker files.
write : Write Bruker files.
"""
if os.path.isdir(dir) != True:
raise IOError, "directory %s does not exist" % (dir)
# determind parameter automatically
if bin_file == None:
if os.path.isfile(os.path.join(dir, "fid")):
bin_file = "fid"
elif os.path.isfile(os.path.join(dir, "ser")):
bin_file = "ser"
else:
raise IOError,"No Bruker binary file could be found in %s" % (dir)
if acqus_files == None:
acqus_files = []
for f in ["acqus", "acqu2s", "acqu3s", "acqu4s"]:
if os.path.isfile(os.path.join(dir, f)):
acqus_files.append(f)
if pprog_file == None:
pprog_file = "pulseprogram"
# create an empty dictionary
dic = dict()
# read the acqus_files and add to the dictionary
if read_acqus:
for f in acqus_files:
dic[f] = read_jcamp(os.path.join(dir, f))
# read the pulse program and add to the dictionary
if read_prog:
dic["pprog"] = read_pprog(os.path.join(dir, pprog_file))
# determind file size and add to the dictionary
dic["FILE_SIZE"] = os.stat(os.path.join(dir, bin_file)).st_size
# determind shape and complexity for direct dim if needed
if shape == None or cplex == None:
gshape, gcplex = guess_shape(dic)
if gcplex == True: # divide last dim by 2 if complex
t = list(gshape)
t[-1] = t[-1] / 2
gshape = tuple(t)
if shape == None:
shape = gshape
if cplex == None:
cplex = gcplex
# determind endianness (assume little-endian unless BYTORDA is 1)
if big == None:
big = False # default value
if "acqus" in dic and "BYTORDA" in dic["acqus"]:
if dic["acqus"]["BYTORDA"] == 1:
big = True
else:
big = False
# read the binary file
f = os.path.join(dir, bin_file)
null, data = read_binary(f, shape=shape, cplex=cplex, big=big)
return dic, data
def read_lowmem(dir=".", bin_file=None, acqus_files=None, pprog_file=None,
shape=None, cplex=None, big=None, read_prog=True, read_acqus=True):
"""
Read Bruker files from a directory using minimal amounts of memory.
See :py:func:`read` for Parameters.
Returns
-------
dic : dict
Dictionary of Bruker parameters.
data : array_like
Low memory object which can access NMR data on demand.
See Also
--------
read : Read Bruker files.
write_lowmem : Write Bruker files using minimal amounts of memory.
"""
if os.path.isdir(dir) != True:
raise IOError, "directory %s does not exist" % (dir)
# determind parameter automatically
if bin_file == None:
if os.path.isfile(os.path.join(dir, "fid")):
bin_file = "fid"
elif os.path.isfile(os.path.join(dir, "ser")):
bin_file = "ser"
else:
raise IOError, "no Bruker binary file could be found in %s" % (dir)
if acqus_files == None:
acqus_files = []
for f in ["acqus", "acqu2s", "acqu3s", "acqu4s"]:
if os.path.isfile(os.path.join(dir, f)):
acqus_files.append(f)
if pprog_file == None:
pprog_file = "pulseprogram"
# create an empty dictionary
dic = dict()
# read the acqus_files and add to the dictionary
if read_acqus:
for f in acqus_files:
dic[f] = read_jcamp(os.path.join(dir, f))
# read the pulse program and add to the dictionary
if read_prog:
dic["pprog"] = read_pprog(os.path.join(dir, pprog_file))
# determind file size and add to the dictionary
dic["FILE_SIZE"] = os.stat(os.path.join(dir, bin_file)).st_size
# determind shape and complexity for direct dim if needed
if shape == None or cplex == None:
gshape, gcplex = guess_shape(dic)
if gcplex == True: # divide last dim by 2 if complex
t = list(gshape)
t[-1] = t[-1] / 2
gshape = tuple(t)
if shape == None:
shape = gshape
if cplex == None:
cplex = gcplex
# determind endianness (assume little-endian unless BYTORDA is 1)
if big == None:
big = False # default value
if "acqus" in dic and "BYTORDA" in dic["acqus"]:
if dic["acqus"]["BYTORDA"] == 1:
big = True
else:
big = False
# read the binary file
f = os.path.join(dir, bin_file)
null, data = read_binary_lowmem(f, shape=shape, cplex=cplex, big=big)
return dic, data
def write(dir, dic, data, bin_file=None, acqus_files=None, pprog_file=None,
overwrite=False, big=None, write_prog=True, write_acqus=True):
"""
Write Bruker files to disk.
Parameters
----------
dir : str
Directory to write files to.
dir : dict
Dictionary of Bruker parameters.
data : array_like
Array of NMR data
bin_file : str, optional
Filename of binary file in directory. None uses standard files.
acqus_files : list, optional
List of filename(s) of acqus parameter files in directory. None uses
standard files.
pprog_file : str, optional
Filename of pulse program in directory. None uses standard files.
overwrite : bool, optional
Set True to overwrite files, False will raise a Warning if files
exist.
big : bool or None, optional
Endiness of binary file. True of big-endian, False for little-endian,
None to determine endiness from Bruker dictionary.
write_pprog : bool, optional
True to write the pulse program file, False prevents writing.
write_acqus : bool, optional
True to write the acqus files(s), False prevents writing.
See Also
--------
write_lowmem : Write Bruker files using minimal amounts of memory.
read : Read Bruker files.
"""
# determind parameters automatically
if bin_file == None:
if data.ndim == 1:
bin_file = "fid"
else:
bin_file = "ser"
if acqus_files == None:
acq = ["acqus", "acqu2s", "acqu3s", "acqu4s"]
acqus_files = [k for k in acq if dic.has_key(k)]
if pprog_file == None:
pprog_file = "pulseprogram"
# write out the acqus files
if write_acqus:
for f in acqus_files:
write_jcamp(dic[f], os.path.join(dir, f), overwrite=overwrite)
# write out the pulse program
if write_prog:
write_pprog(os.path.join(dir, pprog_file), dic["pprog"],
overwrite=overwrite)
# determind endianness (assume little-endian unless BYTORDA is 1)
if big == None:
big = False # default value
if "acqus" in dic and "BYTORDA" in dic["acqus"]:
if dic["acqus"]["BYTORDA"] == 1:
big = True
else:
big = False
# write out the binary data
bin_full = os.path.join(dir, bin_file)
write_binary(bin_full, dic, data, big=big, overwrite=overwrite)
return
def write_lowmem(dir, dic, data, bin_file=None, acqus_files=None,
pprog_file=None, overwrite=False, big=None, write_prog=True,
write_acqus=True):
"""
Write Bruker files using minimal amounts of memory (trace by trace).
See :py:func:`write` for Parameters.
See Also
--------
write : Write Bruker files.
read_lowmem : Read Bruker files using minimal amounts of memory.
"""
# determind parameters automatically
if bin_file == None:
if data.ndim == 1:
bin_file = "fid"
else:
bin_file = "ser"
if acqus_files == None:
acq = ["acqus", "acqu2s", "acqu3s", "acqu4s"]
acqus_files = [k for k in acq if dic.has_key(k)]
if pprog_file == None:
pprog_file = "pulseprogram"
# write out the acqus files
if write_acqus:
for f in acqus_files:
write_jcamp(dic[f], os.path.join(dir, f), overwrite=overwrite)
# write out the pulse program
if write_prog:
write_pprog(os.path.join(dir, pprog_file), dic["pprog"],
overwrite=overwrite)
# determind endianness (assume little-endian unless BYTORDA is 1)
if big == None:
big = False # default value
if "acqus" in dic and "BYTORDA" in dic["acqus"]:
if dic["acqus"]["BYTORDA"] == 1:
big = True
else:
big = False
# write out the binary data
bin_full = os.path.join(dir, bin_file)
write_binary_lowmem(bin_full, dic, data, big=big, overwrite=overwrite)
return
def guess_shape(dic):
"""
Determine data shape and complexity from Bruker dictionary.
Returns
-------
shape : tuple
Shape of data in Bruker binary file (R+I for all dimensions).
cplex : bool
True for complex data in last (direct) dimension, False otherwise.
"""
# determine complexity of last (direct) dimension
try:
aq_mod = dic["acqus"]["AQ_mod"]
except KeyError:
aq_mod = 0
if aq_mod == 0 or aq_mod == 2:
cplex = False
elif aq_mod == 1 or aq_mod == 3:
cplex = True
else:
raise ValueError("Unknown Aquisition Mode")
# file size
try:
fsize = dic["FILE_SIZE"]
except KeyError:
print "Warning: cannot determine shape do to missing FILE_SIZE key"
return (1,), True
# extract td0,td1,td2,td3 from dictionaries
try:
td0 = float(dic["acqus"]["TD"])
except KeyError:
td0 = 1024 # default value
try:
td2 = int(dic["acqu2s"]["TD"])
except KeyError:
td2 = 0 # default value
try:
td1 = float(dic["acqu3s"]["TD"])
except KeyError:
td1 = int(td2) # default value
try:
td3 = int(dic["acqu4s"]["TD"])
except KeyError:
td3 = int(td1) # default value
# last (direct) dimension is given by "TD" parameter in acqus file
# rounded up to nearest 256
# next-to-last dimension may be given by "TD" in acqu2s. In 3D+ data
# this is often the sum of the indirect dimensions
shape = [0, 0, td2, int(np.ceil(td0 / 256.)*256.)]
# additional dimension given by data size
if shape[2] != 0 and shape[3] != 0:
shape[1] = fsize / (shape[3] * shape[2] * 4)
shape[0] = fsize / (shape[3] * shape[2] * 16 * 4)
# if there in no pulse program parameters in dictionary return currect
# shape after removing zeros
if "pprog" not in dic or "loop" not in dic["pprog"]:
return tuple([int(i) for i in shape if i >= 1]), cplex
# if pulseprogram dictionary is missing loop or incr return current shape
pprog = dic["pprog"]
if "loop" not in pprog or "incr" not in pprog:
return tuple([int(i) for i in shape if i >= 1]), cplex
# determine indirect dimension sizes from pulseprogram parameters
loop = pprog["loop"]
loopn = len(loop) # number of loops
li = [len(i) for i in pprog["incr"]] # length of incr lists
# replace td0,td1,td2,td3 in loop list
rep = {'td0' : td0, 'td1' : td1, 'td2' : td2, 'td3' : td3}
for i, v in enumerate(loop):
if v in rep.keys():
loop[i] = rep[v]
# size of indirect dimensions based on number of loops in pulse program
# there are two kinds of loops, active and passive.
# active loops are from indirect dimension increments, the corresponding
# incr lists should have non-zero length and the size of the dimension
# is twice that of the active loop size.
# passive loops are from phase cycles and similar elements, these should
# have zero length incr lists and should be of length 2.
# The following checks for these and updates the indirect dimension
# if the above is found.
if loopn == 1: # 2D with no leading passive loops
if li[0] != 0:
shape[2] = loop[0]
shape = shape[-2:]
elif loopn == 2: # 2D with one leading passive loop
if loop[0] == 2 and li[0] == 0 and li[1] != 0:
shape[2] = 2 * loop[1]
shape = shape[-2:]
elif loopn == 3: # 2D with two leading passive loops
if (loop[0] == 2 and loop[1] == 2 and li[0] == 0 and li[1] == 0
and li[2] != 0):
shape[2] = 2 * loop[2]
shape = shape[-2:]
elif loopn == 4: # 3D with one leading passive loop for each indirect dim
if loop[0] == 2 and li[0] == 0 and li[1] != 0:
shape[2] = 2 * loop[1]
if loop[2] == 2 and li[2] == 0 and li[3] != 0:
shape[1] = 2 * loop[3]
shape = shape[-3:]
elif loopn == 5: # 3D with two/one leading passive loops
if loop[1] == 2 and li[0] == 0 and li[1] == 0 and li[2] != 0:
shape[2] = 2 * loop[2]
if loop[3] == 2 and li[0] == 0 and li[3] == 0 and li[4] != 0:
shape[1] = 2 * loop[4]
shape = shape[-3:]
elif loopn == 6: # 4D with one leading passive loop for each indirect dim
if loop[0] == 2 and li[0] == 0 and li[1] != 0:
shape[2] = 2 * loop[1]
if loop[2] == 2 and li[2] == 0 and li[3] != 0:
shape[1] = 2 * loop[3]
if loop[4] == 2 and li[4] == 0 and li[5] != 0:
shape[0] = 2 * loop[5]
elif loopn == 7:
if loop[1] == 2 and li[0] == 0 and li[1] == 0 and li[2] != 0:
shape[2] = 2 * loop[2]
if loop[3] == 2 and li[0] == 0 and li[3] == 0 and li[4] != 0:
shape[1] = 2 * loop[4]
if loop[5] == 2 and li[0] == 0 and li[5] == 0 and li[6] != 0:
shape[0] = 2 * loop[6]
return tuple([int(i) for i in shape if i >= 2]), cplex
# Bruker binary (fid/ser) reading and writing
def read_binary(filename, shape=(1), cplex=True, big=True):
"""
Read Bruker binary data from file and return dic,data pair
If data cannot be reshaped as described a 1D representation of the data
will be returned after printing a warning message.
Parameters
----------
filename : str
Filename of Bruker binary file.
shape : tuple
Tuple describing shape of resulting data.
cplex : bool
Flag indicating if direct dimension is complex.
big : bool
Endianness of binary file, True for big-endian, False for
little-endian.
Returns
-------
dic : dict
Dictionary containing "FILE_SIZE" key and value.
data : ndarray
Array of raw NMR data.
See Also
--------
read_binary_lowmem : Read Bruker binary file using minimal memory.
"""
# open the file and get the data
f = open(filename, 'rb')
data = get_data(f, big=big)
# complexify if needed
if cplex:
data = complexify_data(data)
# create dictionary
dic = {"FILE_SIZE" : os.stat(filename).st_size}
# reshape if possible
try:
return dic, data.reshape(shape)
except ValueError:
print "Warning:", data.shape, "cannot be shaped into", shape
return dic, data
def read_binary_lowmem(filename, shape=(1), cplex=True, big=True):
"""
Read Bruker binary data from file using minimal memory.
Raises ValueError if shape does not agree with file size.
See :py:func:`read_binary` for Parameters.
Returns
-------
dic : dict
Dictionary containing "FILE_SIZE" key and value.
data : array_like
Low memory object which can access NMR data on demand.
See Also
--------
read_binary: Read Bruker binary file.
"""
# create dictionary
dic = {"FILE_SIZE" : os.stat(filename).st_size}
data = bruker_nd(filename, shape, cplex, big)
return dic, data
def write_binary(filename, dic, data, overwrite=False, big=True):
"""
Write Bruker binary data to file.
Parameters
----------
filename : str
Filename to write to.
dic : dict
Dictionary of Bruker parameters.
data : ndarray
Array of NMR data.
overwrite : bool
True to overwrite files, False will raise a Warning if file exists.
big : bool
Endiness to write binary data with True of big-endian, False for
little-endian.
See Also
--------
write_binary_lowmem : Write Bruker binary data using minimal memory.
"""
# open the file for writing
f = fileiobase.open_towrite(filename, overwrite=overwrite)
# convert objec to an array if it is not already one...
if type(data) != np.ndarray:
data = np.array(data)
if np.iscomplexobj(data):
put_data(f, uncomplexify_data(data), big)
else:
put_data(f, data, big)
f.close()
return
def write_binary_lowmem(filename, dic, data, overwrite=False, big=True):
"""
Write Bruker binary data to file using minimal memory (trace by trace).
See :py:func:`write_binary` for Parameters.
See Also
--------
write_binary : Write Bruker binary data to file.
"""
# open the file for writing
f = fileiobase.open_towrite(filename, overwrite=overwrite)
cplex = np.iscomplexobj(data)
# write out file trace by trace
for tup in np.ndindex(data.shape[:-1]):
trace = data[tup]
if cplex:
put_data(f, uncomplexify_data(trace), big)
else:
put_data(f, trace, big)
f.close()
return
# lowmemory ND object
class bruker_nd(fileiobase.data_nd):
"""
Emulate a ndarray objects without loading data into memory for low memory
reading of Bruker fid/ser 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 Bruker binary file.
fshape : tuple
Shape of NMR data.
cplex : bool
Flag indicating if direct dimension is complex.
big : bool
Endianess of data. True for big-endian, False for little-endian.
order : tuple
Ordering of axis against file.
"""
def __init__(self, filename, fshape, cplex, big, order=None):
"""
Create and set up object.
"""
# check that size is correct
pts = reduce(lambda x, y: x*y, fshape)
if cplex:
if os.stat(filename).st_size != pts * 4 * 2:
raise ValueError("shape does not agree with file size")
else:
if os.stat(filename).st_size != pts * 4:
raise ValueError("shape does not agree with file size")
# check order
if order == None:
order = range(len(fshape))
# finalize
self.filename = filename
self.fshape = fshape
self.cplex = cplex
self.big = big
self.order = order
if self.cplex:
self.dtype = np.dtype("complex128")
else:
self.dtype = np.dtype("int32")
self.__setdimandshape__() # set ndim and shape attributes
def __fcopy__(self, order):
"""
Create a copy
"""
n = bruker_nd(self.filename, self.fshape, self.cplex, self.big, order)
return n
def __fgetitem__(self, slices):
"""
return ndarray of selected values
slices is a well formatted tuple of slices
"""
# seperate the last slice from the first slices
lslice = slices[-1]
fslice = slices[:-1]
# and the same for fshape
lfshape = self.fshape[-1]
ffshape = self.fshape[:-1]
# find the output size and make a in/out nd interator
osize, nd_iter = fileiobase.size_and_ndtofrom_iter(ffshape, fslice)
osize.append(len(range(lfshape)[lslice]))
# create an empty array to store the selected slices
out = np.empty(tuple(osize), dtype=self.dtype)
f = open(self.filename, 'rb')
# read in the data trace by trace
for out_index, in_index in nd_iter:
# determine the trace number from the index
ntrace = fileiobase.index2trace_flat(ffshape, in_index)
# seek to the correct place in the file
if self.cplex:
ts = ntrace * lfshape * 2 * 4
f.seek(ts)
trace = get_trace(f, lfshape * 2, self.big)
trace = complexify_data(trace)
else:
ts = ntrace * lfshape * 2
f.seek(ts)
trace = get_trace(f, lfshape, self.big)
# save to output
out[out_index] = trace[lslice]
return out
# binary get/put functions
def get_data(f, big):
"""
Get binary data from file object with given endiness
"""
if big == True:
return np.frombuffer(f.read(), dtype='>i4')
else:
return np.frombuffer(f.read(), dtype='<i4')
def put_data(f, data, big=True):
"""
Put data to file object with given endiness
"""
if big:
f.write(data.astype('>i4').tostring())
else:
f.write(data.astype('<i4').tostring())
return
def get_trace(f, num_points, big):
"""
Get trace of num_points from file with given endiness
"""
if big == True:
bsize = num_points * np.dtype('>i4').itemsize
return np.frombuffer(f.read(bsize), dtype='>i4')
else:
bsize = num_points * np.dtype('<i4').itemsize
return np.frombuffer(f.read(bsize), dtype='<i4')
# data manipulation functions
def complexify_data(data):
"""
Complexify data packed real, imag.
"""
return data[..., ::2] + data[..., 1::2]*1.j
def uncomplexify_data(data_in):
"""
Uncomplexify data (pack real,imag) into a int32 array
"""
size = list(data_in.shape)
size[-1] = size[-1] * 2
data_out = np.empty(size, dtype="int32")
data_out[..., ::2] = data_in.real
data_out[..., 1::2] = data_in.imag
return data_out
# digital filter functions
# Table of points to frequency shift Bruker data to remove digital filter
# (Phase is 360 degrees * num_pts)
# This table is an 'un-rounded' version base on the table by
# W.M. Westler and F. Abildgaard's offline processing note, online at:
# http://www.boc.chem.uu.nl/static/local/prospectnd/dmx_digital_filters.html
# and the updated table with additional entries at:
# http://sbtools.uchc.edu/help/nmr/nmr_toolkit/bruker_dsp_table.asp
# The rounding in the above tables appear to be based on k / (2*DECIM)
# for example 2 : 44.75 = 44 + 3/4
# 4 : 66.625 = 66 + 5/8
# 8 : 68.563 ~= 68 + 9/16 = 68.5625
# Using this the un-rounded table was created by checking possible unrounded
# fracions which would round to those in the original table.
bruker_dsp_table = {
10: {
2 : 44.75,
3 : 33.5,
4 : 66.625,
6 : 59.083333333333333,
8 : 68.5625,
12 : 60.375,
16 : 69.53125,
24 : 61.020833333333333,
32 : 70.015625,
48 : 61.34375,
64 : 70.2578125,
96 : 61.505208333333333,
128 : 70.37890625,
192 : 61.5859375,
256 : 70.439453125,
384 : 61.626302083333333,
512 : 70.4697265625,
768 : 61.646484375,
1024 : 70.48486328125,
1536 : 61.656575520833333,
2048 : 70.492431640625,
},
11: {
2 : 46.,
3 : 36.5,
4 : 48.,
6 : 50.166666666666667,
8 : 53.25,
12 : 69.5,
16 : 72.25,
24 : 70.166666666666667,
32 : 72.75,
48 : 70.5,
64 : 73.,
96 : 70.666666666666667,
128 : 72.5,
192 : 71.333333333333333,
256 : 72.25,
384 : 71.666666666666667,
512 : 72.125,
768 : 71.833333333333333,
1024 : 72.0625,
1536 : 71.916666666666667,
2048 : 72.03125
},
12: {
2 : 46. ,
3 : 36.5,
4 : 48.,
6 : 50.166666666666667,
8 : 53.25,
12 : 69.5,
16 : 71.625,
24 : 70.166666666666667,
32 : 72.125,
48 : 70.5,
64 : 72.375,
96 : 70.666666666666667,
128 : 72.5,
192 : 71.333333333333333,
256 : 72.25,
384 : 71.666666666666667,
512 : 72.125,
768 : 71.833333333333333,
1024 : 72.0625,
1536 : 71.916666666666667,