ohmpi.py 51.5 KB
Newer Older
                last_measurement.update(tdic)
            last_measurement.pop('fulldata')

Guillaume Blanchy's avatar
Guillaume Blanchy committed
            # Load data file and append data to it
                w = csv.DictWriter(f, last_measurement.keys())
                w.writerow(last_measurement)
                # last_measurement.to_csv(f, header=False)
Guillaume Blanchy's avatar
Guillaume Blanchy committed
        else:
            # create data file and add headers
                w = csv.DictWriter(f, last_measurement.keys())
                w.writeheader()
                w.writerow(last_measurement)
    def _process_commands(self, message):
        """Processes commands received from the controller(s)

        Parameters
        ----------
            message containing a command and arguments or keywords and arguments
            decoded_message = json.loads(message)
            print(f'decoded message: {decoded_message}')
            cmd_id = decoded_message.pop('cmd_id', None)
            cmd = decoded_message.pop('cmd', None)
            args = decoded_message.pop('args', '[]')
            args = json.loads(args)
            kwargs = decoded_message.pop('kwargs', '{}')
            kwargs = json.loads(kwargs)
            self.exec_logger.debug(f'Calling method {cmd}({args}, {kwargs})')
            # e = None  # NOTE: Why this?
            print(cmd, args, kwargs)
            if cmd_id is None:
                self.exec_logger.warning('You should use a unique identifier for cmd_id')
            if cmd is not None:
                try:
                    output = getattr(self, cmd)(*args, **kwargs)
                    self.exec_logger.error(
                        f"{e}\nUnable to execute {cmd}({args + ', ' if args != '[]' else ''}"
                        f"{kwargs if kwargs != '{}' else ''})")
            self.exec_logger.warning(f'Unable to decode command {message}: {e}')
            status = False
        finally:
            reply = {'cmd_id': cmd_id, 'status': status}
            reply = json.dumps(reply)
            self.exec_logger.debug(f'Execution report: {reply}')
    def set_sequence(self, sequence=sequence):
            self.sequence = np.loadtxt(StringIO(sequence)).astype('uint32')
            status = True
        except Exception as e:
            self.exec_logger.warning(f'Unable to set sequence: {e}')
            status = False

    def run_sequence(self, cmd_id=None, **kwargs):
        """Runs sequence synchronously (=blocking on main thread).
           Additional arguments are passed to run_measurement().
        """
        self.status = 'running'
        self.exec_logger.debug(f'Status: {self.status}')
        self.exec_logger.debug(f'Measuring sequence: {self.sequence}')
        t0 = time.time()

        # create filename with timestamp
        filename = self.settings["export_path"].replace('.csv',
                                                        f'_{datetime.now().strftime("%Y%m%dT%H%M%S")}.csv')
        self.exec_logger.debug(f'Saving to {filename}')

        # make sure all multiplexer are off
        self.reset_mux()

        # measure all quadrupole of the sequence
        if self.sequence is None:
            n = 1
        else:
            n = self.sequence.shape[0]
        for i in range(0, n):
            if self.sequence is None:
                quad = np.array([0, 0, 0, 0])
            else:
                quad = self.sequence[i, :]  # quadrupole
            if self.status == 'stopping':
                break

            # call the switch_mux function to switch to the right electrodes
            self.switch_mux_on(quad)

            # run a measurement
            if self.on_pi:
                acquired_data = self.run_measurement(quad, **kwargs)
            else:  # for testing, generate random data
                acquired_data = {
                    'A': [quad[0]], 'B': [quad[1]], 'M': [quad[2]], 'N': [quad[3]],
                    'R [ohm]': np.abs(np.random.randn(1))
                }

            # switch mux off
            self.switch_mux_off(quad)

            # add command_id in dataset
            acquired_data.update({'cmd_id': cmd_id})
            # log data to the data logger
            self.data_logger.info(f'{acquired_data}')
            # save data and print in a text file
            self.append_and_save(filename, acquired_data)
            self.exec_logger.debug(f'quadrupole {i+1:d}/{n:d}')

        self.status = 'idle'

    def run_sequence_async(self, cmd_id=None, **kwargs):
        """Runs the sequence in a separate thread. Can be stopped by 'OhmPi.interrupt()'.
            Additional arguments are passed to run_measurement().
            self.run_sequence(**kwargs)

        self.thread = threading.Thread(target=func)
        self.thread.start()
        self.status = 'idle'
    def measure(self, *args, **kwargs):
        warnings.warn('This function is deprecated. Use run_multiple_sequences() instead.', DeprecationWarning)
        self.run_multiple_sequences(self, *args, **kwargs)

    def run_multiple_sequences(self, cmd_id=None, sequence_delay=None, nb_meas=None, **kwargs):
        """Runs multiple sequences in a separate thread for monitoring mode.
           Can be stopped by 'OhmPi.interrupt()'.
           Additional arguments are passed to run_measurement().
Olivier Kaufmann's avatar
Olivier Kaufmann committed

        Parameters
        ----------
        sequence_delay : int, optional
            Number of seconds at which the sequence must be started from each others.
        nb_meas : int, optional
            Number of time the sequence must be repeated.
        kwargs : dict, optional
            See help(k.run_measurement) for more info.
Guillaume Blanchy's avatar
Guillaume Blanchy committed
        """
        if sequence_delay is None:
            sequence_delay = self.settings['sequence_delay']
        sequence_delay = int(sequence_delay)
        if nb_meas is None:
            nb_meas = self.settings['nb_meas']
        self.status = 'running'
        self.exec_logger.debug(f'Measuring sequence: {self.sequence}')
        def func():
            for g in range(0, nb_meas): # for time-lapse monitoring
                if self.status == 'stopping':
                    self.exec_logger.warning('Data acquisition interrupted')
                    break
                t0 = time.time()
                self.run_sequence(**kwargs)
Guillaume Blanchy's avatar
Guillaume Blanchy committed
                # sleeping time between sequence
                dt = sequence_delay - (time.time() - t0)
                if dt < 0:
                    dt = 0
                    time.sleep(dt)  # waiting for next measurement (time-lapse)
            self.status = 'idle'
Guillaume Blanchy's avatar
Guillaume Blanchy committed
        self.thread = threading.Thread(target=func)
        self.thread.start()
        warnings.warn('This function is deprecated. Use interrupt instead.', DeprecationWarning)
        self.interrupt()

    def interrupt(self):
Guillaume Blanchy's avatar
Guillaume Blanchy committed
        if self.thread is not None:
Guillaume Blanchy's avatar
Guillaume Blanchy committed
            self.thread.join()
        else:
            self.exec_logger.debug('No sequence measurement thread to interrupt.')

    def quit(self):
        """Quit OhmPi.
        """
        self.cmd_listen = False
        if self.cmd_thread is not None:
            self.cmd_thread.join()
        self.exec_logger.debug(f'Stopped listening to control topic.')
    def restart(self):
        self.exec_logger.info('Restarting pi...')
        os.system('reboot')

Olivier Kaufmann's avatar
Olivier Kaufmann committed
VERSION = '2.1.5'

print(colored(r' ________________________________' + '\n' +
              r'|  _  | | | ||  \/  || ___ \_   _|' + '\n' +
              r'| | | | |_| || .  . || |_/ / | |' + '\n' +
              r'| | | |  _  || |\/| ||  __/  | |' + '\n' +
              r'\ \_/ / | | || |  | || |    _| |_' + '\n' +
              r' \___/\_| |_/\_|  |_/\_|    \___/ ', 'red'))
print('Version:', VERSION)
platform, on_pi = OhmPi._get_platform()  # noqa
if on_pi:
    print(colored(f'\u2611 Running on {platform} platform', 'green'))
    # TODO: check model for compatible platforms (exclude Raspberry Pi versions that are not supported...)
    #       and emit a warning otherwise
    if not arm64_imports:
        print(colored(f'Warning: Required packages are missing.\n'
Guillaume Blanchy's avatar
Guillaume Blanchy committed
                      f'Please run ./env.sh at command prompt to update your virtual environment\n', 'yellow'))
    print(colored(f'\u26A0 Not running on the Raspberry Pi platform.\nFor simulation purposes only...', 'yellow'))

current_time = datetime.now()
print(f'local date and time : {current_time.strftime("%Y-%m-%d %H:%M:%S")}')
# for testing
if __name__ == "__main__":
    ohmpi = OhmPi(settings=OHMPI_CONFIG['settings'])
    if ohmpi.controller is not None:
        ohmpi.controller.loop_forever()