Ejemplo n.º 1
0
 def getValue(self):
     ans=Range()
     t=self.begin.get_text()
     if t == '':
         ans.begin=None
     else:
         try:
             ans.begin=Data.compile(self.begin.get_text())
         except Exception:
             msg="Invalid begin specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Begin',msg)
             raise
     t=self.ending.get_text()
     if t == '':
         ans.ending=None
     else:
         try:
             ans.ending=Data.compile(self.ending.get_text())
         except Exception:
             msg="Invalid ending specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Ending',msg)
             raise
     t=self.delta.get_text()
     if t != '':
         try:
             ans.delta=Data.compile(self.delta.get_text())
         except Exception:
             msg="Invalid delta specified.\n\n%s" % (sys.exc_info()[1],)
             MDSplusErrorMsg('Invalid Delta',msg)
             raise
     return ans
 def getValue(self):
     ans=Dispatch(dispatch_type=2)
     ans.ident=self.ident.get_text()
     try:
         ans.ident=Data.compile(ans.ident)
     except Exception:
         pass
     ans.phase=self.phase.get_text()
     try:
         ans.phase=Data.compile(ans.phase)
     except Exception:
         pass
     try:
         ans.when=Data.compile(self.sequence.get_text())
     except Exception:
         msg="Invalid sequence specified.\n\n%s" % (sys.exc_info()[1],)
         MDSplusErrorMsg('Invalid Sequence',msg)
         raise
     ans.completion=self.event.get_text()
     if ans.completion == '':
         ans.completion=None
     else:
         try:
             ans.completion=Data.compile(ans.event)
         except Exception:
             pass
     return ans
Ejemplo n.º 3
0
 def getValue(self):
     ans=Window()
     t=self.startIdx.get_text()
     if t == '':
         ans.startIdx=None
     else:
         try:
             ans.startIdx=Data.compile(self.startIdx.get_text())
         except Exception:
             msg="Invalid startIdx specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid StartIdx',msg)
             raise
     t=self.endIdx.get_text()
     if t == '':
         ans.endIdx=None
     else:
         try:
             ans.endIdx=Data.compile(self.endIdx.get_text())
         except Exception:
             msg="Invalid endIdx specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid EndIdx',msg)
             raise
     t=self.timeAt0.get_text()
     if t != '':
         try:
             ans.timeAt0=Data.compile(self.timeAt0.get_text())
         except Exception:
             msg="Invalid timeAt0 specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid TimeAt0',msg)
             raise
     return ans
Ejemplo n.º 4
0
 def getValue(self):
     ans=Method()
     ans.method=self.method.get_text()
     try:
         ans.method=Data.compile(ans.method)
     except Exception,e:
         pass
 def getValue(self):
     ans=Routine()
     ans.image=self.image.get_text()
     try:
         ans.image=Data.compile(ans.image)
     except Exception,e:
         pass
 def getValue(self):
     ans=Dispatch(dispatch_type=2)
     ans.ident=self.ident.get_text()
     try:
         ans.ident=Data.compile(ans.ident)
     except Exception,e:
         pass
Ejemplo n.º 7
0
 def getValue(self):
     ans=Range()
     t=self.begin.get_text()
     if t == '':
         ans.begin=None
     else:
         try:
             ans.begin=Data.compile(self.begin.get_text())
         except Exception,e:
             msg="Invalid begin specified.\n\n%s" % (e,)
             MDSplusErrorMsg('Invalid Begin',msg)
             raise
Ejemplo n.º 8
0
 def getValue(self):
     ans=Window()
     t=self.startIdx.get_text()
     if t == '':
         ans.startIdx=None
     else:
         try:
             ans.startIdx=Data.compile(self.startIdx.get_text())
         except Exception,e:
             msg="Invalid startIdx specified.\n\n%s" % (e,)
             MDSplusErrorMsg('Invalid StartIdx',msg)
             raise
Ejemplo n.º 9
0
 def getValue(self):
     ans=Method()
     ans.method=self.method.get_text()
     try:
         ans.method=Data.compile(ans.method)
     except Exception:
         pass
     try:
         ans.object=Data.compile(self.device.get_text())
     except Exception:
         msg="Invalid device specified.\n\n%s" % (sys.exc_info(),)
         MDSplusErrorMsg('Invalid Device',msg)
         raise
     if self.timeout.get_text() == '' or self.timeout.get_text() == '*':
         ans.timeout=None
     else:
         try:
             ans.timeout=Data.compile(self.timeout.get_text())
         except Exception:
             msg="Invalid timeout specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid Timeout',msg)
             raise
     idx=len(self.args)-1
     found=False
     while idx >= 0:
         t = self.args[idx].get_text()
         if t == '':
             if found:
                 ans.setArgumentAt(idx,None)
         else:
             try:
                 a=Data.compile(t)
             except Exception:
                 msg="Invalid argument (%d) specified.\n\n%s" % (idx+1,sys.exc_info(),)
                 MDSplusErrorMsg('Invalid Argument',msg)
                 raise
             ans.setArgumentAt(idx,a)
             found=True
         idx=idx-1
     return ans
Ejemplo n.º 10
0
 def getValue(self):
     ans=Routine()
     ans.image=self.image.get_text()
     try:
         ans.image=Data.compile(ans.image)
     except Exception:
         pass
     ans.routine=self.routine.get_text()
     try:
         ans.routine=Data.compile(ans.routine)
     except Exception:
         pass
     if self.timeout.get_text() == '' or self.timeout.get_text() == '*':
         ans.timeout=None
     else:
         try:
             ans.timeout=Data.compile(self.timeout.get_text())
         except Exception:
             msg="Invalid timeout specified.\n\n%s" % (sys.exc_info(),)
             MDSplusErrorMsg('Invalid Timeout',msg)
             raise
     idx=len(self.args)-1
     found=False
     while idx >= 0:
         t = self.args[idx].get_text()
         if t == '':
             if found:
                 ans.setArgumentAt(idx,None)
         else:
             try:
                 a=Data.compile(t)
             except Exception:
                 msg="Invalid argument specified.\n\n%s" % (sys.exc_info(),)
                 MDSplusErrorMsg('Invalid Argument',msg)
                 raise
             ans.setArgumentAt(idx,a)
             found=True
         idx=idx-1
     return ans
Ejemplo n.º 11
0
 def applyPart(self,channel,field,idx):
     value=channel[field].get_text()
     if value == '':
         value=None
     else:
         try:
             value=Data.compile(value)
         except Exception:
             MDSplusErrorMsg('Invalid value','Error compiling %s for channel %d\n\n%s\n\n%s' % (field,idx,value,sys.exc_info()))
             raise
     try:
         if channel[field+'Node'].compare(value) != 1:
             channel[field+'Node'].record=value
     except Exception:
         MDSplusErrorMsg('Error storing value','Error storing value %s for channel %d\n\n\%s' % (field,idx,sys.exc_info()))
Ejemplo n.º 12
0
class MARTE2_RFXMODEL(MC.MARTE2_COMPONENT):
    parameters = [{
        'name': 'AAGain',
        'type': 'float64'
    }, {
        'name': 'BV_GAIN',
        'type': 'float64'
    }, {
        'name': 'CCKp',
        'type': 'float64'
    }, {
        'name': 'CCTEnd',
        'type': 'float64'
    }, {
        'name': 'CCType',
        'type': 'float64'
    }, {
        'name': 'CompMagOn',
        'type': 'float64'
    }, {
        'name': 'DisruptionDetection',
        'type': 'float64'
    }, {
        'name': 'EquiFlux',
        'type': 'float64'
    }, {
        'name': 'EquilNonlinearFactorSaturation',
        'type': 'float64'
    }, {
        'name': 'FDBK_ON',
        'type': 'float64'
    }, {
        'name': 'FFWD_ON',
        'type': 'float64'
    }, {
        'name': 'FS_Bv_RT',
        'type': 'float64'
    }, {
        'name': 'FS_mmf_RT',
        'type': 'float64'
    }, {
        'name': 'GainCompRes',
        'type': 'float64'
    }, {
        'name': 'GainDecoupl',
        'type': 'float64'
    }, {
        'name': 'HorShiftFFGAIN',
        'type': 'float64'
    }, {
        'name': 'HorShiftFFON',
        'type': 'float64'
    }, {
        'name': 'HorShiftQctrlEnable',
        'type': 'float64'
    }, {
        'name': 'HorShiftRefQctrl',
        'type': 'float64'
    }, {
        'name': 'HorShiftTestSatFB',
        'type': 'float64'
    }, {
        'name': 'HorShiftTimeQctrl',
        'type': 'float64'
    }, {
        'name': 'I_to_B',
        'type': 'float64'
    }, {
        'name': 'IpCompMagOn',
        'type': 'float64'
    }, {
        'name': 'K_decoupl',
        'type': 'float64'
    }, {
        'name': 'Kd',
        'type': 'float64'
    }, {
        'name': 'Ki',
        'type': 'float64'
    }, {
        'name': 'Kp',
        'type': 'float64'
    }, {
        'name': 'LeadLagHorShiftON',
        'type': 'float64'
    }, {
        'name': 'Lp',
        'type': 'float64'
    }, {
        'name': 'Max_PVAT_Curr',
        'type': 'float64'
    }, {
        'name': 'MinIpCurr',
        'type': 'float64'
    }, {
        'name': 'PVATFilter_den',
        'type': 'float64'
    }, {
        'name': 'PVATFilter_num',
        'type': 'float64'
    }, {
        'name': 'RFPCCDeltaIpStar',
        'type': 'float64'
    }, {
        'name': 'RFPCCDeltaTBumpless',
        'type': 'float64'
    }, {
        'name': 'RFPCCDeltaTRampDown',
        'type': 'float64'
    }, {
        'name': 'RFPCCInFiltDen',
        'type': 'float64'
    }, {
        'name': 'RFPCCInFiltNum',
        'type': 'float64'
    }, {
        'name': 'RFPCCIpStar',
        'type': 'float64'
    }, {
        'name': 'RFPCCOutFiltDen',
        'type': 'float64'
    }, {
        'name': 'RFPCCOutFiltNum',
        'type': 'float64'
    }, {
        'name': 'RFPCCPOhmMax',
        'type': 'float64'
    }, {
        'name': 'RFPCCTaup',
        'type': 'float64'
    }, {
        'name': 'RFPCCTauz',
        'type': 'float64'
    }, {
        'name': 'ResCablePcat',
        'type': 'float64'
    }, {
        'name': 'Rmag',
        'type': 'float64'
    }, {
        'name': 'Rtransf',
        'type': 'float64'
    }, {
        'name': 'TOKCCTStart',
        'type': 'float64'
    }, {
        'name': 'TOKCCVLoopThreshold',
        'type': 'float64'
    }, {
        'name': 'TOKCCVMax',
        'type': 'float64'
    }, {
        'name': 'TOKCCVRogThreshold',
        'type': 'float64'
    }, {
        'name': 'TStartEquilIntegralAction',
        'type': 'float64'
    }, {
        'name': 'TokFastRampUpIpOn',
        'type': 'float64'
    }, {
        'name': 'TokIpLowQ',
        'type': 'float64'
    }, {
        'name': 'TokThresholdBpmode',
        'type': 'float64'
    }, {
        'name': 'TokTstartCheckMode',
        'type': 'float64'
    }, {
        'name': 'TokTunIpFR',
        'type': 'float64'
    }, {
        'name': 'TokTunVpcat',
        'type': 'float64'
    }, {
        'name': 'TokVpcatRampUp',
        'type': 'float64'
    }, {
        'name': 'Tstep',
        'type': 'float64'
    }, {
        'name': 'Voltage_Control',
        'type': 'float64'
    }, {
        'name': 'equilFFDerivativeVLoopDen',
        'type': 'float64'
    }, {
        'name': 'equilFFDerivativeVLoopNum',
        'type': 'float64'
    }, {
        'name': 'equilFFDerivativeVRogDen',
        'type': 'float64'
    }, {
        'name': 'equilFFDerivativeVRogNum',
        'type': 'float64'
    }, {
        'name': 'equilFFProportionalDen',
        'type': 'float64'
    }, {
        'name': 'equilFFProportionalNum',
        'type': 'float64'
    }, {
        'name': 'invAAGain',
        'type': 'float64'
    }, {
        'name': 'k_comp_res',
        'type': 'float64'
    }, {
        'name': 'tau_1',
        'type': 'float64'
    }, {
        'name': 'taupHorShiftFF',
        'type': 'float64'
    }, {
        'name': 'tauzHorShiftFF',
        'type': 'float64'
    }, {
        'name': 'time_step',
        'type': 'float64'
    }]
    inputs = [{
        'name': 'Horizontal_Shift',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Btw',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Ip',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Field_shaping_forces_OK',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'SoftTerm1',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'SoftTerm2',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Hor_Shift_Shell',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Bv',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'I_M',
        'type': 'float64',
        'dimensions': Data.compile('[4]'),
        'parameters': {}
    }, {
        'name': 'I_FS',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'q',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'V_rog',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'V_loop',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'TorFlux',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'time',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Bv_add',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'delta_ip',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'I_FS_add',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'Hor_Shift_Ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'PMAT',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'PCAT',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'TFAT',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'Btw_ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'q_ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'delta_I_FS_add',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'Ip_ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }]
    outputs = [{
        'name': 'PCAT_Ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'PMAT_Ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'TFAT_Ref',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'PVAT_Ref',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'FS_I_Ref',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'FS_FF_Ref',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'FS_FB_Ref',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }, {
        'name': 'time',
        'type': 'float64',
        'dimensions': 0,
        'parameters': {}
    }, {
        'name': 'FF',
        'type': 'float64',
        'dimensions': Data.compile('[8]'),
        'parameters': {}
    }]

    parts = []
Ejemplo n.º 13
0
 def getValue(self):
     try:
         return Data.compile(self.get_text())
     except Exception:
         MDSplusErrorMsg('Invalid Expression','Invalid expression specified.\n\n%s\n\n%s' % (self.get_text(),sys.exc_info()))
         raise
Ejemplo n.º 14
0
    def storeftp(self, arg):

        try:
            from xml.marshal.generic import 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(96):
            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.º 15
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($,*, $)', a, 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)
            post = int(post)
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
        
            clock_src=self.check('self.clock_src.record.getOriginalPartName().getString()[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 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 = 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
                        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" % (chan_node.getFullPath(), int(start), int(end), 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 = eval('Signal(raw, "", dim)' % chan_node.getPath())
                        else:
			    raw = Data.compile('data($)', chan_raw_node)
                            chan_node.record = Signal(raw, "", Dimension(Window(start, end, self.trig_src), clock))
        
            UUT.uut.acq2sh('mdsClose %s' % (self.boardip.tree.name,))
Ejemplo n.º 16
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, e:
                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)
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            if debug:
                print "pre = %d, post = %d" % (
                    pre,
                    post,
                )
            clock_src = self.check(
                'self.clock_src.record.getOriginalPartName().getString()[1:]',
                "Clock source must be a string")
            if clock_src == 'INT_CLOCK' or clock_src == 'MASTER':
                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(16):
                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
                        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 - start + 1), 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, 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&")
Ejemplo n.º 17
0
    def init(self):

        self.debugPrint('=================  BMC2835 Init ===============')

        # Module in acquisition check
        if self.restoreInfo() == self.DEV_IS_OPEN:
            try:
                self.restoreWorker()
                if self.worker.isAlive():
                    print('stop Store')
                    self.stop_store()
                self.restoreInfo()
            except:
                pass

# Channel configuration
        activeChan = 0
        for chan in range(0, 4):
            # Empy the node which will contain  the segmented data
            getattr(self, 'channel_%d_data_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_data_raw' % (chan + 1)).setCompressOnPut(False)
            getattr(self, 'channel_%d_res_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_res_raw' % (chan + 1)).setCompressOnPut(False)
            try:
                data = Data.compile(
                    "$1 * $2 + $3",
                    getattr(self, 'channel_%d_data_raw' % (chan + 1)),
                    getattr(self, 'channel_%d_gain' % (chan + 1)),
                    getattr(self, 'channel_%d_offset' % (chan + 1)))
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data' % (chan + 1)).putData(data)
            except Exception as e:
                self.debugPrint(estr(e))
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid Configuration for channel ' + str(chan + 1))
                raise DevBAD_PARAMETER
        # endfor
        """
        try:
            nSamples = self.num_samples.data()
        except:
            nSamples = -1
        """

        # Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

# trigger mode
        try:
            trigMode = self.trig_mode.data()
            self.debugPrint('BCM2835 Trigger mode: ', trigMode)
            if (trigMode == 'EXTERNAL'):
                if (acqMode == 'TRANSIENT REC.'):
                    print("External Trigger Transient recorder")
                else:
                    print("External Trigger Continuous recorder")
            else:
                if (acqMode == 'TRANSIENT REC.'):
                    print("Internal Trigger Transient recorder")
                else:
                    print("Internal Trigger Continuous recorder")
        except:
            traceback.print_exc(file=sys.stdout)
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise DevBAD_PARAMETER

# trigger source
        try:
            if (trigMode == 'EXTERNAL'):
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
                except:
                    trigSource = 0
            self.debugPrint('BCM2835 Trigger source: ', trigSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve Trigger source')
            raise DevBAD_PARAMETER

# clock mode
        try:
            clockMode = self.clock_mode.data()
            if (clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if (frequency > 10000 or frequency <= 0):
                    self.debugPrint('BCM2835 Frequency out of limits')
                    frequency = 1000.
                    self.clock_source.putData(frequency)

                clockSource = Range(None, None, Float64(1. / frequency))
                self.debugPrint('BCM2835 CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                print("External clock")
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise DevBAD_PARAMETER

# Time management
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()
            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve time or samples management')
                raise DevBAD_PARAMETER

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime = self.end_time.data()
                    self.debugPrint('BCM2835 startTime = ', startTime)
                    self.debugPrint('BCM2835 endTime   = ', endTime)
                    self.debugPrint('BCM2835 trigSource   = ', trigSource)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Read Start or End time')
                    raise DevBAD_PARAMETER

                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    startTime)
                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    endTime)

                self.debugPrint('BCM2835 startIdx = ',
                                Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                self.debugPrint('BCM2835 endIdx   = ',
                                Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))

                # self.prts.putData(Int32(int(preTrigger)))
                # self.num_samples.putData(Int32(int(postTrigger)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()

            nSamples = endIdx - startIdx + 1
            postTrigger = nSamples + startIdx
            if startIdx >= 0:
                self.debugPrint('BCM2835 Acquire pre and post trigger')
            else:
                if trigSource > startTime:
                    self.debugPrint('BCM2835 Acquire only post trigger')
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigSource))

            self.debugPrint('BCM2835 nSamples   = ', Int32(int(nSamples)))

        else:  # Continuous Acquisition
            nSamples = -1

        self.saveInfo()
        self.debugPrint("===============================================")
        return 1
Ejemplo n.º 18
0
    def init(self):

        self.debugPrint('=================  PXI 6368 Init ===============')


        ##self.restoreInfo()

#Acquisition in progress module check
        if self.restoreInfo() == self.DEV_IS_OPEN :
            try:
               self.restoreWorker()
               print( 'Check Start Store')
               if self.worker.isAlive():
                  print('stop Store')
                  self.stop_store()
               self.restoreInfo()
            except:
               pass


        aiConf = c_void_p(0)

        try:
            inputMode = self.inputModeDict[self.input_mode.data()]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Input Mode')
            raise DevBAD_PARAMETER

        dev_fd = 0;

        fileName = '/dev/pxie-6368.'+str(self.boardId);
        dev_fd = os.open(fileName, os.O_RDWR);
        #self.debugPrint('Open ai_fd: ', self.ai_fd)

        device_info = self.XSERIES_DEV_INFO(0,"",0,0,0,0,0,0,0,0,0,0,0,0,0,0)

        # get card info
        status = NI6368AI.niInterfaceLib._xseries_get_device_info(c_int(dev_fd), byref(device_info));
        if status:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading card information')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        os.close(dev_fd)

        try:
            self.serial_num.putData(device_info.serial_number)
        except:
            pass

        #self.debugPrint('OK xseries_get_device_info')

        #Stop the segment TODO is this necessary since the reset is next
        NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd))

        #reset AI segment
        status = NI6368AI.niLib.xseries_reset_ai(c_int(self.ai_fd))
        if ( status ):
            errno = NI6368AI.niInterfaceLib.getErrno();
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot reset AI segment: (%d) %s' % (errno, os.strerror( errno )) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

#Check Acquisition Configuration
        try:
            bufSize = self.buf_size.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition buffer size')
            raise DevBAD_PARAMETER

        try:
            segmentSize = self.seg_length.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition segment size')
            raise DevBAD_PARAMETER

#Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

#trigger mode
        try:
            trigMode = self.trig_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid triger mode definition')
            raise DevBAD_PARAMETER

#trigger source
        try:
            trigSource = ( self.trig_source.data() )
        except:
            if(trigMode == 'EXTERNAL'):
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source')
                raise DevBAD_PARAMETER
            else:
                trigSource = 0.
                self.trig_source.putData( Float32(trigSource) )
        self.debugPrint('PXI 6368 Trigger source: ', trigSource)

        try:
            numTrigger = len(trigSource) - 1
            """
            Trigger time must be set to 0. in multi trigger
            acquisition for correct evaluation of the number
            of samples to acquire for each trigger
            """
            trigTime = 0.
        except:
            numTrigger = 1
            trigTime = trigSource
        #self.debugPrint('Trigger number: ', numTrigger)


#clock mode
        try:
            clockMode = self.clock_mode.data()
            if(clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if( frequency > 2000000.  ):
                    self.debugPrint('Frequency out of limits')
                    frequency = 2000000.

                clockSource = Range(None,None, Float64(1./frequency))
                self.clock_source.putData(clockSource)
            else:
                #self.debugPrint('External')
                clockSource = self.clock_source.evaluate()
                self.debugPrint('PXI 6368 External CLOCK: ', clockSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid clock definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.debugPrint('PXI 6368 CLOCK: ', clockSource)

#Time management

        try:
            useTime = self.use_time.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve time or samples management')
            raise mdsExceptions.TclFAILED_ESSENTIAL


        if acqMode == 'TRANSIENT REC.':
            if useTime == 'YES':
                try:
                    startTime = float( self.start_time.data() )
                    endTime = float( self.end_time.data() )
                    self.debugPrint('PXI 6368 startTime  = ', startTime) 
                    self.debugPrint('PXI 6368 endTime    = ', endTime)
                    self.debugPrint('PXI 6368 trigTime   = ', trigTime)

                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read Start or End time')
                    raise mdsExceptions.TclFAILED_ESSENTIAL


#Originale
                startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime)
                #self.debugPrint("Originale startIdx ", startIdx
                endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), endTime) + 1
                #self.debugPrint("Originale endIdx ", endIdx)

                """
                if endTime > 0:
                    endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), endTime + trigTime)
                else:
                    endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigTime + endTime), clockSource), trigTime)


                if startTime > 0:
                    startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime + trigTime)
                else:
                    startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigTime + startTime), clockSource), trigTime)
		`"""

                self.debugPrint('PXI 6368 startIdx = ', Int32(int(startIdx)))
                self.start_idx.putData(Int32(int(startIdx)))

                self.debugPrint('PXI 6368 endIdx   = ', Int32(int(endIdx)))
                self.end_idx.putData(Int32(int(endIdx)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()

            nSamples = endIdx - startIdx

            postTrigger = nSamples + startIdx
            preTrigger = nSamples - endIdx

            self.debugPrint('PXI 6368 nSamples     = ', Int32(int(nSamples)))
            self.debugPrint('PXI 6368 seg_length   = ', self.seg_length.data())


        else: #Continuous Acquisition
            if useTime == 'YES':
                try:
                    startTime = float( self.start_time.data() )
                    self.debugPrint('PXI 6368 startTime  = ', startTime)
                    self.debugPrint('PXI 6368 trigTime = ', trigTime)

                    startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime)

                except:
                    startIdx = 0
                self.start_idx.putData(Int32(int(startIdx)))
            else:
                startIdx = self.start_idx.data()
            nSamples = -1


        if acqMode == 'TRANSIENT REC.':
            if startIdx >= 0 :
                NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(startIdx + nSamples), (numTrigger))
                #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0)
            else:
                self.debugPrint('PXI 6368 preTrigger   = ', Int32(int(preTrigger)))
                self.debugPrint('PXI 6368 postTrigger   = ', Int32(int(postTrigger)))
                if  trigTime > startTime or trigMode == 'INTERNAL' : 
                    self.debugPrint ('PXI 6368 Acquire only post trigger when triger time > start Time or trigger mode internal') 
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigTime))
                    NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(-startIdx), c_int(nSamples), (numTrigger))
                    #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0)
        else:
            NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0)


        """
        if(status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set Number of Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        """

        #XSERIES_AI_DMA_BUFFER_SIZE = 0
        status = NI6368AI.niLib.xseries_set_ai_attribute(aiConf, c_int(0) , c_int(80));
        if(status != 0):
            errno = NI6368AI.niInterfaceLib.getErrno();
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Set DMA buffer size : (%d) %s' % (errno, os.strerror( errno )) )
            raise mdsExceptions.TclFAILED_ESSENTIAL




        #disable external gate
        status = NI6368AI.niLib.xseries_set_ai_external_gate(aiConf, self.XSERIES_AI_EXTERNAL_GATE_DISABLED, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE)
        if( status != 0 ):
            errno = NI6368AI.niInterfaceLib.getErrno();
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot disable external gate!: (%d) %s' % (errno, os.strerror( errno )) )
            raise mdsExceptions.TclFAILED_ESSENTIAL


#SET trigger         
        if (trigMode == 'EXTERNAL'):
            #if(acqMode == 'TRANSIENT REC.'):
             self.debugPrint ("PXI 6368 select start trigger External (START1 signal)")
             status = NI6368AI.niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_PFI1, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE ,1)
             #test
             #status = niLib.xseries_set_ai_reference_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_PFI1, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE ,1)


             if( status != 0 ):
                 errno = NI6368AI.niInterfaceLib.getErrno();
                 Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger: (%d) %s' % (errno, os.strerror( errno )) )
                 raise mdsExceptions.TclFAILED_ESSENTIAL

        else:
            self.debugPrint ("PXI 6368 select start trigger Internal (START1 signal)")
            #status = niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_SW_PULSE, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0)
            status = NI6368AI.niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_LOW, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0)
            if( status != 0 ):
                errno = NI6368AI.niInterfaceLib.getErrno();
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set auto start trigger: (%d) %s' % (errno, os.strerror( errno )) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

#SET clock
        if(clockMode == 'INTERNAL'):
            period = int( 100000000/frequency ) #TB3 clock 100MHz 
            self.debugPrint ("PXI 6368 Internal CLOCK TB3 period ", period)

            status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3, self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE, c_int(period), c_int(2));
            if(status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno();
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set internal sample clock: (%d) %s' % (errno, os.strerror( errno )) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


        else:
            self.debugPrint("PXI 6368 Program the sample clock (START signal) to start on a rising edge")
            status = NI6368AI.niLib.xseries_set_ai_sample_clock(aiConf, self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_PFI0, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE, c_int(1))
            if( status == 0):
                #Program the convert to be the same as START.
                status = NI6368AI.niLib.xseries_set_ai_convert_clock(aiConf, self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE)
                self.debugPrint ("xseries_set_ai_convert_clock ", self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING)
            if(status == 0): 
                #Program the sample and convert clock timing specifications
                status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3, self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE, c_int(100),  c_int(2));    
                self.debugPrint ("xseries_set_ai_scan_interval_counter ", self.XSERIES_SCAN_INTERVAL_COUNTER_TB3)
            if(status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno();
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot configure external device clock: (%d) %s' % (errno, os.strerror( errno )) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


#Channel configuration
        numChannels = 16
        activeChan = 0;
        for chan in range(1, numChannels+1):
            try:
                #Empy the node which will contain  the segmented data   
                getattr(self, 'channel_%d_data_raw'%(chan)).deleteData()

                getattr(self, 'channel_%d_data_raw'%(chan)).setCompressOnPut(False)
                enabled = self.enableDict[getattr(self, 'channel_%d_state'%(chan)).data()]
                gain = self.gainDict[getattr(self, 'channel_%d_range'%(chan)).data()]
                data = Data.compile("NIanalogInputScaled( build_path($), build_path($) )", getattr(self, 'channel_%d_data_raw'%(chan)).getPath(),  getattr(self, 'channel_%d_calib_param'%(chan)).getPath() )
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data'%(chan)).putData(data)
            except:
                #self.debugPrint(sys.exc_info()[0])
                self.debugPrint(traceback.format_exc())
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Configuration for channel '+str(chan))
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if(enabled):
                #self.debugPrint(' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode)
                status = NI6368AI.niLib.xseries_add_ai_channel(aiConf, c_short(chan-1), gain, inputMode, c_byte(1))
                if(status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot add channel '+str(chan))
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' CONFIGURED')
                activeChan = chan
            #else:
                #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' DISABLED' )

        #endfor

        NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd))

        try:
            status = NI6368AI.niInterfaceLib.xseries_set_ai_conf_ptr(c_int(self.ai_fd), aiConf)
            #status = NI6368AI.niLib.xseries_load_ai_conf( c_int(self.ai_fd), aiConf)
            if(status != 0):
                errno = NI6368AI.niInterfaceLib.getErrno();
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot load ai configuration : (%d) %s' % (errno, os.strerror( errno )) )
                raise mdsExceptions.TclFAILED_ESSENTIAL
        except IOError:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Exception: cannot load ai configuration: (%d) %s' % (errno, os.strerror( errno )) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

        """
        if(acqMode == 'TRANSIENT REC.'):
            status = NI6368AI.niLib.xseries_start_ai(c_int(self.ai_fd))
            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'Cannot Start Acquisition ')
                return
        """

        self.saveInfo()

        self.debugPrint("===============================================")

        return 1
Ejemplo n.º 19
0
    def store(self, arg):
        #import required symbols from MDSSplus and ctypes packages
        from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
        from ctypes import CDLL, c_char_p, c_short, byref

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

#get name
        try:
            name = self.name.data()
#we expect to get a string in name
        except:
            print 'Missing Name 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(name), 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
        reducedRawChans = []
        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
        self.value=value

    def getValue(self):
        ans=Dispatch(dispatch_type=2)
        ans.ident=self.ident.get_text()
        try:
            ans.ident=Data.compile(ans.ident)
        except Exception,e:
            pass
        ans.phase=self.phase.get_text()
        try:
            ans.phase=Data.compile(ans.phase)
        except Exception,e:
            pass
        try:
            ans.when=Data.compile(self.sequence.get_text())
        except Exception,e:
            msg="Invalid sequence specified.\n\n%s" % (e,)
            MDSplusErrorMsg('Invalid Sequence',msg)
            raise
        ans.completion=self.event.get_text()
        if ans.completion == '':
            ans.completion=None
        else:
            try:
                ans.completion=Data.compile(ans.event)
            except Exception,e:
                pass
        return ans
        
    def setValue(self,d):
Ejemplo n.º 21
0
    def store(self):
        print('************ START STORE ************')
        # Get IP Address
        try:
            ipAddr = self.ip_addr.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid Remote IP Address')
            raise mdsExceptions.TclFAILED_ESSENTIAL
    # Get Base Address
        try:
            baseAddr = self.base_addr.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid,
                         'Invalid Base Address specification')
            raise mdsExceptions.TclFAILED_ESSENTIAL
    # Get Scan Count
        try:
            scanCount = self.scan_count.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Scan Count')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        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')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        print('LNE Mode=', lneMode)
        # Get LNE Source
        try:
            lneSource = self.lne_source.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid LNE Source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        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')
            raise mdsExceptions.TclFAILED_ESSENTIAL
    # 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')
            raise mdsExceptions.TclFAILED_ESSENTIAL

    # 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')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        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')
                raise mdsExceptions.TclFAILED_ESSENTIAL

        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
Ejemplo n.º 22
0
 ans=Routine()
 ans.image=self.image.get_text()
 try:
     ans.image=Data.compile(ans.image)
 except Exception,e:
     pass
 ans.routine=self.routine.get_text()
 try:
     ans.routine=Data.compile(ans.routine)
 except Exception,e:
     pass
 if self.timeout.get_text() == '' or self.timeout.get_text() == '*':
     ans.timeout=None
 else:
     try:
         ans.timeout=Data.compile(self.timeout.get_text())
     except Exception,e:
         msg="Invalid timeout specified.\n\n%s" % (e,)
         MDSplusErrorMsg('Invalid Timeout',msg)
         raise
 idx=len(self.args)-1
 found=False
 while idx >= 0:
     t = self.args[idx].get_text()
     if t == '':
         if found:
             ans.setArgumentAt(idx,None)
     else:
         try:
             a=Data.compile(t)
         except Exception,e:
Ejemplo n.º 23
0
 def prepareMarteInfo(self):
     self.timebase.putData(
         Data.compile('0:1000000 : (build_path("\\' + self.getFullPath() +
                      '.parameters:par_5:value"))'))
Ejemplo n.º 24
0
    def init(self):

        self.debugPrint('================= PXI 6259 Init ===============')
        print('USE PRIVATE CTX: ' + str(self.getTree().usingPrivateCtx()))

        # Module in acquisition check
        if self.restoreInfo() == self.DEV_IS_OPEN:
            try:
                self.restoreWorker()
                if self.worker.isAlive():
                    print('stop Store')
                    self.stop_store()
                self.restoreInfo()
            except:
                pass

        aiConf = c_void_p(0)
        NI6259AI.niInterfaceLib.pxi6259_create_ai_conf_ptr(byref(aiConf))
        try:
            inputMode = self.inputModeDict[self.input_mode.data()]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Input Mode')
            raise DevBAD_PARAMETER
        if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
            numChannels = 16
        else:
            numChannels = 32

# Channel configuration
        activeChan = 0
        for chan in range(0, numChannels):

            # Empy the node which will contain  the segmented data
            getattr(self, 'channel_%d_data_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_data_raw' % (chan + 1)).setCompressOnPut(False)
            getattr(self, 'channel_%d_res_raw' % (chan + 1)).deleteData()
            getattr(self,
                    'channel_%d_res_raw' % (chan + 1)).setCompressOnPut(False)
            try:
                enabled = self.enableDict[getattr(
                    self, 'channel_%d_state' % (chan + 1)).data()]
                polarity = self.polarityDict[getattr(
                    self, 'channel_%d_polarity' % (chan + 1)).data()]
                gain = self.gainDict[getattr(self, 'channel_%d_range' %
                                             (chan + 1)).data()]

                data = Data.compile(
                    "NIpxi6259analogInputScaled(build_path($), build_path($), $ )",
                    getattr(self,
                            'channel_%d_data_raw' % (chan + 1)).getPath(),
                    getattr(self,
                            'channel_%d_calib_param' % (chan + 1)).getPath(),
                    gain)
                data.setUnits("Volts")
                getattr(self, 'channel_%d_data' % (chan + 1)).putData(data)
            except Exception as e:
                self.debugPrint(estr(e))
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid Configuration for channel ' + str(chan + 1))
                raise DevBAD_PARAMETER
            if (enabled):
                if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
                    currChan = self.diffChanMap[chan]
                else:
                    currChan = chan
                # self.debugPrint 'POLARITY: ' + str(polarity) + ' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode)
                status = NI6259AI.niLib.pxi6259_add_ai_channel(
                    aiConf, c_byte(currChan), polarity, gain, inputMode,
                    c_byte(0))
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot add channel ' + str(currChan + 1))
                    raise DevBAD_PARAMETER
                #self.debugPrint('PXI 6259 CHAN '+ str(currChan+1) + ' CONFIGURED')
                activeChan = activeChan + 1
        # endfor
        """
        try:
            nSamples = self.num_samples.data()
        except:
            nSamples = -1
        """

        # Acquisition management
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve acquisition mode management')
            raise DevBAD_PARAMETER

# trigger mode
        try:
            trigMode = self.trig_mode.data()
            self.debugPrint('PXI 6259 Trigger mode: ', trigMode)
            if (trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1'
                    or trigMode == 'EXT_PFI1_R_RTSI1'):
                # self.debugPrint "AI_START_SELECT ", self.AI_START_SELECT
                # self.debugPrint "aiConf ", aiConf
                # self.debugPrint "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                # self.debugPrint "niLib ", NI6259AI.niLib
                # self.debugPrint "AI_START_POLARITY ", self.AI_START_POLARITY
                # self.debugPrint "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE

                if (acqMode == 'TRANSIENT REC.'):
                    """
                    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    self.debugPrint "status ", status
                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_SELECT, self.AI_REFERENCE_SELECT_PFI1)
                        self.debugPrint "status ", status
                    if( status == 0 ):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                        self.debugPrint "status ", status
                    if( status != 0 ):
                        self.debugPrint "status ", status
                        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                    """
                    if (trigMode == 'EXTERNAL_PFI1'
                            or trigMode == 'EXT_PFI1_R_RTSI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                        self.debugPrint('AI_START_SELECT_PFI1 %d' % (status))
                    else:
                        self.debugPrint("1 OK AI_START_SELECT_RTSI1")
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_RTSI1)
                    if (status == 0):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_POLARITY,
                            self.AI_START_POLARITY_RISING_EDGE)
                        self.debugPrint('AI_START_POLARITY_RISING_EDGE %d' %
                                        (status))
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise DevBAD_PARAMETER

                else:
                    if (trigMode == 'EXT_PFI1_R_RTSI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                    else:
                        self.debugPrint("2 OK AI_START_SELECT_RTSI1")
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_RTSI1)

                    if (status == 0):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_POLARITY,
                            self.AI_START_POLARITY_RISING_EDGE)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise DevBAD_PARAMETER

                if (trigMode == 'EXT_PFI1_R_RTSI1'):
                    status = NI6259AI.niLib.pxi6259_export_ai_signal(
                        aiConf, self.PXI6259_AI_START_TRIGGER,
                        self.PXI6259_RTSI1)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot route PFI1 signal to RTSI1')
                        raise DevBAD_PARAMETER
            else:
                # self.debugPrint "AI_START_SELECT ", self.AI_START_SELECT
                # self.debugPrint "aiConf ", aiConf
                # self.debugPrint "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                # self.debugPrint "niLib ", NI6259AI.niLib
                # self.debugPrint "AI_START_POLARITY ", self.AI_START_POLARITY
                # self.debugPrint "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE
                # self.debugPrint "acqMode ", acqMode

                if (acqMode == 'TRANSIENT REC.'):
                    #status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    # if( status == 0 ):
                    status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                        aiConf, self.AI_REFERENCE_SELECT,
                        self.AI_REFERENCE_SELECT_PULSE)
                    # if( status == 0 ):
                    #    status = NI6259AI.niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_POLARITY, self.AI_REFERENCE_POLARITY_RISING_EDGE)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise DevBAD_PARAMETER

        except:
            traceback.print_exc(file=sys.stdout)
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise DevBAD_PARAMETER

# trigger source
        try:
            if (trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1'
                    or trigMode == 'SW_RTSI1'):
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
                except:
                    trigSource = 0
            self.debugPrint('PXI 6259 Trigger source: ', trigSource)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot resolve Trigger source')
            raise DevBAD_PARAMETER

# clock mode
        try:
            clockMode = self.clock_mode.data()
            if (clockMode == 'INTERNAL'):
                frequency = self.clock_freq.data()
                if ((activeChan == 1 and frequency > 1250000) or
                    (activeChan > 1 and frequency > 1000000. / activeChan)):
                    self.debugPrint('PXI 6259 Frequency out of limits')
                    if (activeChan == 1):
                        frequency = 1250000.
                    else:
                        frequency = 1000000. / activeChan
                    self.clock_source.putData(frequency)

                divisions = int(20000000. / frequency)
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(
                    aiConf, c_int(divisions), c_int(3),
                    self.AI_SAMPLE_SELECT_SI_TC,
                    self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Set Sample Clock')
                    raise DevBAD_PARAMETER
                """
                if nSamples > 0:
                    clockSource = Range(Float64(0), Float64(nSamples * divisions/20000000.) , Float64(divisions/20000000.))
                else:
                    clockSource = Range(Float64(0), Float64(3600), Float64(divisions/20000000.))
                """
                clockSource = Range(None, None, Float64(divisions / 20000000.))
                self.debugPrint('PXI 6259 CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                status = NI6259AI.niLib.pxi6259_set_ai_sample_clk(
                    aiConf, c_int(16), c_int(3), self.AI_SAMPLE_SELECT_PFI0,
                    self.AI_SAMPLE_POLARITY_RISING_EDGE)
                if (status != 0):
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot configure device clock')
                    raise DevBAD_PARAMETER

            convClk = self.conv_clk.data()
            if (activeChan == 1 and convClk == 20):
                convClk = 16

            status = NI6259AI.niLib.pxi6259_set_ai_convert_clk(
                aiConf, c_int(convClk), c_int(3), self.AI_CONVERT_SELECT_SI2TC,
                self.AI_CONVERT_POLARITY_RISING_EDGE)
            if (status != 0):
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot Set Convert Clock')
                raise DevBAD_PARAMETER
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise DevBAD_PARAMETER

# Time management
        if acqMode == 'TRANSIENT REC.':
            try:
                useTime = self.use_time.data()

            except:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Cannot resolve time or samples management')
                raise DevBAD_PARAMETER

            if useTime == 'YES':
                try:
                    startTime = self.start_time.data()
                    endTime = self.end_time.data()

                    self.debugPrint('PXI 6259 startTime = ', startTime)
                    self.debugPrint('PXI 6259 endTime   = ', endTime)
                    self.debugPrint('PXI 6259 trigSource   = ', trigSource)

                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Cannot Read Start or End time')
                    raise DevBAD_PARAMETER

                startIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    startTime)

                endIdx = Data.execute(
                    'x_to_i($1, $2)',
                    Dimension(Window(0, None, trigSource), clockSource),
                    endTime)
                """
                if endTime > 0:
                    endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), endTime + trigSource)
                else:
                    endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + endTime), clockSource), trigSource)

                self.debugPrint 'endIdx   = ', Int32(int(endIdx))
                self.end_idx.putData(Int32(int(endIdx)))

                if startTime > 0:
                    startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigSource), clockSource), startTime + trigSource)
                else:
                    startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigSource + startTime), clockSource), trigSource)
                """
                self.debugPrint('PXI 6259 startIdx = ',
                                Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                self.debugPrint('PXI 6259 endIdx   = ',
                                Int32(int(endIdx + 0.5)))
                self.end_idx.putData(Int32(int(endIdx + 0.5)))

                # self.prts.putData(Int32(int(preTrigger)))
                # self.num_samples.putData(Int32(int(postTrigger)))

            else:
                endIdx = self.end_idx.data()
                startIdx = self.start_idx.data()
                """
                postTrigger = nSamples;
                preTrigger = 0
                try:
                    preTrigger = self.prts.data()
                except:
                    preTrigger = 0
                    nSamples =  postTrigger + preTrigger
                """

            nSamples = endIdx - startIdx + 1

            postTrigger = nSamples + startIdx
            #preTrigger  = nSamples - endIdx

            if startIdx >= 0:
                status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(
                    aiConf, c_int(startIdx + nSamples), 0, 0)
            else:
                if trigSource > startTime:
                    self.debugPrint('PXI 6259 Acquire only post trigger')
                    nSamples = postTrigger
                    startIdx = 0
                    self.start_idx.putData(Int32(int(0)))
                    self.start_time.putData(Float32(trigSource))
                    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(
                        aiConf, c_int(nSamples), 0, 0)
            """
            nSamples = endIdx - startIdx + 1
            postTrigger = nSamples + startIdx
            preTrigger = nSamples - endIdx
            """
            self.debugPrint('PXI 6259 nSamples   = ', Int32(int(nSamples)))

#           status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(postTrigger), c_int(preTrigger), 0)

        else:  # Continuous Acquisition
            nSamples = -1
            # if nSamples > 0:
            #    status = NI6259AI.niLib.pxi6259_set_ai_number_of_samples(aiConf, c_int(nSamples), 0, 0)

        if (status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot Set Number of Samples')
            raise DevBAD_PARAMETER

        status = NI6259AI.niLib.pxi6259_load_ai_conf(c_int(self.fd), aiConf)
        if (status != 0):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot load configuration')
            raise DevBAD_PARAMETER
        """
        if acqMode == 'TRANSIENT REC.':
            status = niLib.pxi6259_start_ai(c_int(self.fd))
            #status = 0

            if(status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'Cannot Start Acquisition ')
                return
        """
        self.saveInfo()
        self.debugPrint("===============================================")
        return 1
Ejemplo n.º 25
0
    def start_store(self):

        if (self.restoreInfo() != self.HANDLE_RESTORE):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'DT5724 Device not initialized')
            raise mdsExceptions.DevINV_SETUP

        vmeAddress = 0

        #Module type
        devType = c_int(0)
        status = CAENDT5724.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8140), byref(devType),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        if status != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading board info')
            raise mdsExceptions.DevCOMM_ERROR

        if (devType.value & 0x000000FF) != 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid board type. Device must be DT5724 model')
            raise mdsExceptions.DevCOMM_ERROR

        if (devType.value & 0x0000FF00) >> 8 == 0x01:
            self.chanMemory = self.MEM_512kS
        else:
            self.chanMemory = self.MEM_4MS

        try:
            clock = self.clock_source.evaluate()
            dt = clock.getDelta().data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating clock source')
            raise mdsExceptions.DevBAD_PARAMETER
        try:
            triggerSourceNid = TreePath(self.trig_source.getFullPath())
            #trigTime = self.trig_source.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating trigger source')
            raise mdsExceptions.DevBAD_PARAMETER
        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.DevBAD_PARAMETER
        try:
            pts = self.pts.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating Post Trigger Samples')
            raise mdsExceptions.DevBAD_PARAMETER

        #Compute Segment Size
        try:
            nSegments = self.num_segments.data()
            segmentSamples = self.chanMemory / nSegments
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error reading max number of segments')
            raise mdsExceptions.DevBAD_PARAMETER
        #currStartIdx = segmentSamples - pts + startIdx
        #currEndIdx = segmentSamples - pts + endIdx

        #Get Active channels
        chanMask = c_int(0)
        status = CAENDT5724.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
        acqMode = self.acq_mode.data()

        for chan in range(0, numChannels):
            if (chanMask & (1 << chan)) != 0:
                try:
                    dac_offset = getattr(self, 'channel_%d_dac_offset' %
                                         (chan + 1)).data()
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error reading channel DAC offset')
                    raise
                if acqMode == 'CONTINUOUS WITH COUNTER':
                    useCounter = True
                    data = Data.compile(
                        "2.25*($1 - 8192)/16384.+$2",
                        TreePath(
                            getattr(self, 'channel_%d_seg_raw' %
                                    (chan + 1)).getFullPath()), dac_offset)
                else:
                    useCounter = False
                    segRawPath = TreePath(
                        getattr(self, 'channel_%d_seg_raw' %
                                (chan + 1)).getFullPath())
                    data = Data.compile("(2.25*( $ - 8192)/16384. + $ )",
                                        segRawPath, Float32(dac_offset))
                try:
                    getattr(self, 'channel_%d_data' % (chan + 1)).putData(data)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error Writing data')
                    raise
        #endfor chan in range(0,numChannels):

        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False

        #self.worker.configure(self.handle, acqMode, startIdx, endIdx, pts, chanMask, nActChans, dt, trigTime, triggerSourceNid, segmentSamples, segmentSize, chanMask, self.getNid(), self, self.cv, self.readCv, useCounter, self.irq_events.data() + 1)

        self.worker.configure(self.handle, acqMode, startIdx, endIdx, pts,
                              chanMask, nActChans, dt, triggerSourceNid,
                              segmentSamples, segmentSize, chanMask,
                              self.getNid(), self, self.cv, self.readCv,
                              useCounter,
                              self.irq_events.data() + 1)

        try:
            runCommand = 4
            """
          #External cllock not yet implemented
          if clockMode == 'EXTERNAL':
          runCommand = runCommand | 0x00000040
        """
            #Module SW trigger
            data = c_int(0)
            status = CAENDT5724.caenLib.CAENVME_WriteCycle(
                self.handle, c_int(vmeAddress + 0x8100),
                byref(c_int(runCommand)), c_int(self.cvA32_S_DATA),
                c_int(self.cvD32))
            if status != 0:
                Data.execute('DevLogErr($1,$2)', self.getNid(),
                             'Error starting acquisition on DT5724 Device')
                raise mdsExceptions.DevCOMM_ERROR
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot starting acquisition on DT5724 Device SW exception')
            raise mdsExceptions.DevCOMM_ERROR

        self.saveWorker()
        self.worker.start()
        """
Ejemplo n.º 26
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.º 27
0
    def store(self,arg):
#import required symbols from MDSSplus and ctypes packages
      	from MDSplus import Tree, TreeNode, Int16Array, Float64Array, Int32, Int64, Float32, Float64, Signal, Data, Dimension, Window, Range
      	from ctypes import CDLL, c_char_p, c_short, byref

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


#get name
	try:
   	    name = self.name.data()
#we expect to get a string in name
	except:
	    print 'Missing Name 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(name), 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 
	reducedRawChans = []
	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.º 28
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.º 29
0
    def storeftp(self, arg):

        try:
            from xml.marshal.generic import 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 Exception(
                '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()
        numSampsStr = settings['getNumSamples']
        preTrig = self.getPreTrig(numSampsStr)
        postTrig = self.getPostTrig(numSampsStr)
        #        vins = makeArray(numpy.array(settings['get.vin'].split(',')).astype('float'))
        range_strs = settings['getVoltsRange'].split()[1].split('=')[1].split(
            ',')
        range_strs[0] = range_strs[0][:-1]
        range_strs[1] = range_strs[1][:-1]
        vins = makeArray(numpy.array(range_strs).astype('float32'))
        coefficent = (vins[1] - vins[0]) / (2**16 - 1)
        chanMask = settings['getChannelMask'].split('=')[-1]
        if not 'ACTIVE' in settings['get.ext_clk']:
            # intClkStr=settings['getInternalClock'].split()[0].split('=')[1]
            # intClock=int(intClikStr)
            intClock = float(settings['getInternalClock'].split()[1])
            delta = 1. / float(intClock)
        else:
            delta = 0

        #trigExpr = 'self.%s'% str(self.trig_src.record)
        #trig_src = eval(trigExpr.lower())
        trig_src = self.__getattr__(str(self.trig_src.record).lower())
        #
        # now store each channel
        #
        for chan in range(96):
            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(eval('int(self.input_%2.2d:start_idx)'%(chan+1,)), preTrig)
                        start = max(
                            int(
                                self.__getattr__('input_%2.2d_startidx' %
                                                 (chan + 1, ))), -preTrig)
                    except:
                        start = -preTrig
                    try:
                        #end = min(eval('int(self.input_%2.2d:end_idx)'%(chan+1,)), postTrig)
                        end = min(
                            int(
                                self.__getattr__('input_%2.2d_endidx' %
                                                 (chan + 1, ))), postTrig - 1)
                    except:
                        end = postTrig - 1
                    try:
                        #inc =  max(eval('int(self.input_%2.2d:inc)'%(chan+1,)), 1)
                        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)
                    #                    try:
                    #                        buf = self.readRawData(chanFileName, start, end, inc)
                    #                    except:
                    #                        print("Error Reading Channel %d"%(chan+1,)
                    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)
                    exec('c=self.input_' + '%02d' % (chan + 1, ) +
                         '.record=dat')
        return 1
Ejemplo n.º 30
0
    def storeftp(self, arg):

        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(96):
	    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.º 31
0
                MDSplusErrorMsg('Invalid Begin',msg)
                raise
        t=self.ending.get_text()
        if t == '':
            ans.ending=None
        else:
            try:
                ans.ending=Data.compile(self.ending.get_text())
            except Exception,e:
                msg="Invalid ending specified.\n\n%s" % (e,)
                MDSplusErrorMsg('Invalid Ending',msg)
                raise
        t=self.delta.get_text()
        if t != '':
            try:
                ans.delta=Data.compile(self.delta.get_text())
            except Exception,e:
                msg="Invalid delta specified.\n\n%s" % (e,)
                MDSplusErrorMsg('Invalid Delta',msg)
                raise
        return ans
        
    def setValue(self,d):
        self._value=d
        self.reset()

    def reset(self):
        if isinstance(self._value,Range):
            if self._value.begin is None:
                self.begin.set_text('')
            else:
Ejemplo n.º 32
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
        """
        print "=========== ANUDEVICES SH edited dt132.py 13/06/2012 ==========="
        stall=os.getenv("Shaun_Stall")
        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
            complete2=0
            tries2 = 0
            #SHAUN MODIFICATION SO THAT IT CAN BE RUN IN A LOOP AND WILL STALL HERE UNTIL CARD GOES TO POSTPROCESS
            if stall=="YES":
                print "stall is yes"
                while complete2==0:
                    if UUT.get_state().split()[-1] != "ST_STOP" :
                        tries2 +=1
                        sleep(1)
                        #print 'Still in run state'
                    else:
                        complete2=1
                        print 'Finished'
            #End Shaun Modification
            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]
            print mask
            error="Clock source must be a string"
            #clock_src=self.clock_src.record.getOriginalPartName().getString()[1:]
            clock_src=str(self.clock_src.record)[-3:] #edit!!
            #print "clock_src:", clock_src
            error=None
            if clock_src == 'INT_CLOCK' :
                self.clock.record = Range(delta=1./self.getInternalClock(UUT))
            else:
                self.clock.record = Range(delta=1./self.getInternalClock(UUT)) #TEST FOR 32MHZ clock!!! - getInternalCock is deceptively named - it also works for external clock and is the second value that is given when setting it
                
                #self.clock.record = Range(delta=1./self.clock_src.data()) #SHAUN EDIT!!!!!

                #SHAUN FAST DTACQ EDIT
#                if os.getenv('DTACQFAST')=='YES16' and boardip=='192.168.1.9':
#                    self.clock.record = Range(delta=1./(16000000)) #SHAUN EDIT!!!!!
#                if os.getenv('DTACQFAST')=='YES32' and boardip=='192.168.1.9':
#                    self.clock.record = Range(delta=1./(32000000)) #SHAUN EDIT!!!!!

                #print self.clock_src.data()
                #self.clock.record = self.clock_src
            clock = self.clock.record
            #print 'clock record being used is : '#SHAUN EDIT
            if debug:
                print "about to ask it to mdsconnect"
            #print "mdsConnect %s" % str(self.hostip.record)
            UUT.uut.acq2sh("mdsConnect %s" % str(self.hostip.record))
            if debug:
                print "about to ask it to mdsopen"
            #print 'mdsOpen %s %d'  % (self.boardip.tree.name, self.boardip.tree.shot,)
            UUT.uut.acq2sh('mdsOpen %s %d'  % (self.boardip.tree.name, self.boardip.tree.shot,))

            #SHAUN EDIT START
            mdsputchsent=0 #Remember if command has been sent - initialise to be 0
            listofchannels="" #Initialise list of channels to be used by bulk command
            for spot in range(32):#Build list of channels to be used
                chan_node = self.__getattr__('input_%2.2d' % (spot+1,))
                if chan_node.on:
                    listofchannels=listofchannels + str(spot+1) + ","
            if listofchannels[len(listofchannels)-1]==",": #remove the last comma
                listofchannels=listofchannels[:len(listofchannels)-1]

            #Shaun edit for DTACQ Fast Sampling
            if os.getenv('DTACQFAST')=='YES16' and boardip=='192.168.1.9':
                listofchannels='1,5,17,21'
            if os.getenv('DTACQFAST')=='YES32' and boardip=='192.168.1.9':
                listofchannels='1,17'
                
            mdsputchbulkcommand=1 #switch to use bulk mdsputch or not
            #SHAUN EDIT END
            
            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)
                        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"
                        #!!!!!!!!!!!!!!! SHAUN MODIFIED THE FOLLOWING LINE (ADDED the +1 on the third argument to fix 1 more sample in time/data - ORIGINALLY WASN"T THERE - also replaced %%calsig with %%CAL to reduce complexity of the created tree - Boyd???)
                        command = "mdsPutCh --field %s:raw --expr %%CAL --timebase %d,%d,%d %d" % (chan_node.getFullPath(), int(start-pre), int(end-pre)+1, int(inc), chan+1)
                        command = command.replace('\\','\\\\')
                        if debug:
                            print "about to execute %s" % command

                        #START Shaun EDIT TO USE MDSPUTCH TO DO LOTS OF CHANNELS (mdsputchbulkcommand decides if it is used)
                        if mdsputchbulkcommand==1:
                            if mdsputchsent==0: #Check to see if command has already been sent
                                fieldstring=str(chan_node.getFullPath()) #building the string
                                fieldstring=fieldstring[0:len(fieldstring)-2]+"%02d" #building the string
                                bulkcommand = "mdsPutCh --field %s:raw --expr %%CAL --timebase %d,%d,%d %s" % (fieldstring, int(start-pre), int(end-pre)+1, int(inc), listofchannels)
                                bulkcommand = bulkcommand.replace('\\','\\\\')
                                print bulkcommand
                                UUT.uut.acq2sh(bulkcommand) #send command
                                mdsputchsent=1 #Remember the command has been sent                        
                        else:
                            UUT.uut.acq2sh(command) #ORIGINAL COMMAND
                        #END SHAUN EDIT
                        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.º 33
0
def caesiumSwitch(sigs, dt):
    from MDSplus import Data
    import numpy as np

    rf1 = sigs[0]
    rf2 = sigs[1]
    rf3 = sigs[2]
    rf4 = sigs[3]

    #Compute RFs references resaple at 1 Hz
    rf1_r = Data.compile("resample($1,,,1)", rf1)
    rf2_r = Data.compile("resample($1,,,1)", rf2)
    rf3_r = Data.compile("resample($1,,,1)", rf3)
    rf4_r = Data.compile("resample($1,,,1)", rf4)
    #Sum RFs references resapled at 1 Hz
    rf_sum = Data.compile("make_signal($1+$2+$3+$4,,$5)", rf1_r, rf2_r, rf3_r,
                          rf4_r, rf4_r.dim_of())

    tIn = Data.dim_of(rf_sum)
    yIn = Data.data(rf_sum)
    #yIn is 1 where one RFs references is greater than 50.
    #The offet of 50 is used in case RF references are not set exactly to 0
    yIn = np.asarray([int(1) if v > 50 else int(0) for v in yIn])

    #Compute the caesium enable signal with pre and post margin
    def checkEdge(val):
        # 0:y 1:y+1 2:y+2 3:t
        if val[0] == 0 and val[1] > 0:
            return (val[3] - dt, 0), (val[3] - dt, 1)
        if val[1] > 0 and val[2] == 0:
            return (val[3] + dt, 1), (val[3] + dt, 0)

    csSwitch = [(yp, y, yn, t)
                for yp, y, yn, t in zip(yIn, yIn[1:], yIn[2:], tIn)]
    csSwitch = filter(lambda v: v is not None, map(checkEdge, csSwitch))

    #Set caesium signal boundaries
    tMin = tIn[0]
    tMax = tIn[-1]
    if csSwitch[0][0][0] < tMin:
        csSwitch[0] = ((tMin, 0), (tMin, 1))
    else:
        csSwitch.insert(0, ((tMin, 0), (tMin, 0)))

    if csSwitch[-1][0][0] < tMax:
        csSwitch.append(((tMax, 0), (tMax, 0)))
    else:
        csSwitch[-1] = ((tMax, 1), (tMax, 0))

    #Remove point when margin is overlapped
    csSw = []
    skipNext = False
    for v, v1 in zip(csSwitch, csSwitch[1:]):
        if skipNext:
            skipNext = False
            continue
        if v[0][0] > v1[0][0]:
            skipNext = True
            continue
        else:
            csSw.append(v)
    csSw.append(v1)

    #Reshape List as an array even idx is time, odd idx is value
    csSwitch = np.reshape(csSw, len(np.asarray(csSw)) * 4)

    outSig = Data.compile("build_signal($1,,$2)", csSwitch[1::2],
                          csSwitch[0::2])

    return outSig
Ejemplo n.º 34
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
Ejemplo n.º 35
0
    def storeftp(self, arg):

        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()
        numSampsStr = settings['getNumSamples']
	preTrig = self.getPreTrig(numSampsStr)
        postTrig = self.getPostTrig(numSampsStr)
#        vins = makeArray(numpy.array(settings['get.vin'].split(',')).astype('float'))
        range_strs = settings['getVoltsRange'].split()[1].split('=')[1].split(',')
	range_strs[0] = range_strs[0][:-1]
	range_strs[1] = range_strs[1][:-1]
        vins = makeArray(numpy.array(range_strs).astype('float32'))
        coefficent = (vins[1]-vins[0])/(2**16-1)
        chanMask = settings['getChannelMask'].split('=')[-1]
	if not 'ACTIVE' in settings['get.ext_clk'] :
	    #intClkStr=settings['getInternalClock'].split()[0].split('=')[1]
            #intClock=int(intClikStr)
	    intClock = float(settings['getInternalClock'].split()[1])
            delta=1./float(intClock)
	else:
	    delta = 0
        
        #trigExpr = 'self.%s'% str(self.trig_src.record)
        #trig_src = eval(trigExpr.lower())
        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(eval('int(self.input_%2.2d:start_idx)'%(chan+1,)), preTrig)
                        start = max(int(self.__getattr__('input_%2.2d_startidx'%(chan+1,))),-preTrig)
                    except:
                        start = -preTrig
                    try:
                        #end = min(eval('int(self.input_%2.2d:end_idx)'%(chan+1,)), postTrig)
			end = min(int(self.__getattr__('input_%2.2d_endidx'%(chan+1,))),postTrig-1)
                    except:
                        end = postTrig-1
                    try:
                        #inc =  max(eval('int(self.input_%2.2d:inc)'%(chan+1,)), 1)
                        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)
#                    try:
#                        buf = self.readRawData(chanFileName, start, end, inc)
#                    except:
#			print "Error Reading Channel %d"%(chan+1,)
		    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) 
                    exec('c=self.input_'+'%02d'%(chan+1,)+'.record=dat')
	return 1
Ejemplo n.º 36
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, e:
                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)
            mask = UUT.uut.acqcmd('getChannelMask').split('=')[-1]
            if debug:
                print "pre = %d, post = %d" % (pre, post, )
            clock_src=self.check('self.clock_src.record.getOriginalPartName().getString()[1:]', "Clock source must be a string") 
            if clock_src == 'INT_CLOCK' or clock_src == 'MASTER' :
                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(16) :
                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
                        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-start+1), 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, 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&")
Ejemplo n.º 37
0
                MDSplusErrorMsg('Invalid StartIdx',msg)
                raise
        t=self.endIdx.get_text()
        if t == '':
            ans.endIdx=None
        else:
            try:
                ans.endIdx=Data.compile(self.endIdx.get_text())
            except Exception,e:
                msg="Invalid endIdx specified.\n\n%s" % (e,)
                MDSplusErrorMsg('Invalid EndIdx',msg)
                raise
        t=self.timeAt0.get_text()
        if t != '':
            try:
                ans.timeAt0=Data.compile(self.timeAt0.get_text())
            except Exception,e:
                msg="Invalid timeAt0 specified.\n\n%s" % (e,)
                MDSplusErrorMsg('Invalid TimeAt0',msg)
                raise
        return ans
        
    def setValue(self,d):
        self._value=d
        self.reset()

    def reset(self):
        if isinstance(self._value,Window):
            if self._value.startIdx is None:
                self.startIdx.set_text('')
            else:
Ejemplo n.º 38
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.º 39
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:
                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 = str(self.clock_src.record.getOriginalPartName())[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,
                                                self.trig_src)
                                dim = Dimension(window, axis)
                            else:
                                dim = Data.Compile(
                                    'Map($,$)',
                                    Dimension(
                                        Window(start / inc, end / inc,
                                               self.trig_src), 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, ))
        except Exception as e:
            if error is not None:
                e = error
            print("Error storing DT132 Device\n%s" % (str(e), ))
            return 0

        return 1
Ejemplo n.º 40
0
    def init(self):
      if self.restoreInfo() == 0:
          raise mdsExceptions.TclFAILED_ESSENTIAL

      self.saveInfo()

      try:
        self.frames.setCompressOnPut(False)
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot disable automatic compresson on put for frames node')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      try:
        self.frames_metad.setCompressOnPut(False)
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot disable automatic compresson on put for frames_metad node')
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Object Parameters

      try:
        o_refl_temp = c_double(self.object_refl_temp.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object refletive temperature')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_atm_temp = c_double(self.object_atm_temp.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object atmosfere temperature')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_distance = c_double(self.object_distance.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object distance')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_emissivity = c_double(self.object_emissivity.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object emissivity')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_atm_hum = c_double(self.object_atm_hum.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object atmosfere humidity')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_optic_temp = c_double(self.object_optic_temp.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object optic temperature')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_optic_trans = c_double(self.object_optic_trans.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object optic transmission')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      try:
        o_atm_trans = c_double(self.object_atm_trans.data())
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid value for object atmosfere trasmission')
        raise mdsExceptions.TclFAILED_ESSENTIAL


      status = FLIRSC65X.flirLib.setObjectParameters(self.handle, o_refl_temp, o_atm_temp, o_distance, o_emissivity, o_atm_hum , o_optic_temp, o_optic_trans, o_atm_trans )
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Object Parameters : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Rate
      try:
         frameRate = self.timing_frame_rate.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid frame rate value')
        raise mdsExceptions.TclFAILED_ESSENTIAL
      status = FLIRSC65X.flirLib.setFrameRateNew(self.handle, c_double(frameRate))
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Frame Rate : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Area
      x=c_int(0)
      y=c_int(0)
      width=c_int(0)
      height=c_int(0)
      status = FLIRSC65X.flirLib.getReadoutArea(self.handle, byref(x), byref(y), byref(width), byref(height))
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Get Readout Area : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

      #write data in mdsplus
      self.frame_x.putData(x.value)
      self.frame_y.putData(y.value)
      self.frame_width.putData(width.value)
      self.frame_height.putData(height.value)

###Focal Length
      try:
         focalLength = self.cam_setup_focal_length.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid Focal Length value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      if focalLength == '25':
        focalLengthInt=0
      elif focalLength == '41':
        focalLengthInt=3         #offset to select the correct calibration curve using the Measurement Range

###Measurement Range
      try:
         measureRange = self.cam_setup_meas_range.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid measurement range value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      if measureRange == '-40...150':
        measRangeInt=0
      elif measureRange == '100...650':
        measRangeInt=1
      elif measureRange == '300...2000':
        measRangeInt=2

      status = FLIRSC65X.flirLib.setMeasurementRange(self.handle, c_int(measRangeInt+focalLengthInt))
      if status < 0:
        try:
          FLIRSC65X.flirLib.getLastError(self.handle, self.error)
          Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Measurement Range : ' + self.error.raw)
          raise mdsExceptions.TclFAILED_ESSENTIAL
        except:
          traceback.print_exc()

###Image Temperature
      try:
        frameTempUnit = self.frame_temp_unit.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid image temperature unit (Radiometric, 10mk, 100mk) value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      if frameTempUnit == 'Radiometric':
        frameTempUnitCode=c_int(0)
      elif frameTempUnit == 'LinearTemperature10mK':
        frameTempUnitCode=c_int(1)
      elif frameTempUnit == 'LinearTemperature100mK':
        frameTempUnitCode=c_int(2)

      status = FLIRSC65X.flirLib.setIrFormat(self.handle, frameTempUnitCode)
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Image Temperature unit : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Frame Trigger mode
      try:
        burstDuration = self.timing_burst_dur.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid acquisition duration value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      try:
        triggerMode = self.timing_trig_mode.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid trigger mode value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      try:
        trigSource = self.timing_trig_source.data()
      except:
        if triggerMode == 'EXTERNAL':
           Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid trigger source value')
           raise mdsExceptions.TclFAILED_ESSENTIAL
        else:
           trigSource = array([0.])

      print("OK " + triggerMode )
      if triggerMode == 'EXTERNAL':   #0=internal  1=external trigger
        trigModeCode=c_int(1)
      else:
        trigSource = array([0.])
        trigModeCode=c_int(0)

      numTrigger = trigSource.size
      print("OK - NUM TRIGGER ", numTrigger)
      print("OK - Trigger Source ", trigSource)


      timeBase = Data.compile(" $ : $ + $ :(zero( size( $ ), 0.) + 1.) * 1./$", trigSource, trigSource, burstDuration, trigSource, frameRate)

      print("Data = " + Data.decompile(timeBase))

      self.timing_time_base.putData(timeBase)
      status = FLIRSC65X.flirLib.setTriggerMode(self.handle, trigModeCode, c_double(burstDuration), numTrigger)

      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Internal/External Trigger : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Calibration
      try:
        calibAuto = self.cam_setup_calib_auto.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid auto calibration setup')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      calibModeCode = c_int(1)
      if calibAuto == 'NO':
        try:
           calibTime = self.cam_setup_calib_time.data()
           calibModeCode = c_int(0)
        except:
           Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid calibration duration value')
           raise mdsExceptions.TclFAILED_ESSENTIAL
        if numTrigger > 1 and (burstDuration + calibTime) > (trigSource[1] - trigSource[0]) :
           Data.execute('DevLogErr($1,$2)', self.nid, 'Calibration executed during acquisition')
           raise mdsExceptions.TclFAILED_ESSENTIAL

      status = FLIRSC65X.flirLib.setCalibMode(self.handle, calibModeCode)
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Set Internal/External Trigger : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

###Streaming
      try:
        streamingMode = self.streaming_mode.data()
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming mode setup')
        raise mdsExceptions.TclFAILED_ESSENTIAL


      if streamingMode == 'Stream and Store':
          streamingEnabled = c_int(1)
          storeEnabled = c_int(1)
      elif streamingMode == 'Only Stream':
          streamingEnabled = c_int(1)
          storeEnabled = c_int(0)
      else: #streamingMode == 'Only Store':
          streamingEnabled = c_int(0)
          storeEnabled = c_int(1)


      if streamingEnabled :
          try:
             if self.streaming_autoscale.data() == 'YES' :
                  autoAdjustLimit = c_int(1)
             else:
                  autoAdjustLimit = c_int(0)
          except:
             Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming autoscale parameter value')
             raise mdsExceptions.TclFAILED_ESSENTIAL

          try:
             lowLim = c_int(self.streaming_lolim.data())
          except:
             Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming low temperature limit parameter value')
             raise mdsExceptions.TclFAILED_ESSENTIAL

          try:
             highLim = c_int(self.streaming_hilim.data())
          except:
             Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming high temperature limit parameter value')
             raise mdsExceptions.TclFAILED_ESSENTIAL

          try:
             streamingPort = c_int(self.streaming_port.data())
          except:
             Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming port parameter value')
             raise mdsExceptions.TclFAILED_ESSENTIAL

          try:
             streamingServer = self.streaming_server.data()
          except:
             Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid streaming server parameter value')
             raise mdsExceptions.TclFAILED_ESSENTIAL

#fede 20161012
#      else:
#          autoAdjustLimit = c_int(0)
#          streamingPort = c_int(8888)
#          lowLim = c_int(0)
#          highLim = c_int(36)
#          streamingServer = "localhost"

          print("lowLim ", lowLim)
          print("highLim ", highLim)
          print("frameTempUnitCode ", frameTempUnitCode)
          print("streamingPort ", streamingPort)
          print("streamingServer ", streamingServer)
          deviceName = str(self).rsplit(":",1)
          deviceName = deviceName[1]
          print("Device Name ", deviceName)     
      
#fede: recover device name and pass it to set streaming to overlay text on frame!!!

          status = FLIRSC65X.flirLib.setStreamingMode(self.handle, frameTempUnitCode, streamingEnabled,  autoAdjustLimit, c_char_p(streamingServer), streamingPort,  lowLim,  highLim, c_char_p(deviceName));
          if status < 0:
            FLIRSC65X.flirLib.getLastError(self.handle, self.error)
            Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute streaming setup mode : ' + self.error.raw)
            raise mdsExceptions.TclFAILED_ESSENTIAL


###Acquisition


      try:
        acqSkipFrameNumber = c_int( self.timing_skip_frame.data() )
      except:
        Data.execute('DevLogErr($1,$2)', self.nid, 'Invalid acquisition decimation value')
        raise mdsExceptions.TclFAILED_ESSENTIAL

      status = FLIRSC65X.flirLib.setAcquisitionMode(self.handle, storeEnabled , acqSkipFrameNumber)
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute acquisition setup mode : ' + self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

      try:
       treePtr = c_void_p(0)
       status = FLIRSC65X.mdsLib.camOpenTree(c_char_p(self.getTree().name), c_int(self.getTree().shot), byref(treePtr))
       if status == -1:
         Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot open tree')
         raise mdsExceptions.TclFAILED_ESSENTIAL
      except:
       traceback.print_exc()

      framesNid = self.frames.nid
      timebaseNid = self.timing_time_base.nid
      framesMetadNid = self.frames_metad.nid
      frame0TimeNid = self.frame0_time.nid

      status = FLIRSC65X.flirLib.setTreeInfo( self.handle,  treePtr,  framesNid,  timebaseNid,  framesMetadNid, frame0TimeNid)
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot execute set tree info : '+self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL


###Auto Calibration
      status = FLIRSC65X.flirLib.executeAutoCalib(self.handle)
      if status < 0:
        FLIRSC65X.flirLib.getLastError(self.handle, self.error)
        Data.execute('DevLogErr($1,$2)', self.nid, 'Cannot Execute Auto Calibration : '+self.error.raw)
        raise mdsExceptions.TclFAILED_ESSENTIAL

      print('Init action completed.')
      return
Ejemplo n.º 41
0
class MARTE2_RESAMPLER(MC.MARTE2_COMPONENT):
    inputs = []
    for i in range(16):
        inputs.append({
            'name': 'In' + str(i + 1),
            'type': 'float64',
            'dimensions': Data.compile('[1000]'),
            'parameters': []
        })
    outputs = []
    for i in range(16):
        outputs.append({
            'name': 'Out' + str(i + 1),
            'type': 'float64',
            'dimensions': -1,
            'parameters': []
        })
    parameters = [{
        'name': 'SamplingPeriod',
        'type': 'float64',
        'value': 1
    }, {
        'name': 'ResamplingFactor',
        'type': 'int32',
        'value': 10
    }, {
        'name': 'UseLowPassFilter',
        'type': 'int8',
        'value': 0
    }]
    parts = []

    def prepareMarteInfo(self):
        # SamplingPeriod is derived fro timebase
        samplingPeriod = self.timebase.evaluate().getDelta().data()
        currDim = self.inputs_in1_dimensions.data()
        samplingPeriod = (1. * samplingPeriod) / currDim[0]
        self.parameters_par_1_value.putData(samplingPeriod)
        # All outputs must have the same type of the corresponding input
        # and the dimensior reduced by sampling factor
        resamplingFactor = self.parameters_par_2_value.data()
        # propagate first dimension to all active inputs
        for chan in range(15):
            try:
                # Expected fail if no data samples
                getattr(self, 'inputs_in%d_value' % (chan + 2)).getData()
                getattr(self,
                        'inputs_in%d_dimensions' % (chan + 1)).putData(currDim)
            except:
                pass
# propagate updated dimension (keeping into account resamplinFactor)
        for chan in range(16):
            try:
                getattr(self, 'outputs_out%d_type' % (chan + 1)).putData(
                    getattr(self, 'inputs_in%d_type' % (chan + 1)).data())
                getattr(self,
                        'outputs_out%d_dimensions' % (chan + 1)).putData(-1)
                # Expected fail if no data samples
                getattr(self, 'inputs_in%d_value' % (chan + 1)).getData()
                currDim = getattr(
                    self, 'inputs_in%d_dimensions' %
                    (chan + 1)).data()  # The following should not fail
                currDim[0] /= resamplingFactor
                getattr(self, 'outputs_out%d_dimensions' %
                        (chan + 1)).putData(currDim)
                getattr(self, 'outputs_out%d_samples' % (chan + 1)).putData(
                    currDim[0])
            except:
                pass
        pass