Пример #1
0
    def set_data_test(self, data_shape='3D'):

        x = utils.linspace_step(0, 20, 1)
        y = utils.linspace_step(0, 30, 1)
        t = utils.linspace_step(0, 200, 1)
        z = utils.linspace_step(0, 200, 1)
        datas = np.zeros((len(y), len(x), len(t), len(z)))
        amp = utils.gauss2D(x, 7, 5, y, 12, 10)
        for indx in range(len(x)):
            for indy in range(len(y)):
                datas[indy, indx, :, :] = amp[indy, indx] * (
                            utils.gauss2D(z, 50 + indx * 2, 20, t, 50 + 3 * indy, 30) + np.random.rand(len(t),
                                                                                                       len(z)) / 10)

        nav_axis = dict(nav00=Axis(data=y, nav_index=0, label='y_axis', units='yunits'),
                    nav01=Axis(data=x, nav_index=1, label='x_axis', units='xunits'),
                    nav02=Axis(data=t, nav_index=2, label='t_axis', units='tunits'),
                    nav03=Axis(data=z, nav_index=3, label='z_axis', units='zunits'))

        if data_shape == '4D':
            nav_axes = [2, 3]
            self.show_data(datas, temp_data=False, nav_axes=nav_axes, **nav_axis)
        elif data_shape == '3D':
            self.show_data(np.sum(datas, axis=3), temp_data=False, nav_axes=[0, 1], **nav_axis)
        elif data_shape == '2D':
            self.show_data(np.sum(datas, axis=(2, 3)), **nav_axis)
        elif data_shape == '1D':
            self.show_data(np.sum(datas, axis=(1, 2, 3)), **nav_axis)
Пример #2
0
    def get_xaxis(self):
        """
            Obtain the horizontal axis of the image.

            Returns
            -------
            1D numpy array
                Contains a vector of integer corresponding to the horizontal camera pixels.
        """
        if self.controller is not None:
            # if self.control_type == "camera":
            Nx = self.settings.child('camera_settings', 'image_size',
                                     'Nx').value()
            self.x_axis = Axis(data=np.linspace(0, Nx - 1, Nx, dtype=np.int),
                               label='Pixels')

            if self.control_type == "shamrock" or self.control_type == "both" and self.CCDSIZEX is not None:
                (err,
                 calib) = self.controller.GetCalibrationSR(0, self.CCDSIZEX)
                calib = np.array(calib)
                if self.settings.child('camera_settings', 'readout').value(
                ) == Orsay_Camera_ReadOut['Image'].name:
                    binx = self.settings.child('camera_settings',
                                               'readout_settings',
                                               'image_settings',
                                               'bin_x').value()
                    startx = self.settings.child('camera_settings',
                                                 'readout_settings',
                                                 'image_settings',
                                                 'im_startx').value()
                    endx = self.settings.child('camera_settings',
                                               'readout_settings',
                                               'image_settings',
                                               'im_endx').value()
                    calib = calib[startx:endx + 1:binx]

                if (calib.astype('int') !=
                        0).all():  # check if calib values are equal to zero
                    if self.settings.child('spectro_settings',
                                           'flip_wavelength').value():
                        calib = calib[::-1]

                    self.x_axis = Axis(data=calib, label='Wavelength (nm)')

            self.emit_x_axis()
        else:
            raise (Exception('controller not defined'))
        return self.x_axis
Пример #3
0
    def restore_nav_axes(self, navigation_axes, nav_axes=None):
        if nav_axes is None:
            N_nav_axes = len(self.datas.data.shape)
        else:
            N_nav_axes = len(nav_axes)
        nav_axes_dicts = []
        sorted_indexes = []
        for k in navigation_axes:
            if 'nav' in k:
                if navigation_axes[k]['nav_index'] < N_nav_axes:
                    sorted_indexes.append(navigation_axes[k]['nav_index'])
                    nav_axes_dicts.append(copy.deepcopy(navigation_axes[k]))

        for ind in range(N_nav_axes):  # in case there was no nav axes in kwargs
            if ind not in sorted_indexes:
                sorted_indexes.append(ind)
                nav_axes_dicts.append(Axis(nav_index=ind, label=f'Nav {ind:02d}'))
                N = self.datas.data.shape[ind]
                nav_axes_dicts[-1]['data'] = np.linspace(0, N-1, N)

        # sort nav axes:
        sorted_index = np.argsort(sorted_indexes)
        self.nav_axes_dicts = []
        for ind in sorted_index:
            self.nav_axes_dicts.append(nav_axes_dicts[ind])
Пример #4
0
 def grab_data(self, Naverage=1, **kwargs):
     """
     """
     Naverage = 1
     if not self.controller_ready:
         ret = self.controller.prepare_N_acquisition(
             self.settings.child('acq_params', 'npts_map').value())
         if ret == 'ready':
             self.controller_ready = True
         else:
             self.emit_status(
                 ThreadCommand(
                     'Update_Status',
                     ['Spectrometer not ready to grab data...', 'log']))
     if self.controller_ready:
         data = self.controller.grab_spectrum()
     else:
         data = self.controller.wavelength_axis * 0
     if data is None:
         self.emit_status(
             ThreadCommand('Update_Status',
                           ['No data from spectrometer', 'log']))
         data = self.controller.wavelength_axis * 0
     self.data_grabed_signal.emit([
         DataFromPlugins(name='LabSpec6',
                         data=[data],
                         dim='Data1D',
                         x_axis=Axis(data=self.controller.wavelength_axis,
                                     units='nm',
                                     label='Wavelength'))
     ])
    def grab_data(self, Naverage=1, **kwargs):
        """
            | Start new acquisition.
            | grab the current values with keithley profile procedure.
            | Send the data_grabed_signal once done.

            =============== ======== ===============================================
            **Parameters**  **Type**  **Description**
            *Naverage*      int       Number of values to average
            =============== ======== ===============================================
        """
        data_tot = []
        x_axis = None
        for ind, channel in enumerate(
                self.settings.child(('channels')).value()['selected']):
            if ind == 0:
                x_axis, data_tmp = self.read_channel_data(channel,
                                                          x_axis_out=True)
            else:
                data_tmp = self.read_channel_data(channel, x_axis_out=False)
            data_tot.append(data_tmp)

        self.data_grabed_signal.emit([
            DataFromPlugins(name='Tektronix',
                            data=data_tot,
                            dim='Data1D',
                            x_axis=Axis(data=x_axis, label='Time', units='s'))
        ])
Пример #6
0
    def __init__(
        self,
        parent=None,
        params_state=None
    ):  # init_params is a list of tuple where each tuple contains info on a 1D channel (Ntps,amplitude, width, position and noise)
        super().__init__(parent, params_state)

        self.x_axis = Axis(label='photon wavelength', units='nm')
        self.ind_data = 0
    def emit_data(self, data):
        channels_name = [ch.name for ch in self.channels]
        data_tot = []

        if self.settings.child('diodes').value():
            for ind in range(len(self.channels)):
                data_tot.append(np.array([np.mean(data[ind*self.Nsamples:(ind+1)*self.Nsamples])]))
            self.data_grabed_signal.emit([DataFromPlugins(name='NI AI', data=data_tot, dim='Data0D',
                                          labels=channels_name)])
        else:
            for ind in range(len(self.channels)):
                data_tot.append(data[ind*self.Nsamples:(ind+1)*self.Nsamples])

            ind_cycles = self.settings.child('Ncycles').value()
            if self.settings.child('plot_cycles').value():
                Bfield = data_tot[0] / self.settings.child('resistance').value() * \
                    self.settings.child('solenoid').value()
                delta_diode = data_tot[1]
                diode = (data_tot[2] + data_tot[3]) / 2
            else:
                length = int(1 / self.settings.child('frequency_magnet').value() *
                    self.settings.child('frequency').value())
                Bfields = [data_tot[0][ind*length:(ind+1)*length] / self.settings.child('resistance').value() *
                    self.settings.child('solenoid').value() for ind in range(4)]
                delta_diodes = [data_tot[1][ind*length:(ind+1)*length] for ind in range(4)]
                diodes = [(data_tot[2][ind*length:(ind+1)*length] + data_tot[3][ind*length:(ind+1)*length]) / 2
                          for ind in range(4)]
                if self.settings.child('average_cycles').value():
                    Bfield = np.mean(np.array(Bfields[ind_cycles:]), 0)
                    delta_diode = np.mean(np.array(delta_diodes[ind_cycles:]), 0)
                    diode = np.mean(np.array(diodes[ind_cycles:]), 0)
                else:
                    Bfield = Bfields[ind_cycles]
                    delta_diode = delta_diodes[ind_cycles]
                    diode = diodes[ind_cycles]

            rotation = 180 / np.pi / (self.settings.child('gain').value() * 4) * np.arctan(delta_diode / diode)

            self.data_grabed_signal.emit([DataFromPlugins(name='NI AI', data=[Bfield, rotation], dim='Data1D',
                                          labels=['Bfield', 'Rotation'],
                                          x_axis=Axis(data=np.linspace(0, self.Nsamples /
                                                                       self.clock_settings_ai.frequency, self.Nsamples),
                                          label='Time', units='s'))])
    def ini_detector(self, controller=None):
        """
            Initialisation procedure of the detector updating the status dictionnary.

            See Also
            --------
            set_Mock_data, daq_utils.ThreadCommand
        """
        self.status.update(edict(initialized=False,info="",x_axis=None,y_axis=None,controller=None))
        try:

            if self.settings.child(('controller_status')).value()=="Slave":
                if controller is None: 
                    raise Exception('no controller has been defined externally while this detector is a slave one')
                else:
                    self.controller = controller
            else:
                self.controller = Labspec6Client()
                ret, data, extra = self.controller.connect(self.settings.child('connection', 'ip_address').value(),
                                                           self.settings.child('connection', 'port').value())
                if ret != 'OK':
                    raise IOError('Wrong return from Server')
                self.settings.child('connection',  'controllerid').setValue(data)

            self.controller.timeout_mult = self.settings.child('connection', 'timeout').value()
            self.init_params()

            # initialize viewers with the future type of data
            self.x_axis = self.controller.get_x_axis()

            self.data_grabed_signal_temp.emit([DataFromPlugins(name='LabSpec6', data=[self.x_axis*0], dim='Data1D',
                x_axis=Axis(data=self.x_axis, units='nm', label='Wavelength'), labels=['Spectrum']),])

            self.status.initialized = True
            self.status.controller = self.controller
            self.status.x_axis = self.x_axis
            return self.status

        except Exception as e:
            self.emit_status(ThreadCommand('Update_Status', [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status
Пример #9
0
    def get_yaxis(self):
        """
            Obtain the vertical axis of the image.

            Returns
            -------
            1D numpy array
                Contains a vector of integer corresponding to the vertical camera pixels.
        """
        if self.controller is not None:

            Ny = self.settings.child('camera_settings', 'image_size',
                                     'Ny').value()
            self.y_axis = Axis(data=np.linspace(0, Ny - 1, Ny, dtype=np.int),
                               label='Pixels')
            self.emit_y_axis()
        else:
            raise (Exception('Camera not defined'))
        return self.y_axis
Пример #10
0
    def grab_data(self, Naverage=1, **kwargs):
        """
            | Start new acquisition.
            | Grab the current values.
            | Send the data_grabed_signal once done.

            =============== ======== ===============================================
            **Parameters**  **Type**  **Description**
            *Naverage*      int       Number of values to average
            =============== ======== ===============================================
        """
        channel = self.settings.child(('channels')).value()['selected']

        # The WaitForOPC method is used to wait for previous commands to be interpreted before continuing
        # It may be not needed here
        if not self.controller.WaitForOPC():
            raise Exception("Wait for OPC error")

        waveform = self.controller.GetScaledWaveformWithTimes(
            channel[0], 1e8, 0)

        # The ErrorFlag property checks that there is no error concerning ActiveDSO.
        # If the user changes some parameters on the oscilloscope (for example the horizontal scale) while pymodaq
        # acquisition is running, it will raise this error. We do not know how to deal with this problem.
        # If the error is raised you will probably have to restart the oscilloscope to get the communication back.
        # Restarting can be done with a little script using the DeviceClear(True) method of ActiveDSO. It is much
        # faster than doing it manually.
        #
        # To prevent the error, the user should use the STOP button on pymodaq GUI, then change the parameter of his
        # choice on the oscilloscope and then RUN pymodaq acquisition.
        if self.controller.ErrorFlag:
            raise Exception(self.controller.ErrorString)

        x_axis = np.array(waveform[0])
        data = [np.array(waveform[1])]

        self.data_grabed_signal.emit([
            DataFromPlugins(name='Lecroy Waverunner 6Zi',
                            data=data,
                            dim='Data1D',
                            x_axis=Axis(data=x_axis, label='Time', units='s'))
        ])
Пример #11
0
    def average_data(self, Naverage):
        data_tmp = np.zeros_like(self.image)
        for ind in range(Naverage):
            data_tmp += self.set_Mock_data()
        data_tmp = data_tmp / Naverage

        data = [
            DataFromPlugins(name='MockND_{:d}'.format(ind),
                            data=[data_tmp],
                            dim='DataND',
                            nav_axes=(1, 0),
                            nav_x_axis=NavAxis(data=self.x_axis,
                                               label='X space',
                                               nav_index=1),
                            nav_y_axis=NavAxis(data=self.y_axis,
                                               label='Y space',
                                               nav_index=0),
                            x_axis=Axis(data=self.time_axis,
                                        label='time label'))
        ]
        return data
Пример #12
0
    def set_data(self, datas_transposed, temp_data=False, restore_nav_axes=True, **kwargs):
        """
        """
        try:

            if restore_nav_axes:
                nav_axes = dict([])
                for ind, ax in enumerate(self.nav_axes_dicts):
                    nav_axes[f'nav_{ind}'] = ax
                self.restore_nav_axes(nav_axes)

            ##########################################################################
            #display the correct signal viewer
            if len(datas_transposed.axes_manager.signal_shape) == 0: #signal data are 0D
                self.ui.viewer1D.parent.setVisible(True)
                self.ui.viewer2D.parent.setVisible(False)
            elif len(datas_transposed.axes_manager.signal_shape) == 1: #signal data are 1D
                self.ui.viewer1D.parent.setVisible(True)
                self.ui.viewer2D.parent.setVisible(False)
            elif len(datas_transposed.axes_manager.signal_shape) == 2: #signal data are 2D
                self.ui.viewer1D.parent.setVisible(False)
                self.ui.viewer2D.parent.setVisible(True)
            self.x_axis = Axis()
            self.y_axis = Axis()
            if len(datas_transposed.axes_manager.signal_shape) == 1 or len(datas_transposed.axes_manager.signal_shape) == 2:#signal data are 1D

                if 'x_axis' in kwargs:
                    if not isinstance(kwargs['x_axis'], dict):
                        self.x_axis['data'] = kwargs['x_axis'][:]
                        self.x_axis = kwargs['x_axis']
                    else:
                        self.x_axis = copy.deepcopy(kwargs['x_axis'])
                else:
                    self.x_axis['data'] = self.set_axis(datas_transposed.axes_manager.signal_shape[0])
                if 'y_axis' in kwargs:
                    self.ui.viewer1D.set_axis_label(axis_settings=dict(orientation='left',
                                                                       label=kwargs['y_axis']['label'],
                                                                       units=kwargs['y_axis']['units']))


            if len(datas_transposed.axes_manager.signal_shape)==2:#signal data is 2D
                if 'y_axis' in kwargs:
                    if not isinstance(kwargs['y_axis'], dict):
                        self.y_axis['data'] = kwargs['y_axis'][:]
                        self.y_axis = kwargs['y_axis']
                    else:
                        self.y_axis = copy.deepcopy(kwargs['y_axis'])
                else:
                    self.y_axis['data'] = self.set_axis(datas_transposed.axes_manager.signal_shape[1])

            axes_nav = self.get_selected_axes_indexes()
            if len(axes_nav) == 0 or len(axes_nav) == 1:
                self.update_viewer_data(*self.ui.navigator1D.ui.crosshair.get_positions())
            elif len(axes_nav) == 2:
                self.update_viewer_data(*self.ui.navigator2D.ui.crosshair.get_positions())



            ##get ROI bounds from viewers if any
            ROI_bounds_1D=[]
            try:
                self.ROI1D.getRegion()
                indexes_values = utils.find_index(self.ui.viewer1D.x_axis, self.ROI1D.getRegion())
                ROI_bounds_1D.append(QPointF(indexes_values[0][0], indexes_values[1][0]))
            except Exception as e:
                logger.warning(str(e))

            ROI_bounds_2D = []
            try:
                ROI_bounds_2D.append(QRectF(self.ROI2D.pos().x(), self.ROI2D.pos().y(),
                                            self.ROI2D.size().x(), self.ROI2D.size().y()))
            except Exception as e:
                logger.warning(str(e))

            #############################################################
            # display the correct navigator viewer and set some parameters
            if len(axes_nav) <= 2:
                for view in self.nav_axes_viewers:
                    self.ui.nav_axes_widget.layout().removeWidget(view.parent)
                    view.parent.close()
                self.nav_axes_viewers = []

            nav_axes = self.get_selected_axes()

            if len(nav_axes) == 0:  # no Navigator
                self.ui.navigator1D.parent.setVisible(False)
                self.ui.navigator2D.parent.setVisible(False)
                #self.navigator_label.setVisible(False)
                self.ui.nav_axes_widget.setVisible(False)
                self.ROI1D.setVisible(False)
                self.ROI2D.setVisible(False)
                navigator_data = []


            elif len(nav_axes) == 1:  # 1D Navigator
                self.ROI1D.setVisible(True)
                self.ROI2D.setVisible(True)
                self.ui.navigator1D.parent.setVisible(True)
                self.ui.navigator2D.parent.setVisible(False)
                self.ui.nav_axes_widget.setVisible(False)
                #self.navigator_label.setVisible(True)
                self.ui.navigator1D.remove_plots()
                self.ui.navigator1D.x_axis = nav_axes[0]

                labels = []
                units = []
                if self.scan_type.lower() == 'tabular' or self.is_spread:
                    if 'datas' in self.nav_axes_dicts[0]:
                        navigator_data = self.nav_axes_dicts[0]['datas'][:]
                        if 'labels' in self.nav_axes_dicts[0]:
                            labels = self.nav_axes_dicts[0]['labels'][:]
                        if 'all_units' in self.nav_axes_dicts[0]:
                            units = self.nav_axes_dicts[0]['all_units'][:]
                    else:
                        navigator_data = [self.nav_axes_dicts[0]['data']]
                    if self.is_spread:
                        if self.scan_type.lower() == 'tabular':
                            data_spread = []
                            for ind_label, lab in enumerate(labels):
                                if 'curvilinear' in lab.lower():
                                    data_spread = [self.nav_axes_dicts[0]['datas'][ind]]
                        else:
                            data_spread = self.nav_axes_dicts[0]['datas'][:]

                        data_spread.append(self.get_nav_data(datas_transposed, ROI_bounds_1D, ROI_bounds_2D)[0])
                        data_spread = np.vstack(data_spread).T

                else:
                    navigator_data = self.get_nav_data(datas_transposed, ROI_bounds_1D, ROI_bounds_2D)

                if self.is_spread:
                    self.ui.spread_viewer_2D.parent.setVisible(data_spread.shape[1] == 3)
                    self.ui.spread_viewer_1D.parent.setVisible(data_spread.shape[1] == 2)
                    if data_spread.shape[1] == 3:
                        self.ui.spread_viewer_2D.setImage(data_spread=data_spread)
                        if len(labels) > 1 and len(units) > 1:
                            self.ui.spread_viewer_2D.set_axis_label(dict(orientation='bottom', label=labels[0],
                                                                         units=units[0]))
                            self.ui.spread_viewer_2D.set_axis_label(dict(orientation='left', label=labels[1],
                                                                         units=units[1]))
                    else:
                        ind_sorted = np.argsort(data_spread[:, 0])
                        self.ui.spread_viewer_1D.show_data([data_spread[:, 1][ind_sorted]], labels=['data'],
                                                           x_axis=data_spread[:, 0][ind_sorted])
                        self.ui.spread_viewer_1D.set_axis_label(dict(orientation='bottom',
                                                                     label='Curvilinear value', units=''))

                if temp_data:
                    self.ui.navigator1D.show_data_temp(navigator_data)
                    self.ui.navigator1D.update_labels(labels)
                else:
                    self.ui.navigator1D.show_data(navigator_data)
                    self.ui.navigator1D.update_labels(labels)

            elif len(nav_axes) == 2:#2D Navigator:
                self.ROI1D.setVisible(True)
                self.ROI2D.setVisible(True)

                self.ui.navigator1D.parent.setVisible(False)
                self.ui.navigator2D.parent.setVisible(True)
                self.ui.nav_axes_widget.setVisible(False)
                #self.navigator_label.setVisible(True)


                self.ui.navigator2D.x_axis = nav_axes[0]
                self.ui.navigator2D.y_axis = nav_axes[1]

                navigator_data = self.get_nav_data(datas_transposed, ROI_bounds_1D, ROI_bounds_2D)

                if temp_data:
                    self.ui.navigator2D.setImageTemp(*navigator_data)
                else:
                    self.ui.navigator2D.setImage(*navigator_data)


            else: #more than 2 nv axes, display all nav axes in 1D plots

                self.ui.navigator1D.parent.setVisible(False)
                self.ui.navigator2D.parent.setVisible(False)
                self.ui.nav_axes_widget.setVisible(True)
                if len(self.nav_axes_viewers) != len(axes_nav):
                    for view in self.nav_axes_viewers:
                        self.ui.nav_axes_widget.layout().removeWidget(view.parent)
                        view.parent.close()
                    widgets = []
                    self.nav_axes_viewers = []
                    for ind in range(len(axes_nav)):
                        widgets.append(QtWidgets.QWidget())
                        self.ui.nav_axes_widget.layout().addWidget(widgets[-1])
                        self.nav_axes_viewers.append(Viewer1DBasic(widgets[-1], show_line=True))

                for ind in range(len(axes_nav)):
                    self.nav_axes_viewers[ind].roi_line_signal.connect(self.update_viewer_data)
                    self.nav_axes_viewers[ind].show_data([nav_axes[ind]['data']])
                    self.nav_axes_viewers[ind].set_axis_label(dict(orientation='bottom',
                                                                  label=nav_axes[ind]['label'],
                                                                  units=nav_axes[ind]['units']))

            self.update_viewer_data()

        except Exception as e:
            logger.exception(str(e))
            self.update_status(utils.getLineInfo() + str(e), self.wait_time, 'log')
    def ini_detector(self, controller=None):
        """
            Initialisation procedure of the detector updating the status dictionnary.

            See Also
            --------
            set_Mock_data, daq_utils.ThreadCommand
        """
        self.status.update(
            edict(initialized=False,
                  info="",
                  x_axis=None,
                  y_axis=None,
                  controller=None))
        try:
            #open spectro, check and set spectro connected, check and set min max exposure

            if self.settings.child(('controller_status')).value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while this detector is a slave one'
                    )
                else:
                    self.controller = controller
            else:
                self.controller = self.omnidriver.NETWrapper()

            N = self.controller.openAllSpectrometers()
            self.settings.child('Nspectrometers').setValue(N)
            self.spectro_names = []
            self.spectro_id = []
            data_init = []
            for ind_spectro in range(N):
                name = self.controller.getName(ind_spectro)
                self.spectro_names.append(name)
                self.spectro_id.append('spectro{:d}'.format(ind_spectro))

                exp_max = self.controller.getMaximumIntegrationTime(
                    ind_spectro)
                exp_min = self.controller.getMinimumIntegrationTime(
                    ind_spectro)
                exp = self.controller.getIntegrationTime(ind_spectro) / 1000
                wavelengths = self.get_xaxis(ind_spectro)
                data_init.append(
                    DataFromPlugins(name=name,
                                    data=[np.zeros_like(wavelengths)],
                                    dim='Data1D',
                                    x_axis=Axis(data=wavelengths,
                                                label='Wavelength',
                                                units='nm')))
                for ind in range(
                        2
                ):  #this is to take into account that adding it once doen't work (see pyqtgraph Parameter...)
                    try:
                        self.settings.child(('spectrometers')).addChild({
                            'title':
                            name,
                            'name':
                            'spectro{:d}'.format(ind_spectro),
                            'type':
                            'group',
                            'children': [
                                {
                                    'title': 'grab spectrum:',
                                    'name': 'grab',
                                    'type': 'bool',
                                    'value': True
                                },
                                {
                                    'title': 'Exposure time (ms):',
                                    'name': 'exposure_time',
                                    'type': 'int',
                                    'value': int(exp),
                                    'min': int(exp_min / 1000),
                                    'max': int(exp_max / 1000)
                                },
                            ]
                        })
                    except:
                        pass

                QtWidgets.QApplication.processEvents()
            #init viewers
            if N == 0:
                raise Exception('No detected hardware')
            self.data_grabed_signal_temp.emit(data_init)

            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status
    def ini_detector(self, controller=None):
        """Detector communication initialization

        Parameters
        ----------
        controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if only one detector by controller (Master case)

        Returns
        -------
        self.status (edict): with initialization status: three fields:
            * info (str)
            * controller (object) initialized controller
            *initialized: (bool): False if initialization failed otherwise True
        """

        try:
            self.status.update(
                edict(
                    initialized=False,
                    info="",
                    x_axis=None,
                    y_axis=None,
                    controller=None,
                ))
            if self.settings.child("controller_status").value() == "Slave":
                if controller is None:
                    raise Exception(
                        "no controller has been defined externally while this detector is a slave one"
                    )
                else:
                    self.controller = controller
            else:
                devices = usb.core.find(
                    find_all=True,
                    idVendor=sn.StellarNet._STELLARNET_VENDOR_ID,
                    idProduct=sn.StellarNet._STELLARNET_PRODUCT_ID,
                )
                devices_count = len(list(devices))
                if devices_count > 1:
                    print(
                        "Warning, several Stellarnet devices found. I'll load the first one only."
                    )
                elif devices_count == 0:
                    raise Exception("No device was found")

                self.controller = sn.StellarNet(
                    devices[0])  # Instance of StellarNet class
                self.settings.child("spectrometer_model").setValue(
                    self.controller._config["model"])
                self.settings.child("spectrometer_id").setValue(
                    self.controller._config["device_id"])
                setattr(
                    self.controller,
                    "window_width",
                    self.settings.child("x_smooth").value(),
                )

            # get the x_axis (you may want to to this also in the commit settings if x_axis may have changed
            data_x_axis = self.get_wl_axis()
            self.x_axis = [
                Axis(data=data_x_axis, label="Wavelength", units="m")
            ]
            self.emit_x_axis()

            # initialize viewers pannel with the future type of data
            name = usb.util.get_string(self.controller._device, 100,
                                       self.controller._device.iProduct)
            data_init = [(DataFromPlugins(
                name=name,
                dim="Data1D",
                data=[np.asarray(self.controller.read_spectrum())],
                x_axis=Axis(data=data_x_axis, label="Wavelength", units="m"),
            ))]
            QtWidgets.QApplication.processEvents()
            self.data_grabed_signal_temp.emit(data_init)
            self.data_grabed_signal_temp.emit(
                data_init)  # works the second time for some reason

            try:
                self.do_irradiance_calibration()
            except Exception as e:
                self.emit_status(
                    ThreadCommand("Update_Status",
                                  [getLineInfo() + str(e), "log"]))

            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand("Update_Status",
                              [getLineInfo() + str(e), "log"]))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status
Пример #15
0

if __name__ == '__main__':
    from pymodaq.QtDesigner_Ressources import QtDesigner_ressources_rc

    from pymodaq.daq_utils.gui_utils import DockArea
    from pymodaq.daq_utils.daq_utils import ScalingOptions, ScaledAxis, Axis
    import sys
    import numpy as np

    app = QtWidgets.QApplication(sys.argv)
    area = DockArea()
    win = QtWidgets.QMainWindow()
    win.setCentralWidget(area)
    viewer = ViewerPointList(area)

    Nx = 100
    Ny = 200
    x = (np.linspace(0, Nx - 1, Nx) + 100) / 2
    y = (np.linspace(0, Ny - 1, Ny) - 10) * 2
    from pymodaq.daq_utils.daq_utils import gauss2D

    data_red = 3 * gauss2D(x, 0.2 * Nx, Nx / 5, y, 0.3 * Ny, Ny / 5, 1, 90)

    viewer.setData(data_red)
    viewer.setXaxis(Axis(data=x, label='This is x axis', units='au'))
    viewer.setYaxis(Axis(data=y, label='This is y axis', units='au'))
    win.show()
    app.processEvents()
    sys.exit(app.exec_())
Пример #16
0
    def ini_detector(self, controller=None):
        """Detector communication initialization

        Parameters
        ----------
        controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if only one detector by controller (Master case)

        Returns
        -------
        self.status (edict): with initialization status: three fields:
            * info (str)
            * controller (object) initialized controller
            *initialized: (bool): False if initialization failed otherwise True
        """

        try:
            self.status.update(
                edict(initialized=False,
                      info="",
                      x_axis=None,
                      y_axis=None,
                      controller=None))
            if self.settings.child('controller_status').value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while this detector is a slave one'
                    )
                else:
                    self.controller = controller
            else:
                # From what I understand this will just get the spectro currently selected in the list
                dvc = self.settings.child('device').value()
                self.controller = Spectrometer(dvc)
                self.controller.open()
                #####################################

            # Oceanoptics spectrometers (at least the ones i Know) have fixed axis
            # get inactive pixels
            c0 = self.controller.f.spectrometer.get_electric_dark_pixel_indices(
            )[-1]
            self.settings.child('advanced').child('dark_channels').setValue(c0)
            # get the x_axis
            data_x_axis = self.controller.wavelengths(
            )  # Way to get the x axis
            data_x_axis = data_x_axis[c0:]  # Get rid of the dark pixels
            self.x_axis = Axis(data=data_x_axis,
                               label='wavelength',
                               units='nm')
            self.emit_x_axis()

            # Get the name
            specname = f"Ocean Insight {self.controller.model}"

            # initialize viewers pannel with the future type of data
            self.data_grabed_signal_temp.emit([
                DataFromPlugins(name=specname,
                                data=[np.zeros_like(data_x_axis)],
                                dim='Data1D',
                                labels=['Intensity'],
                                x_axis=self.x_axis),
            ])

            # Update the parameters
            # Here we need to do a few things. Get the integration time limits and set it in the settings
            tlimits = np.array(
                self.controller.integration_time_micros_limits) / 1000
            self.settings.child('integration').setLimits(tlimits)
            # Here we need to update the advanced parameters
            advanced_settings = self.settings.child('advanced')
            sn = self.controller.serial_number
            advanced_settings.child('serial_number').setValue(sn)
            # non linearity coefficients
            nlc_feat = self.controller.f.nonlinearity_coefficients
            if nlc_feat is not None and not any(
                    np.isnan(nlc_feat.get_nonlinearity_coefficients())):
                advanced_settings.child('correct_non_linearity').setValue(True)
            else:
                advanced_settings.child('correct_non_linearity').setValue(
                    False)
                advanced_settings.child('correct_non_linearity').setOpts(
                    enabled=False)

            # measure the readout time
            Nperf = 200
            self.settings.child('integration').setValue(
                tlimits[0])  # Update the parameter value to the lower limit
            self.controller.integration_time_micros(
                tlimits[0] * 1000)  # Set the readout time to lower limit
            perf = timeit(lambda: self.controller.intensities(),
                          number=Nperf)  # time the execution of code in [s]
            self.settings.child('advanced').child('readout_time').setValue(
                1000 * perf / Nperf)  # set the settings

            ##############################

            self.status.info = f"Initialized {specname} spectrometer"
            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status
    def ini_detector(self, controller=None):
        """Detector communication initialization

        Parameters
        ----------
        controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if only one detector by controller (Master case)

        Returns
        -------
        self.status (edict): with initialization status: three fields:
            * info (str)
            * controller (object) initialized controller
            *initialized: (bool): False if initialization failed otherwise True
        """

        try:
            self.status.update(
                edict(initialized=False,
                      info="",
                      x_axis=None,
                      y_axis=None,
                      controller=None))
            if self.settings.child(('controller_status')).value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while this detector is a slave one'
                    )
                else:
                    self.controller = controller
            else:
                ## TODO for your custom plugin
                self.controller = python_wrapper_of_your_instrument(
                )  # any object that will control the stages
                #####################################

            ## TODO for your custom plugin
            # get the x_axis (you may want to to this also in the commit settings if x_axis may have changed
            data_x_axis = self.controller.your_method_to_get_the_x_axis(
            )  # if possible
            self.x_axis = Axis(data=data_x_axis, label='', units='')
            self.emit_x_axis()

            ## TODO for your custom plugin
            #initialize viewers pannel with the future type of data
            self.data_grabed_signal_temp.emit([
                DataFromPlugins(
                    name='Mock1',
                    data=[np.array([0., 0., ...]),
                          np.array([0., 0., ...])],
                    dim='Data1D',
                    labels=['Mock1', 'label2'],
                    x_axis=self.x_axis),
            ])

            ##############################

            self.status.info = "Whatever info you want to log"
            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status
Пример #18
0
    def ini_detector(self, controller=None):
        """Detector communication initialization
        Parameters
        ----------
        controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if
            only one detector by controller (Master case)
        Returns
        -------
        self.status (edict): with initialization status: three fields:
            * info (str)
            * controller (object) initialized controller
            *initialized: (bool): False if initialization failed otherwise True
        """

        try:
            self.status.update(
                edict(initialized=False,
                      info="",
                      x_axis=None,
                      y_axis=None,
                      controller=None))
            if self.settings.child('controller_status').value() == "Slave":
                if controller is None:
                    raise Exception(
                        'no controller has been defined externally while'
                        'this detector is a slave one')
                else:
                    self.controller = controller
            else:
                self.controller = active_dso
                usb_address = "USBTMC:" + self.settings.child(
                    'VISA_ressources').value()
                self.controller.MakeConnection(usb_address)
                # set the timeout of the scope to 10 seconds
                # may be not needed
                self.controller.setTimeout(10)

            channel = self.settings.child('channels').value()['selected']
            waveform = self.controller.GetScaledWaveformWithTimes(
                channel[0], 1e8, 0)
            data_x_axis = np.array(waveform[0])
            self.x_axis = Axis(data=data_x_axis, label="time", units="s")
            self.emit_x_axis()

            self.controller.WriteString(
                r"""vbs? 'return=app.acquisition.horizontal.numsegments' """,
                1)
            self.number_of_segments = self.controller.ReadString(8)

            self.controller.WriteString(
                r"""vbs? 'return=app.acquisition.horizontal.samplemode' """, 1)
            self.sample_mode = self.controller.ReadString(8)

            self.status.info = "Whatever info you want to log"
            self.status.initialized = True
            self.status.controller = self.controller
            return self.status

        except Exception as e:
            self.emit_status(
                ThreadCommand('Update_Status',
                              [getLineInfo() + str(e), 'log']))
            self.status.info = getLineInfo() + str(e)
            self.status.initialized = False
            return self.status