Example #1
0
    def __init__(self, filename, string):
        self.filename = filename
        self.string = string

        msg = "Syntax error at: {filename}\n{string}".format(filename=filename, string=string)

        super().__init__(msg)
Example #2
0
 def __init__(self, *args, **kwargs):
     if 'bulk_form_attrs' in kwargs:
         bulk_form_attrs = kwargs['bulk_form_attrs']
         del kwargs['bulk_form_attrs']
     else:
         bulk_form_attrs = None
     super(BulkParticipantDeleteForm, self).__init__(*args, **kwargs)
     if bulk_form_attrs is not None:
         # setup first_uid widget constraints
         self.fields["first_uid"].widget.attrs.update(
             dict(min=bulk_form_attrs["update_delete_first_uid_min_value"],
                  max=bulk_form_attrs["update_delete_first_uid_max_value"],
                  required=True))
         # setup first_uid fld validation
         self.fields["first_uid"].min_value = \
             bulk_form_attrs["update_delete_first_uid_min_value"]
         self.fields["first_uid"].max_value = \
             bulk_form_attrs["update_delete_first_uid_max_value"]
         # setup last_uid widget constraints
         self.fields["last_uid"].widget.attrs.update(
             dict(min=bulk_form_attrs["update_delete_last_uid_min_value"],
                  max=bulk_form_attrs["update_delete_last_uid_max_value"],
                  required=True))
         # setup last_uid fld validation
         self.fields["last_uid"].min_value = \
             bulk_form_attrs["update_delete_last_uid_min_value"]
         self.fields["last_uid"].max_value = \
             bulk_form_attrs["update_delete_last_uid_max_value"]
Example #3
0
    def writeRoutineEndCode(self, buff):
        # some shortcuts
        name = self.params['name']
        if len(self.exp.flow._loopList):
            currLoop = self.exp.flow._loopList[-1]  # last (outer-most) loop
        else:
            currLoop = self.exp._expHandler

        # write the actual code
        buff.writeIndented("# %(name)s stop & responses\n" % self.params)
        buff.writeIndented("%s.stop()  # sometimes helpful\n" %
                           self.params['name'])
        buff.writeIndented("if not %(name)s.savedFile:\n" % self.params)
        buff.writeIndented("    %(name)s.savedFile = None\n" % self.params)
        buff.writeIndented("# store data for %s (%s)\n" %
                           (currLoop.params['name'], currLoop.type))

        # always add saved file name
        buff.writeIndented("%s.addData('%s.filename', %s.savedFile)\n" %
                           (currLoop.params['name'], name, name))

        # get parent to write code too (e.g. store onset/offset times)
        super().writeRoutineEndCode(buff)

        if currLoop.params['name'].val == self.exp._expHandler.name:
            buff.writeIndented("%s.nextEntry()\n" % self.exp._expHandler.name)
Example #4
0
File: operator.py Project: wjp/odl
    def __init__(self, op, scalar, tmp=None):
        """Initialize a new `OperatorLeftScalarMult` instance.

        Parameters
        ----------
        op : `Operator`
            The domain of ``op`` must be a `LinearSpace` or
            `Field`.
        scalar : ``op.range.field`` element
            A real or complex number, depending on the field of
            the operator domain.
        tmp : domain element, optional
            Used to avoid the creation of a temporary when applying the
            operator.
        """
        if not isinstance(op.domain, (LinearSpace, Field)):
            raise TypeError('domain {!r} not a `LinearSpace` or `Field` '
                            'instance.'.format(op.domain))

        if scalar not in op.domain.field:
            raise TypeError('scalar {!r} not in the field {!r} of the '
                            'operator domain {!r}.'
                            ''.format(scalar, op.domain.field, op.domain))

        if tmp is not None and tmp not in op.domain:
            raise TypeError('temporary {!r} not an element of the '
                            'operator domain {!r}.'.format(tmp, op.domain))

        super().__init__(op.domain, op.range, op.is_linear)
        self._op = op
        self._scalar = scalar
        self._tmp = tmp
Example #5
0
    def learn(self, s, p_actions, a, r, ns, np_actions, na, terminal):
        """Iterative learning method for the agent.

        Args:
            s (ndarray):    The current state features
            p_actions (ndarray):    The actions available in state s
            a (int):    The action taken by the agent in state s
            r (float):  The reward received by the agent for taking action a in state s
            ns (ndarray):   The next state features
            np_actions (ndarray): The actions available in state ns
            na (int):   The action taken by the agent in state ns
            terminal (bool): Whether or not ns is a terminal state
        """
        self.LSPI.process(s, a, r, ns, na, terminal)
        if self.LSPI.samples_count + 1 % self.LSPI.steps_between_LSPI == 0:
            self.LSPI.representationExpansionLSPI()
            if terminal:
                self.episodeTerminated()
        else:
            super(
                LSPI_SARSA,
                self).learn(s,
                            p_actions,
                            a,
                            r,
                            ns,
                            np_actions,
                            na,
                            terminal)
Example #6
0
    def __init__(self, part, axes):
        """Initialize a new instance.

        Parameters
        ----------
        part : 1-dim. `RectPartition`
            Partition of the parameter interval, corresponding to the
            pixels
        axes : 2-tuple of `array-like` (shape ``(3,)``)
            Principal axes of the detector, e.g.
            ``[(0, 1, 0), (0, 0, 1)]``
        """
        super().__init__(part)
        if self.ndim != 2:
            raise ValueError('expected partition to have 2 dimensions, '
                             'got {}.'.format(self.ndim))

        for i, a in enumerate(axes):
            if np.linalg.norm(a) <= 1e-10:
                raise ValueError('axis vector {} {} too close to zero.'
                                 ''.format(i, axes[i]))
            if np.shape(a) != (3,):
                raise ValueError('axis vector {} has shape {}. expected (3,).'
                                 ''.format(i, np.shape(a)))

        self._axes = tuple(np.asarray(a) / np.linalg.norm(a) for a in axes)
        self._normal = np.cross(self.axes[0], self.axes[1])

        if np.linalg.norm(self.normal) <= 1e-4:
            raise ValueError('axes are almost parallel (norm of normal = '
                             '{})'.format(np.linalg.norm(self.normal)))
Example #7
0
    def __init__(self, exp, parentName, name='mic_1',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0, startEstim='',
                 durationEstim='', stereo=False, channel=0):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Microphone'
        self.url = "http://www.psychopy.org/builder/components/microphone.html"
        self.exp.requirePsychopyLibs(['microphone'])

        # params
        msg = _translate(
            "Record two channels (stereo) or one (mono, smaller file)")
        self.params['stereo'] = Param(
            stereo, valType='bool',
            hint=msg,
            label=_localized['stereo'])

        self.params['stopType'].allowedVals = ['duration (s)']

        msg = _translate(
            'The duration of the recording in seconds; blank = 0 sec')
        self.params['stopType'].hint = msg

        msg = _translate("Enter a channel number. Default value is 0. If unsure, run 'sound.backend.get_input_devices()' to locate the system's selected device/channel.")

        self.params['channel'] = Param(channel, valType='int', hint=msg, label=_localized['channel'])
Example #8
0
 def setUp(self):
     super().setUp()
     input_dir = os.path.join(util.file.get_test_input_path(), 'TestMetagenomicsViralMix')
     self.kraken_db_viral_mix = tempfile.mkdtemp('-kraken_db_viral_mix')
     cmd = ['tar', '-C', self.kraken_db_viral_mix, '-xzf', os.path.join(input_dir, 'kraken_db.tar.gz')]
     subprocess.check_call(cmd)
     self.kraken = tools.kraken.Kraken()
 def __init__(self, space, energies, spectrum):
     self.energies = np.array(energies)
     self.spectrum = np.array(spectrum)
     self.spectrum = self.spectrum / self.spectrum.sum()
     super().__init__(odl.ProductSpace(space, 2),
                      space,
                      False)
Example #10
0
    def __init__(self, file, header_fields=None):
        """Initialize a new instance.

        Parameters
        ----------
        file : file-like or str
            Stream or filename from which to read the data. The stream
            is allowed to be already opened in ``'rb'`` mode.
        header_fields : sequence of dicts, optional
            Definition of the fields in the header (per row), each
            containing key-value pairs for the following keys:

            - ``'name'`` : Label for the field.
            - ``'offset'`` : Start of the field in bytes.
            - ``'size'`` : Size of the field in bytes.
            - ``'dtype'`` : Data type in Numpy- or Numpy-readable format.
            - ``'dshape'`` (optional) : The array of values is reshaped to
              this shape.
            - ``'description'`` (optional) : A human-readable description
              of the field.

            For the default ``None``, the MRC2014 format is used, see
            `print_mrc2014_spec`.
        """
        if header_fields is None:
            header_fields = header_fields_from_table(
                spec_table=MRC_2014_SPEC_TABLE,
                keys=MRC_SPEC_KEYS,
                dtype_map=MRC_DTYPE_TO_NPY_DTYPE)

        super().__init__(file, header_fields)
Example #11
0
 def __init__(self, kernel, adjkernel=None):
     self.kernel = kernel
     self.adjkernel = (adjkernel if adjkernel is not None
                       else kernel.space.element(kernel[::-1].copy()))
     self.space = kernel.space
     self.norm = float(np.sum(np.abs(self.kernel.ntuple)))
     super().__init__(self.space, self.space, linear=True)
    def setup_display(self, time_axis, attributes):
        """Create a report for this dispatch, usually done at init

        Arguments
        ---------
        time_axis : string
            Name of attribute representing time eg. iterations, epoch, etc

        attributes : list
            List of strings representing attributes to plot eg. loss, accuracy,
            learning rate, etc. If time_axis attribute is present it will be ignored.

        Returns
        -------
        result : requests.Response
            Result of the report creation request
        """
        super().setup_display(time_axis, attributes)
        report_json = self._new_report()
        if 'id' in report_json:
            self.report_id = report_json['id']
        elif 'data' in report_json:
            # This is for unit testing
            self.report_id = ''
        return self._format_report()
Example #13
0
    def __init__(this, mbus, base_addr, writeback=False, \
                                        log_level = logging.WARN):
        '''
        note: base_addr will need to be updated every time
        '''
        super( RegFile, this).__init__(mbus)
        this.base_addr = base_addr 

        this.log = m3_logging.getLogger( type(this).__name__)
        this.log.setLevel(log_level)
        
        # specific ordering matching on-board gdb code
        this.names = [  'isr_lr', 'sp', 'r8', 'r9', 'r10', 'r11', 
                        'r4', 'r5', 'r6', 'r7', 'r0', 'r1', 'r2', 
                        'r3', 'r12', 'lr', 'pc', 'xpsr', ]
        this.trans_names = { 'r13': 'sp', 'r14':'lr', 'r15':'pc'}
        # The M0 does not include floating-point registers
        this.warn_names = [ 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 
                            'fps', ]
        this.warn_trans_names = { 'cpsr':'xpsr' }                            
        this.offsets = dict( zip(this.names, 
                            range(0, 4* len(this.names), 4))
                          )
        this.writeback = writeback
        this.local =  {}                                
Example #14
0
    def __init__(self, inner, dist_using_inner=True):
        """Initialize a new instance.

        Parameters
        ----------
        inner : `callable`
            The inner product implementation. It must accept two
            `FnVector` arguments, return an element from their space's
            field (real or complex number) and satisfy the following
            conditions for all vectors ``x, y, z`` and scalars ``s``:

            - ``<x, y> = conj(<y, x>)``
            - ``<s*x + y, z> = s * <x, z> + <y, z>``
            - ``<x, x> = 0``  if and only if  ``x = 0``

        dist_using_inner : `bool`, optional
            Calculate ``dist`` using the following formula::

                ||x - y||^2 = ||x||^2 + ||y||^2 - 2 * Re <x, y>

            This avoids the creation of new arrays and is thus faster
            for large arrays. On the downside, it will not evaluate to
            exactly zero for equal (but not identical) ``x`` and ``y``.
        """
        super().__init__(inner, impl='cuda',
                         dist_using_inner=dist_using_inner)
Example #15
0
    def __init__(self, controls):
        # Call the component super class, loading the player's sprite and the on-screen dimensions of the player
        super().__init__("player.png", component_texture_colourkey = WHITE, component_texture_rect = (0, 0, 24, 40), component_bounding_rect_dimensions = (24, 14), component_bounding_rect_position = (0, 26))

        # Player variables
        # Name must be set
        self.name = ""
        # Player starts off not running
        self.running = False
        # The player's speed
        self.speed = 2
        # The amount of time the player has left to run through a room
        self.time = 11
        # The number of rooms the player has run through
        self.rooms_run = 0
        # The level the player is currently in
        self.current_level = 1
        # The player's light and dark scores
        self.light_count = 0
        self.dark_count = 0
        # The set of controls used to move the player
        self.controls = controls

        # Load a new room by initialising a new, random, room object
        self.current_room = Room(random.randint(6, 13), random.randint(4, 7), self.current_level)

        # Set the postion of the player in the initial room
        self.sprite_data.set_position(((BOARD_WIDTH - self.sprite_data.bounding_rect.width) / 2, (BOARD_HEIGHT - self.sprite_data.bounding_rect.height) / 2))
Example #16
0
File: discr_ops.py Project: wjp/odl
    def __init__(self, space, axis=0, dx=1.0, edge_order=2,
                 zero_padding=False):
        """Initialize an operator instance.

        Parameters
        ----------
        space : `DiscreteLp`
            The space of elements which the operator is acting on
        axis : `int`, optional
            The axis along which the partial derivative is evaluated.
            Default: 0
        dx : `float`, optional
            Scalars specifying the sampling distances in dimension ``axis``.
            Default distance: 1.0
        edge_order : {1, 2}, optional
            First-order accurate differences can be used at the boundaries
            if no zero padding is used. Default edge order: 2
        zero_padding : `bool`, optional
            Implicit zero padding. Assumes values outside the domain of ``f``
            to be zero. Default: `False`
        """

        if not isinstance(space, DiscreteLp):
            raise TypeError('space {!r} is not a `DiscreteLp` '
                            'instance.'.format(space))

        super().__init__(domain=space, range=space, linear=True)
        self.axis = axis
        self.dx = dx
        self.edge_order = edge_order
        self.zero_padding = zero_padding
Example #17
0
    def __init__(self, apart, dpart, src_radius, det_radius, axis=[0, 0, 1],
                 **kwargs):
        """Initialize a new instance.

        Parameters
        ----------
        apart : 1-dim. `RectPartition`
            Partition of the angle interval
        dpart : 2-dim. `RectPartition`
            Partition of the detector parameter rectangle
        src_radius : nonnegative float
            Radius of the source circle
        det_radius : nonnegative float
            Radius of the detector circle
        axis : array-like, shape ``(3,)``, optional
            Fixed rotation axis, the symmetry axis of the helix
        src_to_det_init : array-like, shape ``(2,)``, optional
            Initial state of the vector pointing from source to detector
            reference point. The zero vector is not allowed.
            By default, a `perpendicular_vector` to ``axis`` is used.
        det_init_axes : 2-tuple of `array-like`'s (shape ``(2,)``), optional
            Initial axes defining the detector orientation.
            By default, the normalized cross product of ``axis`` and
            ``src_to_det_init`` is used as first axis and ``axis`` as
            second.
        """
        kwargs.pop('pitch_offset', None)
        super().__init__(apart, dpart, src_radius, det_radius, pitch=0,
                         axis=axis, **kwargs)
Example #18
0
File: day.py Project: Kromey/pynano
    def __init__(self, history, *args, **kwargs):
        """Initialize the sequence with our day-to-day history.

        :param dict history: Dictionary (indexed by day-1) of daily data
        """
        super().__init__(*args, **kwargs)
        self._history = history
 def __init__(self, task_params, img_folder):
     super().__init__()
     # Data will be a dictionary of lists
     self._data = {}
     self.task_params = task_params
     self._img_folder = img_folder
     self._legend_keys = []
Example #20
0
    def __init__(self, projection, geometry):

        proj_map = partial(projection, geometry)
        super().__init__(proj_map)

        self._projection = projection
        self._geometry = geometry
Example #21
0
    def __init__(self, backprojection, geometry):

        backproj_map = partial(backprojection, geometry)
        super().__init__(backproj_map)

        self._backprojection = backprojection
        self._geometry = geometry
Example #22
0
    def __init__(self, f_df, theta_init, learning_rate=1e-2, damping=0.1, decay=0.9):
        """
        RMSProp

        Parameters
        ----------
        df : function

        x0 : array_like

        lr : float, optional
            Learning rate (Default: 1e-2)

        momentum : float, optional
            Momentum (Default: 0)

        decay : float, optional
            Decay of the learning rate (Default: 0)

        """

        self.lr = learning_rate
        self.damping = damping
        self.decay = decay

        # initializes objective and gradient
        self.obj, self.gradient = wrap(f_df, theta_init)
        super().__init__(theta_init)
Example #23
0
    def __init__(self, op, vector):
        """ Initialize an instance.

        Parameters
        ----------
        vector : `LinearSpaceVector`
            The vector constant to be returned

        dom : `LinearSpace`, default : vector.space
            The domain of the operator.
        """
        if not isinstance(op, Operator):
            raise TypeError('op {!r} not a Operator instance.'
                            ''.format(op))

        if not isinstance(vector, LinearSpaceVector):
            raise TypeError('space {!r} not a LinearSpaceVector instance.'
                            ''.format(vector))

        if vector not in op.range:
            raise TypeError('space {!r} not in op.range {!r}.'
                            ''.format(vector, op.range))

        self.op = op
        self.vector = vector
        super().__init__(op.domain, vector.space)
Example #24
0
File: LSPI.py Project: okkhoy/rlpy
    def __init__(
            self, policy, representation, discount_factor, max_window, steps_between_LSPI,
            lspi_iterations=5, tol_epsilon=1e-3, re_iterations=100, use_sparse=False):

        self.steps_between_LSPI = steps_between_LSPI
        self.tol_epsilon = tol_epsilon
        self.lspi_iterations = lspi_iterations
        self.re_iterations = re_iterations
        self.use_sparse = use_sparse

        # Make A and r incrementally if the representation can not expand
        self.fixedRep = not representation.isDynamic
        if self.fixedRep:
            f_size = representation.features_num * representation.actions_num
            self.b = np.zeros((f_size, 1))
            self.A = np.zeros((f_size, f_size))

            # Cache calculated phi vectors
            if self.use_sparse:
                self.all_phi_s = sp.lil_matrix(
                    (max_window, representation.features_num))
                self.all_phi_ns = sp.lil_matrix(
                    (max_window, representation.features_num))
                self.all_phi_s_a = sp.lil_matrix((max_window, f_size))
                self.all_phi_ns_na = sp.lil_matrix((max_window, f_size))
            else:
                self.all_phi_s = np.zeros(
                    (max_window, representation.features_num))
                self.all_phi_ns = np.zeros(
                    (max_window, representation.features_num))
                self.all_phi_s_a = np.zeros((max_window, f_size))
                self.all_phi_ns_na = np.zeros((max_window, f_size))

        super(LSPI, self).__init__(policy, representation, discount_factor, max_window)
Example #25
0
 def show(self):
     """Display the dialog.
     """
     super().show()
     if self.OK:
         for n, thisKey in enumerate(self._keys):
             self.dictionary[thisKey] = self.data[n]
Example #26
0
File: operator.py Project: wjp/odl
    def __init__(self, op1, op2):
        """Initialize a new instance.

        Parameters
        ----------
        op1 : `Operator`
            The first factor
        op2 : `Operator`
            The second factor. Must have the same domain and range as
            ``op1``.
        """
        if op1.range != op2.range:
            raise TypeError('operator ranges {!r} and {!r} do not match.'
                            ''.format(op1.range, op2.range))

        if not isinstance(op1.range, (LinearSpace, Field)):
            raise TypeError('range {!r} not a `LinearSpace` or `Field` '
                            'instance.'.format(op1.range))

        if op1.domain != op2.domain:
            raise TypeError('operator domains {!r} and {!r} do not match.'
                            ''.format(op1.domain, op2.domain))

        super().__init__(op1.domain, op1.range, linear=False)
        self._op1 = op1
        self._op2 = op2
Example #27
0
    def __init__(self, indexer):
        super(NzbIndex, self).__init__(indexer)
        self.module = "NZBIndex"

        self.supports_queries = True  # We can only search using queries
        self.needs_queries = True
        self.category_search = False
Example #28
0
    def __init__(self, f_df, theta_init, learning_rate=1e-3, beta=(0.9, 0.999), epsilon=1e-8):
        """
        ADAM

        See: http://arxiv.org/abs/1412.6980

        Parameters
        ----------
        df : function

        x0 : array_like

        maxiter : int

        lr : float, optional
            Learning rate (Default: 1e-2)

        beta : (b1, b2), optional
            Exponential decay rates for the moment estimates

        epsilon : float, optional
            Damping factor

        """

        self.lr = learning_rate
        self.beta = beta
        self.epsilon = epsilon

        # initializes objective and gradient
        self.obj, self.gradient = wrap(f_df, theta_init)
        super().__init__(theta_init)
Example #29
0
File: operator.py Project: wjp/odl
    def __init__(self, left, right, tmp=None):
        """Initialize a new `OperatorComp` instance.

        Parameters
        ----------
        left : `Operator`
            The left ("outer") operator
        right : `Operator`
            The right ("inner") operator. Its range must coincide with the
            domain of ``left``.
        tmp : element of the range of ``right``, optional
            Used to avoid the creation of a temporary when applying the
            operator.
        """
        if right.range != left.domain:
            raise TypeError('range {!r} of the right operator {!r} not equal '
                            'to the domain {!r} of the left operator {!r}.'
                            ''.format(right.range, right,
                                      left.domain, left))

        if tmp is not None and tmp not in left.domain:
            raise TypeError('temporary {!r} not an element of the left '
                            'operator domain {!r}.'.format(tmp, left.domain))

        super().__init__(right.domain, left.range,
                         linear=left.is_linear and right.is_linear)
        self._left = left
        self._right = right
        self._tmp = tmp
Example #30
0
    def __init__(self, vol_gfun, proj_grid, dist, wavenum, rotation=None,
                 **kwargs):


        # The grid warp is a rotation
        warp = lambda vec_arr, rot: vec_arr * rot
        rotate = partial(warp, rot=rotation) if rotation is not None else None

        # Feed the reciprocal projection grid into the frequency geometry
        proj_gr_recip = proj_grid.reciprocal()

        freq_geom = FreqGeomGraphWarp(proj_gr_recip.coord, halfsph_k, rotate)

        # post-processing is a multiplication by a (phase) factor
        def diffr_factor(x, y, k, d):
            sq = np.sqrt(k**2 - x**2 - y**2)
            # TODO: check factors and sign
            return -1j * np.sqrt(np.pi / 2) * np.exp(1j * d * sq) / sq

        diffr_factor_k_d = partial(diffr_factor, k=wavenum, d=dist)

        super().__init__(freq_geom, preproc=None)

        self.vol_gfun = vol_gfun
        self.proj_grid = proj_grid
        self.postproc = lambda x, y, f: f * diffr_factor_k_d(x, y)
Example #31
0
 def __init__(self, callback, reinject=-1, slat_id=0, data=None):
     super().__init__(callback, slat_id, data)
     self._reinject = reinject
Example #32
0
    def __init__(self,
                 exp,
                 parentName,
                 name='bbox',
                 active="(0,1,2,3,4,5,6,7)",
                 store='first button',
                 forceEndRoutine=True,
                 storeCorrect=False,
                 correctAns="0",
                 discardPrev=True,
                 lights=True,
                 lightsOff=False,
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim=''):
        super(ioLabsButtonBoxComponent,
              self).__init__(exp,
                             parentName,
                             name=name,
                             store=store,
                             discardPrev=discardPrev,
                             correctAns=correctAns,
                             forceEndRoutine=forceEndRoutine,
                             storeCorrect=storeCorrect,
                             startType=startType,
                             startVal=startVal,
                             stopType=stopType,
                             stopVal=stopVal,
                             startEstim=startEstim,
                             durationEstim=durationEstim)

        self.type = 'ioLabsButtonBox'
        self.url = "http://www.psychopy.org/builder/components/ioLabs.html"

        self.exp.requirePsychopyLibs(['hardware'])
        del self.params['allowedKeys']

        # NB name and timing params always come 1st
        self.order = [
            'forceEndRoutine', 'active', 'lights', 'store', 'storeCorrect',
            'correctAns'
        ]

        msg = _translate(
            "What is the 'correct' response? NB, buttons are labelled 0 to "
            "7 on a 8-button box. Enter 'None' (no quotes) if withholding "
            "a response is correct. Might be helpful to add a correctAns "
            "column and use $correctAns to compare to the key press.")
        self.params['correctAns'].hint = msg

        self.params['store'].allowedVals = [
            'last button', 'first button', 'all buttons', 'nothing'
        ]

        msg = _translate(
            'Choose which (if any) responses to store at end of a trial')
        self.params['store'].hint = msg

        msg = _translate("Active buttons, such as '1,6', '(1,2,5,6)' or '0' "
                         "(without quotes)")
        self.params['active'] = Param(
            active,
            valType='code',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=msg,
            label=_localized['active'])

        self.params['lights'] = Param(
            lights,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=[],
            hint=_translate("Turn ON the lights for the active buttons?"),
            label=_localized['lights'])

        self.params['lights off'] = Param(
            lightsOff,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=[],
            hint=_translate("Turn OFF all lights at the end of each routine?"),
            label=_localized['lights off'])
Example #33
0
 def tearDownClass(cls):
     super().tearDownClass()
     cls.after_feature(cls.feature)
Example #34
0
 def setUpClass(cls):
     super().setUpClass()
     cls.feature.testclass = cls
     cls.before_feature(cls.feature)
Example #35
0
 def __init__(self, *args, **kwargs):
     """Initialize the step status."""
     self.failed = None
     self.passed = None
     super().__init__(*args, **kwargs)
Example #36
0
    def __init__(self,
                 exp,
                 parentName,
                 name='p_port',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim='',
                 address=None,
                 startData="1",
                 stopData="0",
                 syncScreen=True):
        super(ParallelOutComponent, self).__init__(exp,
                                                   parentName,
                                                   name,
                                                   startType=startType,
                                                   startVal=startVal,
                                                   stopType=stopType,
                                                   stopVal=stopVal,
                                                   startEstim=startEstim,
                                                   durationEstim=durationEstim)

        self.type = 'ParallelOut'
        self.url = "http://www.psychopy.org/builder/components/parallelout.html"
        self.categories = ['I/O']
        self.exp.requirePsychopyLibs(['parallel'])

        # params
        self.order = ['address', 'startData', 'stopData']

        # main parameters
        addressOptions = prefs.hardware['parallelPorts'] + [u'LabJack U3'
                                                            ] + [u'USB2TTL8']
        if not address:
            address = addressOptions[0]

        msg = _translate("Parallel port to be used (you can change these "
                         "options in preferences>general)")
        self.params['address'] = Param(address,
                                       valType='str',
                                       inputType="choice",
                                       allowedVals=addressOptions,
                                       categ='Hardware',
                                       hint=msg,
                                       label=_localized['address'])

        self.params['startData'] = Param(
            startData,
            valType='code',
            inputType="single",
            allowedTypes=[],
            categ='Data',
            hint=_translate("Data to be sent at 'start'"),
            label=_localized['startData'])

        self.params['stopData'] = Param(
            stopData,
            valType='code',
            inputType="single",
            allowedTypes=[],
            categ='Data',
            hint=_translate("Data to be sent at 'end'"),
            label=_localized['stopData'])

        msg = _translate("If the parallel port data relates to visual "
                         "stimuli then sync its pulse to the screen refresh")
        self.params['syncScreen'] = Param(syncScreen,
                                          valType='bool',
                                          inputType="bool",
                                          categ='Data',
                                          allowedVals=[True, False],
                                          updates='constant',
                                          allowedUpdates=[],
                                          hint=msg,
                                          label=_localized['syncScreen'])
Example #37
0
 def to_cffi(self):
     super().to_cffi()
     self._cffi_event.debug_event.reinject = self._reinject
     return self._cffi_event
Example #38
0
 def to_cffi(self):
     super().to_cffi()
     self._cffi_event.interrupt_event.intr = self.intr.value
     self._cffi_event.interrupt_event.reinject = self._reinject
     return self._cffi_event
Example #39
0
 def to_cffi(self):
     super().to_cffi()
     self._cffi_event.ss_event.vcpus = self.vcpus
     self._cffi_event.ss_event.enable = int(self.enable)
     return self._cffi_event
Example #40
0
 def to_dict(self):
     d = super().to_dict()
     d['intr'] = self.intr.name
     d['reinject'] = self._reinject
     return d
Example #41
0
    def __init__(self, adjoint, vfspace, vecfield, weighting=None):
        """Initialize a new instance.

        All parameters are given according to the specifics of the "usual"
        operator. The ``adjoint`` parameter is used to control conversions
        for the inverse transform.

        Parameters
        ----------
        adjoint : bool
            ``True`` if the operator should be the adjoint, ``False``
            otherwise.
        vfspace : `ProductSpace`
            Space of vector fields on which the operator acts.
            It has to be a product space of identical spaces, i.e. a
            power space.
        vecfield : ``vfspace`` `element-like`
            Vector field with which to calculate the point-wise inner
            product of an input vector field
        weighting : `array-like` or float, optional
            Weighting array or constant for the norm. If an array is
            given, its length must be equal to ``domain.size``.
            By default, the weights are is taken from
            ``domain.weighting``. Note that this excludes unusual
            weightings with custom inner product, norm or dist.
        """
        if not isinstance(vfspace, ProductSpace):
            raise TypeError('`vfsoace` {!r} is not a ProductSpace '
                            'instance'.format(vfspace))
        if adjoint:
            super().__init__(domain=vfspace[0],
                             range=vfspace,
                             base_space=vfspace[0],
                             linear=True)
        else:
            super().__init__(domain=vfspace,
                             range=vfspace[0],
                             base_space=vfspace[0],
                             linear=True)

        # Bail out if the space is complex but we cannot take the complex
        # conjugate.
        if (vfspace.field == ComplexNumbers()
                and not hasattr(self.base_space.element_type, 'conj')):
            raise NotImplementedError(
                'base space element type {!r} does not implement conj() '
                'method required for complex inner products'
                ''.format(self.base_space.element_type))

        self._vecfield = vfspace.element(vecfield)

        # Handle weighting, including sanity checks
        if weighting is None:
            if hasattr(vfspace.weighting, 'array'):
                self.__weights = vfspace.weighting.array
            elif hasattr(vfspace.weighting, 'const'):
                self.__weights = (vfspace.weighting.const *
                                  np.ones(len(vfspace)))
            else:
                raise ValueError('weighting scheme {!r} of the domain does '
                                 'not define a weighting array or constant'
                                 ''.format(vfspace.weighting))
        elif np.isscalar(weighting):
            self.__weights = float(weighting) * np.ones(vfspace.size)
        else:
            self.__weights = np.asarray(weighting, dtype='float64')
        self.__is_weighted = not np.array_equiv(self.weights, 1.0)
Example #42
0
 def to_cffi(self):
     super().to_cffi()
     self._cffi_event.reg_event.reg = self.register.value
     self._cffi_event.reg_event.in_access = self.in_access.value
     self._cffi_event.reg_event.equal = self.equal
     return self._cffi_event
Example #43
0
 def __init__(self, input):
     super().__init__()
     self.input = input
     self.context = Context.instance()
Example #44
0
    def __init__(self, matrix, domain=None, range=None):
        """Initialize a new instance.

        Parameters
        ----------
        matrix : `array-like` or `scipy.sparse.base.spmatrix`
            2-dimensional array representing the linear operator.
        domain : `FnBase`, optional
            Space of elements on which the operator can act. Its
            ``dtype`` must be castable to ``range.dtype``.
            For the default ``None``, a `NumpyFn` space with size
            ``matrix.shape[1]`` is used, together with the matrix'
            data type.
        range : `FnBase`, optional
            Space of elements on to which the operator maps. Its
            ``shape`` and ``dtype`` attributes must match the ones
            of the result of the multiplication.
            For the default ``None``, the range is inferred from
            ``matrix`` and ``domain``.

        Examples
        --------
        By default, ``domain`` and ``range`` are `NumpyFn` type spaces:

        >>> matrix = np.ones((3, 4))
        >>> op = MatrixOperator(matrix)
        >>> op
        MatrixOperator(
            [[ 1.,  1.,  1.,  1.],
             [ 1.,  1.,  1.,  1.],
             [ 1.,  1.,  1.,  1.]]
        )
        >>> op.domain
        rn(4)
        >>> op.range
        rn(3)
        >>> op([1, 2, 3, 4])
        rn(3).element([10.0, 10.0, 10.0])

        They can also be provided explicitly, for example with
        `uniform_discr` spaces:

        >>> dom = odl.uniform_discr(0, 1, 4)
        >>> ran = odl.uniform_discr(0, 1, 3)
        >>> op = MatrixOperator(matrix, domain=dom, range=ran)
        >>> op(dom.one())
        uniform_discr(0.0, 1.0, 3).element([4.0, 4.0, 4.0])

        For storage efficiency, SciPy sparse matrices can be used:

        >>> import scipy
        >>> row_idcs = np.array([0, 3, 1, 0])
        >>> col_idcs = np.array([0, 3, 1, 2])
        >>> values = np.array([4.0, 5.0, 7.0, 9.0])
        >>> matrix = scipy.sparse.coo_matrix((values, (row_idcs, col_idcs)),
        ...                                  shape=(4, 4))
        >>> matrix.toarray()
        array([[ 4.,  0.,  9.,  0.],
               [ 0.,  7.,  0.,  0.],
               [ 0.,  0.,  0.,  0.],
               [ 0.,  0.,  0.,  5.]])
        >>> op = MatrixOperator(matrix)
        >>> op(op.domain.one())
        rn(4).element([13.0, 7.0, 0.0, 5.0])
        """
        # TODO: fix dead link `scipy.sparse.spmatrix`
        if scipy.sparse.isspmatrix(matrix):
            self.__matrix = matrix
        else:
            self.__matrix = np.asarray(matrix)

        if self.matrix.ndim != 2:
            raise ValueError('matrix {} has {} axes instead of 2'
                             ''.format(matrix, self.matrix.ndim))

        # Infer domain and range from matrix if necessary
        if domain is None:
            domain = fn(self.matrix.shape[1], dtype=self.matrix.dtype)
        elif not isinstance(domain, FnBase):
            raise TypeError('`domain` {!r} is not an `FnBase` instance'
                            ''.format(domain))

        if range is None:
            range = fn(self.matrix.shape[0], dtype=self.matrix.dtype)
        elif not isinstance(range, FnBase):
            raise TypeError('`range` {!r} is not an `FnBase` instance'
                            ''.format(range))

        # Check compatibility of matrix with domain and range
        if self.matrix.shape != (range.size, domain.size):
            raise ValueError('matrix shape {} does not match the required '
                             'shape {} of a matrix {} --> {}'
                             ''.format(self.matrix.shape,
                                       (range.size, domain.size), domain,
                                       range))

        if not np.can_cast(domain.dtype, range.dtype):
            raise TypeError('domain data type {!r} cannot be safely cast to '
                            'range data type {!r}'
                            ''.format(domain.dtype, range.dtype))

        if not np.can_cast(self.matrix.dtype, range.dtype):
            raise TypeError('matrix data type {!r} cannot be safely cast to '
                            'range data type {!r}.'
                            ''.format(matrix.dtype, range.dtype))

        super().__init__(domain, range, linear=True)
Example #45
0
 def __init__(self, *a, **kw):
     super(TimeZone, self).__init__(*a, **kw)
Example #46
0
    def __init__(self, vfspace, exponent=None, weighting=None):
        """Initialize a new instance.

        Parameters
        ----------
        vfspace : `ProductSpace`
            Space of vector fields on which the operator acts.
            It has to be a product space of identical spaces, i.e. a
            power space.
        exponent : non-zero float, optional
            Exponent of the norm in each point. Values between
            0 and 1 are currently not supported due to numerical
            instability.
            Default: ``vfspace.exponent``
        weighting : `array-like` or positive float, optional
            Weighting array or constant for the norm. If an array is
            given, its length must be equal to ``domain.size``, and
            all entries must be positive.
            By default, the weights are is taken from
            ``domain.weighting``. Note that this excludes unusual
            weightings with custom inner product, norm or dist.

        Examples
        --------
        We make a tiny vector field space in 2D and create the
        standard point-wise norm operator on that space. The operator
        maps a vector field to a scalar function:

        >>> spc = odl.uniform_discr([-1, -1], [1, 1], (1, 2))
        >>> vfspace = odl.ProductSpace(spc, 2)
        >>> pw_norm = PointwiseNorm(vfspace)
        >>> pw_norm.range == spc
        True

        Now we can calculate the 2-norm in each point:

        >>> x = vfspace.element([[[1, -4]],
        ...                      [[0, 3]]])
        >>> print(pw_norm(x))
        [[1.0, 5.0]]

        We can change the exponent either in the vector field space
        or in the operator directly:

        >>> vfspace = odl.ProductSpace(spc, 2, exponent=1)
        >>> pw_norm = PointwiseNorm(vfspace)
        >>> print(pw_norm(x))
        [[1.0, 7.0]]
        >>> vfspace = odl.ProductSpace(spc, 2)
        >>> pw_norm = PointwiseNorm(vfspace, exponent=1)
        >>> print(pw_norm(x))
        [[1.0, 7.0]]
        """
        if not isinstance(vfspace, ProductSpace):
            raise TypeError('`vfspace` {!r} is not a ProductSpace '
                            'instance'.format(vfspace))
        super().__init__(domain=vfspace,
                         range=vfspace[0],
                         base_space=vfspace[0],
                         linear=False)

        # Need to check for product space shape once higher order tensors
        # are implemented

        if exponent is None:
            if self.domain.exponent is None:
                raise ValueError('cannot determine `exponent` from {}'
                                 ''.format(self.domain))
            self._exponent = self.domain.exponent
        elif exponent < 1:
            raise ValueError('`exponent` smaller than 1 not allowed')
        else:
            self._exponent = float(exponent)

        # Handle weighting, including sanity checks
        if weighting is None:
            # TODO: find a more robust way of getting the weights as an array
            if hasattr(self.domain.weighting, 'array'):
                self.__weights = self.domain.weighting.array
            elif hasattr(self.domain.weighting, 'const'):
                self.__weights = (self.domain.weighting.const *
                                  np.ones(len(self.domain)))
            else:
                raise ValueError('weighting scheme {!r} of the domain does '
                                 'not define a weighting array or constant'
                                 ''.format(self.domain.weighting))
        elif np.isscalar(weighting):
            if weighting <= 0:
                raise ValueError('weighting constant must be positive, got '
                                 '{}'.format(weighting))
            self.__weights = float(weighting) * np.ones(self.domain.size)
        else:
            self.__weights = np.asarray(weighting, dtype='float64')
            if (not np.all(self.weights > 0)
                    or not np.all(np.isfinite(self.weights))):
                raise ValueError('weighting array {} contains invalid '
                                 'entries'.format(weighting))
        self.__is_weighted = not np.array_equiv(self.weights, 1.0)
Example #47
0
 def __init__(self, exc, *args, **kwargs):
     self.__exc = exc
     super().__init__(*args, **kwargs)
Example #48
0
 def __init__(self, *a, **kw):
     super(GlobalPosition, self).__init__(*a, **kw)
Example #49
0
 def set_cell(self, cell, scale_atoms=False):
     self._reset_structure()
     super().set_cell(cell, scale_atoms)
Example #50
0
 def save(self, *args, **kwargs):
     if self.type in [
             Question.RADIO, Question.SELECT, Question.SELECT_MULTIPLE
     ]:
         validate_choices(self.choices)
     super(Question, self).save(*args, **kwargs)
Example #51
0
 def set_scaled_positions(self, scaled):
     self._reset_structure()
     super().set_scaled_positions(scaled)
 def __setattr__(self, key, value):
     if key in ('_queries', '_parameters', '_data'):
         return object.__setattr__(self, key, value)
     return super().__setattr__(key, value)
Example #53
0
 def tearDown(self):
     self.stop_request.set()
     super().tearDown()
     self.context.destroy(0)
Example #54
0
 def set_pbc(self, pbc):
     self._reset_structure()
     super().set_pbc(pbc)
Example #55
0
    def __init__(
        self,
        _client=None,
        account_id=None,
        completed_at=None,
        created_at=None,
        errors_count=None,
        errors_report_file=None,
        full_report_file=None,
        id=None,
        processed_count=None,
        status=None,
        total_count=None,
    ):
        """Creates a local `DeviceEnrollmentBulkDelete` instance

        Parameters can be supplied on creation of the instance or given by
        setting the properties on the instance after creation.

        Parameters marked as `required` must be set for one or more operations
        on the entity. For details on when they are required please see the
        documentation for the setter method.

        :param account_id: ID
        :type account_id: str
        :param completed_at: The time the bulk creation task was completed.
            Null when creating
            bulk upload or delete.
        :type completed_at: datetime
        :param created_at: The time of receiving the bulk creation task.
        :type created_at: datetime
        :param errors_count: The number of enrollment identities with failed processing.
        :type errors_count: int
        :param errors_report_file: Link to error report file.
            Null when creating bulk upload or
            delete.
        :type errors_report_file: str
        :param full_report_file: Link to full report file.
            Null when creating bulk upload or
            delete.
        :type full_report_file: str
        :param id: (Required) Bulk ID
        :type id: str
        :param processed_count: The number of enrollment identities processed until now.
        :type processed_count: int
        :param status: The state of the process is 'new' at the time of creation. If
            creation is still in progress, the state shows as 'processing'.
            When the request is fully processed, the state changes to
            'completed'.
        :type status: str
        :param total_count: Total number of enrollment identities found in the input CSV.
        :type total_count: int
        """

        super().__init__(_client=_client)

        # inline imports for avoiding circular references and bulk imports

        # fields
        self._account_id = fields.StringField(value=account_id)
        self._completed_at = fields.DateTimeField(value=completed_at)
        self._created_at = fields.DateTimeField(value=created_at)
        self._errors_count = fields.IntegerField(value=errors_count)
        self._errors_report_file = fields.StringField(value=errors_report_file)
        self._full_report_file = fields.StringField(value=full_report_file)
        self._id = fields.StringField(value=id)
        self._processed_count = fields.IntegerField(value=processed_count)
        self._status = fields.StringField(value=status, enum=enums.DeviceEnrollmentBulkDeleteStatusEnum)
        self._total_count = fields.IntegerField(value=total_count)
Example #56
0
 def set_positions(self, newpositions, apply_constraint=True):
     self._reset_structure()
     super().set_positions(newpositions, apply_constraint)
Example #57
0
 def __init__(self, pi_point):
     super().__init__()
     self.pi_point = pi_point
     self.tag = pi_point.Name
     self.__attributes_loaded = False
     self.__raw_attributes = {}
 def __init__(self, parent):
     super(self.__class__, self).__init__(parent)
     self.initUi()
     self.initConnection()
Example #59
0
 def __repr__(self):
     return "{}: {}".format(self.__class__.__name__, super().__repr__())
 def __init__(self, requests_session, url_base):
     super().__init__(requests_session, url_base)