Exemplo n.º 1
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
Exemplo n.º 2
0
 def getXYSignal(self):
     with Tree('pytree', self.shot + 9, 'new') as pytree:
         node = pytree.addNode('SIG', 'signal')
         pytree.write()
     pytree.normal()
     dim = numpy.array(range(100000), 'float32') / 10000
     pytree.SIG.record = Signal(
         Float32Array(numpy.sin(dim)).setUnits("ylabel"), None,
         Float32Array(dim).setUnits("xlabel")).setHelp('title')
     sig = node.getXYSignal(num=100)
     self.assertEqual(sig.units, "ylabel")
     self.assertEqual(sig.dim_of().units, "xlabel")
     self.assertEqual(sig.help, "title")
Exemplo n.º 3
0
 def storeFrame(self, node, dim, frame):
     dims = Float32Array([dim]).setUnits('s')
     data = Int16Array(array(frame, 'int16').reshape(
         [1, self.PixelsX, self.PixelsY]))
     if Device.debug:
         print('storeFrame', node.minpath, dim, data.shape)
     node.makeSegment(dim, dim, dims, data)
Exemplo n.º 4
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])
Exemplo n.º 5
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])
Exemplo n.º 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)
Exemplo n.º 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)
Exemplo n.º 8
0
 def run(self):
     Tree.usePrivateCtx(True)
     try:  # test open Nodes
         tree = Tree(self.tree, self.shot)
         try:
             tree.getNode(self.pcb)
         except Exception as exc:
             error(exc)
             self.pcb = None
         try:
             tree.getNode(self.cmos)
         except Exception as exc:
             error(exc)
             self.cmos = None
     except Exception as exc:
         error(exc)
         error(
             'Cannot access trend tree. Check TREND:TREE and TREND_SHOT.'
         )
         raise mdsExceptions.TreeTNF
     if self.pcb is None and self.cmos is None:
         error(
             'Cannot access any node for trend. Check TREND:PCB, TREND:CMOS on. Nodes must exist on %s.'
             % repr(tree))
         raise mdsExceptions.TreeNNF
     if self.pcb is None:
         error(
             'Cannot access node for pcb trend. Check TREND:PCB. Continue with cmos trend.'
         )
     elif self.cmos is None:
         error(
             'Cannot access node for cmos trend. Check TREND:CMOS. Continue with pcb trend.'
         )
     print('started trend writing to %s - %s and %s every %fs' %
           (self.tree, self.pcb, self.cmos, self.period))
     self.running = True
     while (not self.stopReq):
         timeTillNextMeasurement = self.period - (time() % self.period)
         if timeTillNextMeasurement > 0.6:
             sleep(.5)  # listen to stopReq
         else:
             sleep(timeTillNextMeasurement)
             # wait remaining period unit self.period
             currTime = int(
                 int(time() / self.period + .1) * self.period * 1000)
             # currTime in steps of self.period
             if self.ns: currTime *= 1000000  # time in nano seconds
             try:
                 if self.shot == 0:
                     if Tree.getCurrent(self.tree) != tree.shot:
                         tree = Tree(self.tree, self.shot)
                 if self.pcb is not None:
                     pcbTemp = CYGNET4K.xclib.getPcbTemp()
                     tree.getNode(self.pcb).makeSegment(
                         currTime, currTime,
                         Dimension(None, Uint64Array(currTime)),
                         Float32Array(pcbTemp).setUnits('oC'), -1)
                 if self.cmos is not None:
                     cmosTemp = CYGNET4K.xclib.getCmosTemp()
                     tree.getNode(self.cmos).makeSegment(
                         currTime, currTime,
                         Dimension(None, Uint64Array(currTime)),
                         Uint16Array(cmosTemp), -1)
                 if Device.debug:
                     print(tree.tree, tree.shot, currTime, pcbTemp,
                           cmosTemp)
             except Exception:
                 error(exc_info()[1])
                 error('failure during temperature readout')
             sleep(0.01)
     self.running = False
     print('done')
Exemplo n.º 9
0
 def store(self):
     """transfer data to tree"""
     self.device.temp_pcb.record = Float32Array(self.pcbTemp)
     self.device.temp_cmos.record = Int16Array(self.cmosTemp)
     CYGNET4K.xclib.storeFrames(self.device.frames)
Exemplo n.º 10
0
    def load_calib(self):

        from openpyxl import load_workbook

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

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

        try:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            wb.close()

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

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

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

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

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

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

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

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

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

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

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

            self.device.setTree(
                Tree(self.device.getTree().name,
                     self.device.getTree().shot))
            self.device = self.device.copy()

            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()
            #counters = [0]*len(self.chanMap)
            boardId = self.device.board_id.data()
            acqMode = self.device.acq_mode.data()
            sampleToSkip = self.device.start_idx.data()
            transientRec = False
            startTime = float(self.device.start_time.data())
            trigSource = self.device.trig_source.data()
            clockSource = self.device.clock_source.evaluate()

            frequency = float(clockSource.getDelta())

            try:
                # In multi trigger acquisition acquired data from trigger_time[i]+start_time up to trigger_time[i] + end_time
                # Time value to be associted at the first sample of the i-esima acquisition must be trigger_time[i]+start_time
                numTrigger = len(trigSource)
                #trigTime = 0.
                timesIdx0 = trigSource
            except:
                # Single trigger acquire data from start time up to end time
                # Time value to be associted at the first sample must be start time
                numTrigger = 1
                timesIdx0 = []
                timesIdx0.append(0)

            if (acqMode == 'TRANSIENT REC.'):
                transientRec = True

            chanFd = []
            chanNid = []
            resNid = []
            coeffsNid = []
            gainDividers = []
            saveList = c_void_p(0)

            # NI6368AI.niInterfaceLib.getStopAcqFlag(byref(self.stopAcq));

            coeff_array = c_float * 4
            coeff = coeff_array()

            for chan in range(len(self.chanMap)):
                try:
                    # self.device.debugPrint('CHANNEL', self.chanMap[chan]+1

                    currFd = os.open(
                        '/dev/pxie-6368.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]),
                        os.O_RDWR | os.O_NONBLOCK)
                    chanFd.append(currFd)
                    chanNid.append(
                        getattr(
                            self.device, 'channel_%d_data_raw' %
                            (self.chanMap[chan] + 1)).getNid())
                    # self.device.debugPrint("chanFd "+'channel_%d_data_raw'%(self.chanMap[chan]+1), chanFd[chan], " chanNid ", chanNid[chan]
                    resNid.append(
                        getattr(
                            self.device, 'channel_%d_res_raw' %
                            (self.chanMap[chan] + 1)).getNid())
                    coeffsNid.append(
                        getattr(
                            self.device, 'channel_%d_calib_param' %
                            (self.chanMap[chan] + 1)).getNid())
                    gain = getattr(
                        self.device,
                        'channel_%d_range' % (self.chanMap[chan] + 1)).data()
                    gain_code = self.device.gainDict[gain]
                    # Gains nou used in calibration for 6368
                    gainDividers.append(1.)
                    status = NI6368AI.niInterfaceLib.getCalibrationParams(
                        currFd, gain_code, coeff)
                    if (status < 0):
                        Data.execute(
                            'DevLogErr($1,$2)', self.device.getNid(),
                            'Cannot read calibration values for Channel %d. Default value assumed ( offset= 0.0, gain = range/32768'
                            % (str(self.chanMap[chan])))
                        coeff[0] = coeff[2] = coeff[3] = 0
                        coeff[1] = c_float(gain / 32768.)

                    getattr(
                        self.device, 'channel_%d_calib_param' %
                        (self.chanMap[chan] + 1)).putData(Float32Array(coeff))

                except:
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot open Channel ' + str(self.chanMap[chan] + 1))
                    self.closeAll(chanFd, saveList)
                    self.error = self.ACQ_ERROR
                    return

            # Make sure hbuf size is a multiple of 100 not to break putSegmentResampled
            if bufSize % 100 != 0:
                bufSize = 100 * (bufSize / 100 + 1)

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

            if (not transientRec):
                numSamples = -1
                self.device.debugPrint("PXI 6368 CONTINUOUS ", numSamples)

            else:
                NI6368AI.niInterfaceLib.setStopAcqFlag(self.stopAcq)
                try:
                    numSamples = self.device.end_idx.data(
                    ) - self.device.start_idx.data()
                except:
                    numSamples = 0

            #self.device.debugPrint("--+++ NUM SAMPLES ", numSamples)
            #self.device.debugPrint("--+++ Segment Size ", segmentSize)
            #self.device.debugPrint("--+++ sample to skip ", sampleToSkip)

            NI6368AI.niInterfaceLib.startSave(byref(saveList))

            chanNid_c = (c_int * len(chanNid))(*chanNid)
            chanFd_c = (c_int * len(chanFd))(*chanFd)
            resNid_c = (c_int * len(resNid))(*resNid)
            coeffsNid_c = (c_int * len(coeffsNid))(*coeffsNid)
            gainDividers_c = (c_float * len(gainDividers))(*gainDividers)

            trigCount = 0

            time.sleep(1)
            timeAt0 = startTime

            # self.device.debugPrint(self.stopAcq)

            while not self.stopReq:
                try:
                    status = NI6368AI.niInterfaceLib.xseriesReadAndSaveAllChannels(
                        c_int(self.ai_fd), c_int(len(self.chanMap)), chanFd_c,
                        c_int(int(round(bufSize))),
                        c_int(int(round(segmentSize))), c_int(sampleToSkip),
                        c_int(numSamples), c_float(timeAt0),
                        c_float(frequency), chanNid_c,
                        gainDividers_c, coeffsNid_c,
                        self.device.clock_source.getNid(), self.treePtr,
                        saveList, self.stopAcq,
                        c_int(self.device.getTree().shot), resNid_c)
                except Exception as ex:
                    self.device.debugPrint(
                        'Acquisition thread start error : %s' % (str(ex)))
                    self.stopReq = True
                    status = -3

                # Check termination
                trigCount += 1
                #self.device.debugPrint("PXI 6368 Trigger count %d num %d num smp %d status %d " %(trigCount , numTrigger, numSamples, status) )
                if ((numSamples > 0 and trigCount == numTrigger)
                        or (status < 0)):
                    self.stopReq = True

                if (transientRec):
                    NI6368AI.niInterfaceLib.setStopAcqFlag(self.stopAcq)

            if (status < 0):
                if (status == -1):
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                                 'PXI 6368 Module is not triggered')
                if (status == -2):
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                                 'PXI 6368 DMA overflow')
                if (status == -3):
                    Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                                 'PXI 6368 Exception on acquisition function')
                self.error = self.ACQ_ERROR

            status = NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd))
            self.closeAll(chanFd, saveList)
Exemplo n.º 12
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:
            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.LOS_NUM + 1)]
            col = sheet['B']
            label_arr = [
                str(c.value if c != None else "") for c in col[1:len(col):1]
            ]

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

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

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

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

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

            param = 'diameter_str_arr'
            col = sheet['H']
            diameter_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]
            ]
            diameter_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 = 'diaphragm_str_arr'
            col = sheet['I']
            diaphragm_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]
            ]
            diaphragm_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 = 'P0_str_arr'
            matrix = sheet['J2':'L%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P0_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P0_str_arr = [str(c) for c in P0_arr]

            param = 'P1_str_arr'
            matrix = sheet['M2':'O%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P1_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P1_str_arr = [str(c) for c in P1_arr]

            param = 'roi_str_arr'
            col = sheet['P']
            roi_arr = [
                int(
                    str(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]
            ]
            roi_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 = 'spec_arr'
            col = sheet['Q']
            spec_arr = [
                str(c.value if c.value != None else "")
                for c in col[1:len(col):1]
            ]

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

            param = 'calib_flag_arr'
            col = sheet['S']
            calib_flag_arr = [
                str(c.value if c.value != None else "false").lower()
                for c in col[1:len(col):1]
            ]

            wb.close()

        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot read or invalid spectro 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.config_los_label.putData(StringArray(label_arr))
            field = 'telescope'
            self.config_los_telescope.putData(StringArray(telescope_arr))
            field = 'a_patch'
            self.config_los_a_patch.putData(StringArray(a_patch_arr))
            field = 'b_patch'
            self.config_los_b_patch.putData(StringArray(b_patch_arr))
            field = 'c_patch'
            self.config_los_c_patch.putData(StringArray(c_patch_arr))
            field = 'or_pannel'
            self.config_los_or_pannel.putData(StringArray(or_pannel_arr))
            field = 'diameter'
            self.config_los_diameter.putData(StringArray(diameter_str_arr))
            field = 'diaphragm'
            self.config_los_diaphragm.putData(StringArray(diaphragm_str_arr))
            field = 'P0'
            self.config_los_p0.putData(StringArray(P0_str_arr))
            field = 'P1'
            self.config_los_p1.putData(StringArray(P1_str_arr))
            field = 'roi'
            self.config_los_roi.putData(StringArray(roi_str_arr))
            field = 'spectrometer'
            self.config_los_spectrometer.putData(StringArray(spec_arr))
            field = 'note'
            self.config_los_note.putData(StringArray(note_arr))
            field = 'calib_flag'
            self.config_los_calib_flag.putData(StringArray(calib_flag_arr))
        except Exception as e:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing %s on LoS  : %s ' % (field, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        spectrometer_list = []
        for i in range(0, self.LOS_NUM):

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

            try:
                getattr(self, 'los_%03d_telescope' % (i + 1)).putData(
                    telescope_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing telescope field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_c_patch' % (i + 1)).putData(c_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing C patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_b_patch' % (i + 1)).putData(b_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing B patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_or_pannel' % (i + 1)).putData(
                    or_pannel_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing OR pannel field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_a_patch' % (i + 1)).putData(a_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing A patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_diameter' % (i + 1)).putData(diameter_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diameter field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_diaphragm' % (i + 1)).putData(
                    diaphragm_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diaphragm field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p0' % (i + 1)).putData(
                    Float32Array(P0_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing start point P0 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p1' % (i + 1)).putData(
                    Float32Array(P1_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing end point P1 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_roi' % (i + 1)).putData(roi_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing roi field on LoS %s ' % (i + 1) + str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_spectrometer' % (i + 1)).putData(spec_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing spectrometer field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

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

            try:
                getattr(self, 'los_%03d_calib_flag' % (i + 1)).putData(
                    calib_flag_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing calib flag field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                if label_arr[i] == 'None':
                    continue

                if len(spec_arr[i].strip()) == 0:
                    print(self.bcolors.OKBLUE +
                          'Info LoS %d (%s) acquisition not configured ' %
                          (i + 1, label_arr[i]) + self.bcolors.ENDC)
                    continue

                if self.getDeviceName(self.__getattr__(
                        '\\%s' % (spec_arr[i]))) == 'PI_SCT320':
                    # Set link LOS_xxx spectra to ROI_xx spectrometer
                    try:
                        # Reset current link
                        getattr(self,
                                'los_%03d_spectra_ref' % (i + 1)).deleteData()
                        if len(spec_arr[i]) > 0 and not (spec_arr[i]
                                                         in spectrometer_list):
                            for r in range(1, 25):
                                self.__getattr__(
                                    '\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                    (spec_arr[i], r)).deleteData()
                            # Register spectrometer already reset
                            spectrometer_list.append(spec_arr[i])

                        if roi_arr[i] == -1:
                            continue

                        spectraRoiNode = self.__getattr__(
                            '\\%s.ROIS.ROI_%02d:SPECTRA' %
                            (spec_arr[i], roi_arr[i]))
                        getattr(self, 'los_%03d_spectra_ref' %
                                (i + 1)).putData(spectraRoiNode)
                        self.__getattr__('\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                         (spec_arr[i], roi_arr[i])).putData(
                                             label_arr[i])

                        print(
                            self.bcolors.OKGREEN +
                            'Info LoS %d (%s) SPECTRO acquisition configured on Spectrometer %s Roi %d'
                            % (i + 1, label_arr[i], spec_arr[i], roi_arr[i]) +
                            self.bcolors.ENDC)

                    except Exception as e:
                        Data.execute(
                            'DevLogErr($1,$2)', self.getNid(),
                            'Error setting link from LoS %d (%s) to ROI %d on spectrometer %s : %s'
                            % (i + 1, label_arr[i], roi_arr[i], spec_arr[i],
                               str(e)))

                # spec_arr for photodiode is the Front End device BOARD
                elif self.getDeviceName(
                        self.__getattr__('\\%s' % (spec_arr[i]))) == 'PLFE':
                    # Set link LOS_xxx photodiode to Front End
                    try:
                        # Reset photodiode acquisitio channel link
                        getattr(self,
                                'los_%03d_photodiode' % (i + 1)).deleteData()

                        # ROI for phothodiode is the Front End Board channel and adc channel coded as NXX
                        # where N is the BOARD channel 1 or 2 and XX is adc channel from 1 to 32
                        if roi_arr[i] == -1:
                            continue

                        # From FE board path retrives FE BOARD index form 1 to 6
                        feBoardIdx = int(spec_arr[i][-1:])
                        if feBoardIdx < 1 or feBoardIdx > 6:
                            raise Exception(
                                'Invalid board index, valid values from 1 to 6'
                            )
                        code = int(roi_arr[i])

                        feBoardCh = code / 100  # ROI for front end identify the FE board channl 1 or 2
                        if feBoardCh != 1 and feBoardCh != 2:
                            raise Exception(
                                'Invalid board channel, valid values 1 or 2')

                        adcChan = code - feBoardCh * 100
                        if adcChan < 1 or adcChan > 32:
                            raise Exception(
                                'Invalid adc channel number %d for adc device define in front end device, valid values are from 1 to 32'
                                % (adcChan))

                        fePath = self.getDevice(
                            self.__getattr__('\\%s' %
                                             (spec_arr[i]))).getMinPath()
                        adcPath = (self.__getattr__(
                            '%s:ADC' % (fePath))).getData().getMinPath()

                        expr = Data.compile(
                            '%s.CHANNEL_%d:DATA / (%s.BOARD_%02d.SETUP.CHANNEL_%02d.WR:GAIN * (%s.BOARD_%02d.SETUP.CHANNEL_%02d.WR:TRANS == 0 ? 1 : 100))'
                            % (adcPath, adcChan, fePath, feBoardIdx, feBoardCh,
                               fePath, feBoardIdx, feBoardCh))

                        getattr(self,
                                'los_%03d_photodiode' % (i + 1)).putData(expr)

                        print(
                            self.bcolors.OKGREEN +
                            'Info LoS %d (%s) PHOTODIODE acquisition configured on Adc %s ch %d Front End %s Board %d Ch %d'
                            % (i + 1, label_arr[i], adcPath, adcChan, fePath,
                               feBoardIdx, feBoardCh) + self.bcolors.ENDC)

                    except Exception as e:
                        Data.execute(
                            'DevLogErr($1,$2)', self.getNid(),
                            'Error setting link from LoS %d (%s) to front end board %s : %s'
                            % (i + 1, label_arr[i], spec_arr[i], str(e)))
                else:
                    Data.execute(
                        'DevLogErr($1,$2)', self.getNid(),
                        'Invalid definition of spectrometer/front-end device (%s) for LoS %d (%s)'
                        % (spec_arr[i], i + 1, label_arr[i]))
            except Exception as e:
                print(str(e))
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error definition of spectrometer/front-end device (%s) for LoS %d (%s) : %s'
                    % (spec_arr[i], i + 1, label_arr[i], str(e)))
        return 1
Exemplo n.º 13
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:
            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.LOS_NUM + 1)]
            col = sheet['B']
            label_arr = [
                str(c.value if c != None else "") for c in col[1:len(col):1]
            ]

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

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

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

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

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

            param = 'diameter_str_arr'
            col = sheet['H']
            diameter_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]
            ]
            diameter_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 = 'diaphragm_str_arr'
            col = sheet['I']
            diaphragm_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]
            ]
            diaphragm_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 = 'P0_str_arr'
            matrix = sheet['J2':'L%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P0_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P0_str_arr = [str(c) for c in P0_arr]

            param = 'P1_str_arr'
            matrix = sheet['M2':'O%d' % (self.LOS_NUM + 1)]
            data_arr = [
                c.value for c in np.asarray(matrix).reshape(3 * self.LOS_NUM)
            ]
            P1_arr = np.array(data_arr, 'float32').reshape([self.LOS_NUM, 3])
            P1_str_arr = [str(c) for c in P1_arr]

            param = 'roi_str_arr'
            col = sheet['P']
            roi_arr = [
                int(
                    str(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]
            ]
            roi_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 = 'spec_arr'
            col = sheet['Q']
            spec_arr = [
                str(c.value if c.value != None else "")
                for c in col[1:len(col):1]
            ]

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

            param = 'calib_flag_arr'
            col = sheet['S']
            calib_flag_arr = [
                str(c.value if c.value != None else "false").lower()
                for c in col[1:len(col):1]
            ]

            wb.close()

        except Exception as e:
            Data.execute(
                'DevLogErr($1,$2)', self.getNid(),
                'Cannot read or invalid spectro 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.config_los_label.putData(StringArray(label_arr))
            field = 'telescope'
            self.config_los_telescope.putData(StringArray(telescope_arr))
            field = 'a_patch'
            self.config_los_a_patch.putData(StringArray(a_patch_arr))
            field = 'b_patch'
            self.config_los_b_patch.putData(StringArray(b_patch_arr))
            field = 'c_patch'
            self.config_los_c_patch.putData(StringArray(c_patch_arr))
            field = 'or_pannel'
            self.config_los_or_pannel.putData(StringArray(or_pannel_arr))
            field = 'diameter'
            self.config_los_diameter.putData(StringArray(diameter_str_arr))
            field = 'diaphragm'
            self.config_los_diaphragm.putData(StringArray(diaphragm_str_arr))
            field = 'P0'
            self.config_los_p0.putData(StringArray(P0_str_arr))
            field = 'P1'
            self.config_los_p1.putData(StringArray(P1_str_arr))
            field = 'roi'
            self.config_los_roi.putData(StringArray(roi_str_arr))
            field = 'spectrometer'
            self.config_los_spectrometer.putData(StringArray(spec_arr))
            field = 'note'
            self.config_los_note.putData(StringArray(note_arr))
            field = 'calib_flag'
            self.config_los_calib_flag.putData(StringArray(calib_flag_arr))
        except Exception as e:
            Data.execute('DevLogErr($1,$2)', self.getNid(),
                         'Error writing %s on LoS  : %s ' % (field, str(e)))
            raise mdsExceptions.TclFAILED_ESSENTIAL

        spectrometer_list = []
        for i in range(0, self.LOS_NUM):

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

            try:
                getattr(self, 'los_%03d_telescope' % (i + 1)).putData(
                    telescope_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing telescope field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_c_patch' % (i + 1)).putData(c_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing C patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_b_patch' % (i + 1)).putData(b_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing B patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_or_pannel' % (i + 1)).putData(
                    or_pannel_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing OR pannel field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_a_patch' % (i + 1)).putData(a_patch_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing A patch field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_diameter' % (i + 1)).putData(diameter_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diameter field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_diaphragm' % (i + 1)).putData(
                    diaphragm_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing diaphragm field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p0' % (i + 1)).putData(
                    Float32Array(P0_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing start point P0 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_p1' % (i + 1)).putData(
                    Float32Array(P1_arr[i]))
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing end point P1 field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self, 'los_%03d_roi' % (i + 1)).putData(roi_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing roi field on LoS %s ' % (i + 1) + str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            try:
                getattr(self,
                        'los_%03d_spectrometer' % (i + 1)).putData(spec_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing spectrometer field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

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

            try:
                getattr(self, 'los_%03d_calib_flag' % (i + 1)).putData(
                    calib_flag_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error writing calib flag field on LoS %s ' % (i + 1) +
                    str(e))
                raise mdsExceptions.TclFAILED_ESSENTIAL

            #Set link LOS_xxx spectra to ROI_xx spectrometer
            try:
                #Reset current link

                getattr(self, 'los_%03d_spectra_ref' % (i + 1)).deleteData()
                if len(spec_arr[i]) > 0 and not (spec_arr[i]
                                                 in spectrometer_list):
                    for r in range(1, 25):
                        self.__getattr__('\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                         (spec_arr[i], r)).deleteData()
                    spectrometer_list.append(spec_arr[i])

                if roi_arr[i] == -1:
                    continue

                spectraRoiNode = self.__getattr__(
                    '\\%s.ROIS.ROI_%02d:SPECTRA' % (spec_arr[i], roi_arr[i]))
                getattr(self, 'los_%03d_spectra_ref' %
                        (i + 1)).putData(spectraRoiNode)
                self.__getattr__('\\%s.ROIS.ROI_%02d:LOS_PATH' %
                                 (spec_arr[i], roi_arr[i])).putData(
                                     label_arr[i])
            except Exception as e:
                Data.execute(
                    'DevLogErr($1,$2)', self.getNid(),
                    'Error setting link from LoS %d (%s) to ROI %d on spectrometer %s : %s'
                    % (i + 1, label_arr[i], roi_arr[i], spec_arr[i], str(e)))

        return 1
Exemplo n.º 14
0
    def time_context(self):
        Tree.setTimeContext()  # test initPinoDb
        self.assertEqual(Tree.getTimeContext(), (None, None, None))
        with Tree(self.tree, self.shot + 5, 'NEW') as ptree:
            node = ptree.addNode('S')
            ptree.write()
        ptree.normal()
        for i in range(-90, 90, 30):
            d = Int64Array(range(30)) * 10 + i * 10
            v = Float32Array(range(30)) + i
            node.makeSegment(d[0], d[29], d, v)
        self.assertEqual(
            node.getSegmentList(200, 599).dim_of(0).tolist(), [0, 300])
        self.assertEqual(
            node.getSegmentList(200, 600).dim_of(0).tolist(), [0, 300, 600])
        self.assertEqual(
            node.getSegmentList(291, 600).dim_of(0).tolist(), [300, 600])
        self.assertEqual(node.record.data().tolist(), list(range(-90, 90)))

        sig = node.getXYSignal(xmin=0., xmax=3e-8, num=5)
        self.assertEqual(sig.data().tolist(), [0, 1, 2, 3])
        self.assertEqual(sig.dim_of().data().tolist(), [0, 10, 20, 30])

        node.tree.setTimeContext(Int64(300), Int64(700), Int64(150))
        Tree.setTimeContext(1, 2, 3)
        self.assertEqual(Tree.getTimeContext(), (1, 2, 3))
        self.assertEqual(node.tree.getTimeContext(), (300, 700, 150))

        set_default_resample_mode("m")  # minmax
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 44, 45, 59, 60, 74])
        self.assertEqual(sig.dim_of().data().tolist(),
                         [375, 375, 525, 525, 675, 675])

        set_default_resample_mode("i")  # interpolation
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 45, 60])
        self.assertEqual(sig.dim_of().data().tolist(), [300, 450, 600])

        node.setExtendedAttribute("ResampleMode", "Average")
        sig = node.record
        self.assertEqual(sig.data().tolist(), [37, 52, 67])
        self.assertEqual(sig.dim_of().data().tolist(), [375, 525, 675])

        node.setExtendedAttribute("ResampleMode", "MinMax")
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 44, 45, 59, 60, 74])
        self.assertEqual(sig.dim_of().data().tolist(),
                         [375, 375, 525, 525, 675, 675])

        node.setExtendedAttribute("ResampleMode", "INTERP")
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 45, 60])
        self.assertEqual(sig.dim_of().data().tolist(), [300, 450, 600])

        node.setExtendedAttribute("ResampleMode", "Previous")
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 44, 60])
        self.assertEqual(sig.dim_of().data().tolist(), [300, 450, 600])

        node.setExtendedAttribute("ResampleMode", "Closest")
        sig = node.record
        self.assertEqual(sig.data().tolist(), [30, 45, 60])
        self.assertEqual(sig.dim_of().data().tolist(), [300, 450, 600])

        node.tree.setTimeContext()
        self.assertEqual(node.tree.getTimeContext(), (None, None, None))
        self.assertEqual(node.record.data().tolist(), list(range(-90, 90)))
        self.assertEqual(Tree.getTimeContext(), (1, 2, 3))
        tdi('treeopen($,$)', self.tree, self.shot + 5)
        Tree.setTimeContext(1, 2, 3)  # test privacy to Tree
        self.assertEqual(Tree.getTimeContext(), (1, 2, 3))
        tdi('treeopennew($,$)', self.tree, self.shot + 6)
        self.assertEqual(Tree.getTimeContext(), (None, None, None))
        Tree.setTimeContext(2, 3, 4)  # test privacy to Tree
        self.assertEqual(Tree.getTimeContext(), (2, 3, 4))
        tdi('treeopen($,$)', self.tree, self.shot + 5)
        self.assertEqual(Tree.getTimeContext(), (1, 2, 3))
        tdi('treeclose()')
        self.assertEqual(Tree.getTimeContext(), (2, 3, 4))
        tdi('treeclose()')
        self.assertEqual(Tree.getTimeContext(), (2, 3, 4))
Exemplo n.º 15
0
        def run(self):

            # info
            self.device.setTree(
                Tree(self.device.getTree().name,
                     self.device.getTree().shot))
            self.device = self.device.copy()

            nid = self.device.getNid()
            chanModes = NI6368EV.ni6368chanModes[nid]
            chanEvents = NI6368EV.ni6368chanEvents[nid]
            chanPreTimes = NI6368EV.ni6368chanPreTimes[nid]
            chanPostTimes = NI6368EV.ni6368chanPostTimes[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  # c_types array
            coeff = coeff_array()  # initialization
            maxDelay = self.device.history_len.data()
            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()

            # channels arrays
            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):  #range(numChans)
                if chanModes[
                        chan] == 'CONTINUOUS(FREQ1)':  # continuous at a single frequence Freq1
                    isBurst_c[chan] = 0  # it is not a burst
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p('')  # no events
                elif chanModes[
                        chan] == 'CONTINUOUS(FREQ2)':  # continuous at a single frequence Freq2
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f2Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p('')
                elif chanModes[
                        chan] == 'BURST(FREQ1)':  # burst at a single frequence Freq1
                    isBurst_c[chan] = 1
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f1Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                    print("CHANEVENTS: " + eventNames_c[chan])
                elif chanModes[
                        chan] == 'BURST(FREQ2)':  # burst at a single frequence 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':  # switching frequence from F1 to F2 on defined period
                    isBurst_c[chan] = 0
                    f1Divs_c[chan] = f1Div
                    f2Divs_c[chan] = f2Div
                    eventNames_c[chan] = c_char_p(chanEvents[chan])
                elif chanModes[chan] == 'DISABLED':
                    continue
                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 = self.device.board_id.data()
                    if boardId > self.device.MAX_NUM_BOARDS:
                        boardId = Data.execute('getPxie6368BoarId(' +
                                               str(boardId) + ')')
                    # print('OPENING', '/dev/pxie-6368.'+str(boardId)+'.ai.'+str(self.hwChanMap[self.chanMap[chan]]))
                    currFd = os.open(
                        '/dev/pxie-6368.' + str(boardId) + '.ai.' +
                        str(self.hwChanMap[self.chanMap[chan]]),
                        os.O_RDWR | os.O_NONBLOCK)
                    # print("FD for "+ str(chan) + " is: "+ str(currFd))
                    chanFd.append(currFd)
                    # print('APERTO')
                except Exception as exc:
                    Data.execute(
                        'DevLogErr($1,$2)', self.device.getNid(),
                        'Cannot open Channel ' + str(self.chanMap[chan]) +
                        " : " + str(exc))
                    self.error = self.ACQ_ERROR
                    return

                chanNid.append(
                    getattr(self.device, 'channel_%d_data_raw' %
                            (self.chanMap[chan] + 1)).getNid())
                #self.device.debugPrint ('chanFd '+'channel_%d_data_raw'%(self.chanMap[chan]+1), chanFd[chan])

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

                # reading calibration params
                status = NI6368EV.niInterfaceLib.getCalibrationParams(
                    currFd, gain_code, coeff)
                if (status < 0):
                    errno = NI6368EV.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 / 32768.)
                print('SCRIVO CALIBRAZIONE', coeff)
                getattr(self.device, 'channel_%d_calib_param' %
                        (self.chanMap[chan] + 1)).putData(Float32Array(coeff))
                print('SCRITTO')

            # handling the buffer size for resampling
            if (bufSize > segmentSize):
                segmentSize = bufSize
            else:
                c = segmentSize / bufSize
                if (segmentSize % bufSize > 0):
                    c = c + 1
                segmentSize = c * bufSize

            # instantiating save list for mdsplus data
            saveList = c_void_p(0)
            NI6368EV.niInterfaceLib.startSaveEV(
                byref(saveList), c_char_p(self.device.getTree().name.lower()),
                c_int(self.device.getTree().shot))

            chanNid_c = (c_int * len(chanNid))(*chanNid)
            chanFd_c = (c_int * len(chanFd))(*chanFd)
            chanMap_c = (c_int * len(chanFd))(*self.chanMap)

            print("STARTING READ AND SAVE...")
            print("numChans : " + str(numChans) + " chanFd: " +
                  str(len(chanFd_c)) + " isBurst: " + str(len(isBurst_c)) +
                  " fiDivs: " + str(len(f1Divs_c)) + " preTimes: " +
                  str(len(preTimes_c)) + " EventNames: " +
                  str(len(eventNames_c)) + " chanNid: " + str(len(chanNid_c)))
            while not self.stopReq:
                try:
                    status = NI6368EV.niInterfaceLib.pxi6368EV_readAndSaveAllChannels(  # main function to handle data
                        self.ai_fd, c_int(numChans), chanMap_c, 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)

                except Exception as ex:
                    self.device.debugPrint(
                        'Acquisition thread start error : %s' % (str(ex)))
                    self.stopReq = True
                    status = -3

                if (status < 0):
                    if (status == -1):
                        Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                                     'PXI 6368 Module is not triggered')
                    if (status == -2):
                        Data.execute('DevLogErr($1,$2)', self.device.getNid(),
                                     'PXI 6368 DMA overflow')
                    if (status == -3):
                        Data.execute(
                            'DevLogErr($1,$2)', self.device.getNid(),
                            'PXI 6368 Exception on acquisition function')
                    self.error = self.ACQ_ERROR
                    self.stopReq = True

            # once stopReq received, stop the acquisition
            status = NI6368EV.niLib.xseries_stop_ai(c_int(self.ai_fd))
            self.closeAll(chanFd, saveList)
Exemplo n.º 16
0
        def run(self):
            bufSize = self.device.buf_size.data()
            segmentSize = self.device.seg_length.data()
            #counters = [0]*len(self.chanMap)
            boardId = self.device.board_id.data();
            acqMode = self.device.acq_mode.data()
            transientRec = False

            sampleToSkip = self.device.start_idx.data()
            #endIdx = self.device.end_idx.data()

            startTime = float( self.device.start_time.data() )
            #trigSource = self.device.trig_source.data()
            clockSource = self.device.clock_source.evaluate()

            frequency = float( clockSource.getDelta() )


            if( acqMode == 'TRANSIENT REC.'):
                transientRec = True

            chanFd = []
            chanNid = []

            coeff_array = c_float*4
            coeff = coeff_array();

            #NI6259AI.niInterfaceLib.getStopAcqFlag(byref(self.stopAcq));

            for chan in range(len(self.chanMap)):
                try:
                    #self.device.debugPrint 'CHANNEL', self.chanMap[chan]+1
                    #self.device.debugPrint '/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)

                    chanNid.append( getattr(self.device, 'channel_%d_data_raw'%(self.chanMap[chan]+1)).getNid() )
                    #self.device.debugPrint "chanFd "+'channel_%d_data'%(self.chanMap[chan]+1), chanFd[chan], " chanNid ", chanNid[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 = NI6259AI.niInterfaceLib.pxi6259_getCalibrationParams(currFd, gain_code, coeff, byref(n_coeff) )

                    if( status < 0 ):
                        errno = NI6259AI.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. )
		    
                    getattr(self.device, 'channel_%d_calib_param'%(self.chanMap[chan]+1)).putData(Float32Array(coeff))

                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 

            if( not transientRec ):

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

                numSamples  = -1
                self.device.debugPrint("PXI 6259 CONTINUOUS ", numSamples)

            else:
                NI6259AI.niInterfaceLib.setStopAcqFlag(self.stopAcq);

                try:
                    numSamples = self.device.end_idx.data() - self.device.start_idx.data()
                except:
                    numSamples = 0
                    self.device.debugPrint("PXI 6259 NUM SAMPLES ", numSamples)


            status = NI6259AI.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)
            NI6259AI.niInterfaceLib.startSave(byref(saveList))
            #count = 0

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

            #timeAt0 = trigSource + startTime
            #self.device.debugPrint("PXI 6259 TIME AT0 ", numSamples)            
            timeAt0 = startTime

            while not self.stopReq:
                status = NI6259AI.niInterfaceLib.pxi6259_readAndSaveAllChannels(c_int(len(self.chanMap)), chanFd_c, c_int(bufSize), c_int(segmentSize), c_int(sampleToSkip), c_int(numSamples), c_float( timeAt0 ), c_float(frequency), chanNid_c, self.device.clock_source.getNid(), self.treePtr, saveList, self.stopAcq)

   ##Check termination
                if ( numSamples > 0 or (transientRec and status == -1) ):
                    self.stopReq = True


            if( transientRec and status == -1 ):
                Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'PXI 6259 Module is not in stop state')
                self.error = self.ACQ_ERROR

            status = NI6259AI.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'
            NI6259AI.niInterfaceLib.stopSave(saveList)
            NI6259AI.niInterfaceLib.freeStopAcqFlag(self.stopAcq)
            self.device.closeInfo()

            return 
Exemplo n.º 17
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(
                            Float32Array(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