Exemplo n.º 1
0
    def _onTimer(self):
        self.last_sample_done = True
        d = dict()
        values = self.instrument.query_ascii_values('FETC:IMP?')
        self.current_bias = float(self.instrument.query('BIAS:VOLT?'))
        self.current_frequency = float(self.instrument.query('FREQ?'))
        self.current_capacitance =  values[0]
        measurement_time = time() - self.start_time

        d[self.output_channels[0]] = (dict({self.x_units[0] : self.sample_nr,
                                            self.x_units[1] : measurement_time}),
                                        dict({self.y_units[0] : self.current_capacitance,
                                            self.y_units[1] : self.current_frequency,
                                            self.y_units[2] : self.current_bias}))
        self.sample_nr += 1
#        logger.warning('_onTimer() time:  %f, primed timer with: %f, ui: %f, sn: %f',\
#            measurement_time,((self.update_interval * float(self.sample_nr)) - measurement_time) * 1000,
#            self.update_interval, float(self.sample_nr))
        if self.running:
            Timer.singleShot(max(0, ((self.update_interval * float(self.sample_nr)) - measurement_time) * 1000), self._onTimer)
        self.acquired_data.append(d)
        if self.settings_changed:
            self.settings_changed = False
            self.instrument.write('VOLT ' + str(self.osc_level))
            self.instrument.write('BIAS:VOLT ' + str(self.bias))
            self.instrument.write('FUNC:IMP ' + str(self.mode))
            self.instrument.write('FREQ ' + str(self.frequency))
Exemplo n.º 2
0
 def start(self):
     self.button_label = 'Stop'
     self.sample_nr = 1
     self.running = True
     self.instrument_init()
     self.start_time = time()
     Timer.singleShot(self.update_interval * 1000 - 200, self._onTimer)
Exemplo n.º 3
0
 def _start_stop_video(self):
     """Starts the video playing"""
     if self.play_timer is None:
         self.play_timer = Timer(500, self._next_frame_looped)
     else:
         self.play_timer.Stop()
         self.play_timer = None
Exemplo n.º 4
0
    def _on_timer(self):
        socks = dict(self.subscriber_poller.poll(POLL_TIMEOUT))
        logger.info(socks)
        if self.subscriber in socks and socks[self.subscriber] == zmq.POLLIN:
            msg = self.subscriber.recv()
            self.connect_timeout = 0
            logger.info(msg.decode('UTF8'))
            if msg.find('NEWCOL') != -1:
                self.current_column = ({self.x_units[0]: 0},
                                       {self.y_units[0]: int(msg.strip('NEWCOL '))})
            elif msg.find('STOP') != -1:
                if self.control_gasmixer:
                    if self.active_instrument.running is True:
                        self.active_instrument.start_stop = True
            elif msg.find('START') != -1:
                if self.control_gasmixer:
                    if self.active_instrument.running is False:
                        self.active_instrument.start_stop = True
                    else:
                        self.active_instrument.start_stop = True
                        self.active_instrument.start_stop = True
                logger.info('Starting measurement')
            elif msg.find('HEARTBEAT') != -1:
                self.state = State.CONNECTED
                self.running_label = 'GasMixer ' + State.strings[self.state]

            self.timer = Timer.singleShot(0.01, self._on_timer)
            return

        self.connect_timeout += UPDATE_INTERVAL
        if self.connect_timeout > CONNECT_TIMEOUT:
            self.state = State.DISCONNECTED
            self.running_label = 'GasMixer ' + State.strings[self.state]
        self.timer = Timer.singleShot(UPDATE_INTERVAL, self._on_timer)
Exemplo n.º 5
0
    def _start_timer(self):
        """Called when the user selects "Start Timer" from the menu."""

        if self.my_timer is None:
            # First call, so create a Timer.  It starts automatically.
            self.my_timer = Timer(500, self._timer_task)
        else:
            self.my_timer.Start()
Exemplo n.º 6
0
 def __init__(self, setchannelName, port, connection, rpiADC):
     self.channelName = setchannelName
     self.x = ad.ADEvalBC()
     self.port = port
     self.connection = connection
     self.rpiADC = rpiADC
     self.wmLockTimer = Timer(1000, self.wmLock2)
     self.wmLockTimer.Stop()
Exemplo n.º 7
0
 def __running_changed(self):
     '''
     '''
     if self._running:
         self.start_time = datetime.datetime.now()
         self.timer = Timer(1000, self._run_time_update)
     else:
         self.timer.Stop()
Exemplo n.º 8
0
 def _reset(self):
     if hasattr(self,'_timer'):
         self._timer.Stop()
     self._create_plot()
     self._counter = Counter(self.tagger, self.channels, int(self.seconds_per_point*1e12), self.number_of_points)
     self.time = self._counter.getIndex() * 1e-12
     self.count_rate = self._counter.getData() / self.seconds_per_point
     self._timer = Timer(100, self._refresh_data)
     self._timer.Start()
Exemplo n.º 9
0
 def __init__(self, config, server):
     HasTraits.__init__(self)
     self.mayavi_view = PlotHead(self, config, server)
     self.tail_data = np.zeros((2,3))
     self.head_data = np.zeros((2,3))
     self.reset = False
     self.init_plot()
     self.timer = Timer(2000, self.update_plot)
     self.timer.Start()
Exemplo n.º 10
0
 def start(self, tasks):
     """This can be called to start timer and to define unfinished tasks
     """
     self.tasks_all = tasks
     self.start_time = time.time()
     try:
         self.timer.Start(1000)
     except AttributeError:
         self.timer = Timer(1000, self._timer_task)
Exemplo n.º 11
0
 def start_readout(self, interval=1.):
     """Starts readout process. GUI must be running for this to work...
     """
     super(DSCUSBUILog, self).start_readout(interval)
     try:
         self.log_timer.Start(1000)
     except AttributeError:
         #self._timer_function()
         self.log_timer = Timer(1000, self._log_timer_function)
Exemplo n.º 12
0
 def start_timer(self, interval=TIMER_INTERVAL):
     """Starts timer process. It updates status of the instrument with the
     interval specified, collects data, etc, depending on the defined
     update method
     """
     self.logger.info('Starting readout.')
     try:
         self.timer.Start(interval * 1000)
     except AttributeError:
         self.timer = Timer(interval * 1000, self._update)
Exemplo n.º 13
0
 def start_readout(self, interval=1.):
     """Starts readout process. GUI must be running for this to work...
     """
     try:
         self.timer.Start(interval * 1000)
         self.timer_fast.Start(self._interval_min * 1000)
     except AttributeError:
         #self._timer_function()
         self.timer = Timer(interval * 1000, self._timer_function)
         self.timer_fast = Timer(self._interval_min * 1000,
                                 self._timer_fast_function)
Exemplo n.º 14
0
 def _watchFolderModeChanged(self):
     eagle = self.view
     eagle.oldFiles = []
     if eagle.watchFolderBool:
         if eagle.watchFolder == '' and os.path.isfile(eagle.selectedFile):
             eagle.watchFolder = os.path.dirname(eagle.selectedFile)
         eagle.oldFiles = self.getPNGFiles()
         self.watchFolderTimer = Timer(2000., self.checkForNewFiles)
     else:
         if self.watchFolderTimer is not None:
             self.watchFolderTimer.stop()
             self.watchFolderTimer = None
Exemplo n.º 15
0
 def startTimers(self):
     """This timer object polls the experiment runner regularly polling at any time"""
     #stop any previous timers
     self.stopTimers()
     #start timer
     self.connectionTimer = Timer(self.connectionPollFrequency,
                                  self.getStatus)
     time.sleep(0.1)
     self.statusStringTimer = Timer(self.statusStringFrequency,
                                    self.updateStatusString)
     time.sleep(0.1)
     self.getCurrentTimer = Timer(self.getCurrentFrequency, self.getCurrent)
     """Menu action function to change logger level """
     logger.info("timers started")
Exemplo n.º 16
0
class MainWindow(ApplicationWindow):
    """ The main application window. """

    # The pyface Timer.
    my_timer = Any()

    # Count each time the timer task executes.
    counter = Int

    def __init__(self, **traits):
        """ Creates a new application window. """

        # Base class constructor.
        super(MainWindow, self).__init__(**traits)

        # Add a menu bar.
        self.menu_bar_manager = MenuBarManager(
            MenuManager(
                Action(name='Start Timer', on_perform=self._start_timer),
                Action(name='Stop Timer', on_perform=self._stop_timer),
                Action(name='E&xit', on_perform=self.close),
                name = '&File',
            )
        )

        return

    def _start_timer(self):
        """Called when the user selects "Start Timer" from the menu."""

        if self.my_timer is None:
            # First call, so create a Timer.  It starts automatically.
            self.my_timer = Timer(500, self._timer_task)
        else:
            self.my_timer.Start()

    def _stop_timer(self):
        """Called when the user selecte "Stop Timer" from the menu."""

        if self.my_timer is not None:
            self.my_timer.Stop()


    def _timer_task(self):
        """The method run periodically by the timer."""

        self.counter += 1
        print "counter = %d" % self.counter
Exemplo n.º 17
0
 def _start_timer(self):
     # Start up the timer! We should do this only when the demo actually
     # starts and not when the demo object is created.
     # FIXME: close timer on exit.
     self.timer_controller.view = self.view
     self.timer_controller.model_view = self
     self.timer = Timer(40, self.timer_controller.onTimer)
Exemplo n.º 18
0
    def run(self):
        MayaviDaemon._viewers.append(self)

        mlab.clf()

        self.cellsource = self.setup_source(self.cellfname)
        self.has_cell, bounds = self._examine_data(source=self.cellsource,
                                                   datatype="cell_data",
                                                   bounds=zeros((0, 6), 'l'))

        self.facesource = self.setup_source(self.facefname)
        self.has_face, bounds = self._examine_data(source=self.facesource,
                                                   datatype="point_data",
                                                   bounds=bounds)

        boundsmin = bounds.min(axis=0)
        boundsmax = bounds.max(axis=0)

        bounds = (boundsmin[0], boundsmax[1], boundsmin[2], boundsmax[3],
                  boundsmin[4], boundsmax[5])

        self.bounds = where(self.bounds == array((None, )), bounds,
                            self.bounds).astype(float)

        self.view_data()

        # Poll the lock file.
        self.timer = Timer(1000 / self.fps, self.poll_file)
Exemplo n.º 19
0
    def _on_timer(self):
        self.sample_number += 1
        data = [self.sample_number, time() - self.start_time]
        if self.derivative_resistance_enabled:
            self.instrument.write('f2, msg2 = InitiatePulseTest(1)')
            response = self.instrument.query('printbuffer(1, {:d}, smua.nvbuffer1)'
                                             .format(self.derivative_resistance_voltage_points))
            self.instrument.write('smua.nvbuffer1.clear()')
            logger.info(response)
            values = [float(n) for n in response.replace(',', '').split()]
            filtered_response = savgol_filter(values, self.derivative_resistance_voltage_points, 2, 1,
                                              2*self.derivative_resistance_voltage_span /
                                              (self.derivative_resistance_voltage_points-1))
            logger.info(1/filtered_response)
            data.append(self.voltage)
            data.append(values[self.derivative_resistance_voltage_points/2])
            data.append(1/filtered_response[self.derivative_resistance_voltage_points/2])
            self.actual_current = values[self.derivative_resistance_voltage_points/2] * 1000
            self.actual_voltage = self.voltage
            self.dispatch_data(data)

        else:
            resp = self.instrument.query('print(smua.measure.iv())')
            values = [float(f) for f in resp.split()]
            data.append(values[1])
            data.append(values[0])
            data.append(values[1]/values[0])
            self.actual_voltage = values[1]
            self.actual_current = values[0] * 1000
            self.dispatch_data(data)

        if self.running:
            self.timer = Timer.singleShot(max(((self.sample_number+1) * self.sampling_interval -
                                           (time()-self.start_time))*1000, 0.01),
                                          self._on_timer)
Exemplo n.º 20
0
    def _create_window(self):
        numpoints = 50
        low = -5
        high = 15.0
        x = arange(low, high, (high - low) / numpoints)
        container = OverlayPlotContainer(bgcolor="lightgray")

        common_index = None
        index_range = None
        value_range = None
        self.animated_plots = []
        for i, color in enumerate(COLOR_PALETTE):
            if not common_index:
                animated_plot = AnimatedPlot(x, jn(i, x), color)
                common_index = animated_plot.plot.index
                index_range = animated_plot.plot.index_mapper.range
                value_range = animated_plot.plot.value_mapper.range
            else:
                animated_plot = AnimatedPlot(common_index, jn(i, x), color)
                animated_plot.plot.index_mapper.range = index_range
                animated_plot.plot.value_mapper.range = value_range
            container.add(animated_plot.plot)
            self.animated_plots.append(animated_plot)

        for i, a_plot in enumerate(self.animated_plots):
            a_plot.plot.position = [
                50 + (i % 3) * (PLOT_SIZE + 50),
                50 + (i // 3) * (PLOT_SIZE + 50)
            ]

        self.timer = Timer(100.0, self.onTimer)
        self.container = container
        return Window(self, -1, component=container)
Exemplo n.º 21
0
 def _configure_timer(self, event):
     """Creates, replaces, or destroys the autosave timer."""
     if self._timer:
         self._timer.Stop()
     if self.autosave and self.saveObject:
         self._timer = Timer(self.autosaveInterval * 1000, self._autosave)
     else:
         self._timer = None
Exemplo n.º 22
0
 def _make_play_timer(self):
     scene = self.scene
     if scene is None or scene.off_screen_rendering:
         timer = NoUITimer(self.play_delay*1000, self._play_event)
     else:
         from pyface.timer.api import Timer
         timer = Timer(self.play_delay*1000, self._play_event)
     return timer
Exemplo n.º 23
0
 def __init__(self, num_frames, callable, millisec=40, figure=None, play=True, *args, **kwargs):
     HasTraits.__init__(self)
     self.delay = millisec
     self._last_frame = num_frames - 1
     self._callable = callable
     if figure is None:
         figure = mlab.gcf()
     self._figure = figure
     self._camera_interpolator = tvtk.CameraInterpolator(interpolation_type='spline')
     self._t_keyframes = {}
     self.render_to_frame = self._last_frame
     self.timer = Timer(millisec, self._on_timer, *args, **kwargs)
     if not play:
         self.stop = True
     self._internal_generator = None
     self.current_frame = 0
     self.on_trait_change(self._render, "render, current_frame", dispatch="ui")
Exemplo n.º 24
0
 def __init__(self, **traits):
     super(Demo, self).__init__(**traits)
     self._create_plot_component()
     self.queue = Queue()
     self.finish_event = threading.Event()
     self.thread = threading.Thread(target=self.get_audio_data)
     self.thread.start()
     self.timer = Timer(10, self.on_timer)
     self.win_func = np.hanning(NUM_SAMPLES + 1)[:NUM_SAMPLES]
Exemplo n.º 25
0
class DSCUSBUILog(DSCUSBUI):
    """Same as :class:`.DSCUSBUI` except that it adds a logger facility. It 
    defines an :attr:`~.DSCUSBUILog.data` that hold the measured data.
    
    Examples
    --------
    
    For a display with a logger ...
    
    >>> dsc = DSCUSBUILog()
    >>> ok = dsc.configure_traits() %(skip)s
    
    """
    #: this holds the measured data
    data = Instance(StructArrayData, ())

    log_timer = Any

    _data = []
    #: set to False to stop writing to :attr:`~.DSCUSBUILog.data`
    do_log = Bool(True, desc='whether logging is activated or not')

    view = dscusbui_log_view

    def _data_default(self):
        return StructArrayData(width=420,
                               height=230,
                               dtype=[('time', 'float'), ('force', 'float'),
                                      ('temperature', 'float')])

    def _timer_function(self):
        value_temp = super(DSCUSBUILog, self)._timer_function()
        if self.do_log and value_temp is not None:
            value, temp = value_temp
            self._data.append((time.time(), value, temp))

    def _log_timer_function(self):
        if len(self._data) != 0:
            data, self._data = self._data, []
            self.data.append(data)

    def start_readout(self, interval=1.):
        """Starts readout process. GUI must be running for this to work...
        """
        super(DSCUSBUILog, self).start_readout(interval)
        try:
            self.log_timer.Start(1000)
        except AttributeError:
            #self._timer_function()
            self.log_timer = Timer(1000, self._log_timer_function)

    def stop_readout(self):
        """Stops readout process
        """
        super(DSCUSBUILog, self).stop_readout()
        self.log_timer.Stop()
Exemplo n.º 26
0
    def start(self):
        self.running = True
        self.acq_start_time = time()
        self.sample_nr = 0
        self.instrument = SerialUtil.open(self.selected_device, self.visa_resource)
        if self.instrument is None:
            self.instrument = None
            self.selected_device = ''

        self.timer = Timer.singleShot(self.sampling_interval * 1000, self.add_data)
Exemplo n.º 27
0
    def __init__(self, millisec, callable, *args, **kwargs):
        """Constructor.

        **Parameters**

          :millisec: int specifying the delay in milliseconds
                     between calls to the callable.

          :callable: callable function to call after the specified
                     delay.

          :\*args: optional arguments to be passed to the callable.

          :\*\*kwargs: optional keyword arguments to be passed to the callable.

        """
        HasTraits.__init__(self)
        self.delay = millisec
        self.timer = Timer(millisec, callable, *args, **kwargs)
Exemplo n.º 28
0
def main():

    fname = 'output.vtk'

    data = setup_data(fname)
    view_data()

    p = Pollster(fname, data)
    timer = Timer(1000, p.poll_file)
    mayavi2.savedtimerbug = timer
Exemplo n.º 29
0
    def run(self):
        MayaviDaemon._viewers.append(self)
        
        mlab.clf()

        bounds = zeros((0, 6), 'l')
        
        self.cellsource = self.setup_source(self.cellfname)
        if self.cellsource is not None:
            tmp = [out.cell_data.scalars for out in self.cellsource.outputs \
                   if out.cell_data.scalars is not None]
            self.has_cell_scalars = (len(tmp) > 0)
            tmp = [out.cell_data.vectors for out in self.cellsource.outputs \
                   if out.cell_data.vectors is not None]
            self.has_cell_vectors = (len(tmp) > 0)
            tmp = [out.cell_data.tensors for out in self.cellsource.outputs \
                   if out.cell_data.tensors is not None]
            self.has_cell_tensors = (len(tmp) > 0)

            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.cellsource.outputs]),
                                 axis=0)


        self.facesource = self.setup_source(self.facefname)
        if self.facesource is not None:
            tmp = [out.point_data.scalars for out in self.facesource.outputs \
                   if out.point_data.scalars is not None]
            self.has_face_scalars = (len(tmp) > 0)
            tmp = [out.point_data.vectors for out in self.facesource.outputs \
                   if out.point_data.vectors is not None]
            self.has_face_vectors = (len(tmp) > 0)
            tmp = [out.point_data.tensors for out in self.facesource.outputs \
                   if out.point_data.tensors is not None]
            self.has_face_tensors = (len(tmp) > 0)
            
            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.facesource.outputs]),
                                 axis=0)
                                 
        boundsmin = bounds.min(axis=0)
        boundsmax = bounds.max(axis=0)
        
        bounds = (boundsmin[0], boundsmax[1], 
                  boundsmin[2], boundsmax[3], 
                  boundsmin[4], boundsmax[5])

        self.bounds = where(self.bounds == array((None,)),
                            bounds, 
                            self.bounds).astype(float)

        self.view_data()

        # Poll the lock file.
        self.timer = Timer(1000 / self.fps, self.poll_file)
Exemplo n.º 30
0
 def start(self):
     self.button_label = "Stop"
     self.sample_nr = 0
     self.running = True
     self.instrument_init()
     self.start_time = time()
     self.bias_table_current_row = 0
     self._row_changed(0)
     if self.timer is None:
         self.timer = Timer(self.update_interval * 1000, self._onTimer)
     else:
         self.timer.Start(self.update_interval * 1000)
Exemplo n.º 31
0
    def start(self):
        self.running = True
        self.acq_start_time = time()
        self.sample_nr = 0
        self.instrument = SerialUtil.open(self.selected_device, self.visa_resource)
        self.instrument_init()
        if self.instrument is None:
#            GenericPopupMessage(message ='Error opening ' + new).edit_traits()
            self.instrument = None
            self.selected_device = ''

        self.timer = Timer.singleShot(self.sampling_interval * 1000, self.add_data)
Exemplo n.º 32
0
    def _start_timer(self, project):
        """
        Resets the timer to work on auto-saving the current project.

        """

        if self.timer is None:
            if self.autosave_interval > 0:
                # Timer needs the interval in millisecs
                self.timer = Timer(self.autosave_interval * 60000,
                                   self._auto_save, project)
        return
Exemplo n.º 33
0
 def _autoRefresh_dialog(self):
     """when user clicks autorefresh in the menu this function calls the dialog 
     after user hits ok, it makes the choices of how to setup or stop the timer"""
     logger.info("auto refresh dialog called")
     if self.autoRefreshDialog is None:
         self.autoRefreshDialog = plotObjects.autoRefreshDialog.AutoRefreshDialog(
         )
     self.autoRefreshDialog.configure_traits()
     logger.info("dialog edit traits finished")
     if self.autoRefreshDialog.autoRefreshBool:
         if self.autoRefreshTimer is not None:
             self.autoRefreshTimer.stop()
         self.selectedLFP.autoRefreshObject = self.autoRefreshDialog  #this gives it all the info it needs
         self.autoRefreshTimer = Timer(
             self.autoRefreshDialog.minutes * 60.0 * 1000.0,
             self.selectedLFP.autoRefresh)
         logger.info("started auto refresh timer to autorefresh")
     else:
         self.selectedLFP.autoRefreshObject = None
         logger.info("stopping auto refresh")
         if self.autoRefreshTimer is not None:
             self.autoRefreshTimer.stop()
Exemplo n.º 34
0
    def __init__(self, **traits):
        if USE_ZMQ is False:
            return
        super(GasMixerPanel, self).__init__(**traits)
        self.context = zmq.Context.instance()

        self.subscriber = self.context.socket(zmq.SUB)
        self.subscriber.connect('tcp://localhost:5561')
        self.subscriber.setsockopt(zmq.SUBSCRIBE, "")
        self.subscriber_poller = zmq.Poller()
        self.subscriber_poller.register(self.subscriber, zmq.POLLIN)
        self.state = State.DISCONNECTED
        self.timer = Timer.singleShot(UPDATE_INTERVAL, self._on_timer)
Exemplo n.º 35
0
 def _portname_changed(self, new):
     if new is '':
         return
     if self.serialport != None:
         self.serialport.close()
     try:
         self.serialport = serial.Serial(self.portname, 115200, timeout = 0.1)
     except Exception as e:
         logger.error(e)
         return
     #self.serialport.open()
     self.serialport.flushInput()
     self.timer = Timer.singleShot(self.sample_interval, self.add_data)
class BrownianMotionVisualization(HasTraits):

    scene = Instance(MlabSceneModel, ())
    plot = Instance(PipelineBase)
    x = Array()
    y = Array()
    z = Array()

    timer = Any()
    timer_button = Button()

    @on_trait_change('scene.activated')
    def create_plot(self):
        """ Wait before the scene is activated before trying to add data,
        modules, filers into it.
        """
        x, y, z = compute_positions()
        self.plot = self.scene.mlab.points3d(x, y, z)

    def _timer_button_fired(self):
        if self.timer is None:
            self.timer = Timer(100, self.update_plot)
        else:
            self.timer.stop()
            self.timer = None

    def update_plot(self):
        """ Recompute the ball positions and redraw
        """
        x, y, z = compute_positions()
        self.plot.mlab_source.set(x=x, y=y, z=z)


    # the layout of the dialog created
    view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene),
                    height=250, width=300, show_label=False),
                Item('timer_button', label = "Start/Stop animation",
                      show_label = False),
                )
Exemplo n.º 37
0
 def add_data(self):
     if not self.running:
         return
     self.timer = Timer.singleShot(500, self.add_data)
     self.response_remainder = self.serial_response[-15:]
     self.serial_response = bytearray(self.serialport.inWaiting())
     self.serialport.readinto(self.serial_response)
     d = self._parse_data(self.response_remainder +self.serial_response)
     data_dict = dict()
     if self.running is True:
         for entry in d:
             data_dict[self.output_channels[0]] = entry[0]
             data_dict[self.output_channels[1]] = entry[1]
             self.acquired_data.append(data_dict)
Exemplo n.º 38
0
 def start(self):
     self.running = True
     self.acq_start_time = time()
     self.sample_nr = 0
     if self.serialport is None:
         try:
             self.serialport = serial.Serial(self.portname, 57600, timeout = 0.2)
         except Exception as e:
             logger.error(e)
             self.stop()
             return
     else:
         self.serialport.open()
     self.serialport.write('a')
     self.timer = Timer.singleShot(900, self.add_data)
Exemplo n.º 39
0
 def add_data(self):
     if not self.running:
         return
     b = bytearray(2)
     self.sample_nr += 1
     measurement_time = time() - self.acq_start_time
     self.serialport.readinto(b)
     d = dict()
     for i, enabled in enumerate(self.enabled_channels):
         d[self.output_channels[i]] = (dict({self.x_units[0]:self.sample_nr,
                                         self.x_units[1]:measurement_time}),\
                         dict({self.y_units[0]:4.9*((b[0]*256 + b[1])/1024.0)}))
     self.timer = Timer.singleShot(max(0, ((float(self.sample_nr)) - measurement_time) * 1000), self.add_data)
     self.sensor_output_voltage = 4.9*((b[0]*256 + b[1])/1024.0)
     self.acquired_data.append(d)
Exemplo n.º 40
0
def main():
    # Change this to suit your needs.  Edit the file after running this
    # script and the pipeline should be updated automatically.

    fname = join(mayavi2.get_data_dir(abspath(dirname(__file__))),
                 'heart.vtk')

    data = setup_data(fname)
    view_data()

    # Poll the file.
    p = Pollster(fname, data)
    timer = Timer(1000, p.poll_file)
    # Keep a reference on the timer
    mayavi2.savedtimerbug = timer
Exemplo n.º 41
0
def create_mayavi(pipe):
    def send_key_callback(widget, event):
        "Send the key-presses to the process which created this mayavi viewer."
        pipe.send(cPickle.dumps(("KEY_DOWN", widget.GetKeyCode())))

    fig = mlab.figure()
    fig.scene.interactor.add_observer("KeyPressEvent", send_key_callback)
    time.sleep(1)

    mayavi_app = Plotter(pipe)

    from pyface.timer.api import Timer
    from mayavi.scripts import mayavi2

    timer = Timer(50, mayavi_app.check_and_process)
    mayavi2.savedtimerbug = timer
Exemplo n.º 42
0
 def start(self):
     self.running = True
     self.acq_start_time = time()
     if self.synced_acqusistion is True:
         self.acqusition_task = CallbackTaskSynced()
     else:
         self.acqusition_task = CallbackTask()
     channels = []
     for i, enabled in enumerate(self.enabled_channels):
         if enabled:
             channels.append('ai' + str(i))
     self.acqusition_task.setup('/' + self.selected_device,
                                channels, self.sampling_interval, self)
     self.acqusition_task.StartTask()
     self.timer = Timer(RENDER_INTERVAL_MS, self.handle_data)
     self.timer.start()
Exemplo n.º 43
0
 def start(self):
     self.running = True
     self.acq_start_time = time()
     self.sample_nr = 0
     if self.serialport is None:
         try:
             self.serialport = serial.Serial(self.portname, 115200, timeout=0.045)
         except Exception as e:
             logger.error(e)
             self.stop()
             return
     else:
         self.serialport.open()
     self.serial_handler = SerialHandler(self.serialport)
     self.serial_handler.start()
     self.timer = Timer.singleShot(self.sample_interval * 1000, self.add_data)
Exemplo n.º 44
0
 def __init__(self, Xmean, tris, components):
     HasTraits.__init__(self)
     self._components = components
     self._max_component_index = len(components)
     self._Xmean = Xmean
     self.pd = tvtk.PolyData(points=Xmean, polys=tris)
     self.pd.point_data.normals = compute_normals(
         self.pd)  # compute normals once for rest-shape (faster)
     self.actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(
         input=self.pd, immediate_mode_rendering=True))
     self.actor.mapper.lookup_table = tvtk.LookupTable(
         hue_range=(0.45, 0.6),
         saturation_range=(0., 0.8),
         value_range=(.6, 1.),
     )
     self.scene.add_actor(self.actor)
     self.timer = Timer(40, self.animate().next)
Exemplo n.º 45
0
 def add_data(self):
     self.sample_nr += 1
     measurement_time = time() - self.acq_start_time
     if not self.running:
         return
     (nox_ppm, lambda_linear, oxygen_millivolt) = self._poll_queue()
     self.serial_out = str(nox_ppm)
     dict_data = dict()
     for i, enabled in enumerate(self.enabled_channels):
         dict_data[
             self.output_channels[i]] = (
             dict(
                 {self.x_units[0]: self.sample_nr, self.x_units[1]: measurement_time}),
                 dict({self.y_units[0]: nox_ppm}))
     self.acquired_data.append(dict_data)
     self.timer = Timer.singleShot(max(0, (self.sample_interval * self.sample_nr -
                                           (time() - self.acq_start_time))*1000), self.add_data)
Exemplo n.º 46
0
 def _connect_fired(self):
     if self.serial_handler is None:
         self.serial_handler = SerialHandler(self.set_parameters_queue, self.get_parameters_queue,
                 self.selected_com_port)
         if not self.serial_handler.open_port():
             return
         self.poll_timer = Timer(POLL_INTERVAL, self._poll_queue)
         self.serial_handler.start()
         self.connected = True
     else:
         self.start_stop(False)
         self.serial_handler.exit_flag = True
         self.serial_handler.join()
         self.serial_handler = None
         if self.poll_timer is not None:
             self.poll_timer.stop()
         self.connected = False
Exemplo n.º 47
0
 def __init__(self, Xmean, tris, components):
     HasTraits.__init__(self)
     self._components = components
     self._max_component_index = len(components)
     self._Xmean = Xmean
     self.pd = tvtk.PolyData(points=Xmean, polys=tris)
     self.normals = tvtk.PolyDataNormals(splitting=False)
     configure_input_data(self.normals, self.pd)
     mapper = tvtk.PolyDataMapper(immediate_mode_rendering=True)
     self.actor = tvtk.Actor(mapper=mapper)
     configure_input(self.actor.mapper, self.normals)
     self.actor.mapper.lookup_table = tvtk.LookupTable(
         hue_range=(0.45, 0.6),
         saturation_range=(0., 0.8),
         value_range=(.6, 1.),
     )
     self.scene.add_actor(self.actor)
     self.timer = Timer(40, self.animate().next)
Exemplo n.º 48
0
 def start(self):
     if self.timer is None:
         self.timer = Timer(self.update_interval * 1000, self._onTimer)
     else:
         self.timer.Start(self.update_interval * 1000)
     self.button_label = "Stop"
     self.current_voltage = self.start_voltage
     self.current_frequency = self.start_frequency
     self.iteration = 0
     self.running = True
     self.bias = random.random_sample() - 0.5
     self.measurement_info = {
         "name": self.sweep_name,
         "start_voltage": self.start_voltage,
         "start_frequency": self.start_frequency,
         "start_bias": self.bias,
     }
     if len(self.measurement_info["name"]) is 0:
         self.measurement_info.pop("name")
Exemplo n.º 49
0
    def add_data(self):
        if not self.running:
            return
        self.sample_nr += 1
        try:
            data = self.instrument.query('READ?')     
        except visa.VisaIOError:
            data = self.acq_value
            pass
        self.acq_value = float(data)
        logger.info(data)
        self.measurement_time = time() - self.acq_start_time   
        d = dict()
        for i, enabled in enumerate(self.enabled_channels):

            d[self.output_channels[i]] = (dict({self.x_units[0]:self.sample_nr,
                                            self.x_units[1]:self.measurement_time}),\
                            self._fix_output_dict(self.acq_value))                           
        self.timer = Timer.singleShot(max(0,
            ((float(self.sample_nr) * self.sampling_interval) - self.measurement_time) * 1000),
            self.add_data)
        self.acquired_data.append(d)
Exemplo n.º 50
0
    def _set_parameters_fired(self):
        enter = '\r\n'
        if self.serialport.isOpen():
            self.serialport.flushOutput()
            self.serialport.read(self.serialport.inWaiting())
            self.timer = None
            self.serialport.write('A')
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.temperature) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(0) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.samples_per_sec) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.max_cur_drain1) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.min_cur_drain1) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.max_cur_drain2) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(self.min_cur_drain2) + enter)
            sleep(0.1)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            self.serialport.write(str(0) + enter)
            sleep(0.1)
#            sleep(0.2)            
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            sleep(0.1)
            self.serialport.write(enter)
            logger.debug(bytearray(self.serialport.read(self.serialport.inWaiting())))
            sleep(0.1)
            self.timer = Timer.singleShot(500, self.add_data)
Exemplo n.º 51
0
class PhysiologyController(Controller):

    buffer_                 = Any
    iface_physiology        = Any
    buffer_raw              = Any
    buffer_proc             = Any
    buffer_ts               = Any
    buffer_ttl              = Any
    physiology_ttl_pipeline = Any
    buffer_spikes           = List(Any)
    state                   = Enum('master', 'client')
    process                 = Instance('tdt.DSPProject')
    timer                   = Instance(Timer)
    parent                  = Any

    shell_variables         = Dict

    # These define what variables will be available in the Python shell.  Right
    # now we can't add various stuff such as the data and interface classes
    # because they have not been created yet.  I'm not sure how we can update
    # the Python shell with new instances once the experiment has started
    # running.
    def _shell_variables_default(self):
        return dict(controller=self, c=self)

    def init(self, info):
        self.setup_physiology()
        self.model = info.object
        if self.state == 'master':
            self.process.start()
            self.iface_physiology.trigger('A', 'high')
            self.start()

    def close(self, info, is_ok, from_parent=False):
        return True
        if self.state == 'client':
            return from_parent
        else:
            # The function confirm returns an integer that represents the
            # response that the user requested.  YES is a constant (also
            # imported from the same module as confirm) corresponding to the
            # return value of confirm when the user presses the "yes" button on
            # the dialog.  If any other button (e.g. "no", "abort", etc.) is
            # pressed, the return value will be something other than YES and we
            # will assume that the user has requested not to quit the
            # experiment.
            if confirm(info.ui.control, 'OK to stop?') == YES:
                self.stop(info)
                return True
            else:
                return False

    def setup_physiology(self):
        # Load the circuit
        circuit = join(get_config('RCX_ROOT'), 'physiology')
        self.iface_physiology = self.process.load_circuit(circuit, 'RZ5')

        # Initialize the buffers that will be spooling the data
        self.buffer_raw = self.iface_physiology.get_buffer('craw',
                'r', src_type='float32', dest_type='float32', channels=CHANNELS,
                block_size=1048)
        self.buffer_filt = self.iface_physiology.get_buffer('cfilt',
                'r', src_type='int16', dest_type='float32', channels=CHANNELS,
                block_size=1048)
        self.buffer_ts = self.iface_physiology.get_buffer('trig/',
                'r', src_type='int32', dest_type='int32', block_size=1)
        self.buffer_ts_start = self.iface_physiology.get_buffer('trig/', 
                'r', src_type='int32', dest_type='int32', block_size=1)
        self.buffer_ts_end = self.iface_physiology.get_buffer('trig\\', 
                'r', src_type='int32', dest_type='int32', block_size=1)
        self.buffer_ttl = self.iface_physiology.get_buffer('TTL',
                'r', src_type='int8', dest_type='int8', block_size=1)

        for i in range(CHANNELS):
            name = 'spike{}'.format(i+1)
            buffer = self.iface_physiology.get_buffer(name, 'r',
                    block_size=SPIKE_SNIPPET_SIZE+2)
            self.buffer_spikes.append(buffer)

    @on_trait_change('model.data')
    def update_data(self):
        # Ensure that the data store has the correct sampling frequency
        for i in range(CHANNELS):
            data_spikes = self.model.data.spikes
            for src, dest in zip(self.buffer_spikes, data_spikes):
                dest.fs = src.fs
                dest.snippet_size = SPIKE_SNIPPET_SIZE
        self.model.data.raw.fs = self.buffer_raw.fs
        self.model.data.processed.fs = self.buffer_filt.fs
        self.model.data.ts.fs = self.iface_physiology.fs
        self.model.data.epoch.fs = self.iface_physiology.fs
        self.model.data.sweep.fs = self.buffer_ttl.fs

        # Setup the pipeline
        targets = [self.model.data.sweep]
        self.physiology_ttl_pipeline = deinterleave_bits(targets)

    def start(self):
        self.timer = Timer(100, self.monitor_physiology)

    def stop(self):
        self.timer.stop()
        self.process.stop()

    def monitor_physiology(self):
        # Acquire raw physiology data
        waveform = self.buffer_raw.read()
        self.model.data.raw.send(waveform)

        # Acquire filtered physiology data
        waveform = self.buffer_filt.read()
        self.model.data.processed.send(waveform)

        # Acquire sweep data
        ttl = self.buffer_ttl.read()
        self.physiology_ttl_pipeline.send(ttl)

        # Get the timestamps
        ts = self.buffer_ts.read().ravel()
        self.model.data.ts.send(ts)

        ends = self.buffer_ts_end.read().ravel()
        starts = self.buffer_ts_start.read(len(ends)).ravel()
        self.model.data.epoch.send(zip(starts, ends))

        # Get the spikes.  Each channel has a separate buffer for the spikes
        # detected online.  Need to add 2 to the snippet size to compensate for
        # the extra samples provided with the snippet (the timestamp and the
        # classifier).
        snippet_shape = (-1, SPIKE_SNIPPET_SIZE+2)
        for i in range(CHANNELS):
            data = self.buffer_spikes[i].read().reshape(snippet_shape)

            # First sample of each snippet is the timestamp (as a 32 bit
            # integer) and last sample is the classifier (also as a 32 bit
            # integer).  The bits in between should be interpreted as 32-bit
            # floating point values.
            snip = data[:,1:-1]
            ts = data[:,0].view('int32')
            cl = data[:,-1].view('int32')
            self.model.data.spikes[i].send(snip, ts, cl)

    @on_trait_change('model.settings.spike_signs')
    def set_spike_signs(self, value):
        for ch, sign in enumerate(value):
            name = 's_spike{}'.format(ch+1)
            self.iface_physiology.set_tag(name, sign)

    @on_trait_change('model.settings.spike_thresholds')
    def set_spike_thresholds(self, value):
        for ch, threshold in enumerate(value):
            name = 'a_spike{}'.format(ch+1)
            self.iface_physiology.set_tag(name, threshold)
            
    @on_trait_change('model.settings.monitor_fc_highpass')
    def set_monitor_fc_highpass(self, value):
        self.iface_physiology.set_tag('FiltHP', value)

    @on_trait_change('model.settings.monitor_fc_lowpass')
    def set_monitor_fc_lowpass(self, value):
        self.iface_physiology.set_tag('FiltLP', value)

    @on_trait_change('model.settings.monitor_ch_1')
    def set_monitor_ch_1(self, value):
        self.iface_physiology.set_tag('ch1_out', value)

    @on_trait_change('model.settings.monitor_ch_2')
    def set_monitor_ch_2(self, value):
        self.iface_physiology.set_tag('ch2_out', value)

    @on_trait_change('model.settings.monitor_ch_3')
    def set_monitor_ch_3(self, value):
        self.iface_physiology.set_tag('ch3_out', value)

    @on_trait_change('model.settings.monitor_gain_1')
    def set_monitor_gain_1(self, value):
        self.iface_physiology.set_tag('ch1_out_sf', value*1e3)

    @on_trait_change('model.settings.monitor_gain_2')
    def set_monitor_gain_2(self, value):
        self.iface_physiology.set_tag('ch2_out_sf', value*1e3)

    @on_trait_change('model.settings.monitor_gain_3')
    def set_monitor_gain_3(self, value):
        self.iface_physiology.set_tag('ch3_out_sf', value*1e3)

    @on_trait_change('model.settings.diff_matrix')
    def set_diff_matrix(self, value):
        self.iface_physiology.set_coefficients('diff_map', value.ravel())

    def load_settings(self, info):
        instance = load_instance(PHYSIOLOGY_ROOT, PHYSIOLOGY_WILDCARD)
        if instance is not None:
            self.model.settings.copy_traits(instance)

    def saveas_settings(self, info):
        dump_instance(self.model.settings, PHYSIOLOGY_ROOT, PHYSIOLOGY_WILDCARD)

    @on_trait_change('model.channel_mode')
    def _channel_mode_changed(self, new):
        if new == 'TDT':
            offset = 0
        elif new =='TBSI':
            offset = 1
        else:
            offset = 2
        self.iface_physiology.set_tag('ch_offset', offset*16+1)
Exemplo n.º 52
0
class Boonton7200(HasTraits):

    name = Unicode("Boonton7200")
    measurement_info = Dict()
    x_units = Dict({0: "SampleNumber", 1: "Time"})
    y_units = Dict({0: "Capacitance"})

    acquired_data = List(Dict)

    start_stop = Event
    running = Bool

    output_channels = Dict({0: "cap", 1: "bias"})

    enabled_channels = List(Bool)

    timer = Instance(Timer)
    timer_dormant = Bool(False)
    update_interval = Float(0.5)

    start_time = Float

    #    bias = Range(-10.0, 10.0, 0.0)
    bias = Float(0.0)
    current_capacitance = Float
    current_bias = Float

    sample_nr = Int(0)
    start_stop = Event
    button_label = Str("Start")

    bias_low_limit = Float(-10.0)  # Instrument supports -100V to +100V
    bias_high_limit = Float(10.0)

    bias_table = List(TableEntry)
    bias_table_current_row = Int(0)
    bias_table_enable = Bool(False)
    stop_meas_after_last_row = Bool(False)
    _available_devices_map = Dict(Unicode, Unicode)
    selected_device = Str
    visa_resource = Instance(visa.ResourceManager, ())
    instrument = Instance(visa.Resource)

    traits_view = View(
        Item(
            "selected_device",
            label="Device",
            editor=EnumEditor(name="_available_devices_map"),
            enabled_when="not running",
        ),
        Item("update_interval", enabled_when="not running"),
        Item("bias", editor=RangeEditor(is_float=True, low_name="bias_low_limit", high_name="bias_high_limit")),
        Group(
            Item("current_capacitance", enabled_when="False"),
            Item("current_bias", enabled_when="False"),
            Item("sample_nr", enabled_when="False"),
            label="Measurement",
            show_border=True,
        ),
        Group(
            Item("bias_table_enable"),
            Item("stop_meas_after_last_row"),
            Item(
                "bias_table",
                show_label=False,
                #                               label       = 'right-click to edit',
                editor=table_editor,
                enabled_when="not running and bias_table_enable",
            ),
            show_border=True,
        ),
        Item("start_stop", label="Start/Stop Acqusistion", editor=ButtonEditor(label_value="button_label")),
        handler=ViewHandler,
    )

    def instrument_init(self):
        if self.instrument is not None:
            self.instrument.write("BI" + str(self.bias))

    def instrument_stop(self):
        if self.instrument is not None:
            pass

    def start(self):
        self.button_label = "Stop"
        self.sample_nr = 0
        self.running = True
        self.instrument_init()
        self.start_time = time()
        self.bias_table_current_row = 0
        self._row_changed(0)
        if self.timer is None:
            self.timer = Timer(self.update_interval * 1000, self._onTimer)
        else:
            self.timer.Start(self.update_interval * 1000)

    def stop(self):
        if self.timer is not None:
            self.timer.Stop()
        self.button_label = "Start"
        self.running = False
        self.timer_dormant = False
        self.instrument_stop()

    def _onTimer(self):
        #        self.timer.Stop()
        self.timer_dormant = True
        d = dict()
        values = self.instrument.query_ascii_values("TM")
        self.current_capacitance = values[0] * 1e-12
        self.current_bias = values[2]
        d[self.output_channels[0]] = (
            dict({self.x_units[0]: self.sample_nr, self.x_units[1]: time() - self.start_time}),
            dict({self.y_units[0]: self.current_capacitance}),
        )
        d[self.output_channels[1]] = (
            dict({self.x_units[0]: self.sample_nr, self.x_units[1]: time() - self.start_time}),
            dict({self.y_units[0]: self.bias}),
        )
        self.sample_nr += 1
        #        self.timer.Start(self.update_interval * 1000)
        self.timer_dormant = False
        self.acquired_data.append(d)

        if self.bias_table_enable:
            if self.bias_table_current_row < len(self.bias_table):
                row_time = time() - self.row_start_time
                self.bias_table[self.bias_table_current_row].remaining = int(
                    self.bias_table[self.bias_table_current_row].time - row_time
                )
                if self.bias_table[self.bias_table_current_row].remaining < 1:
                    self.bias_table_current_row += 1
                    self._row_changed(self.bias_table[self.bias_table_current_row - 1].time - row_time)

    def _row_changed(self, remainder):
        self.row_start_time = time() + remainder
        #        logging.getLogger(__name__).info('self.row_start_time: %f', self.row_start_time)
        if self.bias_table_current_row >= len(self.bias_table):
            if self.stop_meas_after_last_row:
                self.start_stop = True
            return
        self.bias = self.bias_table[self.bias_table_current_row].bias

    def _start_stop_fired(self):
        if self.instrument is None:
            return
        if self.timer is None:
            self.start()
            return
        if self.timer.isActive() or self.timer_dormant:
            self.stop()
        else:
            self.start()

    def _selected_device_changed(self, new):
        logger.info("New instrument %s", new)
        if self.instrument is not None:
            self.instrument.close()
        if new is not "":
            self.instrument = SerialUtil.open(new, self.visa_resource, command="ID")
            if self.instrument is None:
                GenericPopupMessage(message="Error opening " + new).edit_traits()
                self.instrument = None
                self.selected_device = ""

    def _selected_device_default(self):
        try:
            device = self._available_devices_map.items()[0][0]
        except IndexError:
            return ""
        self._selected_device_changed(device)
        return device

    def _enabled_channels_default(self):
        return [True, False]

    def _bias_table_default(self):
        return [TableEntry(time=10, bias=0.0, remaining=0), TableEntry(time=10, bias=0.5, remaining=0)]

    def __available_devices_map_default(self):
        try:
            instruments_info = self.visa_resource.list_resources_info()
        except visa.VisaIOError:
            return {}
        d = {}
        candidates = [n for n in instruments_info.values() if n.resource_name.upper().startswith("GPIB")]
        d.update(SerialUtil.probe(candidates, self.visa_resource, INSTRUMENT_IDENTIFIER, command="ID"))
        return d

    def _bias_changed(self, new):
        if self.instrument is not None:
            self.instrument.write("BI" + str(new))
 def _timer_button_fired(self):
     if self.timer is None:
         self.timer = Timer(100, self.update_plot)
     else:
         self.timer.stop()
         self.timer = None
Exemplo n.º 54
0
class TemperatureControlPanel(HasTraits):
    TIMING_UPDATE_INTERVAL = 500.0

    pane_name = Str('Temperature control ')
    pane_id = Str('sensorscience.unimeas.temperatur_control_pane')
    output_channels = Dict({0:'temp_controller'})
    y_units = Dict({0 : 'temp'})
    enable = Bool(False)
    loop_sequence = Bool(True)
    poll_timer = Instance(Timer)
    timing_timer = Instance(Timer)
    table_entries = List(TableEntry)
    current_row = Int(0)
    current_temp = Float
    actual_temp = Float
    process_value = Float
    adjusted_pv = Float
    PID_out = Float
    pwm_value = Int
    max31865_ctrl = Int
    max31865_error = Int
    setpoint = Float
    supply_voltage = Float
    RT_resistance = Float
    set_temp = Float
    current_time = Float
    row_start_time = Float
    start_time = Float
    running = False
    connected = Bool(False)
    save_detailed_log = Bool(False)

    pid_P = Float(0)
    pid_I = Float(0)
    pid_D = Float(0)
    pid_N = Float(0)
    pwm_table_index = Int(0)
    use_direct_pwm = Bool(False)
    pwm_set_direct = Int(0)

    use_direct_pv = Bool(False)
    pv_set_direct = Int(0)


    temp_setpoint = Float
    resistance_setpoint = Float
    supply_voltage_setpoint = Float(15.0)
    RT_resistance_setpoint = Float(109.71)


    temperature_table = Array
    selected_com_port = Str
    selected_pid_configuration = Str
    available_pid_configurations = List(['Normal TO-8', 'M18 ceramic', 'L-A Cap'])
    com_ports_list = List(Str)
    connect = Button
    connect_button_string = Str('Connect')
    update_PID_values = Int(0)
    set_parameters = Button
    update_pid = Button
    save = Button
    load = Button
    filename = File

    set_parameters_queue = Instance(Queue.Queue)
    get_parameters_queue = Instance(Queue.Queue)
    serial_handler = Instance(SerialHandler)

    traits_view = View(
        HGroup(Item('selected_com_port',  label='Com port',
                    editor=EnumEditor(name='com_ports_list'),
                    enabled_when='not running'),
               Item('connect', editor=ButtonEditor(label_value='connect_button_string'),
                    show_label=False,  enabled_when='selected_com_port != ""')),
        Item('enable', label='Enable temp program', enabled_when='connected'),
        Item('loop_sequence', label='Loop temperature sequence'),
        Group(Item('table_entries', show_label=False, editor=table_editor,
                   enabled_when='True'
                   ),
              HGroup(Item('filename'), spring, Item('save', show_label=False),
                     Item('load', show_label=False)),
              show_border=True,
              ),
        Group(
            HGroup(
                VGroup(Item('actual_temp', style='readonly', format_str='%.2f'),
                       Item('process_value', style='readonly', format_str='%.2f'),
                       Item('adjusted_pv', style='readonly', format_str='%.2f'),
                    Item('setpoint', style='readonly', format_str='%.2f')),
                spring,
                VGroup(Item('pwm_value', style='readonly', format_str='%d'),
                       Item('max31865_ctrl', style='readonly', format_str='%#04x'),
                       Item('max31865_error', style='readonly', format_str='%#04x')),
                spring,
                VGroup(Item('PID_out', style='readonly', format_str='%.2f'),
                       Item('supply_voltage', style='readonly', format_str='%.2f'),
                       Item('RT_resistance', style='readonly', format_str='%.2f'))),
            label='Diagnostic parameters', show_border=True,
        ),
       HGroup(
            Group(
                VGroup(Item('temp_setpoint', format_str='%.1f')),
                VGroup(Item('resistance_setpoint', format_str='%.1f')),
                VGroup(Item('supply_voltage_setpoint', format_str='%.1f')),
                VGroup(Item('RT_resistance_setpoint', format_str='%.1f')),
                Item('set_parameters', enabled_when='connected'),
                label='Adjustable parameters', show_border=True,
                ),
            Group(
                Item('selected_pid_configuration', label='PID adaption',
                     editor=EnumEditor(name='available_pid_configurations'),
                     enabled_when='True'),
                VGroup(Item('pid_P', label='PID P', format_str='%.7f')),
                VGroup(Item('pid_I', label='PID I', format_str='%.7f')),
                VGroup(Item('pid_D', label='PID D',  format_str='%.7f')),
                VGroup(Item('pid_N', label='PID Nd',  format_str='%.7f')),
                VGroup(Item('pwm_table_index', label='tbl_idx')),
                HGroup(Item('use_direct_pwm'), Item('pwm_set_direct', show_label=False)),
                HGroup(Item('use_direct_pv'), Item('pv_set_direct', show_label=False)),
                Item('update_pid', enabled_when='connected'),
                Item('save_detailed_log', enabled_when='connected'),
                label='PID parameters - Don\'t touch', show_border=True,
                ),
        ),
        resizable=True, kind='live', handler=TemperatureControlHandler
    )

    def _set_parameters_queue_default(self):
        return Queue.Queue(QUEUE_LENGHT)

    def _get_parameters_queue_default(self):
        return Queue.Queue(QUEUE_LENGHT)

    def _temp_setpoint_changed(self, new):
        self.resistance_setpoint = temp_to_resistance(new, self.RT_resistance_setpoint)

    def _connected_changed(self, new):
        if new is True:
            self.connect_button_string = 'Disconnect'
            self._selected_pid_configuration_changed(self.selected_pid_configuration)
            self.update_PID_values = 3
        else:
            self.connect_button_string = 'Connect'

    def _save_detailed_log_changed(self, new):
        if new:
            self.fh = open('templog_' + strftime("%y%m%d_%H%M%S") + '.csv', 'w')
            self.csv_writer = csv.writer(self.fh,quoting=csv.QUOTE_NONNUMERIC)
            self.csv_writer.writerow(['pv','pid_out','pwm','max31ctrl','max31err','sp', 'sv','RT_ref','pid_p','pid_i','pid_d','pid_n','time'])
            self.log_start_time = time()
        else:
            self.fh.close()

    def _RT_resistance_setpoint_changed(self, new):
        self.resistance_setpoint = temp_to_resistance(self.temp_setpoint, new)

    def _selected_pid_configuration_changed(self, new):
        self.pid_P = PID_configurations[new]['P']
        self.pid_I = PID_configurations[new]['I']
        self.pid_D = PID_configurations[new]['D']
        self.pid_N = PID_configurations[new]['N']
        self.pwm_table_index = PID_configurations[new]['pwm_table_index']

    def _selected_pid_configuration_default(self):
        return 'Normal TO-8'

    def _available_pid_configurations_default(self):
        return PID_configurations.keys()

    def _onTimer(self):
        self.current_time = time() - self.start_time
        index = int(np.floor(self.current_time))
        if index >= len(self.temperature_table):
            return
        if self.temperature_table[index] is not self.current_temp:
            self.current_temp = self.temperature_table[index]
        if self.current_row >= len(self.table_entries):
            return
        time_left = self.table_entries[self.current_row].time + self.row_start_time - self.current_time
        self.table_entries[self.current_row].remaining = int(time_left)
        if self.table_entries[self.current_row].remaining < 1:
            self.current_row += 1
            self.row_changed(time_left)

    def _poll_queue(self):
        while not self.get_parameters_queue.empty():
            try:
                values = self.get_parameters_queue.get_nowait()
            except Queue.Empty:
                logger.error('No temp recieved from SerialHandler - Strange')
                pass
            self.get_parameters_queue.task_done()
            self.actual_temp = resistance_to_temp(values[0], values[7])
            self.process_value = values[0]
            self.adjusted_pv = values[0]*(109.7/values[7])
            self.PID_out = values[1]
            self.pwm_value = values[2]
            self.max31856_ctrl = values[3]
            self.max31856_error = values[4]
            self.setpoint = values[5]
            self.supply_voltage = values[6]
            self.RT_resistance = values[7]
            if self.update_PID_values > 0:
                self.update_PID_values -= 1
                self.pid_P = values[8]
                self.pid_I = values[9]
                self.pid_D = values[10]
                self.pid_N = values[11]
            if self.save_detailed_log:
                self.csv_writer.writerow(values)

    def _table_entries_default(self):
        return [TableEntry(time = 15, start_temp = 150, end_temp = 150, remaining = -1),
                TableEntry(time = 15, start_temp = 350, end_temp = 350, remaining = -1),
                TableEntry(time = 15, start_temp = 250, end_temp = 250, remaining = -1)]
        #        return [TableEntry(time = 700, start_temp = 50, end_temp = 650, remaining = -1),
        #        TableEntry(time = 200, start_temp = 650, end_temp = 650, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 650, end_temp = 200, remaining = -1),
        #        TableEntry(time = 7300, start_temp = 200, end_temp = 200, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 200, end_temp = 150, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 150, end_temp = 150, remaining = -1),
        #        TableEntry(time = 750, start_temp = 150, end_temp = 650, remaining = -1),
        #        TableEntry(time = 120, start_temp = 650, end_temp = 50, remaining = -1),
        #        TableEntry(time = 700, start_temp = 50, end_temp = 650, remaining = -1),
        #        TableEntry(time = 200, start_temp = 650, end_temp = 650, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 650, end_temp = 300, remaining = -1),
        #        TableEntry(time = 7300, start_temp = 300, end_temp = 300, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 300, end_temp = 150, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 150, end_temp = 150, remaining = -1),
        #        TableEntry(time = 750, start_temp = 150, end_temp = 650, remaining = -1),
        #        TableEntry(time = 120, start_temp = 650, end_temp = 50, remaining = -1),
        #        TableEntry(time = 700, start_temp = 50, end_temp = 650, remaining = -1),
        #        TableEntry(time = 200, start_temp = 650, end_temp = 650, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 650, end_temp = 400, remaining = -1),
        #        TableEntry(time = 7300, start_temp = 400, end_temp = 400, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 400, end_temp = 150, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 150, end_temp = 150, remaining = -1),
        #        TableEntry(time = 750, start_temp = 150, end_temp = 650, remaining = -1),
        #        TableEntry(time = 120, start_temp = 650, end_temp = 50, remaining = -1),
        #        TableEntry(time = 700, start_temp = 50, end_temp = 650, remaining = -1),
        #        TableEntry(time = 200, start_temp = 650, end_temp = 650, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 650, end_temp = 500, remaining = -1),
        #        TableEntry(time = 7300, start_temp = 500, end_temp = 500, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 500, end_temp = 150, remaining = -1),
        #        TableEntry(time = 1200, start_temp = 150, end_temp = 150, remaining = -1),
        #        TableEntry(time = 750, start_temp = 150, end_temp = 650, remaining = -1),
        #        TableEntry(time = 120, start_temp = 650, end_temp = 50, remaining = -1),]

    def start_stop(self, running):
        if not self.enable:
            return

        if running:
            if self.running:
                return

            self.start_time = time()
            self.calculate_temperature_table()
            for row in self.table_entries:
                row.remaining = row.time
            self.current_time = 0
            self.current_row = 0
            self.row_changed(time() - self.start_time)
            self.current_temp = self.temperature_table[0]
            self.timing_timer = Timer(self.TIMING_UPDATE_INTERVAL, self._onTimer)

        else:
            if not self.running:
                return
            if self.timing_timer is not None:
                self.timing_timer.Stop()
        self.running = running

    def add_data(self, data):
        pass

    def get_data(self):
        return {'time': 0}, {'temp': self.actual_temp}

    def calculate_temperature_table(self):
        self.temperature_table = np.array([])
        for row in self.table_entries:
            self.temperature_table = np.hstack((self.temperature_table,
                                                np.linspace(row.start_temp, row.end_temp, row.time)))

    def row_changed(self, remainder):
        self.row_start_time = self.current_time + remainder
        if self.current_row >= len(self.table_entries):
            if self.loop_sequence:
                self.start_time = time()
                for row in self.table_entries:
                    row.remaining = row.time
                self.current_time = 0
                self.current_row = 0
                self.row_changed(time() - self.start_time)

    def _current_temp_changed(self, new):
        self.temp_setpoint = new
        if self.use_direct_pwm:
            self.pwm_set_direct = int(new)
            self._update_pid_fired()
            return
        self._set_parameters_fired()

    def _com_ports_list_default(self):
        import serial.tools.list_ports as lp
        l = []
        for p in lp.grep('Arduino'):
            l.append(p[0])
        return l

    def _set_parameters_fired(self):
        self.set_parameters_queue.put_nowait(struct.pack('<c5B5f', 's', 0, 0, 0, 0, self.pwm_table_index,
            self.resistance_setpoint, self.supply_voltage_setpoint, 
            self.RT_resistance_setpoint, 0, 0))

    def _update_pid_fired(self):
        self.set_parameters_queue.put_nowait(struct.pack('<c4f', 'p', self.pid_P, self.pid_I, self.pid_D, self.pid_N))
        self.set_parameters_queue.put_nowait(struct.pack('<c5B5f', 's', 0, 
            int(self.use_direct_pwm), int(self.use_direct_pv), self.pwm_set_direct, self.pwm_table_index, self.resistance_setpoint,
            self.supply_voltage_setpoint, self.RT_resistance_setpoint, 0, self.pv_set_direct))
        self.update_PID_values = 3

    def _connect_fired(self):
        if self.serial_handler is None:
            self.serial_handler = SerialHandler(self.set_parameters_queue, self.get_parameters_queue,
                    self.selected_com_port)
            if not self.serial_handler.open_port():
                return
            self.poll_timer = Timer(POLL_INTERVAL, self._poll_queue)
            self.serial_handler.start()
            self.connected = True
        else:
            self.start_stop(False)
            self.serial_handler.exit_flag = True
            self.serial_handler.join()
            self.serial_handler = None
            if self.poll_timer is not None:
                self.poll_timer.stop()
            self.connected = False

    def _save_fired(self):
        if self.filename is '':
            GenericPopupMessage(message='No filename given').edit_traits()
            return
        filehandle = open(self.filename, "w", 1)
        fieldnames = self.table_entries[0].trait_get().keys()
        csv_writer = csv.DictWriter(filehandle, fieldnames=fieldnames, delimiter=',',
                                    quotechar='"', quoting=csv.QUOTE_NONNUMERIC,
                                    lineterminator='\n')
        csv_writer.writeheader()
        for row in self.table_entries:
            csv_writer.writerow(row.trait_get())
        filehandle.close()

    def _load_fired(self):
        if self.filename is '':
            GenericPopupMessage(message='No filename given').edit_traits()
            return
        filehandle = open(self.filename, 'rU', 1)
        reader = csv.DictReader(filehandle, lineterminator='\n')
        self.table_entries = []
        for row in reader:
            self.table_entries.append(TableEntry(time = int(row['time']),
                                                start_temp=int(row['start_temp']),
                                                end_temp=int(row['end_temp']),
                                                remaining=int(row['time'])))
        filehandle.close()

    def _set_temp_table_for_calibration(self):
        pwms = [int(a) for a in np.hstack((np.linspace(0, 255, 256), np.linspace(255, 0, 256)))]
        self.table_entries = [TableEntry(time = 60, start_temp = t, end_temp = t, remaining = -1) for t in pwms]
        self.temp_setpoint = self.table_entries[0].start_temp - 1 # Make sure they are unequal
Exemplo n.º 55
0
class NI6215(HasTraits):
    """Dummy instrument for generation of values (V, I, R) over time"""

    """ 'IInstrument' interface ############################################# """
    name = Unicode('NI-DAQmx')
    measurement_info = Dict()
    x_units = Dict({0:'SampleNumber', 1:'Time'})
    y_units = Dict({0: 'Voltage'})
    running = Bool(False)
    output_channels = Dict({0:'ai00', 1:'ai01', 2:'ai02', 3:'ai03',
                            4:'ai04', 5:'ai05', 6:'ai06', 7:'ai07',
                            8:'ai08', 9:'ai09', 10:'ai10', 11:'ai11',
                            12:'ai12', 13:'ai13', 14:'ai14', 15:'ai15'})
    enabled_channels = List(Bool)
    CHANNEL_CELL_WIDTH = 25.0
    sampling_interval = Range(0.05, 10, 1)
    start_stop = Event
    refresh_list = Button
    ai0 =Bool(False)
    ai1 =Bool(False)
    ai2 =Bool(False)
    ai3 =Bool(False)
    ai4 =Bool(False)
    ai5 =Bool(False)
    ai6 =Bool(False)
    ai7 =Bool(False)
    ai8 =Bool(False)
    ai9 =Bool(False)
    ai10 =Bool(False)
    ai11 =Bool(False)
    ai12 =Bool(False)
    ai13 =Bool(False)
    ai14 =Bool(False)
    ai15 =Bool(False)
    button_label = Str('Start')

    value_ai0 = Float
    value_ai1 = Float
    value_ai2 = Float
    value_ai3 = Float

    synced_acqusistion = Bool(False)

    data_acquired = Bool(False)
    data = List(Float)
    output_unit = 0
    timebase = 0
    acqusition_task = Instance(Task)
    acquired_data = List(Dict)
    _available_devices_map = Dict(Unicode, Unicode)
    selected_device = Str
    parameter_group = Group(Item('sampling_interval', enabled_when='not running'),
                            show_border=True)

    traits_view = View(parameter_group,
                       HGroup(Label('Device: '), Item('selected_device',
                                                      show_label=False,
                                                      editor=EnumEditor(name='_available_devices_map'),
                                                      enabled_when='not running'),
                              Item('refresh_list')),
                       HGroup(Label('Channels:'), spring, 
                              VGroup(
                                  HGroup(
                                      Item('ai0', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai1', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai2', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai3', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH)),
                                  HGroup(
                                      Item('ai4', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai5', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai6', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai7', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH)),
                                  HGroup(
                                      Item('ai8', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai9', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai10', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai11', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH)),
                                  HGroup(
                                      Item('ai12', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai13', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai14', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH),
                                      Item('ai15', enabled_when='not running', springy=True, width=CHANNEL_CELL_WIDTH)))),
                       HGroup(Item('value_ai0', style='readonly'),
                              Item('value_ai1', style='readonly'),
                              Item('value_ai2', style='readonly'),
                              Item('value_ai3', style='readonly')),
                       Item('synced_acqusistion', enabled_when='false'),
                       Item('start_stop', label='Start/Stop Acqusistion',
                            editor=ButtonEditor(label_value='button_label')),
                       handler=NI6215Handler)

    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.on_trait_change(self.channel_changed, 'ai+')
        self.ai0 = self.ai1 = self.ai2 = self.ai3 = True

    def _enabled_channels_default(self):
        return [False] * 16

    def __available_devices_map_default(self):
        s = str('000000000000000000000000000000000000000000000000000')
        PyDAQmx.DAQmxGetSysDevNames(s, len(s))
        (a, b, c) = s.partition('\x00')
        devs = a.split(', ')
        serial = c_uint32(0)
        devices=[]
        for d in devs:
            if len(d) > 0:
                PyDAQmx.DAQmxGetDevProductType(d, s, len(s))
                (a, b, c) = s.partition('\x00')
                if a.startswith('USB-'):
                    PyDAQmx.DAQmxGetDevSerialNum(d, serial)
                    devices.append((d, a + ' - ' + hex(serial.value)[2:-1].upper()))
                if a.startswith('PCI-'):
                    PyDAQmx.DAQmxGetDevSerialNum(d, serial)
                    devices.append((d, a + ' - In computer'))
            else:
                break
        retval = dict((device[0], device[1]) for device in devices)
        self.logger.info('_available_devices_map_default %s', retval)
        return retval

    @on_trait_change('_available_devices_map')
    def __available_devices_map_changed(self):
        if self.selected_device not in self._available_devices_map.keys():
            self.selected_device = self._available_devices_map.items()[0][0]

    def _selected_device_default(self):
        try:
            device = self._available_devices_map.items()[0][0]
        except IndexError:
            return ''
        return device

    def _refresh_list_fired(self):
        self._available_devices_map = self.__available_devices_map_default()
        self.__available_devices_map_changed()

    def add_data(self, data):
        self.data = data

    def handle_data(self):
        if self.data_acquired is False:
            return
        self.data_acquired = False
        if len(self.data) < 18:
            return
        d = dict()
        for i, enabled in enumerate(self.enabled_channels):

            d[self.output_channels[i]] = (dict({self.x_units[0]:self.data[0], self.x_units[1]:self.data[1], }),
                                          dict({self.y_units[0]:self.data[i + 2]}))
        self.acquired_data.append(d)
        self.value_ai0 = self.data[2]
        self.value_ai1 = self.data[3]
        # self.timer = Timer.singleShot(RENDER_INTERVAL_MS, self.add_data)

    def start(self):
        self.running = True
        self.acq_start_time = time()
        if self.synced_acqusistion is True:
            self.acqusition_task = CallbackTaskSynced()
        else:
            self.acqusition_task = CallbackTask()
        channels = []
        for i, enabled in enumerate(self.enabled_channels):
            if enabled:
                channels.append('ai' + str(i))
        self.acqusition_task.setup('/' + self.selected_device,
                                   channels, self.sampling_interval, self)
        self.acqusition_task.StartTask()
        self.timer = Timer(RENDER_INTERVAL_MS, self.handle_data)
        self.timer.start()

    def stop(self):
        self.logger.info('stop()')
        self.running = False
        self.acqusition_task.StopTask()
        self.acqusition_task.ClearTask()

    def _start_stop_fired(self, old, new):
        if self.running:
            self.button_label = 'Start'
            self.stop()
        else:
            self.button_label = 'Stop'
            self.start()

    def channel_changed(self, obj, name, new):
        self.enabled_channels[int(name[2:])] = new
Exemplo n.º 56
0
    def start(self):
        self.instrument.write('reset()')
        self.instrument.write('digio.writeprotect = 0')
        self.instrument.write('smua.measure.nplc = 5')
        self.instrument.write('smua.measure.autozero = smua.AUTOZERO_ONCE')
        self.instrument.write('smua.sense = smua.SENSE_REMOTE')
        self.instrument.write('smua.source.autorangei = smua.AUTORANGE_OFF')
        self.instrument.write('smua.source.autorangev = smua.AUTORANGE_OFF')
        self.instrument.write('smua.measure.autorangei = smua.AUTORANGE_OFF')
        self.instrument.write('smua.measure.autorangev = smua.AUTORANGE_OFF')

        if self.constant_current_mode:
            self.instrument.write('smua.source.func = smua.OUTPUT_DCAMPS')
            self.instrument.write('smua.source.limitv = {:f}'.format(self.voltage_limit))
            self.instrument.write('smua.source.leveli = {:f}'.format(self.current/1000))
            self.instrument.write('smua.source.rangei = {:f}'.format(1.2*self.current/1000))
            if self.voltage_range == 'Auto':
                self.instrument.write('smua.measure.autorangev = smua.AUTORANGE_ON')
            else:
                self.instrument.write('smua.measure.rangev = ' + self.voltage_range)
            self.instrument.write('display.smua.measure.func = smua.OUTPUT_DCVOLTS')
        else:
            self.instrument.write('smua.source.func = smua.OUTPUT_DCVOLTS')
            self.instrument.write('smua.source.limiti = {:f}'.format(self.current_limit/1000))
            self.instrument.write('smua.source.levelv = {:f}'.format(self.voltage))
            self.instrument.write('smua.source.rangev = {:f}'.format(self.voltage*1.2))

            if self.current_range == 'Auto':
                self.instrument.write('smua.measure.autorangei = smua.AUTORANGE_ON')
            else:
                self.instrument.write('smua.measure.rangei = {:f}'.format(float(self.current_range)))
            self.instrument.write('display.smua.measure.func = smua.OUTPUT_DCAMPS')
            if self.derivative_resistance_enabled:
                nplc = (0.25*(self.sampling_interval/self.derivative_resistance_voltage_points))/0.02
                logger.info('NPLC=%f', nplc)
                self.instrument.write('smua.measure.nplc = {:f}'.format(nplc))
                self.instrument.write('smua.nvbuffer1.clear()')
                self.instrument.write('smua.nvbuffer1.appendmode = 1')
                self.instrument.write('smua.source.autorangei = smua.AUTORANGE_OFF')
                self.instrument.write('smua.source.autorangev = smua.AUTORANGE_OFF')
                self.instrument.write('smua.source.rangev = {:f}'.format(self.voltage +
                                                                         self.derivative_resistance_voltage_span*1.2))
                query = 'f1, msg1 = ConfigPulseVMeasureISweepLin(smua, {:f}, {:f}, {:f}, {:f}, {:f}, 0, {:d}, ' \
                        'smua.nvbuffer1, 1)'.format(self.voltage,
                                                    self.voltage - self.derivative_resistance_voltage_span,
                                                    self.voltage + self.derivative_resistance_voltage_span,
                                                    self.current_limit/1000,
                                                    0.5*(self.sampling_interval /
                                                         self.derivative_resistance_voltage_points),
                                                    self.derivative_resistance_voltage_points)
                logger.info(query)
                self.instrument.write(query)
                response = self.instrument.query('print(f1, msg1)')
                logger.info(response)

        self.instrument.write('smua.source.output = smua.OUTPUT_ON')
        self.running = True
        self.start_time = time()
        self.sample_number = 0

        if self.running:
            self.timer = Timer.singleShot(max(((self.sample_number+1) * self.sampling_interval -
                                           (time()-self.start_time))*1000, 0.01),
                                          self._on_timer)
Exemplo n.º 57
0
 def start(self):
     self.timer = Timer(100, self.monitor_physiology)
Exemplo n.º 58
0
class DummyIntervalInstrument(HasTraits):

    #    implements(IInstrument)

    name = Unicode("DummyIntervalInstrument")
    model = Unicode("DummyInterval")

    # x_units = Dict
    # y_units = Dict
    x_units = Dict({0: "Voltage"})
    y_units = Dict({0: "Current", 1: "Resistance"})
    acquired_data = List(Dict)

    start_stop = Event
    running = Bool

    output_channels = Dict({0: "IV", 1: "CF"})
    measurement_info = Dict()
    enabled_channels = List(Bool)

    timer = Instance(Timer)
    update_interval = Float(0.03)
    start_voltage = Float(0)
    stop_voltage = Float(5)
    step_voltage = Float(0.05)
    current_voltage = Float
    current_current = Float

    start_frequency = Float(20)
    stop_frequency = Float(1e6)
    step_frequency = Float(10000)
    current_frequency = Float
    current_capacitance = Float
    use_log_steps = Bool(True)
    iteration = Int(0)
    start_stop = Event
    button_label = Str("Start")
    sweep_name = Str
    bias = Float
    measurement_mode = Int

    traits_view = View(
        Item("measurement_mode", editor=EnumEditor(name="output_channels"), enabled_when="not running"),
        Group(
            Item("start_voltage"),
            Item("stop_voltage"),
            Item("step_voltage"),
            Item("current_voltage", enabled_when="False"),
            Item("current_current", enabled_when="False"),
            label="I/V",
            show_border=True,
        ),
        Group(
            Item("start_frequency"),
            Item("stop_frequency"),
            Item("step_frequency"),
            Item("use_log_steps"),
            Item("current_frequency", enabled_when="False"),
            Item("current_capacitance", enabled_when="False"),
            label="C/F",
            show_border=True,
        ),
        Item("update_interval"),
        Item("sweep_name"),
        Item("start_stop", label="Start/Stop Acqusistion", editor=ButtonEditor(label_value="button_label")),
        handler=DummyIntervalInstrumentHandler,
    )

    def start(self):
        if self.timer is None:
            self.timer = Timer(self.update_interval * 1000, self._onTimer)
        else:
            self.timer.Start(self.update_interval * 1000)
        self.button_label = "Stop"
        self.current_voltage = self.start_voltage
        self.current_frequency = self.start_frequency
        self.iteration = 0
        self.running = True
        self.bias = random.random_sample() - 0.5
        self.measurement_info = {
            "name": self.sweep_name,
            "start_voltage": self.start_voltage,
            "start_frequency": self.start_frequency,
            "start_bias": self.bias,
        }
        if len(self.measurement_info["name"]) is 0:
            self.measurement_info.pop("name")

    def stop(self):
        if self.timer is not None:
            self.timer.Stop()
        self.button_label = "Start"
        self.running = False

    def _onTimer(self):
        d = dict()
        self.current_current = self.current_voltage ** 1.3 + self.bias
        self.current_capacitance = (self.current_frequency * (self.stop_frequency - self.current_frequency)) / 1e9
        if self.measurement_mode is 0:
            d[self.output_channels[self.measurement_mode]] = (
                dict({self.x_units[0]: self.current_voltage}),
                dict(
                    {
                        self.y_units[0]: self.current_current,
                        self.y_units[1]: self.current_voltage / self.current_current,
                    }
                ),
            )
        elif self.measurement_mode is 1:
            d[self.output_channels[self.measurement_mode]] = (
                dict({self.x_units[0]: self.current_frequency}),
                dict({self.y_units[0]: self.current_capacitance}),
            )

        self.iteration += 1
        self.current_voltage += self.step_voltage

        # if self.use_log_steps:
        self.current_frequency += self.step_frequency
        self.acquired_data.append(d)
        if self.current_voltage > self.stop_voltage:
            self.start_stop = True

    def _start_stop_fired(self):
        if self.timer is None:
            self.start()
            return
        if self.timer.isActive():
            self.stop()
        else:
            self.start()

    def _enabled_channels_default(self):
        return [True, False]

    def _measurement_mode_changed(self, new):
        if new is 0:
            self.x_units = {0: "Voltage"}
            self.y_units = {0: "Current", 1: "Resistance"}
            self.enabled_channels = [True, False]
        elif new is 1:
            self.x_units = {0: "Frequency"}
            self.y_units = {0: "Capacitance"}
            self.enabled_channels = [False, True]

    def _measurement_mode_default(self):
        return 0

    def get_nr_of_samples(self):
        if self.measurement_mode == 0:
            return (self.stop_frequency - self.start_frequency) / self.step_frequency
        elif self.measurement_mode == 1:
            return (self.stop_voltage - self.start_voltage) / self.step_voltage
        else:
            return 1