/
convert.py
466 lines (379 loc) · 13.8 KB
/
convert.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
"""
Functions to convert between NMR file formats
"""
import datetime
import numpy as np
from . import pipe
from . import varian
from . import bruker
from . import sparky
from . import fileiobase
class converter(object):
"""
Object which allows conversion between NMR file formats, including low
memory data objects.
Conversion between NMR file formats with this class involves three steps.
First a new converter object must be created. Then the converter must be
loaded with data using a ``from_`` method. Finally, the dictionary and
data representation of a NMR data in the desired format is extracted using
a ``to_`` method. This can then be written to disk.
Example conversion::
vdic, vdata = ng.varian.read("varian_dir")
C = ng.convert.converter()
C.from_varian(vdic, vdata)
pdic, pdata = C.to_pipe()
ng.pipe.write("test.fid", pdic, pdata)
Spectral parameters can be provided directly by passing a Universal
dictionary to any of the ``from_`` methods. If not provided the spectral
parameters are guessed from the file format's dictionary of parameters.
"""
def __init__(self):
"""
Create a converter object
"""
pass
# utility functions
def __returndata(self):
"""
Return data or emulated data after error checking
"""
# Error checking
if "_data" not in self.__dict__:
raise IOError("converter not loaded with data")
if "_udic" not in self.__dict__:
raise IOError("converter not loaded with dictionary")
if "_iproc" not in self.__dict__:
raise IOError("converter not loaded with processing parameters")
if "_oproc" not in self.__dict__:
raise IOError("converter not loaded with processing parameters")
if "_odtype" not in self.__dict__:
raise IOError("converter not loaded with output dtype")
# Warnings
if self._data.dtype.kind != np.dtype(self._odtype).kind:
print "Warning: Incompatiable dtypes, conversion not recommended"
# Return data
if isinstance(self._data, np.ndarray): # in memory data
return self.__procdata()
else: # return emulated data
iproc = self._iproc
oproc = self._oproc
odtype = self._odtype
order = self._data.order
return udata_nd(self._data, iproc, oproc, odtype, order)
def __procdata(self):
"""
Process data as indicated by flags
"""
# copy the data
data = np.copy(self._data)
# processing for input type
# sign alt. indirect dimension
if data.ndim >= 2 and "alt_id_sign" in self._iproc:
#data[1::2] = -data[1::2]
s = [slice(None, None, None)] * data.ndim
for i in range(data.ndim-1):
s[i] = slice(1, None, 2)
data[s] = -data[s]
s[i] = slice(None, None, None)
if "realfactor" in self._iproc:
data.real = data.real * self._iproc['realfactor']
if "imagfactor" in self._iproc:
data.imag = data.imag * self._iproc['imagfactor']
# processing for output
# sign alt. indirect dimension
if data.ndim >= 2 and "alt_id_sign" in self._oproc:
s = [slice(None, None, None)] * data.ndim
for i in range(data.ndim-1):
s[i] = slice(1, None, 2)
data[s] = -data[s]
s[i] = slice(None, None, None)
if "realfactor" in self._oproc:
data.real = data.real * self._oproc['realfactor']
if "imagfactor" in self._oproc:
data.imag = data.imag * self._oproc['imagfactor']
return data.astype(self._odtype)
# IMPORTERS (from_*)
def from_universal(self, dic, data):
"""
Load converter with Universal data.
Parameters
----------
dic : dict
Dictionary of universal parameters.
data : array_like
NMR data.
"""
# set data
self._data = data
self._iproc = {}
# set the dictionary
self._udic = dic
def from_varian(self, dic, data, udic=None):
"""
Load converter with Agilent/Varian data.
Parameters
----------
dic : dict
Dictionary of Agilent/Varian parameters.
data : array_like
NMR data.
udic : dict, optional
Universal dictionary, if not provided will be guesses from dic.
"""
# set data
self._data = data
if udic != None and udic[0]['encoding'].lower() == "tppi":
self._iproc = {"imagfactor":-1.0}
else: # states, etc needs sign alt. of indirect dim.
self._iproc = {"alt_id_sign":True, "imagfactor":-1.0}
# set the universal dictionary
if udic != None:
self._udic = udic
else:
self._udic = varian.guess_udic(dic, data)
def from_pipe(self, dic, data, udic=None):
"""
Load converter with NMRPipe data.
Parameters
----------
dic : dict
Dictionary of NMRPipe parameters.
data : array_like
NMR data.
udic : dict, optional
Universal dictionary, if not provided will be guesses from dic.
"""
# set data
self._data = data
self._iproc = {}
# set the universal dictionary
if udic != None:
self._udic = udic
else:
self._udic = pipe.guess_udic(dic, data)
def from_sparky(self, dic, data, udic=None):
"""
Load converter with Sparky data.
Parameters
----------
dic : dict
Dictionary of Sparky parameters.
data : array_like
NMR data.
udic : dict, optional
Universal dictionary, if not provided will be guesses from dic.
"""
# set data
self._data = data
self._iproc = {}
# set the universal dictionary
if udic != None:
self._udic = udic
else:
self._udic = sparky.guess_udic(dic, data)
def from_bruker(self, dic, data, udic=None):
"""
Load converter with Bruker data.
Parameters
----------
dic : dict
Dictionary of Bruker parameters.
data : array_like
NMR data.
udic : dict, optional
Universal dictionary, if not provided will be guesses from dic.
"""
# set data
self._data = data
self._iproc = {}
# set the universal dictionary
if udic != None:
self._udic = udic
else:
self._udic = bruker.guess_udic(dic, data)
# EXPORTERS (to_*)
def to_universal(self):
"""
Return Universal format data.
Returns
-------
dic : dict
Dictionary of Universal parameters.
data : array_like
NMR data in format as provided.
"""
# create dictionary
dic = dict(self._udic)
# add processing flags for output
self._oproc = {}
self._odtype = self._data.dtype
return dic, self.__returndata()
def to_pipe(self, datetimeobj=datetime.datetime.now()):
"""
Return NMRPipe format data.
Parameters
----------
datetime : datetime object, optional
Datetime object to include in the NMRPipe parameters. The current
date and time is used by default.
Returns
-------
dic : dict
Dictionary of NMRPipe parameters.
data : array_like
NMR data in NMRPipe format.
"""
# create dictionary
dic = pipe.create_dic(self._udic, datetimeobj)
# add processing flags for output
self._oproc = {}
if self._udic[self._udic["ndim"] - 1]["complex"]:
self._odtype = "complex64"
else:
self._odtype = "float32"
return dic, self.__returndata()
def to_varian(self):
"""
Return Agilent/Varian format data.
Returns
-------
dic : dict
Dictionary of Agilent/Varian parameters.
data : array_like
NMR data in Agilent/Varian format.
"""
# create dictionary
dic = varian.create_dic(self._udic)
# add processing flags for output
self._oproc = {"alt_id_sign":True, "imagfactor":-1.0}
self._odtype = "complex64"
return dic, self.__returndata()
def to_sparky(self, datetimeobj=datetime.datetime.now(), user='user'):
"""
Return Sparky format data.
Parameters
----------
datetime : datetime object, optional
Datetime object to include in the Sparky parameters. The current
date and time is used by default.
user : str, optional
Username to include in the Sparky parameters. 'user' is the
default.
Returns
-------
dic : dict
Dictionary of Sparky parameters.
data : array_like
NMR data in Sparky format.
"""
# create dictionary
dic = sparky.create_dic(self._udic, datetimeobj, user)
# add processing flags for output
self._oproc = {}
self._odtype = "float32"
return dic, self.__returndata()
def to_bruker(self):
"""
Return Bruker format data.
Returns
-------
dic : dict
Dictionary of Bruker parameters.
data : array_like
NMR data in Bruker format.
"""
# create dictionary
dic = bruker.create_dic(self._udic)
# add processing flags for output
self._oproc = {}
self._odtype = "complex128"
return dic, self.__returndata()
class udata_nd(fileiobase.data_nd):
"""
Wrap other fileiobase.data_nd derived objects with input/output conversion
when slices are requested.
* 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
----------
edata : fileiobase.data_nd derived object
Data object to wrap.
iproc : dict
Dictionary of processing required by input format.
oproc :
Dictionary of processing required by output format.
odtype : dtype
Output dtype.
order : tuple
Axis ordering relative to input data.
Notes
-----
The iproc and oproc dictionary can contains the following keys and values.
=========== ========== ==========================================
key value Description
=========== ========== ==========================================
alt_id_sign True/False True alternates signs along indirect dims.
realfactor float Real channel scaling factor.
imagfactor float Imaginary channel scaling factor.
=========== ========== ==========================================
"""
def __init__(self, edata, iproc, oproc, odtype, order=None):
"""
create and set up
"""
# set converter attributes
self._iproc = iproc # input processing dictionary
self._oproc = oproc # output processing dictionary
self._odtype = odtype # output dtype
self.edata = edata # file
# required data_nd attributes
self.order = order
self.fshape = edata.fshape
self.dtype = odtype
self.__setdimandshape__() # set ndim and shape attributes
def __fcopy__(self, order):
"""
Create a copy
"""
n = udata_nd(self.edata, self._iproc, self._oproc, self._odtype, order)
return n
def __fgetitem__(self, slices):
"""
Return ndarray of selected values
slices is a well formateed n-tuple of slices
"""
data = self.edata.__fgetitem__(slices)
# input processing
if "alt_id_sign" in self._iproc: # sign alt. indirect dimension
if "alt_id_sign" not in self._oproc: # skip if in both
fslice = slices[:-1]
ffshape = self.fshape[:-1]
nd_iter = fileiobase.ndtofrom_iter(ffshape, fslice)
for out_index, in_index in nd_iter:
# negate the trace if there is an odd number of
# odd number indices in the slice
if np.mod(in_index, 2).sum() % 2 == 1:
data[out_index] = -data[out_index]
if "realfactor" in self._iproc:
data.real = data.real * self._iproc['realfactor']
if "imagfactor" in self._iproc:
data.imag = data.imag * self._iproc['imagfactor']
# output processing
if "alt_id_sign" in self._oproc:
if "alt_id_sign" not in self._iproc:
fslice = slices[:-1]
ffshape = self.fshape[:-1]
nd_iter = fileiobase.ndtofrom_iter(ffshape, fslice)
for out_index, in_index in nd_iter:
# negate the trace if there is an odd number of
# odd number indices in the slice
if np.mod(in_index, 2).sum() % 2 == 1:
data[out_index] = -data[out_index]
if "realfactor" in self._oproc:
data.real = data.real * self._oproc['realfactor']
if "imagfactor" in self._oproc:
data.imag = data.imag * self._oproc['imagfactor']
return data.astype(self._odtype)