Ejemplo n.º 1
0
 def test():
     with Tree('pytree', self.shot, 'new') as pytree:
         if pytree.shot != self.shot:
             raise Exception(
                 "Shot number changed! tree.shot=%d, thread.shot=%d" %
                 (pytree.shot, self.shot))
         pytree.default.addNode('pytreesub',
                                'subtree').include_in_pulse = True
         for i in range(10):
             node = pytree.addNode('val%02d' % (i, ), 'numeric')
             node.record = i
             node = pytree.top.addNode('sig%02d' % (i, ), 'signal')
             node.record = Signal(i, None, i)
             node = pytree.top.addNode('child%02d' % (i, ), 'structure')
             node.addNode('text', 'text')
             node.addNode('child', 'structure')
         node = pytree.addNode('SIG_CMPRS', 'signal')
         node.compress_on_put = True
         Device.PyDevice('TestDevice').Add(pytree, 'TESTDEVICE')
         Device.PyDevice('CYGNET4K').Add(pytree, 'CYGNET4K').on = False
         pytree.write()
     with Tree('pytreesub', self.shot, 'new') as pytreesub:
         if pytreesub.shot != self.shot:
             raise Exception(
                 "Shot number changed! tree.shot=%d, thread.shot=%d" %
                 (pytreesub.shot, self.shot))
         pytreesub_top = pytreesub.default
         node = pytreesub_top.addNode('.rog', 'structure')
         for i in range(10):
             node = node.addNode('.child', 'structure')
         node = node.addNode('rogowski', 'structure')
         node.tag = 'MAG_ROGOWSKI'
         node = node.addNode('signals', 'structure')
         node = node.addNode('rog_fg', 'signal')
         node.record = Signal(Range(1., 1000.), None,
                              Range(1., 100., .1))
         node = pytreesub_top.addNode('btor', 'signal')
         node.tag = 'BTOR'
         node.compress_on_put = True
         node.record = Signal(Range(2., 2000., 2.), None,
                              Range(1., 1000.))
         ip = pytreesub_top.addNode('ip', 'signal')
         rec = pytreesub.tdiCompile(
             "Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, 'ampere'), *, DIM_OF(\\BTOR))"
         )
         ip.record = rec
         ip.tag = 'MAG_PLASMA_CURRENT'
         ip.tag = 'MAGNETICS_PLASMA_CURRENT'
         ip.tag = 'MAG_IP'
         ip.tag = 'MAGNETICS_IP'
         ip.tag = 'IP'
         for i in range(10):
             node = pytreesub_top.addNode('child%02d' % (i, ),
                                          'structure')
             node.addDevice('dt200_%02d' % (i, ), 'dt200').on = False
         pytreesub.write()
Ejemplo n.º 2
0
 def data(self):
     shot = self.shot + 7
     with Tree('pytree', shot, 'new') as pytree:
         pytree.default.addNode('pytreesub',
                                'subtree').include_in_pulse = True
         pytree.write()
     with Tree('pytreesub', shot, 'new') as pytreesub:
         node = pytreesub.addNode('.rog', 'structure')
         for i in range(10):
             node = node.addNode('.child', 'structure')
         node = node.addNode('rogowski', 'structure')
         node.tag = 'MAG_ROGOWSKI'
         node = node.addNode('signals', 'structure')
         node = node.addNode('rog_fg', 'signal')
         node.record = Signal(Range(1., 1000.), None, Range(1., 100., .1))
         node = pytreesub.addNode('btor', 'signal')
         node.tag = 'BTOR'
         node.compress_on_put = True
         node.record = Signal(Range(2., 2000., 2.), None, Range(1., 1000.))
         ip = pytreesub.addNode('ip', 'signal')
         ip.tag = "IP"
         rec = pytreesub.tdiCompile(
             "Build_Signal(Build_With_Units(\\MAG_ROGOWSKI.SIGNALS:ROG_FG + 2100. * \\BTOR, 'ampere'), *, DIM_OF(\\BTOR))"
         )
         ip.record = rec
         pytreesub.versions_in_pulse = True
         pytreesub.write()
     pytree.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.versions, False)
     self.assertEqual(ip.getNumSegments(), 0)
     self.assertEqual(ip.getSegment(0), None)
     pytree.normal()
     ip.record = ADD(1, COMPILE("\\BTOR"))
     self.assertEqual(ip.versions, True)
     self.assertEqual(ip.record.decompile(), '1 + COMPILE("\\\\BTOR")')
     self.assertEqual(ip.record.data().tolist(),
                      (pytree.getNode("\\BTOR").data() + 1).tolist())
Ejemplo n.º 3
0
def archive_signal(node, time=None):
    """ use time if tree is archive """
    """ else use TIME node """
    print("archive_signal")
    try:
        # use _time variable if Tree is ARCHIVE
        if str(node.tree.tree) == "ARCHIVE":
            try:
                time = archive.TimeInterval(time)
            except:
                time = archive.TimeInterval([-1800.0, 0])
        else:
            time = archive.TimeInterval(node.getNode("\TIME").data())
        # load channels by datastream + index
        try:
            idx = [node.getNode("$IDX").data()]
            url = node.getParent().getNode("$URL").data()
        except:
            idx = []
            url = node.getNode("$URL").data()
        # request signal
        signal = archive.read_signal(url, time, time.t0T, 0, 0, idx)
        # 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:
        # generate dummy signal with error message as help text
        import getpass

        user = getpass.getuser()
        help = user + ": " + archive.support.error()
        try:
            from MDSplus import Signal

            signal = Signal([6, 66, 666])
            signal.setHelp(help.split("\n")[-1])
            return signal
        except:
            return help
Ejemplo n.º 4
0
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
Ejemplo n.º 5
0
 def getXYSignal(self):
     with Tree('pytree',self.shot+9,'new') as pytree:
         node = pytree.addNode('SIG', 'signal')
         pytree.write()
     pytree.normal()
     dim = numpy.array(range(100000),'float32')/10000
     pytree.SIG.record = Signal(Float32Array(numpy.sin(dim)).setUnits("ylabel"),None,Float32Array(dim).setUnits("xlabel")).setHelp('title')
     sig = node.getXYSignal(num=100)
     self.assertEqual(sig.units,"ylabel")
     self.assertEqual(sig.dim_of().units,"xlabel")
     self.assertEqual(sig.help,"title")
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
def W7X(url,time):
    from archive import base, interface
    try:
        """ use _time variable if Tree is ARCHIVE """
        try:    time = base.TimeInterval(time)
        except: time = base.TimeInterval([-1800.,0,0])
        path = base.Path(url)
        return interface.read_signal(path, time)
    except:
        """ generate dummy signal with error message as help text """
        import getpass,sys
        user = getpass.getuser()
        e = sys.exc_info()[1]
        help = user+": "+str(e)
        try:
            from MDSplus import Signal
            signal = Signal([6,66,666])
            signal.setHelp(help.split('\n')[-1])
            return signal
        except:
            return help
Ejemplo n.º 8
0
 def nodeLinkage(self):
     with Tree('pytree',self.shot+6,'new') as pytree:
         pytree.default.addNode('pytreesub','subtree').include_in_pulse=True
         for i in range(10):
             node=pytree.addNode('val%02d' % (i,),'numeric')
             node.record=i
             node=pytree.top.addNode('sig%02d' % (i,),'signal')
             node.record=Signal(i,None,i)
             node=pytree.top.addNode('child%02d' % (i,),'structure')
             node.addNode('text','text')
             node.addNode('child','structure')
         pytree.write()
     with Tree('pytreesub',self.shot+6,'new') as pytreesub:
         ip=pytreesub.addNode('ip','signal')
         ip.tag='IP'
         for i in range(3):
             node=pytreesub.top.addNode('child%02d' % (i,),'structure')
             node.addDevice('dt200_%02d' % (i,),'dt200').on=False
         pytreesub.write()
     from numpy import array,int32
     pytree.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((Array(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==Array(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())
Ejemplo n.º 9
0
 def nciInfo(self):
     with Tree('pytree',self.shot+7,'new') as pytree:
         pytree.addNode('pytreesub','subtree').include_in_pulse=True
         Device.PyDevice('TestDevice').Add(pytree,'TESTDEVICE')
         Device.PyDevice('CYGNET4K').Add(pytree,'CYGNET4K').on=False
         pytree.write()
     with Tree('pytreesub',self.shot+7,'new') as pytreesub:
         ip=pytreesub.addNode('ip','signal')
         ip.record=Signal(Int32(range(10)),None,Range(1.,10.))
         ip.tag='MAG_PLASMA_CURRENT'
         ip.tag='MAGNETICS_PLASMA_CURRENT'
         ip.tag='MAG_IP'
         ip.tag='MAGNETICS_IP'
         ip.tag='IP'
         ip.setExtendedAttribute('ATT1',100)
         ip.setExtendedAttribute('ATT2',Range(1,200))
         ip.setExtendedAttribute('ATT3','this is ip')
         ip.setExtendedAttribute('ATT3','this is plasma current')
         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')
         exattr = ip.getExtendedAttributes()
         self.assertEqual(exattr['ATT1'],100)
         self.assertEqual(str(exattr['ATT2']),'1 : 200 : *')
         self.assertEqual(exattr['ATT3'],'this is plasma current')
         for i in range(3):
             node=pytreesub.addNode('child%02d' % (i,),'structure')
             node.addDevice('dt200_%02d' % (i,),'dt200').on=False
         pytreesub.write()
     pytree.readonly()
     self.assertEqual(pytree.TESTDEVICE.__class__,Device.PyDevice('TESTDEVICE'))
     self.assertEqual(pytree.CYGNET4K.__class__,Device.PyDevice('CYGNET4K'))
     pytree.CYGNET4K.persistent = {}
     pytree.CYGNET4K.persistent['a'] = 1
     self.assertEqual(pytree.getNode('CYGNET4K').frames.persistent['a'], 1)
     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,136)
     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==Array(['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())
Ejemplo n.º 10
0
	def store(self, arg):
		from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
		from ctypes import CDLL, c_int, c_short, c_long, byref, Structure, c_char_p
		print '************ START STORE ************'
	# Get IP Address
		try:
			ipAddr = self.ip_addr.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Remote IP Address')
			return 0
	# Get Base Address   
		try:
			baseAddr = self.base_addr.data()
		except: 
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Base Address specification')
			return 0
	# Get Scan Count
		try:
			scanCount = self.scan_count.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Scan Count')
			return 0	  
		print 'Scan Count=',scanCount
	# Get LNE Mode
		lneModeDict = {'VME':0, 'CONTROL SIGNAL':1, 'INTERNAL 10MHZ':2, 'CHANNEL N':3, 'PRESET':4}
		try:
			lneMode = lneModeDict[self.lne_mode.data()]
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Mode')
			return 0
		print 'LNE Mode=',lneMode
	# Get LNE Source
		try:
			lneSource = self.lne_source.data()
		except:
			Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
			return 0	  
		print 'LNE Source=',lneSource
	# Get Channels Setup
		channelMask = 0
		for a in range(0, 32):
			if a < 10:
				if getattr(self, 'channel_0%d'%(a)).isOn():
					print 'Channel_0' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
			else:
				if getattr(self, 'channel_%d'%(a)).isOn():
					print 'Channel_' + str(a) + ' IS ON'
					channelMask = channelMask | (1 << a)
		del a
		print 'Channel Mask= ', channelMask
	# Connect to SIS3820 via MDS IP
		status = Data.execute('MdsConnect("'+ ipAddr +'")')
		if status == 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Connect to VME. See VME console for details')
			return 0
	# Wait End Acquisition
		status = Data.execute('MdsValue("SIS3820->sis3820_waitEndAcquisition(val($1), val($2))", $1, $2)', baseAddr, scanCount)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
	# Pre Store Fase
		status = Data.execute('MdsValue("SIS3820->sis3820_preStore(val($1), val($2))", $1, $2)', baseAddr, channelMask)
		if status <> 0:
			Data.execute('MdsDisconnect()')
			Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute HW Acquisition. See VME console for details')
			return 0
		
		DataArray = c_int * scanCount		
		rawChan = []
		rawChan = DataArray()		

		if lneMode == 2:
			trigTime = 0
			clockPeriod = 10e-6
                else:
			try:
				clk = self.lne_source.evaluate()
				clockPeriod = clk.delta
				trigTime = clk.begin
				#ending = clk.end
			except:
				Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
				return 0	  
		
		for chan in range(0,32):
			if channelMask & ( 1 << chan ):
			# Read Chan Data
				rawChan = Data.execute('MdsValue("SIS3820->sis3820_readChData:dsc( val($1))", $1)', chan)
			# Build the Dimension object in a single call
				dim = Dimension(Window(0, scanCount, trigTime), Range(None, None, clockPeriod))
			# Put all togenther in a "Signal" object. 			
				convExpr = Data.compile("$VALUE")
			# Use MDSplus Int32Array object
				rawMdsData = Int32Array( rawChan )
			# Every MDSplus data type can have units associated with it
				rawMdsData.setUnits("Count")
				convExpr.setUnits("Count")
			# Build the signal object
				signal = Signal(convExpr, rawMdsData, dim)		
			# Write the signal in the tree 
				if chan < 10:
					try:
						self.__getattr__('channel_0%d_data'%(chan)).putData(signal)
					except:
						Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot write Signal in the tree')
						print 'Cannot write Signal in the tree' 		
				else:
					try:
						self.__getattr__('channel_%d_data'%(chan)).putData(signal)
					except:
						Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot write Signal in the tree')
						print 'Cannot write Signal in the tree' 		

		Data.execute('MdsDisconnect()')	
		del chan
		print '************ END STORE ************'
		return 1
########################################### END STORE #######################################	  
Ejemplo n.º 11
0
    def storeftp(self, arg):

        try:
            from xml.marshal.generic import dumps, loads, load
        except:
            print "you must install PyXML to use this deprecated device.  Please switch to acq216 device type"

        debug = os.getenv("DEBUG_DEVICES")

        path = self.local_path
        tree = self.local_tree
        shot = self.tree.shot
        CPCIDataDir = os.getenv('CPCI_DATA_DIR')
        if not CPCIDataDir:
            raise 'CPCI_DATA_DIR environment variable must be defined'
        dataDir = "%s/%s/%s/%s" % (
            CPCIDataDir,
            tree,
            shot,
            path,
        )
        try:
            settingsf = open("%s/settings.xml" % (dataDir, ), "r")
        except:
            raise Exception, "Could not open Settings file %s/settings.xml" % (
                dataDir, )
        try:
            settings = load(settingsf)
        except:
            settingsf.close()
            raise Exception, "Could not parse XML settings"
        settingsf.close()
        if debug:
            print "xml is loaded\n"
        status = []
        cmds = self.status_cmds.record
        for cmd in cmds:
            cmd = cmd.strip()
            if debug:
                print "about to append answer for /%s/\n" % (cmd, )
                print "   which is /%s/\n" % (settings[cmd], )
            status.append(settings[cmd])
            if debug:
                print "%s returned %s\n" % (
                    cmd,
                    settings[cmd],
                )
        if debug:
            print "about to write board_status signal"
        self.board_status.record = Signal(cmds, None, status)

        numSampsStr = settings['getNumSamples']
        preTrig = self.getPreTrig(numSampsStr)
        postTrig = self.getPostTrig(numSampsStr)
        vins = makeArray(
            numpy.array(settings['get.vin'].split(',')).astype('float'))
        self.ranges.record = vins
        chanMask = settings['getChannelMask'].split('=')[-1]
        if self.clock_src.record.lower(
        ) == 'int' or self.clock_src.record.lower() == 'master':
            #intClkStr=settings['getInternalClock'].split()[0].split('=')[1]
            #intClock=int(intClikStr)
            intClock = float(settings['getInternalClock'].split()[1])
            delta = 1. / float(intClock)
        else:
            delta = 0

        trig_src = self.__getattr__(str(self.trig_src.record).lower())
        #
        # now store each channel
        #
        for chan in range(16):
            if debug:
                print "working on channel %d" % chan
            #chan_node = eval('self.input_%2.2d' % (chan+1,))
            chan_node = self.__getattr__('input_%2.2d' % (chan + 1, ))
            if chan_node.on:
                if debug:
                    print "it is on so ..."
                if chanMask[chan:chan + 1] == '1':
                    try:
                        start = max(
                            int(
                                self.__getattr__('input_%2.2d_startidx' %
                                                 (chan + 1, ))), -preTrig)
                    except:
                        start = -preTrig
                    try:
                        end = min(
                            int(
                                self.__getattr__('input_%2.2d_endidx' %
                                                 (chan + 1, ))), postTrig - 1)
                    except:
                        end = postTrig - 1
                    try:
                        inc = max(
                            int(
                                self.__getattr__('input_%2.2d_inc' %
                                                 (chan + 1, ))), 1)
                    except:
                        inc = 1
#
# could do the coeffs
#
                    chanFileName = "%s/%2.2d" % (
                        dataDir,
                        chan + 1,
                    )
                    buf = self.readRawData(chanFileName, preTrig, start, end,
                                           inc)
                    if delta != 0:
                        axis = Range(None, None, delta / inc)
                    else:
                        #clockExpr = 'self.%s'% str(self.clock_src.record)
                        #clock_src = eval(clockExpr.lower())
                        clock_src = self.__getattr__(
                            str(self.clock_src.record).lower())
                        axis = clock_src

                    if inc == 1:
                        dim = Dimension(Window(start, end, trig_src), axis)
                    else:
                        dim = Data.compile(
                            'Map($,$)',
                            Dimension(Window(start / inc, end / inc, trig_src),
                                      axis), Range(start, end, inc))
#                    dat = Data.compile('build_signal(build_with_units( $*(0. + $value), "V") ,build_with_units($,"Counts"),$)', coefficent, buf,dim)
                    dat = Data.compile(
                        '_v0=$, _v1=$, build_signal(build_with_units(( _v0+ (_v1-_v0)*($value - -32768)/(32767 - -32768 )), "V") ,build_with_units($,"Counts"),$)',
                        vins[chan * 2], vins[chan * 2 + 1], buf, dim)
                    exec('c=self.input_' + '%02d' % (chan + 1, ) +
                         '.record=dat')
        return 1
Ejemplo n.º 12
0
    def store(self):
        if CAENV1740.caenLib is None:
            CAENV1740.caenLib = CDLL("libCAENVME.so")
        handle = c_long(0)
        status = CAENV1740.caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0),
                                                c_int(0), byref(handle))
        if status != 0:
            print('Error initializing CAENVME')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:  # except line 508
            boardId = self.board_id.data()
            if Device.debug: print('BOARD ID: ', boardId)
            vmeAddress = self.vme_address.data()
            if Device.debug: print('VME ADDRESS: ', vmeAddress)
            try:
                clock = self.clock_source.evaluate()
                dt = clock.getDelta().data()
            except:
                print('Error evaluating clock source')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                trig = self.trig_source.data()
            except:
                print('Error evaluating trigger source')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                startIdx = self.start_idx.data()
                endIdx = self.end_idx.data()
            except:
                print('Error evaluating start or end idx')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
            try:
                pts = self.pts.data()
            except:
                print('Error evaluating Post Trigger Samples')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # Stop device
            status = CAENV1740.caenLib.CAENVME_WriteCycle(
                handle, c_int(vmeAddress + 0x8100), byref(c_int(0)),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error stopping device')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL
        #need to wait a while
            sleep(0.1)

            # Read number of buffers */
            actSegments = c_int(0)
            status = CAENV1740.caenLib.CAENVME_ReadCycle(
                handle, c_int(vmeAddress + 0x812C), byref(actSegments),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            if status != 0:
                print('Error reading number of acquired segments')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

            if Device.debug: print('Acquired segments: ', actSegments.value)
            if actSegments.value == 0:
                CAENV1740.caenLib.CAENVME_End(handle)
                return

        #Compute Segment Size
            try:
                nSegments = self.num_segments.data()
                segmentSamples = 196608 / nSegments
                print('Segment samples: ', segmentSamples)
            except:
                print('Error reading max number of segments')
                CAENV1740.caenLib.CAENVME_End(handle)
                raise mdsExceptions.TclFAILED_ESSENTIAL

        # Get Active groups
            groupMask = c_int(0)
            status = CAENV1740.caenLib.CAENVME_ReadCycle(
                handle, c_int(vmeAddress + 0x8120), byref(groupMask),
                c_int(self.cvA32_S_DATA), c_int(self.cvD32))
            nActGroups = 0
            groupMask = groupMask.value
            for group in range(0, 8):
                if (groupMask & (1 << group)) != 0:
                    nActGroups = nActGroups + 1
            if nActGroups == 0:
                if Device.debug: print('No active groups')
                CAENV1740.caenLib.CAENVME_End(handle)
                return
            segmentSize = 16 + segmentSamples * nActGroups * 8 * 12 / 8

            class V1740Data(Structure):
                _fields_ = [("eventSize", c_int), ("boardGroup", c_int),
                            ("counter", c_int), ("time", c_int),
                            ("data",
                             c_int * (segmentSamples * 64 * 12 / (8 * 4)))]

            actSegments = actSegments.value
            currStartIdx = segmentSamples - pts + startIdx
            currEndIdx = segmentSamples - pts + endIdx

            DataArray = c_short * (
                (currEndIdx - currStartIdx + 1) * actSegments)
            triggers = []
            deltas = []
            channels = []
            for chan in range(0, 64):
                channels.append([])
            for chan in range(0, 64):
                channels[chan] = DataArray()
            c = []
            for i in range(0, 64):
                c.append(0)
            for sample in range(0, actSegments):
                segment = V1740Data()
                retLen = c_int(0)
                status = CAENV1740.caenLib.CAENVME_FIFOBLTReadCycle(
                    handle, c_int(vmeAddress), byref(segment),
                    c_int(segmentSize), c_int(self.cvA32_S_DATA),
                    c_int(self.cvD64), byref(retLen))
                if status != 0:
                    print('Error reading data segment')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                actSize = 4 * (segment.eventSize & 0x0fffffff)
                if actSize != segmentSize:
                    print('Expected event size different from expected size')
                    CAENV1740.caenLib.CAENVME_End(handle)
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                counter = segment.time / 2
                triggers.append(counter * dt)
                deltas.append(dt)
                sizeInInts = (segment.eventSize & 0x0fffffff) - 4
                groupSize = sizeInInts / nActGroups
                groupOffset = 0
                for group in range(0, 8):
                    if (groupMask & (1 << group)) != 0:
                        rpnt = 0
                        sampleCount = 0
                        while rpnt < groupSize:
                            if rpnt % 9 == 0:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8][
                                        c[group * 8 +
                                          0]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8][c[group * 8 + 0]] = (
                                        segment.data[groupOffset + rpnt]
                                        & 0x00FFF000) >> 12
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8][c[group * 8 + 0]] = (
                                        (segment.data[groupOffset + rpnt]
                                         & 0xFF000000) >> 24
                                    ) | ((segment.data[groupOffset + rpnt + 1]
                                          & 0x0000000F) << 8)
                                    c[group * 8 + 0] = c[group * 8 + 0] + 1
                            if rpnt % 9 == 1:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 +
                                        1]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 +
                                        1]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 1][c[
                                        group * 8 + 1]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 1] = c[group * 8 + 1] + 1
                            if rpnt % 9 == 2:
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 2][c[
                                        group * 8 +
                                        2]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 2][c[
                                        group * 8 +
                                        2]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                            if rpnt % 9 == 3:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 2][
                                        c[group * 8 +
                                          2]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 2] = c[group * 8 + 2] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 +
                                        3]] = (segment.data[groupOffset + rpnt]
                                               & 0x00FFF000) >> 12
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 + 3]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xFF000000) >> 24) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x0000000F) << 8)
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                            if rpnt % 9 == 4:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 3][c[
                                        group * 8 +
                                        3]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 3] = c[group * 8 + 3] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 +
                                        4]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 + 4]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                            if rpnt % 9 == 5:
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 4][c[
                                        group * 8 +
                                        4]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 4] = c[group * 8 + 4] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 5][c[
                                        group * 8 +
                                        5]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                            if rpnt % 9 == 6:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 5][
                                        c[group * 8 +
                                          5]] = segment.data[groupOffset +
                                                             rpnt] & 0x00000FFF
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 5][c[
                                        group * 8 +
                                        5]] = (segment.data[groupOffset + rpnt]
                                               & 0x00FFF000) >> 12
                                    c[group * 8 + 5] = c[group * 8 + 5] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 + 6]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xFF000000) >> 24) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x0000000F) << 8)
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                            if rpnt % 9 == 7:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 +
                                        6]] = (segment.data[groupOffset + rpnt]
                                               & 0x0000FFF0) >> 4
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 6][c[
                                        group * 8 +
                                        6]] = (segment.data[groupOffset + rpnt]
                                               & 0x0FFF0000) >> 16
                                    c[group * 8 + 6] = c[group * 8 + 6] + 1
                                if sampleCount >= currStartIdx and sampleCount <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 + 7]] = (
                                            (segment.data[groupOffset + rpnt]
                                             & 0xF0000000) >> 28) | (
                                                 (segment.data[groupOffset +
                                                               rpnt + 1]
                                                  & 0x000000FF) << 4)
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                            if rpnt % 9 == 8:
                                if sampleCount + 1 >= currStartIdx and sampleCount + 1 <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 +
                                        7]] = (segment.data[groupOffset + rpnt]
                                               & 0x000FFF00) >> 8
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                                if sampleCount + 2 >= currStartIdx and sampleCount + 2 <= currEndIdx:
                                    channels[group * 8 + 7][c[
                                        group * 8 +
                                        7]] = (segment.data[groupOffset + rpnt]
                                               & 0xFFF00000) >> 20
                                    c[group * 8 + 7] = c[group * 8 + 7] + 1
                            if rpnt % 9 == 8:
                                sampleCount = sampleCount + 3
                            rpnt = rpnt + 1
                        #endwhile
                        groupOffset = groupOffset + groupSize
                    #endif
                #endfor group in range(0:8)
            #endfor samples in range(0, actSegments)

            if len(self.trig_source.getShape()) > 0:
                dim = Dimension(
                    Window(startIdx,
                           endIdx + (actSegments - 1) * (endIdx - startIdx),
                           trig[0]),
                    Range(
                        Float64Array(trig) + Float64(startIdx * dt),
                        Float64Array(trig) + Float64(endIdx * dt),
                        Float64Array(deltas)))
            else:
                dim = Dimension(
                    Window(startIdx,
                           endIdx + (actSegments - 1) * (endIdx - startIdx),
                           trig),
                    Range(
                        Float64Array(triggers) - Float64(triggers[0]) +
                        Float64(trig) + Float64(startIdx * dt),
                        Float64Array(triggers) - Float64(triggers[0]) +
                        Float64(trig) + Float64(endIdx * dt),
                        Float64Array(deltas)))

            print('DIM: ', dim)
            dim.setUnits("s")
            for group in range(0, 8):
                if groupMask & (1 << group):
                    try:
                        offset = self.__dict__['group_%d_offset' %
                                               (group + 1)].data()
                    except:
                        print('Error evaluating group offset')
                        CAENV1740.caenLib.CAENVME_End(handle)
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                    for chan in range(0, 8):
                        raw = Int16Array(channels[group * 8 + chan])
                        raw.setUnits("counts")
                        data = Data.compile("2*($VALUE - 2048)/4096.+$1",
                                            offset)
                        data.setUnits("Volts")
                        signal = Signal(data, raw, dim)
                        try:
                            self.__dict__['data%02d' %
                                          ((group + 1) *
                                           (chan + 1), )].putData(signal)
                        except:
                            print('Cannot write Signal in the tree')
                            CAENV1740.caenLib.CAENVME_End(handle)
                            raise mdsExceptions.TclFAILED_ESSENTIAL
                    #endfor
                #endif
            #endfor

            CAENV1740.caenLib.CAENVME_End(handle)
            return
        except:  # try line 258
            print('Generic Error')
            CAENV1740.caenLib.CAENVME_End(handle)
            raise mdsExceptions.TclFAILED_ESSENTIAL
Ejemplo n.º 13
0
    def store(self):
        #import required symbols from MDSSplus and ctypes packages

        #instantiate library object
        try:
            deviceLib = CDLL("libDemoAdcShr.so")
        except:
            print('Cannot link to device library')
            return 0

#get addr
        try:
            addr = self.addr.data()
#we expect to get a string in addr
        except:
            print('Missing Addr in device')
            return 0

#instantiate four short arrays with 65536 samples each. They will be passed to the acquire() external routine
        DataArray = c_short * 65536
        rawChan = []
        rawChan.append(DataArray())
        rawChan.append(DataArray())
        rawChan.append(DataArray())
        rawChan.append(DataArray())

        status = deviceLib.acquire(c_char_p(addr), byref(rawChan[0]),
                                   byref(rawChan[1]), byref(rawChan[2]),
                                   byref(rawChan[3]))
        if status == -1:
            print('Acquisition Failed')
            return 0

#at this point the raw signals are contained in rawChan1-4. We must now:
#1) reduce the dimension of the stored array using the start idx and end idx parameters for each channel, which define
#   the number of samples around the trigger which need to be stored in the pulse file (for this purpose the value of
#   post trigger samples is also required)
#2) build the appropriate timing information
#3) Put all together in a Signal object
#4) store the Signal object in the tree

#read PostTriggerSamples
        try:
            pts = self.pts.data()
        except:
            print('Missing or invalid Post Trigger Samples')
            return 0
#for each channel we read start idx and end idx
        startIdx = []
        endIdx = []
        try:
            for chan in range(0, 4):
                currStartIdx = self.__getattr__('channel_%d_start_idx' %
                                                (chan)).data()
                currEndIdx = self.__getattr__('channel_%d_end_idx' %
                                              (chan)).data()
                startIdx.append(currStartIdx)
                endIdx.append(currEndIdx)
        except:
            print('Cannot read start idx or end idx')
            return 0
#1)Build reduced arrays based on start idx and end idx for each channel
#recall that a transient recorder stores acquired data in a circular buffer and stops after acquiring
#PTS samples after the trigger. This means that the sample corresponding to the trigger is at offset PTS samples
#before the end of the acquired sample array.

#the total number of samples returned by routine acquire()
        totSamples = 65536

        #we read the time associated with the trigger. It is specified in the TRIG_SOURCE field of the device tree structure.
        #it will be required in order to associate the correct time with each acquired sample
        try:
            trigTime = self.trig_source.data()
        except:
            print('Missing or invalid Post Trigger Samples')
            return 0
#we need clock frequency as well
        try:
            clockFreq = self.clock_freq.data()
            clockPeriod = 1. / clockFreq
        except:
            print('Missing or invalid clock frequency')
            return 0

#the following steps are performed for each acquired channel
        for chan in range(0, 4):
            actStartIdx = totSamples - pts + startIdx[
                chan]  #first index of the part of interest of the sample array
            actEndIdx = totSamples - pts + endIdx[
                chan]  #last index of the part of interest of the sample array
            #make sure we do not exceed original array limits
            if actStartIdx < 0:
                actStartIdx = 0
            if actEndIdx > totSamples:
                actEndIdx = totSamples - 1
#build reshaped array
            reducedRawChan = rawChan[chan][actStartIdx:actEndIdx]

            #2)Build timing information. For this purpose we use a  MDSplus "Dimension" object which contains two fields:
            # "Window" and "Axis". Window object defines the start and end index of the associated data array and the time which is
            # associated with the sample at index 0. Several possible combination of start and end indexes are possible (the can also be
            #negative numbers). We adopt here the following convention: consider index 0 as the index of the sample corresponding
            #to the trigger, and therefore associated with the trigger time. From the way we have built the reduced raw sample array,
            #it turns out that the start idx and end idx defined
            #in the Window object are the same of the start and end indexes defined in the device configuration.
            #
            #The "Range" object describes a (possibly multispeed or busrt) clock. Its fields specify the clock period, the start and end time
            #for that clock frequency. In our case we need to describe a continuous single speed clock, so there is no need to
            #specify start and end times(it is a continuous, single speed clock).
            #
            #build the Dimension object in a single call
            dim = Dimension(Window(startIdx[chan], endIdx[chan], trigTime),
                            Range(None, None, clockPeriod))

            #3) Put all togenther in a "Signal" object. MDSplus Signal objects define three fields: samples, raw samples, dimension
            #   raw samples are contained in reducedRawChan. The computation required to convert the raw 16 bit sample into a +-10V
            #   value is: sample = 10.*rawSample/32768. We may compute a new float array containing such data and store it together
            #   with the raw sample (in the case we would like to reain also raw data. There is however a better way to do it
            #   by storing only the required information, i.e. the raw(16 bit) samples and the definition of the expression which
            #   converts raw data into actual voltage levels. Therefore, the first field of the Signal object will contain only the
            #   definition of an expression, which refers to the raw samples (the second field) of the same Signal object.
            #   The MDSplus syntax for this conversion is:  10.*$VALUE/32768.
            #   We shall use Data method compile() to build the MDSplus internal representation of this expression, and the stick it
            #   as the first field of the Signal object
            convExpr = Data.compile("10.* $VALUE/32768.")

            #use MDSplus Int16Array object to vest the short array reducedRawChan into the appropriate MDSplus type
            rawMdsData = Int16Array(reducedRawChan)

            #every MDSplus data type can have units associated with it
            rawMdsData.setUnits("Count")
            convExpr.setUnits("Volt")

            #build the signal object
            signal = Signal(convExpr, rawMdsData, dim)

            #write the signal in the tree
            try:
                self.__getattr__('channel_%d_data' % (chan)).putData(signal)
            except:
                print('Cannot write Signal in the tree')
                return 0

#endfor chan in range(0,4):

#return success (odd numbers in MDSplus)
        return 1
Ejemplo n.º 14
0
    def store(self, arg):
        """
        Store the data from the device
        Fetch and store the device status (firmware etc)
        If the device is finished
        For each channel that is on and active in the mask
        read the data
        store the data into the raw nodes
        store the expression into the data nodes
        """

        debug = os.getenv("DEBUG_DEVICES")
        try:
            error = "Must specify a board ipaddress"
            boardip = str(self.boardip.record)
            error = None
            UUT = acq200.ACQ200(transport.factory(boardip))
            try:
                ans = []
                cmds = self.status_cmds.record
                for cmd in cmds:
                    print cmd
                    a = UUT.uut.acq2sh(cmd)
                    ans.append(a)
                self.board_status.record = Signal(makeArray(ans), None,
                                                  makeArray(cmds))
            except Exception, e:
                pass

            complete = 0
            tries = 0
            while not complete and tries < 60:
                if UUT.get_state().split()[-1] == "ST_POSTPROCESS":
                    tries += 1
                    sleep(1)
                else:
                    complete = 1
            if UUT.get_state().split()[-1] != "ST_STOP":
                raise Exception, "Device not Triggered \n device returned -%s-" % UUT.get_state(
                ).split()[-1]
            if debug:
                print "about to get the vins\n"
            vins = self.getVins(UUT)
            self.ranges.record = vins
            (tot, pre, post, run) = UUT.get_numSamples()
            pre = int(pre) * -1
            post = int(post) - 1
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            error = "Clock source must be a string"
            clock_src = self.clock_src.record.getOriginalPartName().getString(
            )[1:]
            error = None
            if clock_src == 'INT_CLOCK':
                self.clock.record = Range(delta=1. /
                                          self.getInternalClock(UUT))
            else:
                self.clock.record = self.clock_src

            clock = self.clock.record
            if debug:
                print "about to ask it to mdsconnect"
            UUT.uut.acq2sh("mdsConnect %s" % str(self.hostip.record))
            if debug:
                print "about to ask it to mdsopen"
            UUT.uut.acq2sh('mdsOpen %s %d' % (
                self.boardip.tree.name,
                self.boardip.tree.shot,
            ))
            for chan in range(32):
                if debug:
                    print "working on channel %d" % chan
                chan_node = self.__getattr__('input_%2.2d' % (chan + 1, ))
                chan_raw_node = self.__getattr__('input_%2.2d_raw' %
                                                 (chan + 1, ))
                if chan_node.on:
                    if debug:
                        print "it is on so ..."
                    if mask[chan:chan + 1] == '1':
                        try:
                            start = max(
                                int(
                                    self.__getattr__('input_%2.2d_start_idx' %
                                                     (chan + 1))), pre)
                            print "start = %d" % start
                        except:
                            start = pre
                        try:
                            end = min(
                                int(
                                    self.__getattr__('input_%2.2d_end_idx' %
                                                     (chan + 1))), post)
                            print "end = %d" % end
                        except:
                            end = post
                        try:
                            inc = int(
                                self.__getattr__('input_%2.2d_inc' %
                                                 (chan + 1)))
                            print "inc = %d" % inc
                        except:
                            inc = 1
                        if debug:
                            print "build the command"
                        command = "mdsPutCh --field %s:raw --expr %%calsig --timebase %d,%d,%d %d" % (
                            chan_node.getFullPath(), int(start - pre),
                            int(end - pre), int(inc), chan + 1)
                        command = command.replace('\\', '\\\\')
                        if debug:
                            print "about to execute %s" % command
                        UUT.uut.acq2sh(command)
                        if inc > 1:
                            clk = ''
                            delta = ''
                            begin = ''
                            end = ''
                            try:
                                clk = self.clock.evaluate()
                                delta = clk.delta
                                begin = clk.begin
                                ending = clk.end
                            except:
                                pass
                            if delta:
                                axis = Range(begin, ending, delta / inc)
                                window = Window(start / inc, end / inc,
                                                trigger)
                                dim = Dimension(window, axis)
                            else:
                                dim = Data.Compile(
                                    'Map($,$)',
                                    Dimension(
                                        Window(start / inc, end / inc,
                                               trigger), clock),
                                    Range(start, end, inc))
                                raw = Data.compile('data($)', chan_raw_node)
                                chan_node.record = Signal(raw, None, dim)
                        else:
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(
                                raw, None,
                                Dimension(Window(start, end, self.trig_src),
                                          clock))

            UUT.uut.acq2sh('mdsClose %s' % (self.boardip.tree.name, ))
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
    def load_calib(self):

        from openpyxl import load_workbook

        gratingsNodeList = [
            ['gratings_grating_%02d_groove',
             'float'],  # <node>, <type>, <values>
            ['gratings_grating_%02d_blaze', 'text'],
            ['gratings_grating_%02d_model', 'text'],
            ['gratings_grating_%02d_offset', 'int'],
            ['gratings_grating_%02d_adjust', 'int'],
            ['gratings_grating_%02d_focal', 'float'],
            ['gratings_grating_%02d_inclusion', 'float'],
            ['gratings_grating_%02d_detector', 'float'],
            ['gratings_grating_%02d_focal_pos', 'float'],
            ['gratings_grating_%02d_dispersion', 'signal']
        ]  # <node>, <signal>, <x values, y values>

        try:
            print "Load Calibration File ", self.calibration_file_path.data()
            spectroCalibFile = self.calibration_file_path.data()
            wb = load_workbook(spectroCalibFile, data_only=True)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot load geometry calibration file  %s %s' %
                (spectroCalibFile, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:

            param = 'INFO'
            sheet = wb['INFO']
            cal_geometry_date = str(sheet['C1'].value)
            cal_geometry_comment = str(sheet['C2'].value)
            cal_dispersion_fit_points = int(sheet['C3'].value)

            cal_intensity_date = str(sheet['C4'].value)
            cal_intensity_comment = str(sheet['C5'].value)
            cal_intensity_degree = int(sheet['C6'].value)
            cal_intensity_type = str(sheet['C7'].value).upper()

            cal_gratings_date = str(sheet['C8'].value)
            cal_gratings_comment = str(sheet['C9'].value)

            param = 'GRATINGS'
            sheet = wb['GRATINGS']
            col = sheet['B']
            geoove_arr = [float(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[0].append(geoove_arr)

            col = sheet['C']
            blaze_arr = [str(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[1].append(blaze_arr)

            col = sheet['D']
            model_arr = [str(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[2].append(model_arr)

            col = sheet['E']
            offset_arr = [int(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[3].append(offset_arr)

            col = sheet['F']
            adjust_arr = [int(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[4].append(adjust_arr)

            col = sheet['G']
            focal_arr = [float(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[5].append(focal_arr)

            col = sheet['H']
            inclusion_arr = [float(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[6].append(inclusion_arr)

            col = sheet['I']
            detector_arr = [float(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[7].append(detector_arr)

            col = sheet['J']
            flocal_pos_arr = [float(c.value) for c in col[1:len(col):1]]
            gratingsNodeList[8].append(flocal_pos_arr)

            param = 'FWHM'
            sheet = wb['FWHM']
            col = sheet['E']
            fwhm_arr = [c.value for c in col[1:len(col):1]]

            param = 'OFFSET'
            sheet = wb['OFFSET']
            col = sheet['E']
            offset_arr = [c.value for c in col[1:len(col):1]]

            param = 'DISPERSION'
            sheet = wb['DISPERSION']
            matrix = sheet['C2':chr(ord('C') + cal_dispersion_fit_points - 1) +
                           '7']
            grating_disp_arr = [
                c.value
                for c in np.asarray(matrix).reshape(cal_dispersion_fit_points *
                                                    2 * 3)
            ]
            gratingsNodeList[9].append(
                Float32Array(
                    np.array(grating_disp_arr, 'float32').reshape(
                        [2 * 3, cal_dispersion_fit_points])))

            param = 'INTENSITY'
            sheet = wb['INTENSITY']
            matrix = sheet['E2':chr(ord('E') + cal_intensity_degree) + '433']
            intensity_coeff_arr = [
                c.value
                for c in np.asarray(matrix).reshape(self.ROI_NUM *
                                                    self.GRATING_NUM *
                                                    self.SLIT_NUM *
                                                    self.WIDTH_NUM *
                                                    (cal_intensity_degree + 1))
            ]

            wb.close()

        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot read or invalid format on sheet %s geometry calibration file %s'
                % (param, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.calibration_geometry_comment.putData(cal_geometry_comment)
        except Exception as e:
            del cal_geometry_comment
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration comment field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.calibration_geometry_date.putData(cal_geometry_date)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration date field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.calibration_intensity_date.putData(cal_intensity_date)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing intensity calibration date field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.calibration_intensity_comment.putData(cal_intensity_comment)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing intensity calibration comment field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            self.intens_cal.putData(cal_intensity_type)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing intensity calibration type field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            data = Float32Array(
                np.array(fwhm_arr, 'float32').reshape([
                    self.WIDTH_NUM, self.SLIT_NUM, self.GRATING_NUM,
                    self.ROI_NUM
                ]))
            self.calibration_geometry_fwhm.putData(data)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration fwhm field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            data = Float32Array(
                np.array(offset_arr, 'float32').reshape([
                    self.WIDTH_NUM, self.SLIT_NUM, self.GRATING_NUM,
                    self.ROI_NUM
                ]))
            self.calibration_geometry_offset.putData(data)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration offset field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            data = Float32Array(
                np.array(grating_disp_arr,
                         'float32').reshape([6, cal_dispersion_fit_points]))
            self.calibration_geometry_grating_disp.putData(data)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration dispersion field ' +
                str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            data = Float32Array(
                np.array(intensity_coeff_arr, 'float32').reshape([
                    self.WIDTH_NUM, self.SLIT_NUM, self.GRATING_NUM,
                    self.ROI_NUM, (cal_intensity_degree + 1)
                ]))
            self.calibration_intensity_coeff.putData(data)
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing geometry calibration offset field ' + str(e))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            for gr_val in gratingsNodeList:
                for gr in range(0, 3):
                    #print gr_val[0]%(gr+1), gr_val[1], gr_val[2]
                    if gr_val[1] == 'text':
                        getattr(self,
                                gr_val[0] % (gr + 1)).putData(gr_val[2][gr])
                    elif gr_val[1] == 'int':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            int(gr_val[2][gr]))
                    elif gr_val[1] == 'float':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            float(gr_val[2][gr]))
                    elif gr_val[1] == 'signal':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            Signal(gr_val[2][1 + (gr * 2)], None,
                                   gr_val[2][gr * 2]))
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing grating calibration %s field %s' %
                (gr_val[0] % (gr + 1), str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL
        return 1
Ejemplo n.º 18
0
    def store(self, arg):
        """
        Store the data from the device
        Fetch and store the device status (firmware etc)
        If the device is finished
        For each channel that is on and active in the mask
        read the data
        store the data into the raw nodes
        store the expression into the data nodes
        """

        debug = os.getenv("DEBUG_DEVICES")
        try:
            boardip = self.check('str(self.boardip.record)',
                                 "Must specify a board ipaddress")
            UUT = acq200.Acq200(transport.factory(boardip))
            try:
                ans = []
                cmds = self.status_cmds.record
                for cmd in cmds:
                    print(cmd)
                    a = UUT.uut.acq2sh(cmd)
                    ans.append(a)
                self.board_status.record = Data.compile(
                    'build_signal($,*, $)', ans, cmds)
            except Exception:
                pass

            complete = 0
            tries = 0
            if UUT.get_state().split()[-1] == "ST_RUN":
                raise Exception(
                    "Device not Triggered \n device returned -%s-" %
                    UUT.get_state().split()[-1])
            if debug:
                print("about to get the vins\n")
            vins = self.getVins(UUT)
            self.ranges.record = vins
            (tot, pre, post, run) = UUT.get_numSamples()
            pre = int(pre)
            post = int(post)
            if pre == 0 and post == 0:
                return 662480266  # DT196B$_NO_SAMPLES
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            if debug:
                print("pre = %d, post = %d" % (
                    pre,
                    post,
                ))
            clock_src = self.check(
                'str(self.clock_src.record.getOriginalPartName())[1:]',
                "Clock source must be a string")
            if clock_src == 'INT_CLOCK':
                self.clock.record = Range(delta=1. /
                                          self.getInternalClock(UUT))
            else:
                self.clock.record = self.clock_src

            clock = self.clock.record
            if debug:
                print("about to start the script")

            (fd, fname) = mkstemp('.sh')
            f = open(fname, 'w')
            f.write("#!/bin/sh\n")
            f.write("touch /tmp/starting_%d\n" % self.boardip.tree.shot)
            f.write("acqcmd --until ST_STOP\n")
            f.write("mdsConnect %s\n" % str(self.hostip.record))
            cmd = "mdsValue \"job_start('%s', %d)\"" % (self.path,
                                                        self.tree.shot)
            cmd = cmd.replace('\\', '\\\\\\\\\\\\\\')
            f.write("%s\n" % (cmd, ))
            f.write("mdsOpen %s %d\n" % (
                self.boardip.tree.name,
                self.boardip.tree.shot,
            ))
            for chan in range(96):
                chan_node = eval('self.input_%2.2d' % (chan + 1, ))
                chan_raw_node = eval('self.input_%2.2d_raw' % (chan + 1, ))
                if chan_node.on:
                    if debug:
                        print("it is on so ...")
                    if mask[chan:chan + 1] == '1':
                        try:
                            start = eval("int(self.input_%2.2d_start_idx)" %
                                         (chan + 1))
                        except:
                            start = pre
                        try:
                            end = eval("int(self.input_%2.2d_end_idx" %
                                       (chan + 1))
                        except:
                            end = post - 1
                        try:
                            inc = eval("int(self.input_%2.2d_inc)" %
                                       (chan + 1))
                        except:
                            inc = 1
                        if debug:
                            print("build the command")
                        command = "mdsPutCh --field %s:raw --expr %%calsig --timebase %d,%d,%d %d\n" % (
                            chan_node.getFullPath(), int(start), int(end),
                            int(inc), chan + 1)
                        command = command.replace('\\', '\\\\')
                        if debug:
                            print("about to execute %s" % command)
                        f.write(command)
                        if inc > 1:
                            clk = None
                            delta = None
                            begin = None
                            ending = None
                            try:
                                clk = self.clock.evaluate()
                                delta = clk.delta
                                begin = clk.begin
                                ending = clk.ending
                            except:
                                pass
                            if delta:
                                axis = Range(begin, ending, delta * inc)
                                window = Window(start / inc, end / inc,
                                                self.trig_src)
                                dim = Dimension(window, axis)
                            else:
                                dim = Data.compile(
                                    'Map($,$)',
                                    Dimension(
                                        Window(start / inc, end / inc,
                                               trig_src), clock),
                                    Range(start, end, inc))
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = eval('Signal(raw, "", dim)')
                        else:
                            raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(
                                raw, "",
                                Dimension(
                                    Window(start, end - 1, self.trig_src),
                                    clock))
            f.write('mdsClose %s\n' % (self.boardip.tree.name, ))
            f.write("touch /tmp/finished_%d\n" % self.boardip.tree.shot)
            cmd = "mdsValue \"job_finish('%s', %d)\"" % (self.path,
                                                         self.tree.shot)
            cmd = cmd.replace('\\', '\\\\\\\\\\\\\\')
            f.write("%s\n" % (cmd, ))
            f.write("rm $0\n")
            f.close()
            cmd = 'curl -s -T %s ftp://%s/%s' % (fname, boardip,
                                                 'post_shot.sh')
            pipe = os.popen(cmd)
            pipe.close()
            UUT.uut.acq2sh("chmod a+rx /home/ftp/post_shot.sh")
            UUT.uut.acq2sh("/home/ftp/post_shot.sh&")
        except Exception as e:
            print("Error storing DT196B Device\n%s" % (str(e), ))
            return 0

        return 1
Ejemplo n.º 19
0
    def store(self):
        self.restoreInfo()
        vmeAddress = 0
        # Stop device
        status = CAENDT5720.caenLib.CAENVME_WriteCycle(
            self.handle, c_int(vmeAddress + 0x8100), byref(c_int(0)),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error stopping device')
            raise mdsExceptions.TclFAILED_ESSENTIAL
    #need to wait a while
        sleep(0.1)
        acqMode = self.acq_mode.data()
        if acqMode == 'CONTINUOUS' or acqMode == 'CONTINUOUS WITH COUNTER':
            self.stop_store(0)
            return

        try:
            clock = self.clock_source.evaluate()
            dt = clock.getDelta().data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating clock source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            trig = self.trig_source.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating trigger source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            startIdx = self.start_idx.data()
            endIdx = self.end_idx.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating start or end idx')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            pts = self.pts.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating Post Trigger Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    # Read number of buffers
        actSegments = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x812C), byref(actSegments),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading number of acquired segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        if actSegments.value == 0:
            return

    #Compute Segment Size
        try:
            nSegments = self.num_segments.data()
            segmentSamples = 1048576 / nSegments
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading max number of segments')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    # Get Active channels
        chanMask = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8120), byref(chanMask),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        nActChans = 0
        chanMask = chanMask.value
        numChannels = self.num_channels.data()
        for chan in range(0, numChannels):
            if (chanMask & (1 << chan)) != 0:
                nActChans = nActChans + 1
        if nActChans == 0:
            print('No active groups')
            return

        segmentSize = 16 + 2 * segmentSamples * nActChans

        class DT5720Data(Structure):
            _fields_ = [("eventSize", c_int), ("boardGroup", c_int),
                        ("counter", c_int), ("time", c_int),
                        ("data", c_short * (segmentSize / 2))]

        actSegments = actSegments.value

        currStartIdx = segmentSamples - pts + startIdx
        currEndIdx = segmentSamples - pts + endIdx
        currChanSamples = Int32(currEndIdx - currStartIdx + 0.5).data()
        triggers = []
        deltas = []
        channels = [None] * numChannels
        for chan in range(numChannels):
            channels[chan] = ndarray(currChanSamples * actSegments)
        for segmentIdx in range(0, actSegments):
            segment = DT5720Data()
            retLen = c_int(0)
            status = CAENDT5720.caenLib.CAENVME_FIFOBLTReadCycle(
                self.handle, c_int(vmeAddress), byref(segment),
                c_int(segmentSize), c_int(self.cvA32_S_DATA),
                c_int(self.cvD64), byref(retLen))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error reading data segment')
                raise mdsExceptions.TclFAILED_ESSENTIAL

            actSize = 4 * (segment.eventSize & 0x0fffffff)
            if actSize != segmentSize:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Expected event size different from expected size')
                raise mdsExceptions.TclFAILED_ESSENTIAL
            counter = segment.time / 2
            triggers.append(counter * dt)
            deltas.append(dt)
            sizeInInts = (segment.eventSize & 0x0fffffff) - 4
            chanSizeInInts = sizeInInts / nActChans
            chanSizeInShorts = chanSizeInInts * 2
            #chanOffset = 0
            for chan in range(numChannels):
                if (chanMask & (1 << chan)) != 0:
                    channels[chan][segmentIdx * currChanSamples:segmentIdx *
                                   currChanSamples + currEndIdx -
                                   currStartIdx] = segment.data[
                                       chan * chanSizeInShorts +
                                       currStartIdx:chan * chanSizeInShorts +
                                       currEndIdx]
            #endfor  chan in range(numChannels)
        #endfor segmentIdx in range(actSegments):
        if len(self.trig_source.getShape()) > 0:
            dim = Dimension(
                Window(startIdx,
                       endIdx + (actSegments - 1) * (endIdx - startIdx),
                       trig[0]),
                Range(
                    Float64Array(trig) + Float64(startIdx * dt),
                    Float64Array(trig) + Float64(endIdx * dt),
                    Float64Array(deltas)))
        else:
            dim = Dimension(
                Window(startIdx,
                       endIdx + (actSegments - 1) * (endIdx - startIdx), trig),
                Range(
                    Float64Array(triggers) - Float64(triggers[0]) +
                    Float64(trig) + Float64(startIdx * dt),
                    Float64Array(triggers) - Float64(triggers[0]) +
                    Float64(trig) + Float64(endIdx * dt),
                    Float64Array(deltas)))
        dim.setUnits("s")
        for chan in range(numChannels):
            if (chanMask & (1 << chan)) != 0:
                try:
                    offset = getattr(self, 'channel_%d_offset' % (chan + 1))
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error reading channel offset')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                raw = Int16Array(channels[chan])
                raw.setUnits("counts")
                data = Data.compile("2*($VALUE - 2048)/4096.+$1", offset)
                data.setUnits("Volts")
                signal = Signal(data, raw, dim)
                try:
                    getattr(self,
                            'channel_%d_data' % (chan + 1)).putData(signal)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot write Signal in tree')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
        #endfor chan in range(numChannels)
        return
Ejemplo n.º 20
0
    def store(self,arg):
      from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
      from ctypes import CDLL, c_int, c_short, c_long, byref, Structure
      import time
      caenLib = CDLL("libCAENVME.so")
      handle = c_long(0)
      status = caenLib.CAENVME_Init(c_int(self.cvV2718), c_int(0), c_int(0), byref(handle))
      if status != 0:
	print 'Error initializing CAENVME' 
	return 0
      try:
	baseNid = self.node.getNid()
    	boardId = TreeNode(baseNid + self.N_BOARD_ID).data()
    	print 'BOARD ID: ', boardId
    	vmeAddress = TreeNode(baseNid + self.N_VME_ADDRESS).data()
    	print 'VME ADDRESS: ', vmeAddress
    	try:
	    clock = TreeNode(baseNid + self.N_CLOCK_SOURCE).evaluate()
	    dt = clock.getDelta().data()
    	except:
	    print 'Error evaluating clock source' 
	    caenLib.CAENVME_End(handle)
	    return 0
    	try:
	    trig = TreeNode(baseNid + self.N_TRIG_SOURCE).data()
    	except:
	    print 'Error evaluating trigger source' 
	    caenLib.CAENVME_End(handle)
	    return 0
    	try:
	    startIdx = TreeNode(baseNid + self.N_START_IDX).data()
	    endIdx = TreeNode(baseNid + self.N_END_IDX).data()
    	except:
	    print 'Error evaluating start or end idx' 
	    caenLib.CAENVME_End(handle)
	    return 0
        try:
    	    pts = TreeNode(baseNid + self.N_PTS).data()
        except:
    	    print 'Error evaluating Post Trigger Samples' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    
    
    # Stop device 
        status = caenLib.CAENVME_WriteCycle(handle, c_int(vmeAddress + 0x8100), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
    	    print 'Error stopping device' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    #need to wait a while
        time.sleep(0.1)
    
    
    # Read number of buffers */
        actSegments = c_int(0)
        status = caenLib.CAENVME_ReadCycle(handle, c_int(vmeAddress + 0x812C), byref(actSegments), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
    	    print 'Error reading number of acquired segments' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    
        print 'Acquired segments: ', actSegments.value
	if actSegments.value == 0:
    	    caenLib.CAENVME_End(handle)
    	    return 1

    
    #Compute Segment Size
        try:
            nSegments = TreeNode(baseNid + self.N_NUM_SEGMENTS).data()
            segmentSamples = 196608/nSegments
    	    print 'Segment samples: ', segmentSamples
        except: 
    	    print 'Error reading max number of segments' 
    	    caenLib.CAENVME_End(handle)
    	    return 0
    	
    
    # Get Active groups
        groupMask = c_int(0)
        status = caenLib.CAENVME_ReadCycle(handle, c_int(vmeAddress + 0x8120), byref(groupMask), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        nActGroups = 0
        groupMask = groupMask.value
        for group in range(0,8):
    	    if (groupMask & (1 << group)) != 0:
    	    	nActGroups = nActGroups + 1
            if nActGroups == 0:
    		print 'No active groups' 
    		caenLib.CAENVME_End(handle)
    		return 1
 
       	segmentSize = 16 + segmentSamples * nActGroups * 8 * 12 / 8
       	class V1740Data(Structure):
        	_fields_ = [("eventSize", c_int), ("boardGroup", c_int), ("counter", c_int), ("time", c_int), ("data", c_int * (segmentSamples * 64*12/(8*4)))]
    
        actSegments = actSegments.value
        currStartIdx = segmentSamples - pts + startIdx
        currEndIdx = segmentSamples - pts + endIdx
    
        DataArray = c_short * ((currEndIdx - currStartIdx + 1) * actSegments)
        triggers = []
        deltas = []
        channels = [] 
        for chan in range(0,64):
    	    channels.append([])
        for chan in range(0,64):
    	    channels[chan] = DataArray()
    
        c = []
        for i in range(0,64):
    	    c.append(0)
        for sample in range(0,actSegments):
    	    segment= V1740Data()
    	    retLen = c_int(0)
    	    status = caenLib.CAENVME_FIFOBLTReadCycle(handle, c_int(vmeAddress), byref(segment), c_int(segmentSize), 
    		c_int(self.cvA32_S_DATA), c_int(self.cvD64), byref(retLen))
            if status != 0:
    		print 'Error reading data segment' 
    	  	caenLib.CAENVME_End(handle)
    		return 0
      	    actSize = 4 * (segment.eventSize & 0x0fffffff)
    	    if actSize != segmentSize: 
    		print 'Expected event size different from expected size' 
    	  	caenLib.CAENVME_End(handle)
    		return 0
    	    counter = segment.time/2
    	    triggers.append(counter*dt)
    	    deltas.append(dt)
    	    sizeInInts = (segment.eventSize & 0x0fffffff) - 4;
    	    groupSize = sizeInInts/nActGroups;
    	    groupOffset = 0
            for group in range(0,8):
    	    	if (groupMask & (1 << group)) != 0:
    		    rpnt = 0
    		    sampleCount = 0;
    		    while rpnt < groupSize :
    		        if rpnt % 9 == 0:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = segment.data[groupOffset+rpnt] & 0x00000FFF
    				c[group*8+0] = c[group*8+0]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = (segment.data[groupOffset+rpnt] & 0x00FFF000) >> 12
    				c[group*8+0] = c[group*8+0]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    			    	channels[group*8][c[group*8+0]] = ((segment.data[groupOffset+rpnt] & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+0] = c[group*8+0]+1
    		        if rpnt % 9 == 1:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+1] = c[group*8+1]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+1] = c[group*8+1]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    			    	channels[group*8+1][c[group*8+1]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+1] = c[group*8+1]+1
    		        if rpnt % 9 == 2:
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    			    	channels[group*8+2][c[group*8+2]] = (segment.data[groupOffset+rpnt] &   0x000FFF00) >> 8
    				c[group*8+2] = c[group*8+2]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+2][c[group*8+2]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+2] = c[group*8+2]+1
    		        if rpnt % 9 == 3:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+2][c[group*8+2]] = segment.data[groupOffset+rpnt] &  0x00000FFF
    				c[group*8+2] = c[group*8+2]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = (segment.data[groupOffset+rpnt]  & 0x00FFF000) >> 12
    				c[group*8+3] = c[group*8+3]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = ((segment.data[groupOffset+rpnt]  & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+3] = c[group*8+3]+1
    		        if rpnt % 9 == 4:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+3][c[group*8+3]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+3] = c[group*8+3]+1
   			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+4] = c[group*8+4]+1
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+4] = c[group*8+4]+1
    		        if rpnt % 9 == 5:
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+4][c[group*8+4]] = (segment.data[groupOffset+rpnt]  & 0x000FFF00) >> 8
    				c[group*8+4] = c[group*8+4]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+5] = c[group*8+5]+1
    		        if rpnt % 9 == 6:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = segment.data[groupOffset+rpnt]  & 0x00000FFF
    				c[group*8+5] = c[group*8+5]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+5][c[group*8+5]] = (segment.data[groupOffset+rpnt] & 0x00FFF000) >> 12
    				c[group*8+5] = c[group*8+5]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = ((segment.data[groupOffset+rpnt] & 0xFF000000) >> 24) | ((segment.data[groupOffset+rpnt+1] & 0x0000000F) << 8)
    				c[group*8+6] = c[group*8+6]+1
    		        if rpnt % 9 == 7:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = (segment.data[groupOffset+rpnt] & 0x0000FFF0) >> 4
    				c[group*8+6] = c[group*8+6]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+6][c[group*8+6]] = (segment.data[groupOffset+rpnt] & 0x0FFF0000) >> 16
    				c[group*8+6] = c[group*8+6]+1
    			    if sampleCount >= currStartIdx and sampleCount <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = ((segment.data[groupOffset+rpnt] & 0xF0000000) >> 28) | ((segment.data[groupOffset+rpnt+1] & 0x000000FF) << 4)
    				c[group*8+7] = c[group*8+7]+1
    		        if rpnt % 9 == 8:
    			    if sampleCount +1 >= currStartIdx and sampleCount + 1 <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = (segment.data[groupOffset+rpnt] & 0x000FFF00) >> 8
    				c[group*8+7] = c[group*8+7]+1
    			    if sampleCount +2 >= currStartIdx and sampleCount +2 <= currEndIdx :
    		    	    	channels[group*8+7][c[group*8+7]] = (segment.data[groupOffset+rpnt] & 0xFFF00000) >> 20
    				c[group*8+7] = c[group*8+7]+1
    		        if rpnt % 9 == 8:
    		    	    sampleCount = sampleCount + 3
    		        rpnt = rpnt + 1
    		    #endwhile
    		    groupOffset = groupOffset + groupSize
    	        #endif 
            #endfor group in range(0:8)
        #endfor samples in range(0, actSegments)
    
    	
        if len(TreeNode(baseNid + self.N_TRIG_SOURCE).getShape()) > 0:
            dim = Dimension(Window(startIdx,endIdx+(actSegments - 1) * (endIdx - startIdx), trig[0]),Range(Float64Array(trig) + Float64(startIdx * dt),  Float64Array(trig) + Float64(endIdx * dt), Float64Array(deltas)))
        else:
            dim = Dimension(Window(startIdx,endIdx+(actSegments - 1) * (endIdx - startIdx), trig),Range(Float64Array(triggers) - Float64(triggers[0]) + Float64(trig) + Float64(startIdx * dt),  Float64Array(triggers) - Float64(triggers[0]) + Float64(trig) + Float64(endIdx * dt), Float64Array(deltas)))
    
        print 'DIM: ', dim
        dim.setUnits("s");
        chan0Nid = baseNid + self.N_CHANNEL_0
        data0Nid = baseNid + self.N_DATA_0
        for group in range(0,8):
    	    if groupMask & (1 << group):
        	try:
    	    	    offset = TreeNode(baseNid + self.N_CHANNEL_0 + group * self.N_CHAN_DATA + self.N_CHAN_OFFSET).data()
        	except:
    		    print 'Error evaluating group offset' 
    		    caenLib.CAENVME_End(handle)
    		    return 0
    	        for chan in range(0,8):
    		    raw = Int16Array(channels[group * 8 + chan])
    		    raw.setUnits("counts")
    		    data = Data.compile("2*($VALUE - 2048)/4096.+$1", offset);
    		    data.setUnits("Volts")
    		    signal = Signal(data, raw, dim)
    		    try:
    		    	TreeNode(baseNid + self.N_DATA_0 + group * 8 + chan).putData(signal)
        	    except:
    		    	print 'Cannot write Signal in the tree' 
    		    	caenLib.CAENVME_End(handle)
    		    	return 0
        	#endfor
    	    #endif
        #endfor
    
        caenLib.CAENVME_End(handle)
        return 1
      except:
	print 'Generic Error' 
	caenLib.CAENVME_End(handle)
	return 0