Beispiel #1
0
 def __init__(self, tstart=0, tend=None, dur=None, delay=None, time='time'):
     """
     t0 is always event[time]; A time window is specified through 'tstart' 
     and either 'tend' or 'dur' (=duration) 
     
     tend as Var is read relative to t0
     
     kwargs
     ------
     tstart = 0 (relative to t0)
     tend 
     dur (duration)
     delay (constant shift of time points)
     time: event-Variable specifying t0
     
     """
     # check input
     for t in tstart, tend, dur, delay:
         if t is not None:
             assert np.isscalar(t) or _vars.isvar(t)
     self.tstart = tstart
     assert (tend is None) or (dur is None)
     self.tend = tend
     self.dur = dur
     self.delay = delay
     assert isinstance(time, basestring) or _vars.isvar(time)
     self.time = time
Beispiel #2
0
 def t2(self, colony):
     "return t2 relative to the var-colony"
     t0 = colony[self.time]
     if _vars.isvar(self.tend):
         out =  t0 + colony[self.tend]
     elif np.isscalar(self.tend):
         out =  t0 + self.tend
     else:
         if _vars.isvar(self.dur):
             return self.t1(colony) + colony[self.dur]
         elif np.isscalar(self.dur):
             return self.t1(colony) + self.dur
         else:
             raise NotImplementedError()
     return self._add_delay(out, colony)
Beispiel #3
0
 def __setitem__(self, name, value):
     if isvar(name):
         self.variables[name]=value
     elif isinstance(name, basestring):
         self.properties[name] = value
     else:
         raise KeyError("Key must be VarCommander or String (for setting properties)")
 def _derive_segment_data_(self, segment, preview=False):
     source = segment._p_attr['source']
     var = self.compiled['var']
     key = self.compiled['key']
     shift = self.compiled['shift']
     data = deepcopy(source.data)
     
     var_i = source.varlist.index(var)
     
     if np.isscalar(shift):
         data[:, var_i] += shift
     
     elif type(shift) == list:
         data_len = data.shape[0]
         shift = deepcopy(shift)
         while len(shift) < data_len:
             shift.append(shift[-1])
         if len(shift) > data_len:
             shift = shift[:data_len]
         data[:, var_i] += np.array(shift)
     
     else:
         if isvar(key):
             for i, evt in enumerate(source):
                 data[i, var_i] += shift[evt[key]]
         else:
             for i, evt in enumerate(source):
                 data[i, var_i] += evt[shift]
             
     
     return data
Beispiel #5
0
    def __setitem__(self, name, value):
        isslice = isinstance(name, slice)
        isint = isinstance(name, int)
        if isslice:
            name = _slice2tuple_(name)
        if isint or isslice:
            if isvar(value):
                var = value
            elif isinstance(value, basestring):
                try:
                    var = self._p._dataset.experiment.variables.get(value)
                except:
#                    create = ui.ask(title="Create Variable",
#                                    message="No variable named '%s', create variable?"%value,
#                                    cancel=False)
                    create = True
                    if create is True:
                        var = self._p._dataset.experiment.variables.new(value, dtype='dict')
                    else:
                        ui.msg("Aborted")
                        return
            self._value[name] = var
            self._changed()
        else:
            raise ValueError("key needs to be int or slice")
Beispiel #6
0
 def _add_delay(self, t, colony):
     if self.delay is None:
         return t
     elif np.isscalar(self.delay):
         return t + self.delay
     elif _vars.isvar(self.delay):
         return t + colony[self.delay]
 def _derive_segment_data_(self, segment, preview=False):
     source = segment._p_attr['source']
     add = self.compiled['add']
     e_list = deepcopy(source.data)
     for var, LIST in add.iteritems():
         if isvar(LIST[0]):
             keyvar, list_dic = LIST
             key = source[keyvar] # ???
             if key not in list_dic:
                 key_label = keyvar.label(key)
                 if key_label in list_dic:
                     key = key_label
                 else:
                     msg = "Append: key {k}='{l}' not in list-dic"
                     raise KeyError(msg.format(k=key, l=key_label))
             new = np.array(list_dic[key])
         else:
             new = np.array(LIST)
         if new.ndim == 1:
             new = new[:,None]
         l_diff = e_list.shape[0] - new.shape[0]
         if l_diff > 0:
             logging.warning(" Append-LIST too short; nan-padded")
             new = np.vstack((new, np.array([[np.NAN]]*l_diff)))
         elif l_diff < 0:
             logging.warning(" Append-LIST too long; clipped")
             new = new[:l_diff,:]
         e_list = np.hstack((e_list, new))
     return e_list
Beispiel #8
0
    def toax(self, ax, t0, t1, rc=True, dur=.5):
        """

        """
#        print "TOAX: %s -- %s"%(t0, t1)
        # index from t0 and t1
        
        # find standard color and color_var
        color = self._seg.color
        if color is None:
            color = (.1, .1, .9)
        
        if _vars.isvar(self._color):
            color_var = self._color
        else:
            color_var = None
            if self._color is not None:
                color = self._color
        
        
        time = self._var_time
        kwargs = {'alpha':.4}

        # prepare scaling factor
        if rc and self._var_magnitude:
            scaling = max(self._seg.subdata(var=self._var_magnitude))
        else:
            scaling = 1

#        print "TOAX FOR start"
        # loop events
        for evt in self._seg.sub_iter(time, t0, t1):
#            print 'evt'
            #time
            e_start = evt[time]
#            if self._var_duration in evt:
            try:
                e_end = e_start + evt[self._var_duration]
            except:
                e_end = e_start + self.duration
            
            # color
            if color_var is None:
                kwargs['color'] = color
            else:
                c = self._color.get_color_for_colony(evt)
                if c is None:
                    kwargs['color'] = color
                else:
                    kwargs['color'] = c
            
            # height
#            if self._var_magnitude and self._var_magnitude in evt:
            try:
                y = evt[self._var_magnitude] / scaling
            except:
                y = self.magnitude

            span = ax.axvspan(e_start, e_end, ymax=y, **kwargs)
Beispiel #9
0
 def names_to_vars(self):
     """
     converts all the variables provided as strings into real
     variables
     """
     for k, v in self._value.items():
         if not isvar(v):
             var = self._p._dataset.experiment.get_var_with_name(v)
             self._value[k] = var
Beispiel #10
0
 def t1(self, colony):
     "return t1 relative to the var-colony"
     t0 = colony[self.time]
     if _vars.isvar(self.tstart):
         out = t0  + colony[self.tstart]
     elif np.isscalar(self.tstart):
         out = t0 + self.tstart
     else:
         out = t0
     return self._add_delay(out, colony)
Beispiel #11
0
    def __init__(self, dataset, mag=None, dur=None, color=None, i=0, address=None):
        """
        kwargs
        ------
        mag: variable coding the magnitude (displayed as block height). By
                default, all blocks will have the same height. 
        dur: shown event duration, variable or scalar
        color: event color (variable)
        i: index of the initial segment 
        address: address indicating the subset of events to draw. By default,
                all events are drawn.

        """
        self._var_time = dataset.experiment.variables.get('time')
        
        if _vars.isvar(mag):
            if id(mag) in [id(v) for v in dataset[0].varlist]:
                self._var_magnitude = mag
            else:
                raise KeyError("segment does not contain magnitude var")
        else:
            self._var_magnitude = None
        if np.isscalar(mag):
            self.magnitude = mag
        else:
            self.magnitude = 1
        
        if dur is None:
            self._var_duration = dataset.experiment.variables.get('duration')
            self.duration = .5
        elif _vars.isvar(dur):
            self._var_duration = dur
            self.duration = .5
        elif np.isscalar(dur):
            self._var_duration = None
            self.duration = dur
        else:
            raise ValueError("duration must be either scalar or variable, "
                             "not %r"%type(dur))
        
        self.set_evt_address(address)
        
        _Visualizer.__init__(self, dataset, color=color, i=i)
Beispiel #12
0
 def __repr__(self):
     s = self.get()
     if isvar(s):
         return s.name
     elif s is None:
         return "None"
     elif np.isreal(s):
         return "%f sec."%s
     elif np.iscomplex(s):
         return "%i samples"%(s.imag)
Beispiel #13
0
 def __getitem__(self, name):
     "accepts: VarCommanders, str(->properties), indices(->data)"
     if isvar(name):
         return self.variables[name]
     elif isinstance(name, basestring):
         if name in self.properties:
             return self.properties[name]
         elif hasattr(self, 'dataset'): 
             return self.dataset[name]
         else:
             raise KeyError("%r not in properties"%name)
     else:
         return self.data[name]
Beispiel #14
0
 def in_samples(self, samplingrate, varcolony=None):
     "returns None if Time is a variable and segment is None"
     v = Param.get(self)
     if isvar(v):
         if varcolony is None:
             return None
         else:
             v = varcolony[v]
     
     if np.isreal(v):
         return int(v * samplingrate)
     elif np.iscomplex(v):
         out = v.imag
         return out
Beispiel #15
0
 def dt(self, colony=None):
     "return t2-t1"
     if self.tend is None:
         if np.isscalar(self.dur):
             return self.dur
         elif _vars.isvar(self.dur):
             return colony[self.dur]
     else:
         if np.isscalar(self.tend):
             tend = self.tend
         else: # _vars.isvar(self.tend)
             tend = colony[self.tend]
         # subtract tstart
         if np.isscalar(self.tstart):
             return tend - self.tstart
         else:
             return tend - colony[self.tstart]
Beispiel #16
0
 def set(self, time):
     """
     Use real values to indicate time in seconds, and complex values to 
     indicate sample points (e.g. at 200 Hz, 100i == .5)
     
     Note
     ----
     the value is stored in sample points and does not adapt when the 
     samlingrate of the dataset changes; the value has to be changed 
     manually.
     
     """
     if isvar(time):
         if not self._can_be_var:
             raise ValueError("Parameter does not accept variable")
     else:
         assert np.isscalar(time)
     Param.set(self, time)
Beispiel #17
0
    def __getitem__(self, name):
        """
        returns, for the following inputs:
        int -> return event with index
        Address -> 
        else -> Segment.__getitem__
        
        """
#        if hasattr(name, 'contains'):
        if isvar(name) or isinstance(name, basestring):
            return Segment.__getitem__(self, name)
        elif np.isscalar(name):
            if int(name) != name:
                raise ValueError("index needs to be int")
            if name >= len(self.data):
                raise KeyError("n events < %s"%name)
            else:
                values = self.data[name]
                evt = self._get_static_vars()
                for var, val in zip(self.varlist, values):
                    evt[var] = val
                return evt
        else:
            properties = self.get_full_properties()
            if isaddress(name):
                select = []
                for i, evt in enumerate(self):
                    if name.contains(evt):
                        select.append(i)
                data = self.data[select]
            else:
                data = self.data[name]
                assert data.shape[1] == len(self.varlist)
                
            return Event_Segment(properties, self.varlist[:], 
                                 varsource=self.variables, data=data,
                                 name=self.name)
Beispiel #18
0
 def __setitem__(self, var, value):
     if isinstance(var, basestring):
         var = self._p._dataset.experiment.variables.var_with_name(var)
     if not isvar(var):
         raise ValueError("Key needs to be variable")
     Dict.__setitem__(self, var, value)