Exemple #1
0
    def arrayDimensionOrder(self):
        from numpy import int16, zeros
        from random import randint
        ptree = Tree('seg_tree', -1, 'NEW')
        ptree.addNode('IMM')
        ptree.write()
        ptree = Tree('seg_tree', -1)
        ptree.createPulse(1)
        ptree = Tree('seg_tree', 1)
        node = ptree.getNode('IMM')
        WIDTH = 640
        HEIGHT = 480
        currFrame = zeros(WIDTH * HEIGHT, dtype=int16)
        currTime = float(0)
        for i in range(0, WIDTH):
            for j in range(0, HEIGHT):
                currFrame[i * HEIGHT + j] = randint(0, 255)
        currTime = float(0)
        startTime = Float32(currTime)
        endTime = Float32(currTime)
        dim = Float32Array(currTime)
        segment = Int16Array(currFrame)
        segment.resize([1, HEIGHT, WIDTH])
        shape = segment.getShape()
        node.makeSegment(startTime, endTime, dim, segment)
        retShape = node.getShape()

        self.assertEqual(shape[0], retShape[0])
        self.assertEqual(shape[1], retShape[1])
        self.assertEqual(shape[2], retShape[2])
Exemple #2
0
        def run(self):
            DataArray = c_short * self.NUM_CHUNK_SAMPLES
            rawChan = DataArray()
            self.dataNode.deleteData()

            while not self.stopped:
                status = self.deviceLib.acquireChunk(
                    c_char_p(self.addr), byref(rawChan), c_int(self.NUM_CHUNK_SAMPLES))
                if status == -1:
                    print ('Acquisition Failed')
                    return

                Event.stream(0, 'demostream_chan', Float32(self.currTime), Float32(rawChan[0]))
                dataArr = Int16Array(rawChan)
                startTime = Float64(self.currTime)
                endTime = Float64(
                    self.currTime + self.period * self.NUM_CHUNK_SAMPLES)
                dim = Range(startTime, endTime, Float64(self.period))
                self.dataNode.makeSegment(startTime, endTime, dim, dataArr)
                self.currTime += self.period * self.NUM_CHUNK_SAMPLES

                currSecond = time.time()
                if currSecond > self.prevSecond + 2:
                    Event.setevent('DEMOSTREAM_READY')
                    self.prevSecond = currSecond
Exemple #3
0
 def test():
     from MDSplus import Tree, Float32, Float32Array, Int16Array
     from numpy import int16, zeros
     from random import randint
     with Tree(self.tree, self.shot, 'NEW') as ptree:
         node = ptree.addNode('IMM')
         ptree.write()
     node.tree = Tree(self.tree, self.shot)
     WIDTH = 64
     HEIGHT = 48
     currFrame = zeros(WIDTH * HEIGHT, dtype=int16)
     currTime = float(0)
     for i in range(0, WIDTH):
         for j in range(0, HEIGHT):
             currFrame[i * HEIGHT + j] = randint(0, 255)
     currTime = float(0)
     startTime = Float32(currTime)
     endTime = Float32(currTime)
     dim = Float32Array(currTime)
     segment = Int16Array(currFrame)
     segment.resize([1, HEIGHT, WIDTH])
     shape = segment.getShape()
     node.makeSegment(startTime, endTime, dim, segment)
     retShape = node.getShape()
     self.assertEqual(shape[0], retShape[0])
     self.assertEqual(shape[1], retShape[1])
     self.assertEqual(shape[2], retShape[2])
Exemple #4
0
    def store(self):
        try:
            hConn = httplib.HTTPConnection(self.ip_addr.data())
        except:
            print('Cannot connect to ' + self.ip_addr.data())
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            hConn.request("GET", "/data")
            r = hConn.getresponse()
            jans = json.load(r)
        except:
            print('Cannot get data')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        chan1 = jans['datasets']['g1'][0]['data']
        chan2 = jans['datasets']['g1'][1]['data']

        x1 = []
        y1 = []
        x2 = []
        y2 = []
        for i in range(0, len(chan1)):
            x1.append(chan1[i][0] * 1E-6)
            y1.append(chan1[i][1])
            x2.append(chan2[i][0] * 1E-6)
            y2.append(chan2[i][1])

        try:
            triggerTime = self.trig_time.data()
        except:
            triggerTime = 0

        try:
            dim1 = Data.compile('$1 + $2', Float32Array(x1),
                                Float32(triggerTime))
            data1 = Float32Array(y1)
            sig1 = Data.compile('build_signal($1,,$2)', data1, dim1)
            self.channel_1.putData(sig1)
        except:
            print('Cannot Save Channel 1')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            dim2 = Data.compile('$1 + $2', Float32Array(x1),
                                Float32(triggerTime))
            data2 = Float32Array(y2)
            sig2 = Data.compile('build_signal($1,,$2)', data2, dim2)
            self.channel_2.putData(sig2)
        except:
            print('Cannot Save Channel 2')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        return
Exemple #5
0
 def thread(test, name, node, count):
     i = -1
     max_period = 0
     last = start = time.time()
     for i in range(count):
         data = Float32([i * 10 + 1])
         dim = Float32([last])
         node.makeSegment(dim[0], dim[0], data, dim)
         end = time.time()
         max_period = max(end - last, max_period)
         last = end
     i += 1
     test.assertEqual(i, count)
     print("%s: rate=%f, max_period=%f" % (name, i /
                                           (end - start), max_period))
Exemple #6
0
    def dim_order(self):
        from numpy import zeros

        with Tree(self.tree, self.shot + 0, 'NEW') as ptree:
            node = ptree.addNode('IMM')
            ptree.write()
        ptree.normal()
        WIDTH = 32
        HEIGHT = 16
        curr_frame = zeros((1, HEIGHT, WIDTH), 'int16').shape
        curr_time = float(0)
        start_time = Float32(curr_time)
        end_time = Float32(curr_time)
        dim = Float32Array(curr_time)
        segment = Int16Array(curr_frame)
        shape = segment.getShape()
        node.makeSegment(start_time, end_time, dim, segment)
        ret_shape = node.getShape()
        self.assertEqual(shape, ret_shape)
Exemple #7
0
 def test():
     from MDSplus import Tree, Float32, Float32Array, Int16Array
     from numpy import zeros
     with Tree(self.tree, self.shot, 'NEW') as ptree:
         node = ptree.addNode('IMM')
         ptree.write()
     node.tree = Tree(self.tree, self.shot)
     WIDTH = 32
     HEIGHT = 16
     currFrame = zeros((1, HEIGHT, WIDTH), 'int16').shape
     currTime = float(0)
     startTime = Float32(currTime)
     endTime = Float32(currTime)
     dim = Float32Array(currTime)
     segment = Int16Array(currFrame)
     shape = segment.getShape()
     node.makeSegment(startTime, endTime, dim, segment)
     retShape = node.getShape()
     self.assertEqual(shape, retShape)
Exemple #8
0
 def prepareMarteInfo(self):
     print('(' + self.getFullPath() +
           '.parameters.par_3:value):1000000 : (1./' + self.getFullPath() +
           '.parameters.par_2:value)')
     self.timebase.putData(self.getTree().tdiCompile(
         '(' + self.getFullPath() +
         '.parameters.par_3:value):1000000 : (1./' + self.getFullPath() +
         '.parameters.par_2:value)'))
     # declare only outputs for which event name is specified
     for trigIdx in range(8):
         try:
             eventName = getattr(
                 self, 'outputs_trigger%d_parameters_par_1_value' %
                 (trigIdx + 1)).data()
             print(eventName)
             if eventName == '':
                 getattr(self, 'outputs_trigger%d_dimensions' %
                         (trigIdx + 1)).putData(Float32(-1))
             else:
                 getattr(self, 'outputs_trigger%d_dimensions' %
                         (trigIdx + 1)).putData(Float32(0))
         except:
             getattr(self, 'outputs_trigger%d_dimensions' %
                     (trigIdx + 1)).putData(Float32(-1))
Exemple #9
0
def ECEcalib(node, _unit=None, _freq=None, _calib=None):
    from archive import calibrations
    from MDSplus import Ident, String, Float32, StringArray
    sig = node.evaluate()
    ecechannel = int(node.getNode('$IDX').data()) + 1
    offset, factor, unit, info = calibrations.ECEcalib(sig, ecechannel)
    if offset is None: return
    # construct output
    if isinstance(_unit, Ident):
        String(unit).setTdiVar(_unit.name)
    if isinstance(_freq, Ident):
        Float32(info['freq']).setUnits('GHz').setTdiVar(_freq.name)
    if isinstance(_calib, Ident):
        StringArray([info['cfg'], info['cal'],
                     info['par']]).setTdiVar(_calib.name)
    return [offset, factor]
Exemple #10
0
    def init(self):

        self.debugPrint('================= 11 PXI 6259 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

        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)
            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)))
            self.seg_length.putData(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
Exemple #11
0
    def init(self):

        try:
            fifoDepthSize = self.fifo_depth.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Fifo depth undefined, value set to defaul 40000')
            fifoDepthSize = 40000
            self.fifo_depth.putData(Int32(fifoDepthSize))

        try:
            boardId = self.board_id.data();
            boardIdDev='RIO%d'%(int(boardId))  
            print ('-------->'+boardIdDev)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Board Identifier undefined')
            raise DevBAD_PARAMETER

        try:

            if self.restoreInfo() == self.DEV_IS_OPEN :
               if self.restoreWorker():
                  if self.worker.isAlive():
                      print ('stop Store')
                      self.stop_store()
                      self.wait_store()
               self.closeInfo()
               sleep(1)

            self.initializeInfo(boardIdDev, fifoDepthSize)
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot open MPAG device : %s'%(str(ex)))
            raise mdsExceptions.TclFAILED_ESSENTIAL


        self.saveInfo()

        try:
            bufferSize = self.buf_size.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Buffer size undefined, value set to defaul 1000')
            bufferSize = 1000
            self.buf_size.putData(Int32(bufferSize))


        try:
            segmentLength = self.seg_length.data();
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Segment length undefined, value set to defaul 10000')
            segmentLength = 10000
            self.seg_size.putData(Int32(segmentLength))



#clock mode
        try:
            clockMode = self.clock_mode.data()
            print ('ClockMode -------->'+clockMode)
            if clockMode == 'INTERNAL' :
                frequency = self.clock_freq.data()
                print (frequency)
                if( frequency > self.MAX_ACQ_FREQUENCY ):
                    frequency = self.MAX_ACQ_FREQUENCY
                    self.debugPrint('cRIO MPAG Frequency out of limits. Set to max frequency value : %f' %(self.MAX_ACQ_FREQUENCY))
                    self.clock_freq.putData(frequency)

                clockSource = Range(None, None, Float64(1./frequency))
                print (clockSource)
                self.debugPrint('cRIO MPAG CLOCK: ', clockSource)
                self.clock_source.putData(clockSource)
            else:
                clockSource = self.clock_source.evaluate()
                print (clockSource)
                frequency = self.clock_freq.data()
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid clock definition : '+str(ex))
            raise DevBAD_PARAMETER

#trigger source
        try:
            trigMode = self.trig_mode.data()
            print ('Trig --------> '+trigMode)
            if trigMode == 'EXTERNAL':
                trigSource = self.trig_source.data()
            else:
                try:
                    trigSource = self.trig_source.data()
                except:
                    trigSource = 0;
                    self.trig_source.putData(Float32(trigSource))
            self.debugPrint('cRIO MPAG Trigger source: ',trigSource)
        except Exception as ex:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source : '+str(ex))
            raise DevBAD_PARAMETER


#Time management
        """
        try:
            acqMode = self.acq_mode.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Acquisition Mode undefined')
            raise DevBAD_PARAMETER
        """
        acqMode = 'CONTINUOUS'
        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('cRIO MPAG startTime    = ', startTime)
                    self.debugPrint('cRIO MPAG endTime      = ', endTime)
                    self.debugPrint('cRIO MPAG 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('cRIO MPAG  startIdx = ', Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

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

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

            #Solo acquisizione continua per il momento
            nSamples = -1

        else: #Continuous Acquisition
            nSamples = -1
 

#Channel configuration
        #activeChan = 0
        #chanState = []
        #chanNid = []
        #resNid = []

        mapToAO_Array =c_int32*16
        mapToAO = mapToAO_Array()

        for slave in ['a','b','c']:
            for chan in range(1, self.NUM_SLAVE_CHANNEL+1):                   
                #Empy the node which will contain  the segmented data   
                dataRawNode = getattr(self, 'slave_crio_%c_channel_%02d_data_raw'%(slave, chan))
                dataRawNode.deleteData()
                dataRawNode.setCompressOnPut(False)
                dataResNode = getattr(self, 'slave_crio_%c_channel_%02d_res_raw'%(slave, chan))  
                dataResNode.deleteData()
                dataResNode.setCompressOnPut(False)

        for adcIdx in ['1','2']:
            for chan in range(1, self.NUM_9220_CHANNEL+1):                   
                #Empy the node which will contain  the segmented data   
                dataRawNode = getattr(self, 'ni_9220_%c_channel_%02d_data_raw'%(adcIdx, chan))
                dataRawNode.deleteData()
                dataRawNode.setCompressOnPut(False)
                dataResNode = getattr(self, 'ni_9220_%c_channel_%02d_res_raw'%(adcIdx, chan))  
                dataResNode.deleteData()
                dataResNode.setCompressOnPut(False)


        #Da definire in base alla frequenza di acquisizione impostata

        #highStrobeTick = 50 
        highStrobeTick = int(1e6/frequency)*6 

        status = CRIO_MPAG.niInterfaceLib.setMpagAcqParam(self.session, c_float(frequency), c_uint16(highStrobeTick), mapToAO) 
        if status < 0 :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'cRIO MPAG acquisition device initialization error.')
            return 0

        """
        status = CRIO_MPAG.niInterfaceLib.startMpagFpga(self.session)
        if status < 0 :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'cRIO MPAG start FPGA error.')
            return 0
        """

        return 1
Exemple #12
0
    def start_store(self):

        if (self.restoreInfo() != self.HANDLE_RESTORE):
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'DT5720 Device not initialized')
            return 0

        vmeAddress = 0

        #Module type
        devType = c_int(0)
        status = CAENDT5720.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')
            return 0
        """
      if (devType.value & 0x000000FF) != 0 :
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid board type. Device must be DT5720 model')
        return 0

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

        if (devType.value & 0x000000FF) != 0 and (devType.value
                                                  & 0x000000FF) != 0x3:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid board type. Device must be DT5720 model')
            return 0

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

        if (devType.value & 0x000000FF) == 0x3:
            if (devType.value & 0x0000FF00) >> 8 == 0x2:
                #self.chanMemory = self.MEM_1_25MS
                self.chanMemory = self.MEM_1MS
            else:
                self.chanMemory = self.MEM_10MS

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

        #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')
            return 0
        # currStartIdx = segmentSamples - pts + startIdx
        # currEndIdx = segmentSamples - pts + endIdx

        #Get Active channels
        chanMask = c_int(0)
        status = CAENDT5720.caenLib.CAENVME_ReadCycle(
            self.handle, c_int(vmeAddress + 0x8120), byref(chanMask),
            c_int(self.cvA32_S_DATA), c_int(self.cvD32))
        nActChans = 0
        chanMask = chanMask.value
        numChannels = self.num_channels.data()
        for chan in range(0, numChannels):
            if (chanMask & (1 << chan)) != 0:
                nActChans = nActChans + 1
        if nActChans == 0:
            print('No active groups')
            return 1
        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')
                    return 0
                if acqMode == 'CONTINUOUS WITH COUNTER':
                    useCounter = True
                    data = Data.compile(
                        "2.25*($1 - 2048)/4096.+$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*( $ - 2048)/4096. + $ )",
                                        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')
                    return 0
        #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 = CAENDT5720.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 DT5720 Device')
                return 0
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot starting acquisition on DT5720 Device SW exception')
            return 0

        self.saveWorker()
        self.worker.start()
        """
      try:
        if  acqMode == 'TRANSIENT RECORDER':
          trigSoft = self.trig_soft.data()
          if trigSoft == 'ENABLED':
             trigSource = self.trig_source.data()
             t0 = trigSource[0]
             sleep(t0)
             print "SW Trigger ", trigSource[0]
             status = CAENDT5720.caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
             if status != 0:
               Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger DT5720 Device'  )
               return 0

             if len(trigSource) == 1 :
               sleep( 1 )
               status = CAENDT5720.caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
               if status != 0:
                 Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger(1) DT5720 Device'  )
                 return 0

             for delay in trigSource[1 : ] :
               sleep( delay - t0 )
               t0 = delay
               print "SW Trigger ", delay
               status = CAENDT5720.caenLib.CAENVME_WriteCycle(self.handle, c_int(vmeAddress + 0x8108), byref(c_int(0L)), c_int(self.cvA32_S_DATA), c_int(self.cvD32))
               if status != 0:
                 Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error in sofware trigger DT5720 Device'  )
                 return 0
      except:
        Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot starting acquisition on DT5720 Device SW exception'  )
        return 0
      """

        return 1
Exemple #13
0
    def thick(self):
        def testnci(thick, local, con, nci):
            l = local.S.__getattribute__(nci)
            t = thick.S.__getattribute__(nci)
            if nci.endswith("_nids"):
                l, t = str(l), str(t)
                try:
                    c = str(con.get("getnci(getnci(S,$),'nid_number')", nci))
                except TreeNNF:
                    c = '[]'
            else:
                c = con.get("getnci(S,$)", nci)
            try:
                self.assertEqual(t, c)
                self.assertEqual(t, l)
            except:
                print(nci, t, l, c)
                raise

        server, server_port = self._setup_mdsip('ACTION_SERVER', 'ACTION_PORT',
                                                7000 + self.index, True)

        svr, svr_log = self._start_mdsip(server, server_port, 'thick')
        try:
            con = Connection(server)
            self.assertEqual(
                con.get("zero([1,1,1,1,1,1,1,1],1)").tolist(),
                [[[[[[[[0]]]]]]]])
            with Tree(self.tree, -1, "new") as local:
                local.addNode(self.treesub, "SUBTREE")
                s = local.addNode("S", "SIGNAL")
                s.addTag("tagS")
                s.record = ADD(Float32(1), Float32(2))
                t = local.addNode("T", "TEXT")
                t.addNode("TT", "TEXT").addTag("tagTT")
                t.record = t.TT
                t.TT = "recTT"
                local.write()
            with Tree(self.treesub, -1, "new") as sub:
                sub.addNode("OK")
                sub.write()
            local.normal()
            Tree.setCurrent(self.tree, 7)
            setenv("%s_path" % self.tree, "%s::" % server)
            print(con.get("getenv($//'_path')", self.tree))
            con.get("TreeShr->TreeOpen(ref($),val($),val(1))", self.tree, -1)
            thick = Tree(self.tree, -1)
            thick.createPulse(1)
            thick1 = Tree(self.tree, 1)
            self.assertEqual(
                getattr(local, self.treesub.upper()).OK.nid,
                getattr(thick1, self.treesub.upper()).OK.nid)
            local_filename = local.getFileName()
            thick_filename = thick.getFileName()
            self.assertTrue("::" in thick_filename, thick_filename)
            self.assertTrue(local_filename, thick_filename.split("::", 1)[1])
            """ TreeTurnOff / TreeTurnOn """
            thick.S.on = False
            self.assertEqual(local.S.on, False)
            thick.S.on = True
            self.assertEqual(local.S.on, True)
            """ TreeSetCurrentShotId / TreeGetCurrentShotId """
            Tree.setCurrent(self.tree, 1)
            self.assertEqual(Tree.getCurrent(self.tree), 1)
            """ TreeGetRecord / TreeSetRecord """
            self.assertEqual(str(local.S.record), "1. + 2.")
            self.assertEqual(str(thick.S.record), "1. + 2.")
            thick.S.record = ADD(Float32(2), Float32(4))
            self.assertEqual(str(local.S.record), "2. + 4.")
            self.assertEqual(str(thick.S.record), "2. + 4.")
            self.assertEqual(str(local.T.record), str(thick.T.record))
            """ GetDefaultNid / SetDefaultNid """
            self.assertEqual(thick.getDefault(), thick.top)
            thick.setDefault(thick.S)
            self.assertEqual(thick.getDefault(), thick.top.S)
            thick.setDefault(thick.top)
            """ FindNodeWildRemote """
            self.assertEqual(str(thick.getNodeWild("T*")),
                             str(local.getNodeWild("T*")))
            """ FindTagWildRemote """
            self.assertEqual(thick.findTags("*"), local.findTags("*"))
            """ nci """
            thick.S.write_once = True
            self.assertEqual(thick.S.write_once, True)
            for nci in (
                    'on',
                    'depth',
                    'usage_str',
                    'dtype',
                    'length',
                    'rlength',
                    'fullpath',
                    'minpath',
                    'member_nids',
                    'children_nids',
                    'rfa',
                    'write_once',
            ):
                testnci(thick, local, con, nci)
            """ new stuff """
            self.assertEqual(local.getFileName(),
                             con.get("treefilename($,-1)", self.tree))
        finally:
            if svr_log:
                svr_log.close()
            self._stop_mdsip((svr, server))
Exemple #14
0
    def __checkChanneParam__(self, ch, gain):

        chAOX = []
        chAOY = []

        isOn = getattr(self, 'ao_%d' % (ch + 1)).isOn()

        try:
            chGain = getattr(self, 'ao_%d_gain' % (ch + 1)).data()
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d gain value : %s' % (ch + 1, str(ex)))
            raise mdsExceptions.DevBAD_PARAMETER

        try:
            chOffset = getattr(self, 'ao_%d_offset' % (ch + 1)).data()
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d offset value : %s' % (ch + 1, str(ex)))
            raise mdsExceptions.DevBAD_PARAMETER

        try:
            chMax = getattr(self, 'ao_%d_max' % (ch + 1)).data() / gain
            bitAdc = int(chMax * chGain + chOffset)
            if bitAdc < 0 or bitAdc > 4095:
                raise mdsExceptions.DevBAD_PARAMETER
        except Exception as ex:
            val = 0
            if bitAdc > 0:
                val = (4095 - chOffset) / chGain
            getattr(self, 'ao_%d_max' % (ch + 1)).putData(Float32(val))
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d max value : value cut to value %.2f []' %
                (ch + 1, val))
            #raise mdsExceptions.DevBAD_PARAMETER

        try:
            chMin = getattr(self, 'ao_%d_min' % (ch + 1)).data() / gain
            bitAdc = int(chMin * chGain + chOffset)
            if bitAdc < 0 or bitAdc > 4095:
                raise mdsExceptions.DevBAD_PARAMETER
        except Exception as ex:
            val = 0
            if bitAdc > 0:
                val = (4095 - chOffset) / chGain
            getattr(self, 'ao_%d_min' % (ch + 1)).putData(Float32(val))
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d min value : value cut to %.2f [V]' %
                (ch + 1, val))
            #raise mdsExceptions.DevBAD_PARAMETER

        try:
            chType = getattr(self, 'ao_%d_type' % (ch + 1)).data()
            self.waveTypeDict[chType]
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d wave type : %s' % (ch + 1, str(ex)))
            raise mdsExceptions.DevBAD_PARAMETER

        try:
            chFreq = getattr(self, 'ao_%d_freq' % (ch + 1)).data()
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d waveform frequency : %s' %
                (ch + 1, str(ex)))
            raise mdsExceptions.DevBAD_FREQ
        if chFreq < (self.MIN_FREQ - 1e-6) or chFreq > (self.MAX_FREQ + 1e-4):
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Invalid channel %d waveform frequency %f out of limit (%0.2f:%0.2f)'
                % (ch + 1, chFreq, self.MIN_FREQ, self.MAX_FREQ))
            raise mdsExceptions.DevBAD_FREQ

        if chType == "AS_IS":
            try:
                chAOX = getattr(self, 'ao_%d_x' % (ch + 1)).data()
            except Exception as ex:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid channel %d wave aoY : %s' % (ch + 1, str(ex)))
                raise mdsExceptions.DevBAD_PARAMETER

            try:
                chAOY = getattr(self, 'ao_%d_y' % (ch + 1)).data()
            except Exception as ex:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid channel %d wave aoX : %s' % (ch + 1, str(ex)))
                raise mdsExceptions.DevBAD_PARAMETER

        self.chState = isOn
        self.chMax = chMax
        self.chMin = chMin
        self.chType = chType
        self.chAOX = chAOX
        self.chFreq = chFreq
        self.chAOY = chAOY
        self.chGain = chGain
        self.chOffset = chOffset
Exemple #15
0
 def requests(c, idx):
     args = [Float32(i / 10 + idx) for i in range(10)]
     for i in range(10):
         self.assertEqual(
             c.get("[$,$,$,$,$,$,$,$,$,$]", *args).tolist(),
             args)
Exemple #16
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)

                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)

        #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 = self.getTree().tdiCompile(
                    "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

        self.saveInfo()

        self.debugPrint("===============================================")
Exemple #17
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()
        """
Exemple #18
0
    def init(self):

        print('================= PXI 6259 Init ===============')

        self.restoreInfo()
        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 mdsExceptions.TclFAILED_ESSENTIAL
        if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
            numChannels = 16
        else:
            numChannels = 32

        activeChan = 0
        for chan in range(0, numChannels):
            getattr(self,
                    'channel_%d_data' % (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()]
            except:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Invalid Configuration for channel ' + str(chan + 1))
                raise mdsExceptions.TclFAILED_ESSENTIAL
            if (enabled):
                if (inputMode == self.AI_CHANNEL_TYPE_DIFFERENTIAL):
                    currChan = self.diffChanMap[chan]
                else:
                    currChan = chan
                #print '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 mdsExceptions.TclFAILED_ESSENTIAL
                print('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 mdsExceptions.TclFAILED_ESSENTIAL

#trigger mode
        try:
            trigMode = self.trig_mode.data()
            print(trigMode)
            if (trigMode == 'EXTERNAL_PFI1' or trigMode == 'EXTERNAL_RTSI1'):
                #print "AI_START_SELECT ", self.AI_START_SELECT
                #print "aiConf ", aiConf
                #print "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #print "niLib ", niLib
                #print "AI_START_POLARITY ", self.AI_START_POLARITY
                #print "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE

                if (acqMode == 'TRANSIENT REC.'):
                    """
                    status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PULSE)
                    if( status == 0 ):
                        status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_REFERENCE_SELECT, self.AI_REFERENCE_SELECT_PFI1)
                    if( status == 0 ):
                        status = 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 mdsExceptions.TclFAILED_ESSENTIAL
                    """
                    # Sostituzione temporanea per gestire acquisizione a IPP trigger preso dal 6368
                    # status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)

                    if (trigMode == 'EXTERNAL_PFI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                    else:
                        print("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)
                    if (status != 0):
                        Data.execute('DevLogErr($1,$2)', self.getNid(),
                                     'Cannot set external trigger')
                        raise mdsExceptions.TclFAILED_ESSENTIAL
                else:
                    # Sostituzione etmporanea per gestire acquisizione a IPP trigger preso dal 6368
                    # status = niLib.pxi6259_set_ai_attribute(aiConf, self.AI_START_SELECT, self.AI_START_SELECT_PFI1)

                    if (trigMode == 'EXTERNAL_PFI1'):
                        status = NI6259AI.niLib.pxi6259_set_ai_attribute(
                            aiConf, self.AI_START_SELECT,
                            self.AI_START_SELECT_PFI1)
                    else:
                        print("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 mdsExceptions.TclFAILED_ESSENTIAL

                if (trigMode == 'EXTERNAL_PFI1'):
                    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 mdsExceptions.TclFAILED_ESSENTIAL

            else:
                #print "AI_START_SELECT ", self.AI_START_SELECT
                #print "aiConf ", aiConf
                #print "AI_START_SELECT_PFI1 ", self.AI_START_SELECT_PFI1
                #print "niLib ", NI6259AI.niLib
                #print "AI_START_POLARITY ", self.AI_START_POLARITY
                #print "AI_START_POLARITY_RISING_EDGE ", self.AI_START_POLARITY_RISING_EDGE
                #print "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 mdsExceptions.TclFAILED_ESSENTIAL

        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid triger mode definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

#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)):
                    print('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 mdsExceptions.TclFAILED_ESSENTIAL
                """
                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.))
                print('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 mdsExceptions.TclFAILED_ESSENTIAL

            status = NI6259AI.niLib.pxi6259_set_ai_convert_clk(
                aiConf, c_int(20), 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 mdsExceptions.TclFAILED_ESSENTIAL
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid clock definition')
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

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

                    print('PXI 6259 startTime = ', startTime)
                    print('PXI 6259 endTime   = ', endTime)
                    print('PXI 6259 trigSource   = ', trigSource)

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

                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)

                print '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)
                """
                print('PXI 6259 startIdx = ', Int32(int(startIdx + 0.5)))
                self.start_idx.putData(Int32(int(startIdx + 0.5)))

                print('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:
                    print('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
            """
            print('PXI 6259 nSamples   = ', Int32(int(nSamples)))
            self.seg_length.putData(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 mdsExceptions.TclFAILED_ESSENTIAL

        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 mdsExceptions.TclFAILED_ESSENTIAL
        """
        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()
        print("===============================================")
        return
Exemple #19
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
Exemple #20
0
    def init(self):

        try:
            self.initializeInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot open FAU device')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        #try:
        #    pteMask = self.pte_mask.data();
        #except:
        #    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Read FAU pulse train mask error. Set to 0')
        #    pteMask = 0

        try:
            pteFreqFast = self.pte_frq_fast.data()
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU pulse train fast frequency error. Set to 50kHz')
            pteFreqFast = 50000

        pteFastCount = int(self.TICK_40MHz / pteFreqFast + 100)

        try:
            pteFreqSlow = self.pte_frq_slow.data()
        except:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU pulse train slow frequency error. Set to 50Hz')
            pteFreqSlow = 50

        pteSlowCount = int(self.TICK_40MHz / pteFreqSlow + 100)

        try:
            trigMode = self.trig_mode.data()
            print("Trigger Node = ", trigMode)
        except Exception as ex:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Read FAU trigger mode error. Set to INTERNAL' + str(ex))
            trigMode = 'INTERNAL'
            self.trig_mode.putData(trigMode)

        try:
            tsmpFreq = self.tsmp_freq.data()
            tickFreqCode = self.tsmpDict[tsmpFreq]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU time stamp frequency error. Set to 40MHz')
            tsmpFreq = 40000000
            tickFreqCode = 0
            self.tsmp_freq.putData(Int32(tsmpFreq))

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

        print("Trigger Source = ", trigSource)

        bit = 0
        pteEnaMask = long(0)
        pteSlowFastMask = long(0)
        for mod in range(0, 8):
            for ch in range(0, 8):
                pteModeCode = self.TPEModeDict[getattr(
                    self,
                    'module_%d_channel_%d_pte_mode' % (mod + 1, ch)).data()]
                pteEnaMask = pteEnaMask | ((pteModeCode & long(1) == 1) << bit)
                pteSlowFastMask = pteSlowFastMask | (
                    (pteModeCode & long(2) == 2) << bit)
                bit = bit + 1

        print('pteSlowFastMask ', pteSlowFastMask)
        status = CRIO_FAU.niInterfaceLib.setFauAcqParam(
            self.session, c_uint64(pteEnaMask), c_uint64(pteSlowFastMask),
            c_uint(pteSlowCount), c_uint(pteFastCount), c_short(tickFreqCode))

        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU acquisition device initialization error.')
            return 0

        status = CRIO_FAU.niInterfaceLib.startFauFpga(self.session)
        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU start FPGA error.')
            return 0

        acqState = c_short()
        CRIO_FAU.niInterfaceLib.getFauAcqState(self.session, byref(acqState))
        print("Acquisition State ", acqState.value)

        return 1
Exemple #21
0
    def load_calib(self):

        from openpyxl import load_workbook

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

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

        try:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            wb.close()

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

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

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

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

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

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

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

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

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

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

        try:
            for gr_val in gratingsNodeList:
                for gr in range(0, 3):
                    #print gr_val[0]%(gr+1), gr_val[1], gr_val[2]
                    if gr_val[1] == 'text':
                        getattr(self,
                                gr_val[0] % (gr + 1)).putData(gr_val[2][gr])
                    elif gr_val[1] == 'int':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            int(gr_val[2][gr]))
                    elif gr_val[1] == 'float':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            float(gr_val[2][gr]))
                    elif gr_val[1] == 'signal':
                        getattr(self, gr_val[0] % (gr + 1)).putData(
                            Signal(gr_val[2][1 + (gr * 2)], None,
                                   gr_val[2][gr * 2]))
        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Error writing grating calibration %s field %s' %
                (gr_val[0] % (gr + 1), str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL
        return 1
Exemple #22
0
    def init(self):

        try:
            self.initializeInfo()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Cannot open FAU device')
            raise mdsExceptions.TclFAILED_ESSENTIAL

        self.saveInfo()

        try:
            pteMask = self.pte_mask.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU pulse train mask error. Set to 0')
            pteMask = 0

        try:
            pteFreq = self.pte_freq.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU pulse train frequency error. Set to 50KHz')
            pteMask = 50000

        try:
            trigMode = self.trig_mode.data()
            print("Trigger Node = ", trigMode)
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU trigger mode error. Set to INTERNAL')
            trigMode = 'INTERNAL'
            self.trig_mode.putData(trigMode)

        try:
            tsmpFreq = self.tsmp_freq.data()
            tickFreqCode = self.tsmpDict[tsmpFreq]
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Read FAU time stamp frequency error. Set to 40MHz')
            tsmpFreq = 40000000
            tickFreqCode = 0
            self.tsmp_freq.putData(Int32(tsmpFreq))

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

        print("Trigger Source = ", trigSource)

        status = CRIO_FAU.niInterfaceLib.setFauAcqParam(
            self.session, c_short(pteMask), c_int(pteFreq),
            c_short(tickFreqCode))

        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU acquisition device initialization error.')
            raise mdsExceptions.DevCANNOT_LOAD_SETTINGS

        status = CRIO_FAU.niInterfaceLib.startFauFpga(self.session)
        if status < 0:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'FAU start FPGA error.')
            raise mdsExceptions.DevCOMM_ERROR
Exemple #23
0
        def run(self):

            nid = self.device.getNid()
            chanModes = NI6259EV.ni6259chanModes[nid]
            chanEvents = NI6259EV.ni6259chanEvents[nid]
            chanPreTimes = NI6259EV.ni6259chanPreTimes[nid]
            chanPostTimes = NI6259EV.ni6259chanPostTimes[nid]
            chanFd = []
            chanNid = []
            f1Div = self.device.freq1_div.data()
            f2Div = self.device.freq2_div.data()
            baseFreq = self.device.clock_freq.data()
            baseStart = self.device.clock_start.data()
            coeff_array = c_float * 4
            coeff = coeff_array()

            maxDelay = self.device.history_len.data()
            # NI6259AI.niInterfaceLib.getStopAcqFlag(byref(self.stopAcq));
            numChans = len(self.chanMap)
            isBurst_c = (c_int * numChans)()
            f1Divs_c = (c_int * numChans)()
            f2Divs_c = (c_int * numChans)()
            preTimes_c = (c_double * numChans)()
            postTimes_c = (c_double * numChans)()
            eventNames_c = (c_char_p * numChans)()

            for chan in range(numChans):
                # self.device.debugPrint 'CHANNEL', self.chanMap[chan]+1
                # self.device.debugPrint '/dev/pxi6259.'+str(boardId)+'.ai.'+str(self.hwChanMap[self.chanMap[chan]])
                if chanModes[chan] == 'CONTINUOUS(FREQ1)':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p('')
                elif chanModes[chan] == 'CONTINUOUS(FREQ2)':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f2Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p('')
                elif chanModes[chan] == 'BURST(FREQ1)':
                    isBurst_c[chan] = 1
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                elif chanModes[chan] == 'BURST(FREQ2)':
                    isBurst_c[chan] = 1
                    f1Divs_c[chan] = f2Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                elif chanModes[chan] == 'DUAL SPEED':
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                else:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Invalid Mode for channel ' + str(chan + 1))
                    raise DevBAD_PARAMETER

                preTimes_c[chan] = chanPreTimes[chan]
                postTimes_c[chan] = chanPostTimes[chan]

                try:
                    boardId = getattr(self.device, 'board_id').data()
                    print(
                        'APRO', '/dev/pxi6259.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]))
                    currFd = os.open(
                        '/dev/pxi6259.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]),
                        os.O_RDWR | os.O_NONBLOCK)
                    chanFd.append(currFd)
                    print('APERTO')
                except Exception as e:
                    self.device.debugPrint(e)
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot open Channel ' + str(self.chanMap[chan]))
                    self.error = self.ACQ_ERROR
                    return
                chanNid.append(
                    getattr(self.device, 'channel_%d_raw' %
                            (self.chanMap[chan] + 1)).getNid())

                self.device.debugPrint(
                    'chanFd ' + 'channel_%d_raw' % (self.chanMap[chan] + 1),
                    chanFd[chan])

                gain = getattr(self.device, 'channel_%d_range' %
                               (self.chanMap[chan] + 1)).data()
                gain_code = self.device.gainDict[gain]

                # time.sleep(0.600)
                n_coeff = c_int(0)
                status = NI6259EV.niInterfaceLib.pxi6259_getCalibrationParams(
                    currFd, gain_code, coeff, byref(n_coeff))

                if (status < 0):
                    errno = NI6259EV.niInterfaceLib.getErrno()
                    msg = 'Error (%d) %s' % (errno, os.strerror(errno))
                    self.device.debugPrint(msg)
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot read calibration values for Channel %d. Default value assumed ( offset= 0.0, gain = range/65536'
                        % (self.chanMap[chan]))

                gainValue = self.device.gainValueDict[gain] * 2.
                coeff[0] = coeff[2] = coeff[3] = 0
                coeff[1] = c_float(gainValue / 65536.)
                print('SCRIVO CALIBRAZIONE', coeff)
                getattr(self.device,
                        'channel_%d_calib' % (self.chanMap[chan] + 1)).putData(
                            Float32(coeff))
                print('SCRITTO')

            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()

            if (bufSize > segmentSize):
                segmentSize = bufSize
            else:
                c = segmentSize / bufSize
                if (segmentSize % bufSize > 0):
                    c = c + 1
                segmentSize = c * bufSize

            status = NI6259EV.niLib.pxi6259_start_ai(c_int(self.fd))

            if (status != 0):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                             'Cannot Start Acquisition ')
                self.error = self.ACQ_ERROR
                return

            saveList = c_void_p(0)
            NI6259EV.niInterfaceLib.startSaveEV(byref(saveList))
            #count = 0

            chanNid_c = (c_int * len(chanNid))(*chanNid)
            chanFd_c = (c_int * len(chanFd))(*chanFd)

            while not self.stopReq:
                status = NI6259EV.niInterfaceLib.pxi6259EV_readAndSaveAllChannels(
                    c_int(numChans), chanFd_c, isBurst_c, f1Divs_c, f2Divs_c,
                    c_double(maxDelay), c_double(baseFreq), preTimes_c,
                    postTimes_c, c_double(baseStart), c_int(bufSize),
                    c_int(segmentSize), eventNames_c, chanNid_c, self.treePtr,
                    saveList, self.stopAcq)

                if status < 1:
                    return 0

            status = NI6259EV.niLib.pxi6259_stop_ai(c_int(self.fd))

            for chan in range(len(self.chanMap)):
                os.close(chanFd[chan])
            self.device.debugPrint('ASYNCH WORKER TERMINATED')
            #            NI6259EV.niInterfaceLib.stopSaveEV(saveList)
            #            NI6259EV.niInterfaceLib.freeStopAcqFlag(self.stopAcq)
            self.device.closeInfo()

            return
Exemple #24
0
    def start_store(self):
        try:
            self.board_id.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Invalid Board ID specification')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        vmeAddress = 0
        try:
            clock = self.clock_source.evaluate()
            dt = clock.getDelta().data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating clock source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            trigTime = self.trig_source.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating trigger source')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            startIdx = self.start_idx.data()
            endIdx = self.end_idx.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating start or end idx')
            raise mdsExceptions.TclFAILED_ESSENTIAL
        try:
            pts = self.pts.data()
        except:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error evaluating Post Trigger Samples')
            raise mdsExceptions.TclFAILED_ESSENTIAL

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

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

        for chan in range(0, numChannels):
            if (chanMask & (1 << chan)) != 0:
                try:
                    offset = getattr(self,
                                     'channel_%d_offset' % (chan + 1)).data()
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error reading channel offset')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
                if acqMode == 'CONTINUOUS WITH COUNTER':
                    useCounter = True
                    data = Data.compile(
                        "2*($1 - 2048)/4096.+$2",
                        TreePath(
                            getattr(self, 'channel_%d_seg_raw' %
                                    (chan + 1)).getFullPath()), offset)
                else:
                    useCounter = False
                    startTime = startIdx * dt
                    endTime = (endIdx - 1) * dt
                    segRawPath = TreePath(
                        getattr(self, 'channel_%d_seg_raw' %
                                (chan + 1)).getFullPath())
                    trigPath = TreePath(self.trig_source.getFullPath())
                    data = Data.compile(
                        "BUILD_SIGNAL(2*($VALUE - 2048)/4096.+$1, DATA($2), MAKE_RANGE($3+$4, $3+$5, REPLICATE($6,0,SIZE($3))))",
                        Float32(offset), segRawPath, trigPath,
                        Float64(startTime), Float64(endTime), Float64(dt))
                try:
                    getattr(self, 'channel_%d_data' % (chan + 1)).putData(data)
                except:
                    Data.execute('DevLogErr($1,$2)', self.getNid(),
                                 'Error Writing data')
                    raise mdsExceptions.TclFAILED_ESSENTIAL
        #endfor chan in range(0,numChannels):

        self.worker = self.AsynchStore()
        self.worker.daemon = True
        self.worker.stopReq = False
        self.worker.configure(self.handle, startIdx, endIdx, pts, chanMask,
                              nActChans, dt, trigTime,
                              segmentSamples, segmentSize, chanMask,
                              self.getNid(), self, self.cv, self.readCv,
                              useCounter,
                              self.irq_events.data() + 1)
        self.worker.start()
        return
Exemple #25
0
    def load_config(self):

        #print sys.version_info
        
        from openpyxl import load_workbook

        try:
            configurationFile = self.config_file.data()
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot read configuration file' + str(e) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

        try:
            print ('Loading data from excel configuration file [%s] ...'%(configurationFile),  )          

            param='configurationFile'
            wb = load_workbook(configurationFile, data_only=True)

            sheet=wb['INFO']
            config_date = str(sheet['C1'].value)
            config_comment = str(sheet['C2'].value)
          
            sheet=wb['CONFIG']

            param = 'label_arr'
            #Set column range for all read column. Diect access, with value fild, on the first col value dosen't work
            col=sheet['B2:B%d'%(self.PROBES_NUM+1)]
            col=sheet['B']
            label_arr = [str( c.value if c != None else "") for c in col[1:len(col):1]]

            param = 'front_end_arr'
            col=sheet['C']
            front_end_arr = [str(  c.value if c.value != None else "" ) for c in col[1:len(col):1]]

            param = 'front_end_ch_arr'
            col=sheet['D']
            front_end_ch_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_slow_arr'
            col=sheet['E']
            adc_slow_arr = [str( c.value if c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_slow_con_arr'
            col=sheet['F']
            adc_slow_con_arr = [str( c.value if c.value != None else "") for c in col[1:len(col):1]]

            param = 'adc_fast_arr'
            col=sheet['G']
            adc_fast_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            param = 'calib_RV_arr'
            col=sheet['H']
            calib_RV_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float) else -1) for c in col[1:len(col):1]]
            calib_RV_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'calib_RI_high_arr'
            col=sheet['I']
            calib_RI_high_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else -1) for c in col[1:len(col):1]]
            calib_RI_high_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'calib_RI_low_arr'
            col=sheet['J']
            calib_RI_low_arr = [float(c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else -1) for c in col[1:len(col):1]]
            calib_RI_low_str_arr = [str( c.value if c.value != None and (type(c.value) == long or type(c.value) == float)  else "") for c in col[1:len(col):1]]

            param = 'note_arr'
            col=sheet['K']
            note_arr = [str( c.value if  c.value != None else "") for c in col[1:len(col):1]]

            wb.close()

            print (' data loaded')            


        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot read or invalid probes param : [%s] configuration file : %s '%(param,str(e)) )
            raise mdsExceptions.TclFAILED_ESSENTIAL
        
        try:
            self.comment.putData(config_comment)
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing comment field ' + str(e) )
            raise mdsExceptions.TclFAILED_ESSENTIAL

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


        try:
            field = 'label'
            self.cfg_probes_label.putData(StringArray(label_arr))
            field = 'front_end'
            self.cfg_probes_front_end.putData(StringArray(front_end_arr))
            field = 'front_end_ch'
            self.cfg_probes_front_end_ch.putData(StringArray(front_end_ch_arr))
            field = 'adc_slow'
            self.cfg_probes_adc_slow.putData(StringArray(adc_slow_arr))
            field = 'adc_slow_con'
            self.cfg_probes_adc_slow_con.putData(StringArray(adc_slow_con_arr))
            field = 'adc_fast'
            self.cfg_probes_adc_fast.putData(StringArray(adc_fast_arr))
            field = 'calib_RV'
            self.cfg_probes_calib_rv.putData(StringArray(calib_RV_str_arr))
            field = 'calib_RI_high'
            self.cfg_probes_calib_ri_h.putData(StringArray(calib_RI_high_str_arr))
            field = 'calib_RI_low'
            self.cfg_probes_calib_ri_l.putData(StringArray(calib_RI_low_str_arr))
            field = 'note'
            self.cfg_probes_note.putData(StringArray(note_arr))
        except Exception as e :
            Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing param %s probes : %s '%(field, str(e)) )
            raise mdsExceptions.TclFAILED_ESSENTIAL


        # Set off oll channel of the ADC module fast and slow defined in the configuration. 
        # ADC Channel is set ON if it is used. Thi is done to not acquire not usefull signals  

        adcSet = []
        for adc in adc_slow_arr :
            adc = adc.strip()
            if len(adc) == 0 :
                continue
            if not (adc in adcSet) :
                adcSet.append(adc)
                for i in range(1,33):
                    self.__setNodeState('\\%s.CHANNEL_%d'%(adc, i), False)
        del adcSet

        adcSet = []
        for adc in adc_fast_arr :
            adc = adc.strip()
            if len(adc) == 0 :
                continue
            if not (adc in adcSet) :
                adcSet.append(adc)
                for i in range(1,17):
                    self.__setNodeState('\\%s.CHANNEL_%d'%(adc, i), False)


        for i in range(0, self.PROBES_NUM):


            if  len( label_arr[i].strip() ) == 0 or label_arr[i].strip() == 'None' :
                continue

            print ('[%0.2d] Configuration for probe %s : '%(i+1, label_arr[i]),) 

            #print "Save probes %d %s"%(i+1, label_arr[i])

            try:
                getattr(self, 'probe_%02d_label'%(i+1)).putData(label_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing label field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            try:
                getattr(self, 'probe_%02d_note'%(i+1)).putData(note_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing note field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            if  len( front_end_arr[i].strip() ) == 0 or  front_end_arr[i].strip() == 'None':
                #print label_arr[i] + " probe reset data and set off"
                getattr(self, 'probe_%02d'%(i+1)).setOn(False)
                getattr(self, 'probe_%02d_front_end'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_front_end_ch'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_slow'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_slow_con'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_adc_fast'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_rv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_ri_h'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_calib_ri_l'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_bias_source'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_bias'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_irange'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_sv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_sv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_si'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_si'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_fv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_fv'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_data_fi'%(i+1)).deleteData()
                getattr(self, 'probe_%02d_help_fi'%(i+1)).deleteData()

                try :
                   self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(False)
                   self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(False)
                except Exception :
                   print ('WARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) )  

                print ('[set OFF]')

                continue 
            else :
                print ('[set ON]')
                getattr(self, 'probe_%02d'%(i+1)).setOn(True)

            try:
                getattr(self, 'probe_%02d_front_end'%(i+1)).putData(front_end_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing front end field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_front_end_ch'%(i+1)).putData(Int32(int(front_end_ch_arr[i])))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), '---Error writing front end channel field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:                
                getattr(self, 'probe_%02d_adc_slow'%(i+1)).putData(adc_slow_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc slow field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                if adc_slow_con_arr[i] == "CON_0" or adc_slow_con_arr[i] == "CON_1" : 
                    getattr(self, 'probe_%02d_adc_slow_con'%(i+1)).putData(adc_slow_con_arr[i])
                else:
                    Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid value on adc slow connection field on probe %d, valid values CON_0, CON 1 '%(i+1) )
                    raise mdsExceptions.TclFAILED_ESSENTIAL
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc slow connection field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_adc_fast'%(i+1)).putData(adc_fast_arr[i])
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing adc fast field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_rv'%(i+1)).putData(Float32(calib_RV_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing resistence voltage calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_ri_h'%(i+1)).putData(Float32(calib_RI_high_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing high current resistence calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'probe_%02d_calib_ri_l'%(i+1)).putData(Float32(calib_RI_low_arr[i]))
            except Exception as e :
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error writing low current resistence calibration field on probe %d : %s '%(i+1 , str(e)) )
                raise mdsExceptions.TclFAILED_ESSENTIAL


            try:
               #Reset current link

               node = self.__getattr__('\\%s.CH_%02d:SOURCE'%(front_end_arr[i], int( front_end_ch_arr[i])));
               expr_val = Data.compile('build_path($)', node.getFullPath())	
               getattr(self, 'probe_%02d_bias_source'%(i+1)).putData( expr_val )
          
               """
               node = self.__getattr__('\\%s.CH_%02d:BIAS'%(front_end_arr[i], int( front_end_ch_arr[i])));
	       expr_val = Data.compile('build_path($)', node.getFullPath())	
               getattr(self, 'probe_%02d_bias'%(i+1)).putData( expr_val ) 
               """

               node = self.__getattr__('\\%s.CH_%02d:IRANGE'%(front_end_arr[i], int( front_end_ch_arr[i])));
               expr_val = Data.compile('build_path($)', node.getFullPath())
               irange_node = getattr(self, 'probe_%02d_irange'%(i+1)) 	
               irange_node.putData( expr_val )

               calib_rv_node = getattr(self, 'probe_%02d_calib_rv'%(i+1))
               calib_ri_high_node = getattr(self, 'probe_%02d_calib_ri_h'%(i+1))
               calib_ri_low_node = getattr(self, 'probe_%02d_calib_ri_l'%(i+1))
	
        
               if len( adc_slow_arr[i].strip() ) != 0 and adc_slow_arr[i].strip() != 'None' :

                   if adc_slow_con_arr[i] == "CON_0" :
                       adc_slow_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])) )
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])), True)
                       adc_slow_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+8 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+8), True)
                   elif adc_slow_con_arr[i] == "CON_1" :
                       adc_slow_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+16 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+16), True)
                       adc_slow_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_slow_arr[i], int( front_end_ch_arr[i])+24 ))
                       self.__setNodeState('\\%s.CHANNEL_%d'%(adc_slow_arr[i], int( front_end_ch_arr[i])+24), True)
                   else:
                       Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error invalid slow adc commector for probe %d (%s)'%(i+1, label_arr[i]) )
                       raise mdsExceptions.TclFAILED_ESSENTIAL



                   expr_slow_v = Data.compile('build_path($) *  build_path($)', calib_rv_node.getFullPath()  , adc_slow_v_node.getFullPath()) 
                   expr_slow_i = Data.compile("(build_path($) == 'LOW'  ?  build_path($) : build_path($) ) *  Build_path($)", irange_node.getFullPath() , calib_ri_low_node.getFullPath(), calib_ri_high_node.getFullPath()  , adc_slow_i_node.getFullPath()) 

                   getattr(self, 'probe_%02d_data_sv'%(i+1)).putData(expr_slow_v);
                   getattr(self, 'probe_%02d_help_sv'%(i+1)).putData('%s slow acquisition voltage'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_si'%(i+1)).putData(expr_slow_i);
                   getattr(self, 'probe_%02d_help_si'%(i+1)).putData('%s slow acquisition current'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_sv'%(i+1)).setOn(True)
                   getattr(self, 'probe_%02d_data_si'%(i+1)).setOn(True)

                   print ('[slow adc %s %s]'%(adc_slow_arr[i], adc_slow_con_arr[i]),)

                   try :
                      self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(True)
                      self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(True)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) )  

               else :
                   print (' ')
                   getattr(self, 'probe_%02d_data_sv'%(i+1)).deleteData()
                   getattr(self, 'probe_%02d_data_sv'%(i+1)).setOn(False)
                   getattr(self, 'probe_%02d_data_si'%(i+1)).deleteData()
                   getattr(self, 'probe_%02d_data_si'%(i+1)).setOn(False)
                   try :
                      self.__getattr__('\\%sSV'%(label_arr[i]) ).setOn(False)
                      self.__getattr__('\\%sSI'%(label_arr[i]) ).setOn(False)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]))   


               if len( adc_fast_arr[i].strip() ) != 0 and adc_fast_arr[i].strip() != 'None' :


                   getattr(self, 'probe_%02d_data_fv'%(i+1)).setOn(True);
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).setOn(True);

                   adc_fast_i_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_fast_arr[i], int( front_end_ch_arr[i]) ))
                   self.__setNodeState('\\%s.CHANNEL_%d'%(adc_fast_arr[i], int( front_end_ch_arr[i])), True)
                   adc_fast_v_node = self.__getattr__('\\%s.CHANNEL_%d:DATA'%(adc_fast_arr[i], int( front_end_ch_arr[i])+8 ))
                   self.__setNodeState('\\%s.CHANNEL_%d'%(adc_fast_arr[i], int( front_end_ch_arr[i])+8), True)

                   expr_fast_v = Data.compile('build_path($) *  build_path($)', calib_rv_node.getFullPath()  , adc_fast_v_node.getFullPath()) 
                   expr_fast_i = Data.compile("(build_path($) == 'LOW'  ?  build_path($) : build_path($) ) *  Build_path($)", irange_node.getFullPath() , calib_ri_low_node.getFullPath(), calib_ri_high_node.getFullPath()  , adc_fast_i_node.getFullPath()) 

                   getattr(self, 'probe_%02d_data_fv'%(i+1)).putData(expr_fast_v);
                   getattr(self, 'probe_%02d_help_fv'%(i+1)).putData('%s fast acquisition voltage'%(label_arr[i]));

                   getattr(self, 'probe_%02d_data_fi'%(i+1)).putData(expr_fast_i);
                   getattr(self, 'probe_%02d_help_fi'%(i+1)).putData('%s fast acquisition current'%(label_arr[i]));

                   print ('[fast adc %s]'%(adc_fast_arr[i]))

                   try :
                      self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(True)
                      self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(True)
                   except Exception :
                      print ('\nWARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]))   

               else :
                   print (' ')
                   getattr(self, 'probe_%02d_data_fv'%(i+1)).deleteData();
                   getattr(self, 'probe_%02d_data_fv'%(i+1)).setOn(False);
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).deleteData();
                   getattr(self, 'probe_%02d_data_fi'%(i+1)).setOn(False);
                   try :
                      self.__getattr__('\\%sFV'%(label_arr[i]) ).setOn(False)
                      self.__getattr__('\\%sFI'%(label_arr[i]) ).setOn(False)
                   except Exception :
                      print ('WARNING : The configuration excel file added the probe %s.\nThe updateSignalsProbes command MUST be execute'%(label_arr[i]) ) 

            except Exception as e:
                traceback.print_exc()
                Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error setting link for probe %d (%s) to Front End %s ch %s : %s'%(i+1, label_arr[i], front_end_arr[i], front_end_ch_arr[i] ,str(e)))
                raise mdsExceptions.TclFAILED_ESSENTIAL

        return 1