def getCurrentShot(self): """ 获取当前炮号 """ try: shot_num = self.tree.getCurrent() new_tree = Tree(self.dbname, shot_num) shot_num = shot_num if new_tree.getNode( 'FBC:DUPS1').getLength() else shot_num - 1 except mdsExceptions.TreeNNF: # MDSplus.mdsExceptions.TreeNNF: %TREE-W-NNF, Node Not Found shot_num = shot_num if new_tree.getNode( 'FBC:IP').getLength() else shot_num - 1 except mdsExceptions.TreeNOCURRENT: # MDSplus.mdsExceptions.TreeNOCURRENT: %TREE-E-NOCURRENT, No current shot number set for this tree. shot_num = None return shot_num
def arrayDimensionOrder(self): from numpy import int16, zeros from random import randint ptree = Tree('seg_tree', -1, 'NEW') ptree.addNode('IMM') ptree.write() ptree = Tree('seg_tree', -1) ptree.createPulse(1) ptree = Tree('seg_tree', 1) node = ptree.getNode('IMM') WIDTH = 640 HEIGHT = 480 currFrame = zeros(WIDTH * HEIGHT, dtype=int16) currTime = float(0) for i in range(0, WIDTH): for j in range(0, HEIGHT): currFrame[i * HEIGHT + j] = randint(0, 255) currTime = float(0) startTime = Float32(currTime) endTime = Float32(currTime) dim = Float32Array(currTime) segment = Int16Array(currFrame) segment.resize([1, HEIGHT, WIDTH]) shape = segment.getShape() node.makeSegment(startTime, endTime, dim, segment) retShape = node.getShape() self.assertEqual(shape[0], retShape[0]) self.assertEqual(shape[1], retShape[1]) self.assertEqual(shape[2], retShape[2])
def archive_program(node, time=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_program') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive',-1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800.,0,0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) prog = interface.get_program(time)[-1] return prog[node.node_name.lower()] except: """ generate dummy signal with error message as help text """ import getpass,sys user = getpass.getuser() e = sys.exc_info() help = user+': '+str(e[1])+', %d' % e[2].tb_lineno print(help) return help
def archive_program(node, time=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_program') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive', -1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800., 0, 0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) prog = interface.get_program(time)[-1] return prog[node.node_name.lower()] except: """ generate dummy signal with error message as help text """ import getpass, sys user = getpass.getuser() e = sys.exc_info() help = user + ': ' + str(e[1]) + ', %d' % e[2].tb_lineno print(help) return help
def archive_image(node, time=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_image') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive', -1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800., 0, 0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) url = base.Path(node.getNode('$URL').data()).url_datastream() """ request signal """ signal = interface.read_pngs_url(url, time, 3) """ generate help text (HELP, DESCRIPTION, $NAME) """ try: help = node.getNode('HELP').data() except: try: help = node.getNode('DESCRIPTION').data() except: help = node.getNode('$NAME').data() signal.setHelp(str(help)) return signal except: local = locals() """ generate dummy signal with error message as help text """ import getpass, sys e = sys.exc_info() user = getpass.getuser() help = user + ': %s, %d' % (repr(e[1]), e[2].tb_lineno) print(help) print(local) try: from MDSplus import Signal signal = Signal([6, 66, 666]) signal.setHelp(help.split('\n')[-1]) return (signal) except: return help
def archive_log(node, time=None, cache=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_log') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive',-1).getNode(node) """ use _time variable if Tree is ARCHIVE """ try: node.getNode('$CFGLOG') url = base.Path(node.getNode('$URL').data()).url_cfglog() except: try: node.getNode('$PARLOG') url = base.Path(node.getNode('$URL').data()).url_parlog() except: raise Exception('could not specify log type. No Member named $CFGLOG or $PARLOG') if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval(['now']) else: time = base.TimeInterval(node.getNode('\TIME').data()) """ request signal """ return str(interface._get_json(url, time=time).read()) except: """ generate error message""" import getpass,sys user = getpass.getuser() e = sys.exc_info() help = user+': '+str(e[1])+', %d' % e[2].tb_lineno print(help) return help
def copy_tree(shot): tree_raw = Tree('exl50', shot) tree_cop = Tree('exl50_copy', shot, 'NEW') pools = ["AI", "FBC"] for pool in pools: # nodes_list = [] nodes_array = tree_raw.getNode(pool).getDescendants() # nodes_list.extend(nodes_array) pool_nodes = [node.getNodeName() for node in nodes_array] tree_raw.setDefault(tree_raw.getNode(pool)) tree_cop.setDefault(tree_cop.addNode(pool, "STRUCTURE")) for node in pool_nodes: tree_cop.addNode(node, "SIGNAL").addTags(node) # print(node) try: data = tree_raw.getNode(node).getData() tree_cop.getNode(node).putData(data) print(str(shot) + ':' + node) except Exception as e: pass tree_raw.setDefault(tree_raw.getNode(r"\EXL50::TOP")) tree_cop.setDefault(tree_cop.getNode(r"\EXL50_COPY::TOP")) # tree_raw.setDefault(node.getParent()) # tree_cop.setDefault(node.getParent()) tree_cop.write()
def currentShot(dbname): """ 获取当前炮,与mdsTree类分开原因:调用的时候不用先实例化一个tree了 """ try: shot_num = Tree.getCurrent(dbname) new_tree = Tree(dbname, shot_num) shot_num = shot_num if new_tree.getNode( 'FBC:DUPS1').getLength() else shot_num - 1 new_tree.close() except mdsExceptions.TreeNNF: # MDSplus.mdsExceptions.TreeNNF: %TREE-W-NNF, Node Not Found shot_num = shot_num if new_tree.getNode( 'FBC:IP').getLength() else shot_num - 1 new_tree.close() except mdsExceptions.TreeNOCURRENT: # MDSplus.mdsExceptions.TreeNOCURRENT: %TREE-E-NOCURRENT, No current shot number set for this tree. # 本地测试的时候用的exl50_copy数据库获取不到当前炮,里面只有4983炮数据 shot_num = 4983 return shot_num
def test(): pytree = Tree('pytree', self.shot, 'ReadOnly') ip = pytree.getNode('\\ip') self.assertEqual(str(ip), '\\PYTREESUB::IP') self.assertEqual(ip.nid, pytree._IP.nid) self.assertEqual(ip.nid, pytree.__PYTREESUB.IP.nid) self.assertEqual(ip.nid, pytree.__PYTREESUB__IP.nid) self.assertEqual(pytree.TESTDEVICE.__class__, Device.PyDevice('TESTDEVICE')) self.assertEqual(pytree.CYGNET4K.__class__, Device.PyDevice('CYGNET4K'))
def archive_image(node, time=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_image') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive',-1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800.,0,0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) url = base.Path(node.getNode('$URL').data()).url_datastream() """ request signal """ signal = interface.read_pngs_url(url, time, 3) """ generate help text (HELP, DESCRIPTION, $NAME) """ try: help = node.getNode('HELP').data() except: try: help = node.getNode('DESCRIPTION').data() except: help = node.getNode('$NAME').data() signal.setHelp(str(help)) return signal except: local = locals() """ generate dummy signal with error message as help text """ import getpass,sys e = sys.exc_info() user = getpass.getuser() help = user+': %s, %d' % (repr(e[1]), e[2].tb_lineno) print(help) print(local) try: from MDSplus import Signal signal = Signal([6,66,666]) signal.setHelp(help.split('\n')[-1]) return(signal) except: return help
def test(): pytree = Tree('pytree', self.shot, 'ReadOnly') ip = pytree.getNode('\\ip') pytree.setDefault(ip) self.assertEqual( str(ip.record), 'Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, "ampere"), *, DIM_OF(\\BTOR))' ) self.assertEqual(str(ip.record), str(ip.getData())) self.assertEqual(ip.segmented, ip.isSegmented()) self.assertEqual(ip.versions, ip.containsVersions()) self.assertEqual(ip.getNumSegments(), 0) self.assertEqual(ip.getSegment(0), None)
def getNode(self): with Tree('pytree',self.shot+3,'new') as pytree: pytree.addNode('pytreesub','subtree').include_in_pulse=True pytree.write() with Tree('pytreesub',self.shot+3,'new') as pytreesub: ip=pytreesub.addNode('ip','signal') ip.tag='IP' pytreesub.write() pytree=Tree('pytree',self.shot+3,'ReadOnly') ip = pytree.getNode('\\ip') self.assertEqual(str(ip),'\\PYTREESUB::IP') self.assertEqual(ip.nid,pytree._IP.nid) self.assertEqual(ip.nid,pytree.__PYTREESUB.IP.nid) self.assertEqual(ip.nid,pytree.__PYTREESUB__IP.nid)
def setTransitionTimes(treeName, nchan, delta, stlpath): #This function is kind of a Unit Test. tree = Tree(treeName, -1, 'EDIT') print('Tree Name: ', treeName) nchan = int(nchan) current = 0.0 delta = float(delta) # sec end = 40.0 # sec times = np.arange(current, end, delta) transitions1 = np.array([[times[1], int(0)], [times[2], int(1)], [times[3], int(0)], [times[4], int(1)], [times[5], int(0)], [times[6], int(1)], [times[8], int(1)], [times[9], int(1)], [times[10], int(0)], [times[11], int(1)], [times[12], int(0)], [times[13], int(1)], [times[14], int(0)], [times[15], int(1)], [times[16], int(0)], [times[17], int(1)], [times[18], int(0)], [times[19], int(1)], [times[30], int(0)]]) transitions2 = np.array([[times[0], int(0)], [times[3], int(1)], [times[7], int(0)]]) for i in range(nchan): t_times = tree.getNode('ACQ2106_WRPG:OUTPUT_%3.3d' % (i + 1)) if (i % 2) == 0: #Even Channels t_times.record = transitions1 else: t_times.record = transitions2 tree.write() tree.close() set_stl(treeName, times, nchan, stlpath)
def test(): pytree = Tree('pytree', self.shot, 'ReadOnly') ip = pytree.getNode('\\ip') pytree.setDefault(ip) self.assertEqual( str(ip.record), 'Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, "ampere"), *, DIM_OF(\\BTOR))' ) self.assertEqual(str(ip.record), str(ip.getData())) self.assertEqual(ip.segmented, ip.isSegmented()) self.assertEqual(ip.versions, ip.containsVersions()) self.assertEqual(ip.getNumSegments(), 0) self.assertEqual(ip.getSegment(0), None) self.assertEqual(str(ip.getExtendedAttribute('ATT1')), '100') self.assertEqual(str(ip.getExtendedAttribute('ATT2')), '1 : 200 : *') self.assertEqual(str(ip.getExtendedAttribute('ATT3')), 'this is plasma current') self.assertEqual( str(ip.getExtendedAttributes()), "{'ATT3': 'this is plasma current', 'ATT2': 1 : 200 : *, 'ATT1': 100}" )
def archive_log(node, time=None, cache=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_log') try: from archive import base, interface from MDSplus import TreeNode, Tree if not isinstance(node, (TreeNode)): node = Tree('archive', -1).getNode(node) """ use _time variable if Tree is ARCHIVE """ try: node.getNode('$CFGLOG') url = base.Path(node.getNode('$URL').data()).url_cfglog() except: try: node.getNode('$PARLOG') url = base.Path(node.getNode('$URL').data()).url_parlog() except: raise Exception( 'could not specify log type. No Member named $CFGLOG or $PARLOG' ) if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval(['now']) else: time = base.TimeInterval(node.getNode('\TIME').data()) """ request signal """ return str(interface._get_json(url, time=time).read()) except: """ generate error message""" import getpass, sys user = getpass.getuser() e = sys.exc_info() help = user + ': ' + str(e[1]) + ', %d' % e[2].tb_lineno print(help) return help
def doScopepanel(self): def getStringExp(self,name,response_headers): if name in self.args: try: response_headers.append((name,str(Data.execute(self.args[name][-1]).data()))) except Exception: response_headers.append((name,str(sys.exc_info()[1]))) response_headers=list() response_headers.append(('Cache-Control','no-store, no-cache, must-revalidate')) response_headers.append(('Pragma','no-cache')) if 'tree' in self.args: Tree.usePrivateCtx() try: t=Tree(self.args['tree'][-1],int(self.args['shot'][-1].split(',')[0])) except: pass for name in ('title','xlabel','ylabel','xmin','xmax','ymin','ymax'): getStringExp(self,name,response_headers) sig_idx=0 output='' if 'tree' in self.args: shots=self.args['shot'][-1].split(',') for shot in shots: y_idx=1 y_idx_s='%d' % (y_idx,) while 'y'+y_idx_s in self.args: x_idx_s=y_idx_s sig_idx=sig_idx+1 sig_idx_s='%d' % (sig_idx,) expr=self.args['y'+y_idx_s][-1] y_idx=y_idx+1 y_idx_s='%d' % (y_idx,) try: t=Tree(self.args['tree'][-1],int(shot)) response_headers.append(('SHOT'+sig_idx_s,str(t.shot))) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1],shot,sys.exc_info()[1]))) continue if 'default_node' in self.args: try: t.setDefault(t.getNode(self.args['default_node'][-1])) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error setting default to %s in tree %s, shot %s, error: %s' % (self.args['default_node'][-1], self.args['tree'][-1],shot,sys.exc_info()[1]))) continue try: sig=Data.execute(expr) y=makeData(sig.data()) except Exception: response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue if 'x'+x_idx_s in self.args: expr=self.args['x'+x_idx_s][-1] try: x=Data.execute(expr) x=makeData(x.data()) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue else: try: x=makeData(sig.dim_of().data()) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error getting x axis of %s: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue response_headers.append(('X'+sig_idx_s+'_DATATYPE',x.__class__.__name__)) response_headers.append(('Y'+sig_idx_s+'_DATATYPE',y.__class__.__name__)) response_headers.append(('X'+sig_idx_s+'_LENGTH',str(len(x)))) response_headers.append(('Y'+sig_idx_s+'_LENGTH',str(len(y)))) output=output+str(x.data().data)+str(y.data().data) else: y_idx=1 y_idx_s='%d' % (y_idx,) while 'y'+y_idx_s in self.args: x_idx_s = y_idx_s expr=self.args['y'+y_idx_s][-1] y_idx=y_idx+1 y_idx_s='%d' % (y_idx,) sig_idx=sig_idx+1 sig_idx_s='%d' % (sig_idx,) try: sig=Data.execute(expr) y=makeData(sig.data()) except Exception: response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue if 'x'+x_idx_s in self.args: expr=self.args['x'+x_idx_s][-1] try: x=Data.execute(expr) x=makeData(x.data()) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue else: try: x=makeData(sig.dim_of().data()) except Exception: response_headers.append(('ERROR'+sig_idx_s,'Error getting x axis of %s: "%s", error: %s' % (expr,sys.exc_info()[1]))) continue response_headers.append(('X'+sig_idx_s+'_DATATYPE',x.__class__.__name__)) response_headers.append(('Y'+sig_idx_s+'_DATATYPE',y.__class__.__name__)) response_headers.append(('X'+sig_idx_s+'_LENGTH',str(len(x)))) response_headers.append(('Y'+sig_idx_s+'_LENGTH',str(len(y)))) output=output+str(x.data().data)+str(y.data().data) return ('200 OK', response_headers, output)
def doScopepanel(self): def getStringExp(self, name, response_headers): if name in self.args: try: response_headers.append( (name, str(Data.execute(self.args[name][-1]).data()))) except Exception: response_headers.append((name, str(sys.exc_info()[1]))) response_headers = list() response_headers.append( ('Cache-Control', 'no-store, no-cache, must-revalidate')) response_headers.append(('Pragma', 'no-cache')) if 'tree' in self.args: Tree.usePrivateCtx() try: t = Tree(self.args['tree'][-1], int(self.args['shot'][-1].split(',')[0])) except: pass for name in ('title', 'xlabel', 'ylabel', 'xmin', 'xmax', 'ymin', 'ymax'): getStringExp(self, name, response_headers) sig_idx = 0 output = '' if 'tree' in self.args: shots = self.args['shot'][-1].split(',') for shot in shots: y_idx = 1 y_idx_s = '%d' % (y_idx, ) while 'y' + y_idx_s in self.args: x_idx_s = y_idx_s sig_idx = sig_idx + 1 sig_idx_s = '%d' % (sig_idx, ) expr = self.args['y' + y_idx_s][-1] y_idx = y_idx + 1 y_idx_s = '%d' % (y_idx, ) try: t = Tree(self.args['tree'][-1], int(shot)) response_headers.append(('SHOT' + sig_idx_s, str(t.shot))) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1], shot, sys.exc_info()[1]))) continue if 'default_node' in self.args: try: t.setDefault(t.getNode(self.args['default_node'][-1])) except Exception: response_headers.append(( 'ERROR' + sig_idx_s, 'Error setting default to %s in tree %s, shot %s, error: %s' % (self.args['default_node'][-1], self.args['tree'][-1], shot, sys.exc_info()[1]))) continue try: sig = Data.execute(expr) y = makeData(sig.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue if 'x' + x_idx_s in self.args: expr = self.args['x' + x_idx_s][-1] try: x = Data.execute(expr) x = makeData(x.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue else: try: x = makeData(sig.dim_of().data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error getting x axis of %s: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue response_headers.append( ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__)) response_headers.append( ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__)) response_headers.append( ('X' + sig_idx_s + '_LENGTH', str(len(x)))) response_headers.append( ('Y' + sig_idx_s + '_LENGTH', str(len(y)))) output = output + str(x.data().data) + str(y.data().data) else: y_idx = 1 y_idx_s = '%d' % (y_idx, ) while 'y' + y_idx_s in self.args: x_idx_s = y_idx_s expr = self.args['y' + y_idx_s][-1] y_idx = y_idx + 1 y_idx_s = '%d' % (y_idx, ) sig_idx = sig_idx + 1 sig_idx_s = '%d' % (sig_idx, ) try: sig = Data.execute(expr) y = makeData(sig.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue if 'x' + x_idx_s in self.args: expr = self.args['x' + x_idx_s][-1] try: x = Data.execute(expr) x = makeData(x.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue else: try: x = makeData(sig.dim_of().data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error getting x axis of %s: "%s", error: %s' % (expr, sys.exc_info()[1]))) continue response_headers.append( ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__)) response_headers.append( ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__)) response_headers.append(('X' + sig_idx_s + '_LENGTH', str(len(x)))) response_headers.append(('Y' + sig_idx_s + '_LENGTH', str(len(y)))) output = output + str(x.data().data) + str(y.data().data) return ('200 OK', response_headers, output)
def run(self): Tree.usePrivateCtx(True) try: # test open Nodes tree = Tree(self.tree, self.shot) try: tree.getNode(self.pcb) except Exception as exc: error(exc) self.pcb = None try: tree.getNode(self.cmos) except Exception as exc: error(exc) self.cmos = None except Exception as exc: error(exc) error( 'Cannot access trend tree. Check TREND:TREE and TREND_SHOT.' ) raise mdsExceptions.TreeTNF if self.pcb is None and self.cmos is None: error( 'Cannot access any node for trend. Check TREND:PCB, TREND:CMOS on. Nodes must exist on %s.' % repr(tree)) raise mdsExceptions.TreeNNF if self.pcb is None: error( 'Cannot access node for pcb trend. Check TREND:PCB. Continue with cmos trend.' ) elif self.cmos is None: error( 'Cannot access node for cmos trend. Check TREND:CMOS. Continue with pcb trend.' ) print('started trend writing to %s - %s and %s every %fs' % (self.tree, self.pcb, self.cmos, self.period)) self.running = True while (not self.stopReq): timeTillNextMeasurement = self.period - (time() % self.period) if timeTillNextMeasurement > 0.6: sleep(.5) # listen to stopReq else: sleep(timeTillNextMeasurement) # wait remaining period unit self.period currTime = int( int(time() / self.period + .1) * self.period * 1000) # currTime in steps of self.period if self.ns: currTime *= 1000000 # time in nano seconds try: if self.shot == 0: if Tree.getCurrent(self.tree) != tree.shot: tree = Tree(self.tree, self.shot) if self.pcb is not None: pcbTemp = CYGNET4K.xclib.getPcbTemp() tree.getNode(self.pcb).makeSegment( currTime, currTime, Dimension(None, Uint64Array(currTime)), Float32Array(pcbTemp).setUnits('oC'), -1) if self.cmos is not None: cmosTemp = CYGNET4K.xclib.getCmosTemp() tree.getNode(self.cmos).makeSegment( currTime, currTime, Dimension(None, Uint64Array(currTime)), Uint16Array(cmosTemp), -1) if Device.debug: print(tree.tree, tree.shot, currTime, pcbTemp, cmosTemp) except Exception: error(exc_info()[1]) error('failure during temperature readout') sleep(0.01) self.running = False print('done')
def archive_signal(node, time=None, cache=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_signal') try: from archive import base, interface from MDSplus import TreeNode, Tree, Data, mdsExceptions if not isinstance(node, (TreeNode)): node = Tree('archive',-1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800.,0,0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) """handle arguments""" kwargs = {} if str(node.node_name)[0]=='$': kwargs['scaled'] = str(node.node_name)[1:].lower() node = node.getParent() else: try: kwargs['scaling'] = node.getNode('AIDEVSCALING').data() except: pass try: kwargs['value'] = node.getNode('$VALUE').data() except: try: gain = node.getNode('GAIN').data() zero = node.getNode('ZEROOFFSET').data() if gain!=1. or zero!=0.: kwargs['value'] = Data.compile('$VALUE*$+$',(gain,zero)) except Exception as exc: if not isinstance(exc,mdsExceptions.TreeNNF): print(exc) if cache is not None: kwargs['cache'] = cache try: # load channels by datastream + index kwargs['channel'] = node.getNode('$IDX').data() url = node.getParent().getNode('$URL').data() except: url = node.getNode('$URL').data() """ request signal """ signal = interface.read_signal(url, time, **kwargs) """ generate help text (HELP, DESCRIPTION, $NAME) """ try: help = node.getNode('HELP').data() except: try: help = node.getNode('DESCRIPTION').data() except: help = node.getNode('$NAME').data() signal.setHelp(str(help)) return(signal) except: local = locals() """ generate dummy signal with error message as help text """ import getpass,sys e = sys.exc_info() user = getpass.getuser() help = user+': %s, %d' % (repr(e[1]), e[2].tb_lineno) print(help) print(local) try: from MDSplus import Signal signal = Signal([6,66,666]) signal.setHelp(help.split('\n')[-1]) return(signal) except: return help
def set_stl(treeName, times, nchan): tree = Tree(treeName, -1) states_hex = [] states_bits = [] all_t_times = [] all_t_times_states = [] for i in range(nchan): chan_t_times = tree.getNode('ACQ2106_WRPG:OUTPUT_%3.3d' % (i + 1)) # Pair of (transition time, state) for each channel: chan_t_states = chan_t_times.data() # Creation of an array that contains as EVERY OTHER element all the transition times in it, adding them # for each channel: for x in np.nditer(chan_t_states): all_t_times_states.append(x) #Appends arrays made of one element, # Choosing only the transition times: all_t_times = all_t_times_states[0::2] # Removing duplicates and then sorting in ascending manner: t_times = [] for i in all_t_times: if i not in t_times: t_times.append(i) # t_times contains the unique set of transitions times used in the experiment: t_times = sorted(np.float64(t_times)) print(t_times) # initialize the state matrix rows, cols = (len(t_times), nchan) state = [[0] * cols] * rows # Building the state matrix. For each transition times given by t_times, we look for those that # appear in the channel. If a transition time does not appear in that channel, then the state # for this transition time is consider the same as the previous state for this channel (i.e. the state # hasn't changed) i = 0 for t in t_times: #print(i, state[i]) for j in range(nchan): chan_t_states = tree.getNode('ACQ2106_WRPG:OUTPUT_%3.3d' % (j + 1)) for s in range(len(chan_t_states[0])): #Check if the transition time is one of the times that belongs to this channel: if t in chan_t_states[0][s]: #print("inside Chan%i" %(j+1), t, i, j, int(np.asscalar(chan_t_states[1][s]))) state[i][j] = int(np.asscalar(chan_t_states[1][s])) #print(" Chan%i" %(j+1), t, i, j, state[i][j]) # Building the string of 1s and 0s for each transition time: binstr = '' for element in np.flip(state[i]): binstr += str(element) states_bits.append(binstr) i += 1 print(states_bits) #Converting those strings into HEX numbers for elements in states_bits: states_hex.append( hex(int(elements, 2))[2:] ) # the [2:] is because I don't need to 0x part of the hex string # Converting the original units of the transtion times in seconds, to micro-seconts: times_usecs = [] for elements in t_times: times_usecs.append(int(elements * 1E6)) #in micro-seconds # Building a pair between the t_times and hex states: state_list = zip(times_usecs, states_hex) stlpath = '/home/fsantoro/HtsDevice/acq400_hapi/user_apps/STL/do_states.stl' outputFile = open(stlpath, 'w') with outputFile as f: writer = csv.writer(f, delimiter=',') writer.writerows(state_list) outputFile.close()
class mdsTree: """ 构建MDSplus.Tree的一些常用方法 """ def __init__(self, dbname, shot): self.shot = shot self.dbname = dbname self.tree = Tree(self.dbname, self.shot) def formChannelPool(self): """ 构建一个通道池, 对外显示的通道均有与通道名称相同的tags """ node_list = self.tree.getNodeWild("***") channels = [] for node in node_list: if node.usage == 'SIGNAL' and len(node.tags) == 1 and str( node.tags[0]) == node.name: channels.append(node.name.strip()) return channels def close(self): self.tree.close() def getCurrentShot(self): """ 获取当前炮号 """ try: shot_num = self.tree.getCurrent() new_tree = Tree(self.dbname, shot_num) shot_num = shot_num if new_tree.getNode( 'FBC:DUPS1').getLength() else shot_num - 1 except mdsExceptions.TreeNNF: # MDSplus.mdsExceptions.TreeNNF: %TREE-W-NNF, Node Not Found shot_num = shot_num if new_tree.getNode( 'FBC:IP').getLength() else shot_num - 1 except mdsExceptions.TreeNOCURRENT: # MDSplus.mdsExceptions.TreeNOCURRENT: %TREE-E-NOCURRENT, No current shot number set for this tree. shot_num = None return shot_num def renameChaName(self, channel_name): """ 通道名加r'\'是通道的tags, 不在使用'子树:通道名'方式进行索引""" return '\\' + channel_name.upper() def isHaveData(self, channel_name): """ 返回储存内容长度, 当里面不是数据是公式的时候也有长度(此时如果公式索引的通道没数据同样没有数据) """ # length = self.tree.getNode(self.renameChaName(channel_name)).getCompressedLength() length = self.tree.getNode( self.renameChaName(channel_name)).getLength() return length def getWrittenTime(self, channel_name): """ 获得数据写入时间 """ return self.tree.getNode( self.renameChaName(channel_name)).getTimeInserted().date def setTimeContext(self, begin, end, delta): """ 设置起止时间及采样率,参数单位s """ self.tree.setTimeContext(begin, end, delta) def getData(self, channel_name, begin=None, end=None, delta=None): """ 返回x,y数据,如果没有数据,或出错,返回两个空列表 """ self.setTimeContext(begin, end, delta) channel_name = self.renameChaName(channel_name) try: data_x = self.tree.getNode(channel_name).dim_of().data() data_y = self.tree.getNode(channel_name).data() except mdsExceptions.TreeNODATA: # MDSplus.mdsExceptions.TreeNODATA: %TREE-E-NODATA, No data available for this node data_x = [] data_y = [] except mdsExceptions.TreeNNF: # MDSplus.mdsExceptions.TreeNNF: %TREE-W-NNF, Node Not Found data_x = [] data_y = [] except Exception as e: print('Check {} find that {}'.format(channel_name, str(e))) data_x = [] data_y = [] return data_x, data_y def getYInfo(self, channel_name): """ 获得通道数据Y轴单位 """ try: unit = self.tree.getNode( self.renameChaName(channel_name)).units_of() unit = '-' if unit == ' ' else unit except Exception as e: print('get {} unit find that {}'.format(channel_name, str(e))) unit = '-' return {"unit": unit}
from MDSplus import Tree import sys limits = [[-10.775885, 10.632514], [-10.841410, 10.729164], [-10.515574, 10.401434], [-10.618536, 10.632407], [-10.767994, 10.615872], [-10.780648, 10.789758], [-10.633335, 10.595271], [-11.007920, 10.958671], [-10.716168, 10.600871], [-10.757820, 10.753945], [-10.528884, 10.418159], [-10.687237, 10.582137], [-10.589798, 10.680742], [-10.973911, 10.871290], [-10.334272, 10.356784], [-10.796816, 10.618926]] t = Tree('magnetics', int(sys.argv[1])) for i in range(16): node = t.getNode('.active_mhd.data_acq.cpci.acq_216_1.input_%02d' % (i + 1, )) try: sig = node.record except: sig = None if sig is not None: sig.value[0] = limits[i][1] sig.value[1][0][0][0] = limits[i][0] sig.value[1][0][0][1] = limits[i][1] try: node.write_once = False node.record = sig node.write_once = True except Exception, e: print "Error fixing node %s, error was: %s" % (str(node), str(e))
t = Tree('my_tree', -1) # ----------------------- Instance Methods ----------------------- dfs = t.getDatafileSize() # t.cleanDatafile() # t.compressDatafile() fn = t.getFileName() t2 = t.copy() # t.close() # top = t.top() # ad = t.addDevice('SUB3') # an = t.addNode('SUB4') # createPulse(1) dir = t.dir() # gc = t.getCurrent('SUB1') gd = t.getDefault() gn = t.getNode("SUB1") gnwi_iterator = t.getNodeWildIter('***') gnw_array = t.getNodeWild('***') gtc_tuple = t.getTimeContext() im_bool = t.isModified() # sd_tn = t.setDefault("SUB1") # ----------------------- Static Methods ----------------------- # gvd_str = t.getVersionDate() # --------------------------- TreeNode Methods --------------------------- # from MDSplus import TreeNode tn = t.getNode("SUB1") c_tn = tn.copy() opn_str = tn.ORIGINAL_PART_NAME() pn_str = tn.PART_NAME() # cn = tn.children_nids()
#! python3 # -*- coding:utf-8 -*- from MDSplus import Tree from MDSplus import TreeNode t = Tree('my_tree', -1) node_str = "SUB1" node1 = t.getNode(node_str) node_path = node1.getMinPath() node_path2 = node1.getPath() node_path3 = node1.getFullPath() node_name = node1.getNodeName() node_father = node1.getParent() node_dtype = node1.getDtype() node_att = node1.getExtendedAttribute('NUMERIC') # ?? node_nid = node1.getNid() child_num = node1.getNumChildren() child_num2 = node1.getNumDescendants() print(11)
def archive_signal(node, time=None, cache=None): """ use time if tree is archive """ """ else use TIME node """ print('archive_signal') try: from archive import base, interface from MDSplus import TreeNode, Tree, Data, mdsExceptions if not isinstance(node, (TreeNode)): node = Tree('archive', -1).getNode(node) """ use _time variable if Tree is ARCHIVE """ if node.tree.shot == -1: try: time = base.TimeInterval(time) except: time = base.TimeInterval([-1800., 0, 0]) else: time = base.TimeInterval(node.getNode('\TIME').data()) """handle arguments""" kwargs = {} if str(node.node_name)[0] == '$': kwargs['scaled'] = str(node.node_name)[1:].lower() node = node.getParent() else: try: kwargs['scaling'] = node.getNode('AIDEVSCALING').data() except: pass try: kwargs['value'] = node.getNode('$VALUE').data() except: try: gain = node.getNode('GAIN').data() zero = node.getNode('ZEROOFFSET').data() if gain != 1. or zero != 0.: kwargs['value'] = Data.compile('$VALUE*$+$', (gain, zero)) except Exception as exc: if not isinstance(exc, mdsExceptions.TreeNNF): print(exc) if cache is not None: kwargs['cache'] = cache try: # load channels by datastream + index kwargs['channel'] = node.getNode('$IDX').data() url = node.getParent().getNode('$URL').data() except: url = node.getNode('$URL').data() """ request signal """ signal = interface.read_signal(url, time, **kwargs) """ generate help text (HELP, DESCRIPTION, $NAME) """ try: help = node.getNode('HELP').data() except: try: help = node.getNode('DESCRIPTION').data() except: help = node.getNode('$NAME').data() signal.setHelp(str(help)) return (signal) except: local = locals() """ generate dummy signal with error message as help text """ import getpass, sys e = sys.exc_info() user = getpass.getuser() help = user + ': %s, %d' % (repr(e[1]), e[2].tb_lineno) print(help) print(local) try: from MDSplus import Signal signal = Signal([6, 66, 666]) signal.setHelp(help.split('\n')[-1]) return (signal) except: return help
def test(): from numpy import array, int32 pytree = Tree('pytree', self.shot, 'ReadOnly') top = TreeNode(0, pytree) members = pytree.getNodeWild(':*') self.assertEqual((members == top.member_nids).all(), True) self.assertEqual((members == top.getMembers()).all(), True) self.assertEqual(top.member.nid_number, members[0].nid_number) member = top.member for idx in range(1, len(members)): self.assertEqual(member.brother.nid_number, members[idx].nid_number) member = member.brother children = pytree.getNodeWild('.*') self.assertEqual((children == top.children_nids).all(), True) self.assertEqual((children == top.getChildren()).all(), True) self.assertEqual(top.child.nid_number, children[0].nid_number) child = top.child for idx in range(1, len(children)): self.assertEqual(child.brother.nid_number, children[idx].nid_number) child = child.brother self.assertEqual(top.child.nid_number, pytree.getNode(str(top.child)).nid_number) self.assertEqual(top.child.child.parent.nid_number, top.child.nid_number) x = array(int32(0)).repeat(len(members) + len(children)) x[0:len(children)] = children.nid_number.data() x[len(children):] = members.nid_number.data() self.assertEqual( (makeArray(x) == top.descendants.nid_number).all(), True) self.assertEqual( (top.descendants.nid_number == top.getDescendants().nid_number ).all(), True) self.assertEqual(top.child.child.depth, 3) self.assertEqual(top.getNumDescendants(), len(x)) self.assertEqual(top.getNumMembers(), len(members)) self.assertEqual(top.getNumChildren(), len(children)) self.assertEqual(top.number_of_members, len(members)) self.assertEqual(top.number_of_children, len(children)) self.assertEqual(top.number_of_descendants, len(x)) devs = pytree.getNodeWild('\\PYTREESUB::TOP.***', 'DEVICE') dev = devs[0].conglomerate_nids self.assertEqual( (dev.nid_number == devs[0].getConglomerateNodes().nid_number ).all(), True) self.assertEqual( (dev.conglomerate_elt == makeArray(array(range(len(dev))) + 1)).all(), True) for idx in range(len(dev)): self.assertEqual(dev[idx].conglomerate_elt, idx + 1) self.assertEqual(dev[idx].getConglomerateElt(), idx + 1) self.assertEqual(top.child.is_child, True) self.assertEqual(top.child.is_member, False) self.assertEqual(top.member.is_child, False) self.assertEqual(top.member.is_member, True) self.assertEqual(top.child.is_child, top.child.isChild()) self.assertEqual(top.child.is_member, top.child.isMember()) ip = pytree.getNode('\\ip') pytree.setDefault(ip) self.assertEqual(ip.fullpath, "\\PYTREE::TOP.PYTREESUB:IP") self.assertEqual(ip.fullpath, ip.getFullPath()) self.assertEqual(ip.minpath, "\\IP") self.assertEqual(ip.minpath, ip.getMinPath()) self.assertEqual(ip.node_name, 'IP') self.assertEqual(ip.node_name, ip.getNodeName()) self.assertEqual(ip.path, "\\PYTREESUB::IP") self.assertEqual(ip.path, ip.getPath())
def set_stl(treeName, times, nchan, stlpath): tree = Tree(treeName, -1) states_hex = [] states_bits = [] all_t_times = [] all_t_times_states = [] for i in range(nchan): chan_t_times = tree.getNode('ACQ2106_WRPG:OUTPUT_%3.3d' % (i + 1)) # Pair of (transition time, state) for each channel: chan_t_states = chan_t_times.data() # Creation of an array that contains as EVERY OTHER element all the transition times in it, adding them # for each channel: for x in np.nditer(chan_t_states): all_t_times_states.append(x) #Appends arrays made of one element, # Choosing only the transition times: all_t_times = all_t_times_states[0::2] # Removing duplicates and then sorting in ascending manner: t_times = [] for i in all_t_times: if i not in t_times: t_times.append(i) # t_times contains the unique set of transitions times used in the experiment: t_times = sorted(np.float64(t_times)) print(t_times) # initialize the state matrix rows, cols = (len(t_times), nchan) state = [[0 for i in range(cols)] for j in range(rows)] # Building the state matrix. For each transition times given by t_times, we look for those times that # appear in the channel. If a transition time does not appear in that channel, then the state # doesn't change. for j in range(nchan): chan_t_states = tree.getNode('ACQ2106_WRPG:OUTPUT_%3.3d' % (j + 1)) for i in range(len(t_times)): #print(j, i, state[i][j]) if i == 0: state[i][j] = 0 else: state[i][j] = state[i - 1][j] # chan_t_states its elements are pairs of [ttimes, state]. e.g [[0.0, 0],[1.0, 1],...] # chan_t_states[0] are all the first elements of those pairs, i.e the trans. times: e.g [[1D0], [2D0], [3D0], [4D0] ... ] # chan_t_states[1] are all the second elements of those pairs, the states: .e.g [[0],[1],...] for t in range(len(chan_t_states[0])): #Check if the transition time is one of the times that belongs to this channel: if t_times[i] == chan_t_states[0][t][0]: #print("t_times is in chan ", int(chan_t_states[1][t][0])) state[i][j] = int(chan_t_states[1][t][0]) # Building the string of 1s and 0s for each transition time: binrows = [] for row in state: rowstr = [str(i) for i in np.flip(row)] binrows.append(''.join(rowstr)) print(binrows) # Converting the original units of the transtion times in seconds, to micro-seconts: times_usecs = [] for elements in t_times: times_usecs.append(int(elements * 1E6)) #in micro-seconds # Building a pair between the t_times and hex states: state_list = zip(times_usecs, binrows) f = open(stlpath, 'w') for s in state_list: f.write('%d,%08X\n' % (s[0], int(s[1], 2))) f.close()
def doScopepanel(self): def getStringExp(self, name, response_headers): if name in self.args: try: response_headers.append( (name, str(Data.execute(self.args[name][-1]).data()))) except Exception: response_headers.append( (name + '_error:', str(sys.exc_info()))) def manageContinuousUpdate(self, x): if x.getShape().size == 1: new_max_x = x.data()[-1] else: new_max_x = x.data()[0][-1] curr_max_x = float(self.args['curr_max_x' + x_idx_s][-1]) displayed_width = float(self.args['displayed_width'][-1]) default_num_samples = float(self.args['default_num_samples'][-1]) num_samples = int( (new_max_x - curr_max_x) * default_num_samples / displayed_width) if new_max_x > curr_max_x and num_samples > 1: if issubclass(x.dtype.type, integer): min_req_x = floor(curr_max_x + 1) else: min_req_x = curr_max_x + finfo(new_max_x).eps update_function = 'MdsMisc->GetXYWave:DSC' infinity = sys.float_info.max if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array': update_function = 'MdsMisc->GetXYWaveLongTimes:DSC' min_req_x = str(int(min_req_x)) + 'QU' infinity = str((1 << 63) - 1) + 'QU' sig = Data.execute( update_function + '(\'' + expr.replace('\\', '\\\\').replace('\'', '\\\'') + '\',' + str(min_req_x) + ',' + str(infinity) + ',' + str(num_samples) + ')') return makeData(sig.dim_of().data()), makeData(sig.data()) else: return Float64Array([]), Float64Array([]) response_headers = list() response_headers.append( ('Cache-Control', 'no-store, no-cache, must-revalidate')) response_headers.append(('Pragma', 'no-cache')) if 'tree' in self.args: Tree.usePrivateCtx() try: t = Tree(self.args['tree'][-1], int(self.args['shot'][-1].split(',')[0])) except: pass for name in ('title', 'xlabel', 'ylabel', 'xmin', 'xmax', 'ymin', 'ymax'): getStringExp(self, name, response_headers) continuous_update = 'continuous_update' in self.args sig_idx = 0 output = '' if 'tree' in self.args: shots = self.args['shot'][-1].split(',') for shot in shots: y_idx = 1 y_idx_s = '%d' % (y_idx, ) while 'y' + y_idx_s in self.args: x_idx_s = y_idx_s sig_idx = sig_idx + 1 sig_idx_s = '%d' % (sig_idx, ) expr = self.args['y' + y_idx_s][-1] y_idx = y_idx + 1 y_idx_s = '%d' % (y_idx, ) try: t = Tree(self.args['tree'][-1], int(shot)) response_headers.append(('SHOT' + sig_idx_s, str(t.shot))) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1], shot, sys.exc_info()))) continue if 'default_node' in self.args: try: t.setDefault(t.getNode(self.args['default_node'][-1])) except Exception: response_headers.append(( 'ERROR' + sig_idx_s, 'Error setting default to %s in tree %s, shot %s, error: %s' % (self.args['default_node'][-1], self.args['tree'][-1], shot, sys.exc_info()))) continue try: sig = Data.execute(expr) if not continuous_update: y = makeData(sig.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()))) continue if 'x' + x_idx_s in self.args: expr = self.args['x' + x_idx_s][-1] try: x = Data.execute(expr) x = makeData(x.data()) if continuous_update: x, y = manageContinuousUpdate(self, x) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()))) continue else: try: x = makeData(sig.dim_of().data()) if continuous_update: x, y = manageContinuousUpdate(self, x) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error getting x axis of %s:, error: %s' % (expr, sys.exc_info()))) continue if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array': x = Float64Array( x) # Javascript doesn't support 64 bit integers response_headers.append(('X_IS_DATETIME', 'true')) response_headers.append( ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__)) response_headers.append( ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__)) response_headers.append( ('X' + sig_idx_s + '_LENGTH', str(len(x)))) response_headers.append( ('Y' + sig_idx_s + '_LENGTH', str(len(y)))) output = output + str(x.data().data) + str(y.data().data) else: y_idx = 1 y_idx_s = '%d' % (y_idx, ) while 'y' + y_idx_s in self.args: x_idx_s = y_idx_s expr = self.args['y' + y_idx_s][-1] y_idx = y_idx + 1 y_idx_s = '%d' % (y_idx, ) sig_idx = sig_idx + 1 sig_idx_s = '%d' % (sig_idx, ) try: sig = Data.execute(expr) if not continuous_update: y = makeData(sig.data()) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()))) continue if 'x' + x_idx_s in self.args: expr = self.args['x' + x_idx_s][-1] try: x = Data.execute(expr) x = makeData(x.data()) if continuous_update: x, y = manageContinuousUpdate(self, x) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error evaluating expression: "%s", error: %s' % (expr, sys.exc_info()))) continue else: try: x = makeData(sig.dim_of().data()) if continuous_update: x, y = manageContinuousUpdate(self, x) except Exception: response_headers.append( ('ERROR' + sig_idx_s, 'Error getting x axis of %s: "%s", error: %s' % (expr, sys.exc_info()))) continue if x.__class__.__name__ == 'Uint64Array' or x.__class__.__name__ == 'Int64Array': x = Float64Array( x) # Javascript doesn't support 64 bit integers response_headers.append(('X_IS_DATETIME', 'true')) response_headers.append( ('X' + sig_idx_s + '_DATATYPE', x.__class__.__name__)) response_headers.append( ('Y' + sig_idx_s + '_DATATYPE', y.__class__.__name__)) response_headers.append(('X' + sig_idx_s + '_LENGTH', str(len(x)))) response_headers.append(('Y' + sig_idx_s + '_LENGTH', str(len(y)))) output = output + str(x.data().data) + str(y.data().data) return ('200 OK', response_headers, output)
""" Created on Wed Aug 12 00:30:33 2015 @author: Cloud """ from MDSplus import Tree def setRecord(node, istop=True): from MDSplus import TdiCompile for dec in node.getDescendants(): if dec.getNodeName() == '$URL' and ~istop: dec.record = TdiCompile('codac_url($)', (node,)) elif dec.usage == 'ANY' and dec.getNodeName() == '$PARLOG': dec.record = TdiCompile('archive_parlog($,_time)', (node,)) elif dec.getNodeName() == '$CFGLOG': dec.record = TdiCompile('archive_cfglog($,_time)', (node,)) elif dec.usage == 'SIGNAL': dec.record = TdiCompile('archive_signal($,_time)', (dec,)) setRecord(dec, False) tree = Tree('ARCHIVESB', -1) setRecord(tree.getNode('\TOP'))
def test(): pytree = Tree('pytree', self.shot, 'ReadOnly') ip = pytree.getNode('\\ip') self.assertEqual(ip.getUsage(), 'SIGNAL') self.assertEqual(ip.usage, ip.getUsage()) try: # do not continue and print when no match self.assertEqual(ip.getClass(), 'CLASS_R') except AssertionError: print("ip.nid=%d" % (ip.nid, )) print("Error with ip in %s" % (str(ip.tree), )) raise self.assertEqual(ip.class_str, 'CLASS_R') self.assertEqual(ip.compressible, False) self.assertEqual(ip.compressible, ip.isCompressible()) self.assertEqual(ip.compress_on_put, True) self.assertEqual(ip.compress_on_put, ip.isCompressOnPut()) self.assertEqual(ip.data_in_nci, False) self.assertEqual(ip.on, True) self.assertEqual(ip.on, ip.isOn()) self.assertEqual(ip.do_not_compress, False) self.assertEqual(ip.do_not_compress, ip.isDoNotCompress()) self.assertEqual(ip.dtype_str, 'DTYPE_SIGNAL') self.assertEqual(ip.dtype_str, ip.getDtype()) self.assertEqual(ip.essential, False) self.assertEqual(ip.essential, ip.isEssential()) mhdtree = pytree.getNode('\\PYTREESUB::TOP') self.assertEqual(mhdtree.include_in_pulse, True) self.assertEqual(mhdtree.include_in_pulse, mhdtree.isIncludeInPulse()) self.assertEqual(ip.length, int(Data.execute('getnci($,"LENGTH")', ip))) self.assertEqual(ip.length, ip.getLength()) self.assertEqual(ip.no_write_shot, False) self.assertEqual(ip.no_write_shot, ip.isNoWriteShot()) self.assertEqual(ip.no_write_model, False) self.assertEqual(ip.no_write_model, ip.isNoWriteModel()) self.assertEqual(ip.write_once, False) self.assertEqual(ip.write_once, ip.isWriteOnce()) pydev = pytree.TESTDEVICE part = pydev.conglomerate_nids[1] self.assertEqual(part.PART_NAME(), ':ACTIONSERVER') self.assertEqual(part.original_part_name, ':ACTIONSERVER') self.assertEqual( str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part)), ':ACTIONSERVER') self.assertEqual(pydev.__class__, Device.PyDevice('TestDevice')) devs = pytree.getNodeWild('\\PYTREESUB::TOP.***', 'DEVICE') part = devs[0].conglomerate_nids[3] self.assertEqual(part.original_part_name, ':COMMENT') self.assertEqual( part.original_part_name, str(Data.execute('GETNCI($,"ORIGINAL_PART_NAME")', part))) self.assertEqual(ip.owner_id, ip.getOwnerId()) self.assertEqual(ip.rlength, 168) self.assertEqual(ip.rlength, ip.getCompressedLength()) self.assertEqual(ip.setup_information, False) self.assertEqual(ip.setup_information, ip.isSetup()) self.assertEqual(ip.status, 0) self.assertEqual(ip.status, ip.getStatus()) self.assertEqual((ip.tags == makeArray([ 'IP', 'MAGNETICS_IP', 'MAG_IP', 'MAGNETICS_PLASMA_CURRENT', 'MAG_PLASMA_CURRENT' ])).all(), True) self.assertEqual((ip.tags == ip.getTags()).all(), True) self.assertEqual(ip.time_inserted, ip.getTimeInserted())
while 'y'+y_idx_s in self.args: x_idx_s=y_idx_s sig_idx=sig_idx+1 sig_idx_s='%d' % (sig_idx,) expr=self.args['y'+y_idx_s][-1] y_idx=y_idx+1 y_idx_s='%d' % (y_idx,) try: t=Tree(self.args['tree'][-1],int(shot)) response_headers.append(('SHOT'+sig_idx_s,str(t.shot))) except Exception,e: response_headers.append(('ERROR'+sig_idx_s,'Error opening tree %s, shot %s, error: %s' % (self.args['tree'][-1],shot,e))) continue if 'default_node' in self.args: try: t.setDefault(t.getNode(self.args['default_node'][-1])) except Exception,e: response_headers.append(('ERROR'+sig_idx_s,'Error setting default to %s in tree %s, shot %s, error: %s' % (self.args['default_node'][-1], self.args['tree'][-1],shot,e))) continue try: sig=Data.execute(expr) y=makeData(sig.data()) except Exception,e: response_headers.append(('ERROR' + sig_idx_s,'Error evaluating expression: "%s", error: %s' % (expr,e))) continue if 'x'+x_idx_s in self.args: expr=self.args['x'+x_idx_s][-1] try: x=Data.execute(expr) x=makeData(x.data())