Ejemplo n.º 1
0
    def func_wrapper(cls, *args, **kwargs):
        logger = get_logger(name=__name__)
        logger.info(f'Checking if function {func.__name__} was already triggered')
        update = False
        if hasattr(cls, 'cache_setters'):
            if len(args) >= 1:
                for i, arg in enumerate(args[1:]):
                    old_arg = args[0].cache_setters.get('args')[i]
                    if arg != old_arg:
                        update = True
            if len(kwargs) > 1:
                for key, value in kwargs.items():
                    old_value = args[0].cache_setters.get('kwargs')[key]
                    if value != old_value:
                        update = True
        else:
            cls.cache_setters = dict()
            update = True

        if update:
            cls.cache_setters.update({'args': args, 'kwargs': kwargs})
            logger.info('Updating values')
            return func
        else:
            logger.info('Nothing to update')
            return lambda *args, **kwargs: None
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        super(DataViewWidget, self).__init__(parent=parent)
        self.logger = get_logger()

        self._layout = None
        self.set_layout()
        self.data = None
Ejemplo n.º 3
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # Settings for the image
        self.viewport = GraphicsLayoutWidget()
        self.view = self.viewport.addViewBox(lockAspect=False, enableMenu=True)

        self.img = pg.ImageItem()
        self.view.addItem(self.img)
        self.imv = pg.ImageView(view=self.view, imageItem=self.img)

        self.scene().sigMouseClicked.connect(self.mouse_clicked)

        # Add everything to the widget
        layout = self.get_layout()
        layout.addWidget(self.imv)

        self.show_roi_lines = False  # ROI lines are shown or not
        self.show_cross_hair = False  # Cross hair is shown or not
        self.show_cross_cut = False  # Cross cut is shown or not
        self.cross_hair_setup = False  # Cross hair was setup or not
        self.cross_cut_setup = False  # Cross cut was setup or not

        self.rois = []

        self.corner_roi = [0, 0]  # Initial ROI corner for the camera

        self.first_image = True

        self.logger = get_logger()

        self.last_image = None

        self.add_actions_to_menu()
        self.setup_mouse_tracking()
Ejemplo n.º 4
0
 def __init__(self, parent: BaseModel, **kwargs):
     self._parent = parent
     self._properties = dict()
     self._links = dict()
     self.logger = get_logger()
     if kwargs:
         for key, value in kwargs.items():
             self.__setitem__(key, value)
Ejemplo n.º 5
0
    def __init__(self, camera, initial_config=None):
        super().__init__()
        self.logger = get_logger(__name__)

        self.camera = camera
        self.running = False
        self.data_type = np.uint16
        self.temp_image = None
        self.initial_config = initial_config
Ejemplo n.º 6
0
 def __init__(self, camera, initial_config=None):
     super().__init__(camera, initial_config=initial_config)
     self.logger = get_logger(__name__)
     self.friendly_name = ''
     self.free_run_running = False
     self._stop_free_run = Event()
     self.fps = 0
     self.keep_reading = False
     self.continuous_reads_running = False
     self.finalized = False
     self._buffer_size = None
     self.current_dtype = None
Ejemplo n.º 7
0
    def __init__(self, filename=None):
        super().__init__()
        self.config = {
        }  # Dictionary storing the configuration of the experiment
        self.logger = get_logger(name=__name__)

        self._connections = []
        self.subscriber_events = []
        self.initialize_threads = [
        ]  # Threads to initialize several devices at the same time
        if filename:
            self.load_configuration(filename)

        atexit.register(self.finalize)
        self.is_alive = True
Ejemplo n.º 8
0
 def __init__(self,
              func,
              topic,
              publish_topic=None,
              args=None,
              kwargs=None):
     super(Subscriber, self).__init__()
     self.func = func
     self.topic = topic
     self.publish_topic = publish_topic
     self.args = args
     self.kwargs = kwargs
     self.logger = get_logger()
     self.logger.info(
         f'Starting subscriber for {func.__name__} on topic {topic}')
Ejemplo n.º 9
0
    def func_wrapper(*args, **kwargs):
        logger = get_logger(name=__name__)
        logger.info('Starting new thread for {}'.format(func.__name__))
        if isinstance(args[0], BaseModel):
            args[0].clean_up_threads()

        if not hasattr(args[0], '_threads'):
            args[0]._threads = []

        elif not isinstance(args[0]._threads, list):
            raise ValueError('The variable _threads must be a list in order to store a new Thread in it')

        args[0]._threads.append([func.__name__, Thread(target=func, args=args, kwargs=kwargs)])
        args[0]._threads[-1][1].start()
        logger.info('In total there are {} threads'.format(len(args[0]._threads)))
Ejemplo n.º 10
0
    def __init__(self,experiment_model=None, initialize=True, logger=logging.INFO):
        self.log = get_logger()
        if logger is not None:
            handler = log_to_screen(logger=self.log, level=logger)
        self.log.info(f'Experiment Model: {settings.EXPERIMENT_MODEL}')
        if experiment_model is not None:
            exp_model = settings.EXPERIMENT_MODEL.split('.')
            experiment_module = importlib.import_module('.'.join(exp_model[:-1]))
            experiment_model_class = getattr(experiment_module, exp_model[-1])
        else:
            experiment_model_class = experiment_model

        if settings.EXPERIMENT_MODEL_INIT is not None:
            self.experiment_model = experiment_model_class(**settings.EXPERIMENT_MODEL_INIT)
        else:
            self.experiment_model = experiment_model_class()

        if initialize:
            self.experiment_model.initialize()

        self.gui_thread = Thread(target=start_gui, args=(self.experiment_model, ))
        self.gui_thread.start()
Ejemplo n.º 11
0
from experimentor.lib.log import get_logger


logger = get_logger(__name__)


class Signal:
    """ Base signal which implements the common pattern for defining, emitting and connecting a signal
    """
    def __init__(self):
        self.name = None

    def __set_name__(self, owner, name):
        model_signals = getattr(owner, '_signals')

        if getattr(model_signals, 'model_name', None) != object.__qualname__:
            model_signals = model_signals.__class__(*model_signals)
            setattr(model_signals, 'model_name', object.__qualname__)
            setattr(owner, '_signals', model_signals)

        model_signals[name] = self

        self.name = name
        self.owner = str(owner)

    def __get__(self, instance, owner):
        self.instance = instance
        return self

    def emit(self, payload=None, **kwargs):
        """ Emitting a signal relies on the owner's publisher or whatever method the owner specifies for broadcasting.
Ejemplo n.º 12
0
    that objects where pickled. There is also a possibility of assuming numpy arrays and using a zero-copy strategy.

:copyright:  Aquiles Carattino
:license: MIT, see LICENSE for more details
"""
import atexit
from time import sleep

import zmq

from experimentor.config import settings
from experimentor.core.pusher import Pusher
from experimentor.lib.log import get_logger
from .meta import MetaProcess, ExperimentorProcess

logger = get_logger(name=__name__)


class Publisher(ExperimentorProcess, metaclass=MetaProcess):
    """ Publisher class in which the queue for publishing messages is defined and also a separated process is started.
    It is important to have a new process, since the serialization/deserialization of messages from the QUEUE may be
    a bottleneck for performance.
    """

    def __init__(self, event, name=None):
        super(Publisher, self).__init__(name=name or 'Publisher')
        self._event = event  # This event is used to stop the process
        self.running = False
        atexit.register(self.stop)

    def run(self):
Ejemplo n.º 13
0
acquisition synchronized via an external trigger (which can also be on the board itself).
"""
import ctypes
import sys
from ctypes import byref, c_bool, c_byte, c_double, c_int, c_ubyte, c_uint, cdll, create_string_buffer

import numpy as np

from experimentor.drivers.digilent.dwfconst import AcquisitionMode, AnalogAcquisitionFilter, AnalogChannelNodeType, \
    AnalogInTriggerMode, \
    AnalogOutNode, AnalogOutSignalType, DigitalOutIdle, DigitalOutOutput, DigitalOutType, InstrumentState, \
    TriggerLength, TriggerSlope, TriggerSource, DeviceFilter
from experimentor.drivers.exceptions import DriverException
from experimentor.lib.log import get_logger

logger = get_logger()

try:
    if sys.platform.startswith("win"):
        dwf = cdll.dwf
    elif sys.platform.startswith("darwin"):
        dwf = cdll.LoadLibrary("/Library/Frameworks/dwf.framework/dwf")
    else:
        dwf = cdll.LoadLibrary("libdwf.so")
except:
    logger.error("The library for controlling the digilent cards was not found. Please check your own "
                 "installation before proceeding")


class AnalogDiscovery:
    def __init__(self):
Ejemplo n.º 14
0
 def func_wrapper(cls, *args, **kwargs):
     logger = get_logger(__name__)
     logger.warning(f'{func.__name__} from {cls} not Implemented')
     return func(cls, *args, **kwargs)
Ejemplo n.º 15
0
 def __init__(self):
     atexit.register(self.finalize)
     self._threads = []
     self._ctx = self.create_context()
     self._publisher = self.create_publisher()
     self.logger = get_logger()
Ejemplo n.º 16
0
 def __init__(self, *args, **kwargs):
     super(ExperimentorThread, self).__init__(args, kwargs)
     self.logger = get_logger()
Ejemplo n.º 17
0
 def __init__(self, *args, **kwargs):
     super(ExperimentorProcess, self).__init__()
     self.logger = get_logger()