-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path.#compound.py.1.19
457 lines (403 loc) · 14.6 KB
/
.#compound.py.1.19
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
import mdsdata as _data
import _mdsdtypes as _dtypes
import copy as _copy
import numpy as _N
class Compound(_data.Data):
mdsdtype=None
mdsclass=194
def __init__(self,*args, **params):
"""MDSplus compound data.
"""
if self.__class__.__name__=='Compound':
raise TypeError("Cannot create instances of class Compound")
if 'args' in params:
args=params['args']
if 'params' in params:
params=params['params']
if 'opcode' in params:
self._opcode=params['opcode']
try:
self._argOffset=self.argOffset
except:
self._argOffset=len(self.fields)
if isinstance(args,tuple):
if len(args) > 0:
if isinstance(args[0],tuple):
args=args[0]
self.args=args
for keyword in params:
if keyword in self.fields:
super(type(self),self).__setitem__(self._fields[keyword],params[keyword])
def __hasBadTreeReferences__(self,tree):
for arg in self.args:
if isinstance(arg,_data.Data) and arg.__hasBadTreeReferences__(tree):
return True
return False
def __fixTreeReferences__(self,tree):
ans = _copy.deepcopy(self)
newargs=list(ans.args)
for idx in range(len(newargs)):
if isinstance(newargs[idx],_data.Data) and newargs[idx].__hasBadTreeReferences__(tree):
newargs[idx]=newargs[idx].__fixTreeReferences__(tree)
ans.args=tuple(newargs)
return ans
def __getattr__(self,name,*args):
if name in self.__dict__:
return self.__dict__[name]
if name == '_opcode_name':
return 'undefined'
if name == '_fields':
return dict()
if name == 'args':
try:
return self.__dict__[name]
except:
return None
if name == '_opcode':
return None
if name == '_argOffset':
return 0
if name == 'opcode':
return self._opcode
if name == 'dtype':
return self._dtype
if name == self._opcode_name:
return self._opcode
if name in self._fields:
try:
return self.args[self._fields[name]]
except:
return None
raise AttributeError('No such attribute '+str(name))
def __getitem__(self,num):
try:
return self.args[num]
except:
return None
def __setattr__(self,name,value):
if name == 'opcode':
self._opcode=value
if name == 'args':
if isinstance(value,tuple):
self.__dict__[name]=value
return
else:
raise TypeError('args attribute must be a tuple')
if name in self._fields:
tmp=list(self.args)
while len(tmp) <= self._fields[name]:
tmp.append(None)
tmp[self._fields[name]]=value
self.args=tuple(tmp)
return
if name == self._opcode_name:
self._opcode=value
return
super(Compound,self).__setattr__(name,value)
def __setitem__(self,num,value):
if isinstance(num,slice):
indices=num.indices(num.start+len(value))
idx=0
for i in range(indices[0],indices[1],indices[2]):
self.__setitem__(i,value[idx])
idx=idx+1
else:
try:
tmp=list(self.args)
except:
tmp=list()
while len(tmp) <= num:
tmp.append(None)
tmp[num]=value
self.args=tuple(tmp)
return
# def decompile(self):
# arglist=list()
# for arg in self.args:
# arglist.append(_data.makeData(arg).decompile())
# return 'Build_'+self.__class__.__name__+'('+','.join(arglist)+')'
def getArgumentAt(self,idx):
"""Return argument at index idx (indexes start at 0)
@rtype: Data,None
"""
return Compound.__getitem__(self,idx+self._argOffset)
def getArguments(self):
"""Return arguments
@rtype: Data,None
"""
return Compound.__getitem__(self,slice(self._argOffset,None))
def getDescAt(self,idx):
"""Return descriptor with index idx (first descriptor is 0)
@rtype: Data
"""
return Compound.__getitem__(self,idx)
def getDescs(self):
"""Return descriptors or None if no descriptors
@rtype: tuple,None
"""
return self.args
def getNumDescs(self):
"""Return number of descriptors
@rtype: int
"""
try:
return len(self.args)
except:
return 0
def setArgumentAt(self,idx,value):
"""Set argument at index idx (indexes start at 0)"""
return Compound.__setitem__(self,idx+self._argOffset,value)
def setArguments(self,args):
"""Set arguments
@type args: tuple
"""
return Compound.__setitem__(self,slice(self._argOffset,None),args)
def setDescAt(self,n,value):
"""Set descriptor at index idx (indexes start at 0)"""
return Compound.__setitem__(self,n,value)
def setDescs(self,args):
"""Set descriptors
@type args: tuple
"""
self.args=value
class _compoundMeta(type):
def __new__(meta,classname,bases,classDict):
if len(classDict)==0:
classDict=dict(bases[0].__dict__)
newClassDict=classDict
newClassDict['_fields']=dict()
idx=0
for f in classDict['fields']:
name=f[0:1].upper()+f[1:]
exec ("def get"+name+"(self): return self.__getattr__('"+f+"')")
exec ("newClassDict['get'+name]=get"+name)
newClassDict['get'+name].__doc__='Get the '+f+' field\n@rtype: Data'
exec ('def set'+name+'(self,value): return self.__setattr__("'+f+'",value)')
exec ("newClassDict['set'+name]=set"+name)
newClassDict['set'+name].__doc__='Set the '+f+' field\n@type value: Data\n@rtype: None'
# exec ("newClassDict['_dtype']=DTYPE_"+classname.upper())
newClassDict['_fields'][f]=idx
idx=idx+1
c=type.__new__(meta,classname,bases,newClassDict)
else:
c=type.__new__(meta,classname,bases,classDict)
return c
class _Action(Compound):
"""
An Action is used for describing an operation to be performed
by an MDSplus action server. Actions are typically dispatched
using the mdstcl DISPATCH command
"""
_dtype=_dtypes.DTYPE_ACTION
fields=('dispatch','task','errorLog','completionMessage','performance')
Action=_compoundMeta('Action',(_Action,),{})
class _Call(Compound):
"""
A Call is used to call routines in shared libraries.
"""
_dtype=_dtypes.DTYPE_CALL
fields=('image','routine')
_opcode_name='retType'
Call=_compoundMeta('Call',(_Call,),{})
class _Conglom(Compound):
"""
A Conglom is used at the head of an MDSplus conglomerate.
A conglomerate is a set of tree nodes used to define a
device such as a piece of data acquisition hardware. A
conglomerate is associated with some external code
providing various methods which can be performed on the
device. The Conglom class contains information used for
locating the external code.
"""
_dtype=_dtypes.DTYPE_CONGLOM
fields=('image','model','name','qualifiers')
Conglom=_compoundMeta('Conglom',(_Conglom,),{})
class _Dependency(Compound):
"""A Dependency object is used to describe action dependencies. This is a legacy class and may not be recognized by
some dispatching systems
"""
_dtype=_dtypes.DTYPE_DEPENDENCY
fields=('arg1','arg2')
Dependency=_compoundMeta('Dependency',(_Dependency,),{})
class _Dimension(Compound):
"""
A dimension object is used to describe a signal dimension,
typically a time axis. It provides a compact description
of the timing information of measurements recorded by devices
such as transient recorders. It associates a Window object
with an axis. The axis is generally a range with possibly
no start or end but simply a delta. The Window object is
then used to bracket the axis to resolve the appropriate
timestamps.
"""
_dtype=_dtypes.DTYPE_DIMENSION
fields=('window','axis')
Dimension=_compoundMeta('Dimension',(_Dimension,),{})
class _Dispatch(Compound):
"""
A Dispatch object is used to describe when an where an
action should be dispatched to an MDSplus action server.
"""
_dtype=_dtypes.DTYPE_DISPATCH
fields=('ident','phase','when','completion')
def __init__(self,*args,**kwargs):
if 'dispatch_type' not in kwargs:
kwargs['dispatch_type']=2
kwargs['opcode']=kwargs['dispatch_type']
super(Dispatch,self).__init__(args=args,params=kwargs)
if self.completion is None:
self.completion = None
Dispatch=_compoundMeta('Dispatch',(_Dispatch,),{})
class _Method(Compound):
"""
A Method object is used to describe an operation to
be performed on an MDSplus conglomerate/device
"""
_dtype=_dtypes.DTYPE_METHOD
fields=('timeout','method','object')
Method=_compoundMeta('Method',(_Method,),{})
class _Procedure(Compound):
"""
A Procedure is a deprecated object
"""
_dtype=_dtypes.DTYPE_PROCEDURE
fields=('timeout','language','procedure')
Procedure=_compoundMeta('Procedure',(_Procedure,),{})
class _Program(Compound):
"""A Program is a deprecated object"""
_dtype=_dtypes.DTYPE_PROGRAM
fields=('timeout','program')
Program=_compoundMeta('Program',(_Program,),{})
class _Range(Compound):
"""
A Range describes a ramp. When used as an axis in
a Dimension object along with a Window object it can be
used to describe a clock. In this context it is possible
to have missing begin and ending values or even have the
begin, ending, and delta fields specified as arrays to
indicate a multi-speed clock.
"""
_dtype=_dtypes.DTYPE_RANGE
fields=('begin','ending','delta')
def decompile(self):
parts=list()
for arg in self.args:
parts.append(str(_data.makeData(arg).decompile()))
return ' : '.join(parts)
Range=_compoundMeta('Range',(_Range,),{})
class _Routine(Compound):
"""
A Routine is a deprecated object"""
_dtype=_dtypes.DTYPE_ROUTINE
fields=('timeout','image','routine')
Routine=_compoundMeta('Routine',(_Routine,),{})
class _Signal(Compound):
"""
A Signal is used to describe a measurement, usually time
dependent, and associated the data with its independent
axis (Dimensions). When Signals are indexed using s[idx],
the index is resolved using the dimension of the signal
"""
_dtype=_dtypes.DTYPE_SIGNAL
fields=('value','raw')
def _getDims(self):
return self.getArguments()
dims=property(_getDims)
"""The dimensions of the signal"""
# def decompile(self):
# arglist=list()
# for arg in self.args:
# arglist.append(_data.makeData(arg).decompile())
# return 'Build_Signal('+','.join(arglist)+')'
def dim_of(self,idx=0):
"""Return the signals dimension
@rtype: Data
"""
if idx < len(self.dims):
return self.dims[idx]
else:
return _data.makeData(None)
def __getitem__(self,idx):
"""Subscripting <==> signal[subscript]. Uses the dimension information for subscripting
@param idx: index or Range used for subscripting the signal based on the signals dimensions
@type idx: Data
@rtype: Signal
"""
import tdibuiltins as _builtins
return _builtins.SUBSCRIPT(self,_data.makeData(idx)).evaluate()
def getDimensionAt(self,idx=0):
"""Return the dimension of the signal
@param idx: The index of the desired dimension. Indexes start at 0. 0=default
@type idx: int
@rtype: Data
"""
try:
return self.dims[idx]
except:
return None
def getDimensions(self):
"""Return all the dimensions of the signal
@rtype: tuple
"""
return self.dims
def setDimensionAt(self,idx,value):
"""Set the dimension
@param idx: The index into the dimensions of the signal.
@rtype: None
"""
return self.setArgumentAt(idx,value)
def setDimensions(self,value):
"""Set all the dimensions of a signal
@param value: The dimensions
@type value: tuple
@rtype: None
"""
return self.setArguments(value)
Signal=_compoundMeta('Signal',(_Signal,),{})
class _Window(Compound):
"""
A Window object can be used to construct a Dimension
object. It brackets the axis information stored in the
Dimension to construct the independent axis of a signal.
"""
_dtype=_dtypes.DTYPE_WINDOW
fields=('startIdx','endIdx','timeAt0')
# def decompile(self):
# return 'Build_Window('+_data.makeData(self.startIdx).decompile()+','+_data.makeData(self.endIdx).decompile()+','+_data.makeData(self.timeAt0)+')'
Window=_compoundMeta('Window',(_Window,),{})
class _Opaque(Compound):
"""An Opaque object containing a binary uint8 array
and a string identifying the type.
"""
_dtype=_dtypes.DTYPE_OPAQUE
fields=('data','otype')
# def decompile(self):
# return 'Build_Opaque('+_data.makeData(self.data).decompile()+','+_data.makeData(self.otype).decompile()+')'
def getImage(self):
try:
import Image
except:
print("Image module required but unable to import it")
return None
try:
import StringIO
except:
print("StringIO module required but unable to import it")
return None
return Image.open(StringIO.StringIO(_data.makeData(self.getData()).data().data))
def fromFile(filename,typestring):
"""Read a file and return an Opaque object
@param filename: Name of file to read in
@type filename: str
@param typestring: String to denote the type of file being stored
@type typestring: str
@rtype: Opaque instance
"""
f = open(filename,'rb')
try:
opq=Opaque(_data.makeData(_N.fromstring(f.read(),dtype="uint8")),typestring)
finally:
f.close()
return opq
fromFile=staticmethod(fromFile)
Opaque=_compoundMeta('Opaque',(_Opaque,),{})