def mainloop(self):
     # HDF5 prints lots of errors by default, for things that aren't
     # actually errors. These are silenced on a per thread basis,
     # and automatically silenced in the main thread when h5py is
     # imported. So we'll silence them in this thread too:
     h5py._errors.silence_errors()
     while True:
         # data is now a dictionary
         task, data = self.from_parent.get()
         with kill_lock:
             if task == 'quit':
                 inmain(qapplication.quit)
             elif task == 'analyse':
                 path = data['filepath']
                 success = self.do_analysis(
                     path,
                     {k: v
                      for k, v in data.iteritems() if k != 'filepath'})
                 if success:
                     self.to_parent.put(['done', None])
                 else:
                     self.to_parent.put(['error', None])
             else:
                 self.to_parent.put(
                     ['error', 'invalid task %s' % str(task)])
Пример #2
0
    def do_delay(self, h5_filepath):
        if self.target_cycle_time is not None and self.time_of_last_shot is not None:
            # Wait until it has been self.target_cycle_time since the start of the last
            # shot. Otherwise, return immediately.
            deadline = self.time_of_last_shot + self.target_cycle_time
            inmain(self.BLACS['ui'].queue_abort_button.clicked.connect, self._abort)
            # Store the current queue manager status, to restore it after we are done:
            previous_status = self.queue_manager.get_status()
            while True:
                remaining = deadline - monotonic()
                if remaining <= 0:
                    break
                self.queue_manager.set_status(
                    'Waiting {:.1f}s for target cycle time'.format(remaining),
                    h5_filepath,
                )
                try:
                    self.queue.get(timeout=remaining % 0.1)
                    break # Got an abort
                except Empty:
                    continue
            # Disconnect from the abort button:
            inmain(self.BLACS['ui'].queue_abort_button.clicked.disconnect, self._abort)
            # Restore previous_status:
            self.queue_manager.set_status(previous_status, h5_filepath)

        self.time_of_last_shot = monotonic()
Пример #3
0
def run_sims():
    try:
        psi = simulator.elements.make_vector(initial_guess)
        simulator.normalise(psi, N_2D)
        psi = simulator.find_groundstate(psi,
                                         H,
                                         mu,
                                         output_group='initial',
                                         output_interval=10,
                                         output_callback=plot)
    finally:
        if SHOW_PLOT:
            inmain(qapplication.exit)
 def mainloop(self):
     # HDF5 prints lots of errors by default, for things that aren't
     # actually errors. These are silenced on a per thread basis,
     # and automatically silenced in the main thread when h5py is
     # imported. So we'll silence them in this thread too:
     h5py._errors.silence_errors()
     while True:
         task, data = self.from_parent.get()
         with kill_lock:
             if task == 'quit':
                 inmain(qapplication.quit)
             elif task == 'analyse':
                 path = data
                 success = self.do_analysis(path)
                 if success:
                     self.to_parent.put(['done', None])
                 else:
                     self.to_parent.put(['error', None])
             else:
                 self.to_parent.put(['error','invalid task %s'%str(task)])
Пример #5
0
 def mainloop(self):
     # HDF5 prints lots of errors by default, for things that aren't
     # actually errors. These are silenced on a per thread basis,
     # and automatically silenced in the main thread when h5py is
     # imported. So we'll silence them in this thread too:
     h5py._errors.silence_errors()
     while True:
         task, data = self.from_parent.get()
         with kill_lock:
             if task == 'quit':
                 inmain(qapplication.quit)
             elif task == 'analyse':
                 path = data
                 success = self.do_analysis(path)
                 if success:
                     if lyse._delay_flag:
                         lyse.delay_event.wait()
                     self.to_parent.put(['done', lyse._updated_data])
                 else:
                     self.to_parent.put(['error', lyse._updated_data])
             else:
                 self.to_parent.put(['error','invalid task %s'%str(task)])
Пример #6
0
 def mainloop(self):
     running = False
     self.clear_bar()
     while True:
         try:
             if running:
                 # How long until the next thing of interest occurs, and
                 # what is it? It can be either a wait, a marker, or a
                 # regular update.
                 next_thing, timeout = self.get_next_thing()
                 try:
                     command, _ = self.command_queue.get(timeout=timeout)
                 except Empty:
                     if next_thing == 'update':
                         self.update_bar_value()
                     if next_thing == 'marker':
                         self.update_bar_style(marker=True)
                         self.update_bar_value(marker=True)
                         self.next_marker_index += 1
                     elif next_thing == 'wait':
                         wait_start_time = time.time()
                         self.update_bar_style(wait=True)
                         self.update_bar_value(wait=True)
                         self.next_wait_index += 1
                         # wait for the wait to complete, but abandon
                         # processing if the command queue is non-empty,
                         # i.e. if a stop command is sent.
                         while self.command_queue.empty():
                             try:
                                 # Wait for only 0.1 sec at a time, so that
                                 # we can check if the queue is empty in between:
                                 self.wait_completed.wait(self.h5_filepath,
                                                          timeout=0.1)
                             except TimeoutError:
                                 # Only wait for wait completed events if the wait
                                 # monitor device supports them. Otherwise, skip
                                 # after this first timeout, and it will just look
                                 # like the wait had 0.1 sec duration.
                                 if self.wait_completed_events_supported:
                                     # The wait is still in progress:
                                     continue
                             # The wait completed (or completion events are not
                             # supported):
                             self.time_spent_waiting += time.time(
                             ) - wait_start_time
                             # Set the bar style back to whatever the
                             # previous marker was, if any:
                             self.update_bar_style(marker=True,
                                                   previous=True)
                             self.update_bar_value()
                             break
                     continue
             else:
                 command, h5_filepath = self.command_queue.get()
             if command == 'close':
                 break
             elif command == 'start':
                 assert not running
                 running = True
                 self._start(h5_filepath)
                 self.update_bar_value()
                 if (self.waits is not None and len(self.waits) > 0
                         and not self.wait_completed_events_supported):
                     inmain(self.ui.wait_warning.show)
             elif command == 'stop':
                 self.clear_bar()
                 running = False
                 self._stop()
             else:
                 raise ValueError(command)
         except Exception:
             logger.exception("Exception in mainloop, ignoring.")
             # Stop processing of the current shot, if any.
             self.clear_bar()
             inmain(self.bar.setFormat, "Error in progress bar plugin")
             running = False
             self._stop()
Пример #7
0
    def update_graph(self):
        """This method is run on a thread.
        It uses a 'stop_event' event to define if it will capture data or not.
        If not capturing, it sleeps to reduce CPU usage.
        When capturing, it sends a request to DAQ (Arduino) with the sensor it wants to read,
        which it gets from the QButtonGroup 'sensor'.
        After receiving the sensor it wants to read, the DAQ performs measurements at 500Hz and returns a string.
        The communication is secured by a 'reading' event so the serial port is not closed during comunication.
        The thread waits for this string and performs decoding and processing to convert it into a numpy array,
        which eases other processing, like removing the bites offset and transforming them into real units.
        After, it performs fft, and then integrates the fft dividing by each corresponding frequency.
        Finally, it sets data for the plot axes, and sends plotting signal to main thread."""
        while True:
            while not self.stop_event.is_set():
                try:
                    inmain(self.ui.status_lbl.setText, 'Leyendo datos @ {} del sensor {}'.format(
                        self.serial.port, self.sensor)
                           )
                    self.reading.set()
                    if not self.stop_event.is_set():
                        self.serial.write('{}'.format(self.sensor).encode('ASCII'))
                        time.sleep(0.1)
                        signal = self.serial.readline()
                    else:
                        continue
                    self.reading.clear()
                    # print(signal)  # Make a logging
                    signal = signal.decode('ASCII')
                    signal = signal.split(',')
                    if len(signal) != 500:
                        continue
                except UnicodeDecodeError as e:
                    print(e)
                    continue
                except TypeError as e:
                    print('Se ha interrumpido la comunicación.\n{}: {}'.format(
                        type(e), e))
                    continue
                except AttributeError as e:
                    print('Se ha interrumpido la comunicación.\n{}: {}'.format(
                        type(e), e))
                    continue
                except serial.SerialException as e:
                    if self.stop_event.is_set():
                        print('Se ha interrumpido la comunicación.\n{}'.format(e))
                    else:
                        self.ui.status_lbl.setText('Ha desconectado el DAQ. Conéctelo y reinicie la toma de datos.')
                        self.serial.close()
                        self.stop_event.set()
                    continue
                # except Exception as e:
                #     print(e, type(e))
                #     continue
                try:
                    signal_p = list(map(int, signal))
                    signal_p = 3 * 1.68 * 9810 * (np.array(signal_p)-512) / 512  # 9810 y no 9.81 porque es mm/s2
                    # print(signal_p)  # Signal debug
                    yf = scipy.fftpack.fft(signal_p)
                    xf = np.linspace(0.0, fs / 2.0 - 1, fs / 2)
                    xf[0] = 2 / (np.sqrt(2) * 2 * np.pi)
                    yf = (2.0 / fs * np.abs(yf[:fs // 2]))
                    yfv = yf / (2 * np.pi * xf)
                    yfv = yfv / np.sqrt(2)
                    self.ui.le_f.setText(f'{yfv[self.freq]}')
                    self.ui.le_f.setText(f'{yf[self.freq]}')
                    # Clear previous data sets
                    # self.ui.WaveWidget.canvas.ax3.clear()
                    # Add new data
                except RuntimeError:
                    continue
                except Exception as e:
                    print('{}: {}.\n\n{}\n'.format(type(e), e, signal))
                    # Printing both legends
                    # leg = lns2 + lns3
                    # labs = [l.get_label() for l in leg]
                    # self.ui.WaveWidget.canvas.ax2.legend(leg, labs, loc='upper right')
                    # Update graph with new data
                self.ui.WaveWidget.canvas.line1.set_ydata(signal_p)
                self.ui.WaveWidget.canvas.line2.set_ydata(yfv)  # 2.0 / fs * np.abs(yf[:fs // 2]))

                # self.ui.WaveWidget.canvas.ax1.plot(t, signal_p)
                # self.ui.WaveWidget.canvas.ax2.plot(xf, 2.0/fs * np.abs(yf[:fs//2]),  'co-', alpha=0.5,  # fs = n_samples
                #                                    label='Amplitude')

                inmain(self.ui.WaveWidget.canvas.draw)  # Moving to event callback method
                inmain(self.ui.WaveWidget.canvas.flush_events)
            time.sleep(0.2)