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`""")
class ConnectivityMeasureImporterModel(UploaderViewModel): data_file = Str(label='Connectivity measure file (.mat format)') dataset_name = Attr(field_type=str, default='M', label='Matlab dataset name', doc='Name of the MATLAB dataset where data is stored') connectivity = DataTypeGidAttr( linked_datatype=Connectivity, label='Large Scale Connectivity', doc='The Connectivity for which these measurements were made')
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"]
def __init__(self, prefix=''): super(MultiplicativeNoiseForm, self).__init__(prefix) self.equation_choices = get_ui_name_to_equation_dict() default_equation = list(self.equation_choices.values())[0] self.nsig = ArrayField(MultiplicativeNoiseViewModel.nsig, self) self.equation = SelectField( Attr(Equation, label='Equation', default=default_equation), self, name='equation', choices=self.equation_choices, subform=get_form_for_equation(default_equation))
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
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
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
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, self.project_id, name=self.GID_FIELD.format(param_key), dynamic_conditions=param.range_definition, has_all_option=True, show_only_all_option=True) self.__setattr__(self.GID_FIELD.format(param_key), pse_param_dt)
def __init__(self, project_id=None): super(SimulatorModelFragment, self).__init__(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=SimulatorAdapterModel.model.label, doc=SimulatorAdapterModel.model.doc), self.project_id, choices=self.model_choices, name='model')
def __init__(self, project_id=None, is_surface_simulation=False): super(SimulatorStimulusFragment, self).__init__(project_id) 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, self.project_id, name='stimulus')
class NetworkxImporterModel(UploaderViewModel): data_file = Str(label='Please select file to import') key_edge_weight = Attr(field_type=str, required=False, default=NetworkxParser.KEY_EDGE_WEIGHT[0], label='Key Edge Weight') key_edge_tract = Attr(field_type=str, required=False, default=NetworkxParser.KEY_EDGE_TRACT[0], label='Key Edge Tract') key_node_coordinates = Attr(field_type=str, required=False, default=NetworkxParser.KEY_NODE_COORDINATES[0], label='Key Node Coordinates') key_node_label = Attr(field_type=str, required=False, default=NetworkxParser.KEY_NODE_LABEL[0], label='Key Node Label') key_node_region = Attr(field_type=str, required=False, default=NetworkxParser.KEY_NODE_REGION[0], label='Key Node Region') key_node_hemisphere = Attr(field_type=str, required=False, default=NetworkxParser.KEY_NODE_HEMISPHERE[0], label='Key Node Hemisphere')
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.""")
def __init__(self, path): super(BurstConfigurationH5, self).__init__(path) self.name = Scalar(Attr(str), self, name='name') self.status = Scalar(Attr(str), self, name='status') self.error_message = Scalar(Attr(str, required=False), self, name='error_message') self.start_time = Scalar(Attr(str), self, name='start_time') self.finish_time = Scalar(Attr(str, required=False), self, name='finish_time') self.simulator = Reference(Attr(uuid.UUID), self, name='simulator') self.range1 = Scalar(Attr(str, required=False), self, name='range1') self.range2 = Scalar(Attr(str, required=False), self, name='range2')
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)
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 )
def __init__(self, prefix='', project_id=None): super(SimulatorAdapterForm, self).__init__(prefix, project_id) self.coupling_choices = get_ui_name_to_coupling_dict() default_coupling = list(self.coupling_choices.values())[0] self.connectivity = TraitDataTypeSelectField(SimulatorAdapterModel.connectivity, self, name=self.get_input_name(), conditions=self.get_filters()) self.coupling = SelectField( Attr(Coupling, default=default_coupling, label="Coupling", doc=Simulator.coupling.doc), self, name='coupling', choices=self.coupling_choices) self.conduction_speed = FloatField(Simulator.conduction_speed, self) self.ordered_fields = (self.connectivity, self.conduction_speed, self.coupling) self.range_params = [Simulator.connectivity, Simulator.conduction_speed]
def test_select_field_optional_none(self): str_attr = Attr(field_type=str, default='2', label='Dummy Bool', choices=('1', '2', '3'), required=False) select_field = SelectField(str_attr, self.name) post_data = {'dummy_name': 'explicit-None-value'} select_field.fill_from_post(post_data) assert select_field.data == None, "Data was not set correctly on SelectField!" assert select_field.validate( ), "Validation should have passed on SelectField!"
def test_select_field_required(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': '1'} select_field.fill_from_post(post_data) assert select_field.data == post_data[ self.name], "Data was not set correctly on SelectField!" assert select_field.validate( ), "Validation should have passed on SelectField!"
def __init__(self, project_id=None, default_simulation_name="simulation_1"): super(SimulatorFinalFragment, self).__init__(project_id) self.simulation_length = FloatField( SimulatorAdapterModel.simulation_length, self.project_id) self.simulation_name = StrField(Attr( str, doc='Name for the current simulation configuration', default=default_simulation_name, label='Simulation name'), self.project_id, name='input_simulation_name_id')
class TimeSeriesSEEG(TimeSeriesSensors, TimeSeriesSEEGTVB): title = Attr(str, default="SEEG Time Series") def configure(self): super(TimeSeriesSensors, self).configure() if isinstance(self.sensors, Sensors) and not isinstance( self.sensors, SensorsInternal): warning("Creating %s with sensors of type %s!" % (self.__class__.__name__, self.sensors.__class__.__name__)) @property def SEEGsensor_labels(self): return self.space_labels
class ZIPSurfaceImporterModel(UploaderViewModel): uploaded = Str( label='Surface file (zip)' ) surface_type = EnumAttr( default=SurfaceTypesEnum.CORTICAL_SURFACE, label='Surface type' ) zero_based_triangles = Attr( field_type=bool, required=False, default=True, label='Zero based triangles' ) should_center = Attr( field_type=bool, required=False, label='Center surface using vertex means along axes' )
def __init__(self, model_params): super(SurfaceModelParametersForm, self).__init__() self.model_param = SelectField(Str(label='Model parameter'), choices=model_params, name='model_param') self.equation = SelectField(Attr(SpatialApplicableEquation, label='Equation', default=self.default_equation), choices=self.equation_choices, name='equation', subform=get_form_for_equation( self.default_equation))
def __init__(self, prefix='', project_id=None, default_simulation_name="simulation_1"): super(SimulatorFinalFragment, self).__init__(prefix, project_id) self.simulation_length = ScalarField(Simulator.simulation_length, self) self.simulation_name = ScalarField(Attr( str, doc='Name for the current simulation configuration', default=default_simulation_name, label='Simulation name'), self, name='input_simulation_name_id')
class TimeSeriesVolume(TimeSeries): """ A time-series associated with a Volume. """ volume = Attr(field_type=volumes.Volume) _default_labels_ordering = List(of=str, default=("Time", "X", "Y", "Z")) def summary_info(self): """ Gather scientifically interesting summary information from an instance of this datatype. """ summary = super(TimeSeriesVolume, self).summary_info() summary.update({"Source Volume": self.volume.title}) return summary
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.""" ) neural_input_transformation = Attr( field_type=str, label="Neural input transformation", choices=("none", "abs_diff", "sum"), default="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 = Attr( field_type=str, label="Select BOLD model equations", choices=("linear", "nonlinear"), default="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.""")
class VolumeVisualizerModel(BaseVolumeVisualizerModel): measure = DataTypeGidAttr(linked_datatype=DataTypeMatrix, label='Measure', doc='A measure to view on anatomy') region_mapping_volume = DataTypeGidAttr( linked_datatype=RegionVolumeMapping, required=False, label='Region mapping') data_slice = Attr(field_type=str, required=False, label='slice indices in numpy syntax')
class Multiplicative(Noise): r""" With "external" fluctuations the intensity of the noise often depends on the state of the system. This results in the (general) stochastic differential formulation: .. math:: dX_t = a(X_t)\,dt + b(X_t)\,dW_t for appropriate coefficients :math:`a(x)` and :math:`b(x)`, which might be constants. From [KloedenPlaten_1995]_, Equation 1.9, page 104. """ nsig = NArray( # configurable_noise=True, label=":math:`D`", required=True, default=numpy.array([ 1.0, ]), domain=Range(lo=0.0, hi=10.0, step=0.1), doc="""The noise dispersion, it is the standard deviation of the distribution from which the Gaussian random variates are drawn. NOTE: Sensible values are typically ~<< 1% of the dynamic range of a Model's state variables.""") b = Attr( field_type=equations.TemporalApplicableEquation, label=":math:`b`", default=equations.Linear(parameters={ "a": 1.0, "b": 0.0 }), doc= """A function evaluated on the state-variables, the result of which enters as the diffusion coefficient.""" ) def gfun(self, state_variables): """ Scale the noise by the noise dispersion and the diffusion coefficient. By default, the diffusion coefficient :math:`b` is a constant. It reduces to the simplest scheme of a linear SDE with Multiplicative Noise: homogeneous constant coefficients. See [KloedenPlaten_1995]_, Equation 4.6, page 119. """ g_x = numpy.sqrt(2.0 * self.nsig) * self.b.evaluate(state_variables) return g_x
class ConnectivityViewerModel(ViewModel): """ Attributes meaning: connectivity: GID towards the `Connectivity` object which will be displayed surface_data: if provided, it is displayed as a shadow to give an idea of the connectivity position relative to the full brain cortical surface colors: used to establish a colormap for the nodes displayed in 2D Connectivity viewers rays: used to establish the size of the spheres representing each node in 3D Nodes viewer step: a threshold applied to the 2D Connectivity Viewers to differentiate 2 types of nodes the ones with a value greater that this will be displayed as red discs, instead of yellow """ connectivity = DataTypeGidAttr( linked_datatype=Connectivity, label='Connectivity Matrix' ) surface_data = DataTypeGidAttr( linked_datatype=Surface, required=False, label='Brain Surface', doc='The Brain Surface is used to give you an idea of the connectivity ' 'position relative to the full brain cortical surface. This surface' ' will be displayed as a shadow (only used in 3D Edges tab).' ) step = Attr( field_type=float, required=False, label='Color Threshold', doc='All nodes with a value greater or equal (>=) than this threshold will be ' 'displayed as red discs, otherwise (<) they will be yellow. (This applies to ' '2D Connectivity tabs and the threshold will depend on the metric used to set ' 'the Node Color)' ) colors = DataTypeGidAttr( linked_datatype=ConnectivityMeasure, required=False, label='Node Colors', doc='A ConnectivityMeasure DataType that establishes a colormap for the nodes displayed ' 'in the 2D Connectivity tabs.' ) rays = DataTypeGidAttr( linked_datatype=ConnectivityMeasure, required=False, label='Shapes Dimensions', doc='A ConnectivityMeasure datatype used to establish the size of the spheres representing each node. ' '(It only applies to 3D Nodes tab).' )
class FFTAdapterModel(ViewModel): """ Parameters have the following meaning: - time_series: the input time series to which the fft is to be applied - segment_length: the block size which determines the frequency resolution of the resulting power spectra - window_function: windowing functions can be applied before the FFT is performed - detrend: None; specify if detrend is performed on the time series """ time_series = DataTypeGidAttr( linked_datatype=TimeSeries, label="Time Series", doc="""The TimeSeries to which the FFT is to be applied.""") segment_length = Float( label="Segment(window) length (ms)", default=1000.0, required=False, doc="""The TimeSeries can be segmented into equally sized blocks (overlapping if necessary). The segment length determines the frequency resolution of the resulting power spectra -- longer windows produce finer frequency resolution.""") window_function = Attr( field_type=str, label="Windowing function", choices=tuple(SUPPORTED_WINDOWING_FUNCTIONS), required=False, doc="""Windowing functions can be applied before the FFT is performed. Default is None, possibilities are: 'hamming'; 'bartlett'; 'blackman'; and 'hanning'. See, numpy.<function_name>.""") detrend = Attr(field_type=bool, label="Detrending", default=True, required=False, doc="""Detrending is not always appropriate. Default is True, False means no detrending is performed on the time series""" )
def __init__(self, prefix='', project_id=None): super(SimulatorIntegratorFragment, self).__init__(prefix, project_id) self.integrator_choices = get_ui_name_to_integrator_dict() default_integrator = list(self.integrator_choices.values())[0] self.integrator = SelectField( Attr(Integrator, default=default_integrator, label=Simulator.integrator.label, doc=Simulator.integrator.doc), self, name='integrator', choices=self.integrator_choices, subform=get_form_for_integrator(default_integrator))