Exemplo n.º 1
0
 def __init__(self, project_id=None):
     super(StimulusRegionSelectorForm, self).__init__(project_id=project_id)
     traited_attr = Attr(StimuliRegionIndex,
                         label='Load Region Stimulus',
                         required=False)
     self.region_stimulus = TraitDataTypeSelectField(
         traited_attr, self.project_id, name='existentEntitiesSelect')
     self.display_name = StrField(RegionStimulusCreatorModel.display_name,
                                  self.project_id,
                                  name='display_name')
Exemplo n.º 2
0
class RegionStimulusCreatorModel(ViewModel, StimuliRegion):
    temporal = Attr(field_type=TemporalApplicableEquation,
                    label="Temporal Equation",
                    default=PulseTrain())

    connectivity = DataTypeGidAttr(field_type=uuid.UUID,
                                   linked_datatype=Connectivity,
                                   label="Connectivity")

    display_name = Str(label='Display name', required=False)
Exemplo n.º 3
0
 def __init__(self, default_simulation_name="simulation_1"):
     super(SimulatorFinalFragment, self).__init__()
     self.simulation_length = FloatField(
         SimulatorAdapterModel.simulation_length)
     self.simulation_name = StrField(Attr(
         str,
         doc='Name for the current simulation configuration',
         default=default_simulation_name,
         label='Simulation name'),
                                     name='input_simulation_name_id')
Exemplo n.º 4
0
class ObjSurfaceImporterModel(UploaderViewModel):
    surface_type = EnumAttr(label='Specify file type :',
                            default=SurfaceTypesEnum.CORTICAL_SURFACE)

    data_file = Str(label='Please select file to import')

    should_center = Attr(field_type=bool,
                         required=False,
                         default=False,
                         label='Center surface using vertex means along axes')
Exemplo n.º 5
0
class NodeCoherence(HasTraits):
    "Adapter for cross-coherence algorithm(s)"

    time_series = Attr(
        field_type=time_series.TimeSeries,
        label="Time Series",
        required=True,
        doc="""The timeseries to which the FFT is to be applied.""")

    nfft = Int(
        label="Data-points per block",
        default=256,
        doc="""Should be a power of 2...""")

    def evaluate(self):
        "Evaluate coherence on time series."
        cls_attr_name = self.__class__.__name__+".time_series"
        # self.time_series.trait["data"].log_debug(owner=cls_attr_name)
        srate = self.time_series.sample_rate
        coh, freq = coherence(self.time_series.data, srate, nfft=self.nfft)
        self.log.debug("coherence")
        self.log.debug(narray_describe(coh))
        self.log.debug("freq")
        self.log.debug(narray_describe(freq))

        spec = spectral.CoherenceSpectrum(
            source=self.time_series,
            nfft=self.nfft,
            array_data=coh,
            frequency=freq)
        return spec

    def result_shape(self, input_shape):
        """Returns the shape of the main result of NodeCoherence."""
        freq_len = self.nfft/2 + 1
        freq_shape = (freq_len,)
        result_shape = (freq_len, input_shape[2], input_shape[2], input_shape[1], input_shape[3])
        return [result_shape, freq_shape]

    def result_size(self, input_shape):
        """
        Returns the storage size in Bytes of the main result of NodeCoherence.
        """
        # TODO This depends on input array dtype!
        result_size = numpy.sum(list(map(numpy.prod, self.result_shape(input_shape)))) * 8.0 #Bytes
        return result_size

    def extended_result_size(self, input_shape):
        """
        Returns the storage size in Bytes of the extended result of the FFT.
        That is, it includes storage of the evaluated FourierSpectrum attributes
        such as power, phase, amplitude, etc.
        """
        extend_size = self.result_size(input_shape) #Currently no derived attributes.
        return extend_size
Exemplo n.º 6
0
class BalloonModelAdapterModel(ViewModel):
    time_series = DataTypeGidAttr(
        linked_datatype=TimeSeriesRegion,
        label="Time Series",
        required=True,
        doc="""The timeseries that represents the input neural activity"""
    )

    dt = Float(
        label=":math:`dt`",
        default=0.002,
        required=True,
        doc="""The integration time step size for the balloon model (s).
            If none is provided, by default, the TimeSeries sample period is used."""
    )

    tau_s = Float(
        label=r":math:`\tau_s`",
        default=1.54,
        required=True,
        doc="""Balloon model parameter. Time of signal decay (s)""")

    tau_f = Float(
        label=r":math:`\tau_f`",
        default=1.44,
        required=True,
        doc=""" Balloon model parameter. Time of flow-dependent elimination or
            feedback regulation (s). The average  time blood take to traverse the
            venous compartment. It is the  ratio of resting blood volume (V0) to
            resting blood flow (F0).""")

    neural_input_transformation = EnumAttr(
        label="Neural input transformation",
        default=NeuralInputTransformations.NONE,
        doc=""" This represents the operation to perform on the state-variable(s) of
            the model used to generate the input TimeSeries. ``none`` takes the
            first state-variable as neural input; `` abs_diff`` is the absolute
            value of the derivative (first order difference) of the first state variable; 
            ``sum``: sum all the state-variables of the input TimeSeries."""
    )

    bold_model = EnumAttr(
        label="Select BOLD model equations",
        default=BoldModels.NONLINEAR,
        doc="""Select the set of equations for the BOLD model."""
    )

    RBM = Attr(
        field_type=bool,
        label="Revised BOLD Model",
        default=True,
        required=True,
        doc="""Select classical vs revised BOLD model (CBM or RBM).
            Coefficients  k1, k2 and k3 will be derived accordingly."""
    )
Exemplo n.º 7
0
class WaveletAdapterModel(ViewModel):
    time_series = DataTypeGidAttr(
        linked_datatype=TimeSeries,
        label="Time Series",
        required=True,
        doc="""The timeseries to which the wavelet is to be applied.""")

    mother = Attr(
        field_type=str,
        label="Wavelet function",
        default="morlet",
        doc="""The mother wavelet function used in the transform. Default is
            'morlet', possibilities are: 'morlet'...""")

    sample_period = Float(
        label="Sample period of result (ms)",
        default=7.8125,  # 7.8125 => 128 Hz
        doc="""The sampling period of the computed wavelet spectrum. NOTE:
            This should be an integral multiple of the of the sampling period
            of the source time series, otherwise the actual resulting sample
            period will be the first correct value below that requested.""")

    frequencies = Attr(
        field_type=Range,
        label="Frequency range of result (kHz).",
        default=Range(lo=0.008, hi=0.060, step=0.002),
        doc="""The frequency resolution and range returned. Requested
            frequencies are converted internally into appropriate scales.""")

    normalisation = Attr(
        field_type=str,
        label="Normalisation",
        default="energy",
        doc="""The type of normalisation for the resulting wavet spectrum.
            Default is 'energy', options are: 'energy'; 'gabor'.""")

    q_ratio = Float(
        label="Q-ratio",
        default=5.0,
        doc=
        """NFC. Must be greater than 5. Ratios of the center frequencies to bandwidths."""
    )
Exemplo n.º 8
0
class StimuliRegion(SpatioTemporalPattern):
    """
    A class that bundles the temporal profile of the stimulus, together with the
    list of scaling weights of the regions where it will applied.
    """
    connectivity = Attr(field_type=connectivity.Connectivity,
                        label="Connectivity")

    spatial = Attr(
        field_type=equations.DiscreteEquation,
        label="Spatial Equation",
        default=equations.DiscreteEquation())  # fixed_type=True, order=-1)

    weight = NArray(label="scaling")  # , locked=True, order=4)

    @staticmethod
    def get_default_weights(number_of_regions):
        """
        Returns a list with a number of elements
        equal to the given number of regions.
        """
        return numpy.array([0.0] * number_of_regions)

    @property
    def weight_array(self):
        """
        Wrap weight List into a Numpy array, as it is requested by the simulator.
        """
        return numpy.array(self.weight)[:, numpy.newaxis]

    def configure_space(self, region_mapping=None):
        """
        Do necessary preparations in order to use this stimulus.
        NOTE: this was previously done in simulator configure_stimuli() method.
        It no needs to be used in stimulus viewer also.
        """
        if region_mapping is not None:
            # TODO: smooth at surface region boundaries
            distance = self.weight_array[region_mapping, :]
        else:
            distance = self.weight_array
        super(StimuliRegion, self).configure_space(distance)
Exemplo n.º 9
0
class TimeSeriesVolume(TimeSeries, TimeSeriesVolumeTVB):
    labels_ordering = List(
        of=str,
        default=(TimeSeriesDimensions.TIME.value, TimeSeriesDimensions.X.value,
                 TimeSeriesDimensions.Y.value, TimeSeriesDimensions.Z.value))

    title = Attr(str, default="Volume Time Series")

    @property
    def volume_labels(self):
        return self.space_labels
Exemplo n.º 10
0
class PulseTrain(TemporalApplicableEquation):
    """
    A pulse train , offset with respect to the time axis.

    **Parameters**:

    * :math:`\\tau` :  pulse width or pulse duration
    * :math:`T`     :  pulse repetition period
    * :math:`f`     :  pulse repetition frequency (1/T)
    * duty cycle    :  :math:``\\frac{\\tau}{T}`` (for a square wave: 0.5)
    * onset time    :
    """

    equation = Final(label="Pulse Train",
                     default="where((var % T) < tau, amp, 0)",
                     doc=""":math:`\\frac{\\tau}{T}
        +\\sum_{n=1}^{\\infty}\\frac{2}{n\\pi}
        \\sin\\left(\\frac{\\pi\\,n\\tau}{T}\\right)
        \\cos\\left(\\frac{2\\pi\\,n}{T} var\\right)`.
        The starting time is halfway through the first pulse.
        The phase can be offset t with t - tau/2""")

    # onset is in milliseconds
    # T and tau are in milliseconds as well

    parameters = Attr(field_type=dict,
                      default=lambda: {
                          "T": 42.0,
                          "tau": 13.0,
                          "amp": 1.0,
                          "onset": 30.0
                      },
                      label="Pulse Train Parameters")

    def evaluate(self, var):
        """
        Generate a discrete representation of the equation for the space
        represented by ``var``.

        The argument ``var`` can represent a distance, or effective distance,
        for each node in a simulation. Or a time, or in principle any arbitrary
        `` space ``. ``var`` can be a single number, a numpy.ndarray or a
        ?scipy.sparse_matrix? TODO: think this last one is true, need to check
        as we need it for LocalConnectivity...

        """
        # rolling in the deep ...
        onset = self.parameters["onset"]
        off = var < onset
        var = numpy.roll(var, off.sum() + 1)
        var[..., off] = 0.0
        _pattern = RefBase.evaluate(self.equation, global_dict=self.parameters)
        _pattern[..., off] = 0.0
        return _pattern
Exemplo n.º 11
0
class MatrixVisualizerModel(ViewModel):
    datatype = DataTypeGidAttr(
        linked_datatype=DataTypeMatrix,
        label='Array data type'
    )

    slice = Attr(
        field_type=str,
        required=False,
        label='slice indices in numpy syntax'
    )
Exemplo n.º 12
0
class ConnectivityMeasure(HasTraits):
    """Measurement of based on a connectivity."""

    array_data = NArray()

    connectivity = Attr(field_type=Connectivity)

    def summary_info(self):
        summary = {"Graph type": self.__class__.__name__}
        summary.update(narray_summary_info(self.array_data))
        return summary
Exemplo n.º 13
0
    def __init__(self):
        super(IntegratorStochasticForm, self).__init__()
        self.noise_choices = get_ui_name_to_noise_dict()
        default_noise = list(self.noise_choices.values())[0]

        self.noise = SelectField(Attr(NoiseViewModel,
                                      label='Noise',
                                      default=default_noise),
                                 name='noise',
                                 choices=self.noise_choices,
                                 subform=get_form_for_noise(default_noise))
Exemplo n.º 14
0
 def __init__(self, is_surface_simulation=False):
     super(SimulatorStimulusFragment, self).__init__()
     stimuli_index_class = StimuliRegionIndex
     if is_surface_simulation:
         stimuli_index_class = SpatioTemporalPatternIndex
     traited_field = Attr(stimuli_index_class,
                          doc=SimulatorAdapterModel.stimulus.doc,
                          label=SimulatorAdapterModel.stimulus.label,
                          required=SimulatorAdapterModel.stimulus.required)
     self.stimulus = TraitDataTypeSelectField(traited_field,
                                              name='stimulus')
Exemplo n.º 15
0
    def __init__(self):
        super(SimulatorModelFragment, self).__init__()
        self.model_choices = get_ui_name_to_model()
        default_model = list(self.model_choices.values())[0]

        self.model = SelectField(Attr(Model,
                                      default=default_model,
                                      label=SimulatorAdapterModel.model.label,
                                      doc=SimulatorAdapterModel.model.doc),
                                 choices=self.model_choices,
                                 name='model')
Exemplo n.º 16
0
 def __init__(self, project_id=None):
     super(StimulusSurfaceSelectorForm,
           self).__init__(project_id=project_id)
     traited_attr = Attr(StimuliSurfaceIndex,
                         label='Load Surface Stimulus',
                         required=False)
     self.surface_stimulus = TraitDataTypeSelectField(
         traited_attr, self, name='existentEntitiesSelect')
     self.display_name = SimpleStrField(self,
                                        name='display_name',
                                        label='Display name')
Exemplo n.º 17
0
class CrossCorrelate(HasTraits):
    """
    Model class defining the traited attributes used by the CrossCorrelateAdapter.
    """
    time_series = Attr(
        field_type=TimeSeries,
        label="Time Series",
        required=True,
        doc=
        """The time-series for which the cross correlation sequences are calculated."""
    )
Exemplo n.º 18
0
 def _add_field_for_gid(self, param, param_key):
     # type: (RangeParameter, str) -> None
     traited_attr = Attr(h5.REGISTRY.get_index_for_datatype(param.type),
                         label='Choice for {}'.format(param.name))
     pse_param_dt = TraitDataTypeSelectField(
         traited_attr,
         name=self.GID_FIELD.format(param_key),
         conditions=param.range_definition,
         has_all_option=True,
         show_only_all_option=True)
     self.__setattr__(self.GID_FIELD.format(param_key), pse_param_dt)
Exemplo n.º 19
0
    def test_bool_field(self):
        bool_attr = Attr(field_type=bool, default=True, label='Dummy Bool')
        bool_field = BoolField(bool_attr, self.name)

        post_data = {'dummy_name': 'on'}
        bool_field.fill_from_post(post_data)
        assert bool_field.data, "True (boolean) was not set correctly on BoolField!"

        post_data = {}
        bool_field.fill_from_post(post_data)
        assert bool_field.data is False, "False (boolean) was not set correctly on BoolField!"
Exemplo n.º 20
0
class ObjSurfaceImporterModel(UploaderViewModel):
    surface_type = Str(label='Specify file type :',
                       choices=tuple(ALL_SURFACES_SELECTION.values()),
                       default=tuple(ALL_SURFACES_SELECTION.values())[0])

    data_file = Str(label='Please select file to import')

    should_center = Attr(field_type=bool,
                         required=False,
                         default=False,
                         label='Center surface using vertex means along axes')
Exemplo n.º 21
0
    def test_select_field_invalid(self):
        str_attr = Attr(field_type=str,
                        default='2',
                        label='Dummy Bool',
                        choices=('1', '2', '3'))
        select_field = SelectField(str_attr, self.name)

        post_data = {'dummy_name': '4'}
        select_field.fill_from_post(post_data)
        assert select_field.validate(
        ) is False, "Validation should have failed on SelectField!"
Exemplo n.º 22
0
    def __init__(self):
        super(MultiplicativeNoiseForm, self).__init__()
        self.equation_choices = get_ui_name_to_equation_dict()
        default_equation = list(self.equation_choices.values())[0]

        self.nsig = ArrayField(MultiplicativeNoiseViewModel.nsig)
        self.equation = SelectField(
            Attr(Equation, label='Equation', default=default_equation),
            name='equation',
            choices=self.equation_choices,
            subform=get_form_for_equation(default_equation))
Exemplo n.º 23
0
class DoubleExponential(HRFKernelEquation):
    """
    A difference of two exponential functions to define a kernel for the bold monitor.

    **Parameters** :

    * :math:`\\tau_1`: Time constant of the second exponential function [s]
    * :math:`\\tau_2`: Time constant of the first exponential function [s].
    * :math:`f_1`  : Frequency of the first sine function [Hz].
    * :math:`f_2`  : Frequency of the second sine function [Hz].
    * :math:`amp_1`: Amplitude of the first exponential function.
    * :math:`amp_2`: Amplitude of the second exponential function.
    * :math:`a`    : Amplitude factor after normalization.


    **Reference**:

    .. [P_2000] Alex Polonsky, Randolph Blake, Jochen Braun and David J. Heeger
        (2000). Neuronal activity in human primary visual cortex correlates with
        perception during binocular rivalry. Nature Neuroscience 3: 1153-1159

    """

    equation = Final(
        label="Double Exponential Equation",
        default=
        "((amp_1 * exp(-var/tau_1) * sin(2.*pi*f_1*var)) - (amp_2 * exp(-var/ tau_2) * sin(2.*pi*f_2*var)))",
        doc=""":math:`h(var) = amp_1\\exp(\\frac{-var}{\tau_1})
        \\sin(2\\cdot\\pi f_1 \\cdot var) - amp_2\\cdot \\exp(-\\frac{var}
        {\\tau_2})*\\sin(2\\pi f_2 var)`.""")

    parameters = Attr(field_type=dict,
                      label="Double Exponential Parameters",
                      default=lambda: {
                          "tau_1": 7.22,
                          "f_1": 0.03,
                          "amp_1": 0.1,
                          "tau_2": 7.4,
                          "f_2": 0.12,
                          "amp_2": 0.1,
                          "a": 0.1,
                          "pi": numpy.pi
                      })

    def evaluate(self, var):
        """
        Generate a discrete representation of the equation for the space
        represented by ``var``.
        """
        _pattern = RefBase.evaluate(self.equation, global_dict=self.parameters)
        _pattern /= max(_pattern)

        _pattern *= self.parameters["a"]
        return _pattern
Exemplo n.º 24
0
class iEEG(Projection):
    "Forward solution for intracranial EEG (not ECoG!)."

    _ui_name = "Intracerebral / Stereo EEG"

    projection = Attr(
        projections_module.ProjectionSurfaceSEEG,
        default=None, label='Projection matrix',
        doc='Projection matrix to apply to sources.')

    sigma = Float(label="conductivity", default=1.0)  #, order=4)

    sensors = Attr(
        sensors_module.SensorsInternal,
        label="Internal brain sensors", default=None, required=True,
        doc="The set of SEEG sensors for which the forward solution will be calculated.")


    @classmethod
    def from_file(cls, sensors_fname='seeg_588.txt',
                   projection_fname='projection_seeg_588_surface_16k.npy', **kwargs):
        return Projection.from_file.__func__(cls, sensors_fname, projection_fname, **kwargs)

    def analytic(self, loc, ori):
        r"""Compute the projection matrix -- simple distance weight for now.
        Equation 12 from sarvas1987basic (point dipole in homogeneous space):
          V(r) = 1/(4*pi*\sigma)*Q*(r-r_0)/|r-r_0|^3
        """
        r_0, Q = loc, ori
        V_r = numpy.zeros((self.sensors.locations.shape[0], r_0.shape[0]))
        for sensor_k in numpy.arange(self.sensors.locations.shape[0]):
            a = self.sensors.locations[sensor_k, :] - r_0
            na = numpy.sqrt(numpy.sum(a ** 2, axis=1))[:, numpy.newaxis]
            V_r[sensor_k, :] = numpy.sum(Q * (a / na ** 3), axis=1) / (4.0 * numpy.pi * self.sigma)
        return V_r

    def create_time_series(self, connectivity=None, surface=None,
                           region_map=None, region_volume_map=None):
        return TimeSeriesSEEG(sensors=self.sensors,
                              sample_period=self.period,
                              title=' ' + self.__class__.__name__)
Exemplo n.º 25
0
class ANNarchyOutputDeviceConnection(HasTraits):
    """ANNarchyOutputDeviceConnection class holds properties of connections
       between ANNarchyOutputDevice instances and ANNarchyPopulation ones"""

    from ANNarchy import Population, Monitor

    pre = Attr(field_type=Population,
               default=None,
               required=True,
               label="Population connection source ",
               doc="""The ANNarchy.Population as the connection's source.""")

    post = Attr(field_type=Monitor,
                default=None,
                required=True,
                label="Monitor connection target",
                doc="""The ANNarchy.Monitor as the connection's target.""")

    @property
    def attributes(self):
        return ["pre", "post"]
Exemplo n.º 26
0
class RegionMapping(HasTraits):
    """
    An array (of length Surface.vertices). Each value is representing the index in Connectivity regions
    to which the current vertex is mapped.
    """

    array_data = NArray(dtype=int)

    connectivity = Attr(field_type=Connectivity)

    surface = Attr(field_type=Surface)

    @staticmethod
    def from_file(source_file="regionMapping_16k_76.txt"):
        source_full_path = try_get_absolute_path("tvb_data.regionMapping",
                                                 source_file)
        reader = FileReader(source_full_path)

        result = RegionMapping()
        result.array_data = reader.read_array(dtype=numpy.int32)
        return result
Exemplo n.º 27
0
class DiscreteEquation(FiniteSupportEquation):
    """
    A special case for 'discrete' spaces, such as the regions, where each point
    in the space is effectively just assigned a value.

    """
    equation = Attr(
        field_type=str,
        label="Discrete Equation",
        default="var",
        # locked=True,
        doc="""The equation defines a function of :math:`x`""")
Exemplo n.º 28
0
class TimeSeriesRegion(TimeSeriesBrain, TimeSeriesRegionTVB):
    labels_ordering = List(of=str,
                           default=(TimeSeriesDimensions.TIME.value,
                                    TimeSeriesDimensions.VARIABLES.value,
                                    TimeSeriesDimensions.REGIONS.value,
                                    TimeSeriesDimensions.SAMPLES.value))

    title = Attr(str, default="Region Time Series")

    @property
    def region_labels(self):
        return self.space_labels
Exemplo n.º 29
0
    def __init__(self, prefix='', project_id=None):
        super(SimulatorModelFragment, self).__init__(prefix, project_id)
        self.model_choices = get_ui_name_to_model()
        default_model = list(self.model_choices.values())[0]

        self.model = SelectField(Attr(Model,
                                      default=default_model,
                                      label=Simulator.model.label,
                                      doc=Simulator.model.doc),
                                 self,
                                 choices=self.model_choices,
                                 name='model')
Exemplo n.º 30
0
class TimeSeriesSurface(TimeSeriesBrain, TimeSeriesSurfaceTVB):
    labels_ordering = List(of=str,
                           default=(TimeSeriesDimensions.TIME.value,
                                    TimeSeriesDimensions.VARIABLES.value,
                                    TimeSeriesDimensions.VERTEXES.value,
                                    TimeSeriesDimensions.SAMPLES.value))

    title = Attr(str, default="Surface Time Series")

    @property
    def surface_labels(self):
        return self.space_labels