Exemplo n.º 1
0
    def test_modifying_attributes(self):
        """
        Test that when modifying an instance attributes, they are only visible on that instance.
        """
        eqn_t = equations.Gaussian()
        eqn_t.parameters["midpoint"] = 8.0

        eqn_x = equations.Gaussian()
        eqn_x.parameters["amp"] = -0.0625

        assert eqn_t.parameters is not None
        assert eqn_t.parameters['amp'] == 1.0
        assert eqn_t.parameters['midpoint'] == 8.0
        assert eqn_x.parameters is not None
        assert eqn_x.parameters['amp'] == -0.0625
        assert eqn_x.parameters['midpoint'] == 0.0

        a1 = numpy.array([20.0, ])
        a2 = deepcopy(a1)
        a2 = numpy.array([42.0, ])
        assert a1[0] != a2[0]

        model1 = ReducedSetHindmarshRose()
        model1.a = numpy.array([55.0, ])
        model1.number_of_modes = 10

        model2 = ReducedSetHindmarshRose()
        model2.a = numpy.array([42.0])
        model2.number_of_modes = 15
        assert model1.number_of_modes != model2.number_of_modes
        assert model1.a[0] != model2.a[0]
Exemplo n.º 2
0
 def test_gaussian(self):
     dt = equations.Gaussian()
     assert dt.parameters == {
         'amp': 1.0,
         'sigma': 1.0,
         'midpoint': 0.0,
         'offset': 0.0
     }
Exemplo n.º 3
0
 def test_gaussian(self):
     dt = equations.Gaussian()
     self.assertEqual(dt.parameters, {
         'amp': 1.0,
         'sigma': 1.0,
         'midpoint': 0.0,
         'offset': 0.0
     })
Exemplo n.º 4
0
 def test_gaussian(self):
     dt = equations.Gaussian()
     self.assertEqual(dt.parameters, {
         'amp': 1.0,
         'sigma': 1.0,
         'midpoint': 0.0
     })
     self.assertEqual(
         dt.ui_equation,
         'amp * 2.71**(-((var-midpoint)**2 / (2.0 * sigma**2)))')
Exemplo n.º 5
0
    def test_modifying_attributes(self):
        """ 
        Test that when modifying an instance attributes, they are only visible on that instance.
        """
        eqn_t = equations.Gaussian()
        eqn_t.parameters["midpoint"] = 8.0

        eqn_x = equations.Gaussian()
        eqn_x.parameters["amp"] = -0.0625

        self.assertTrue(eqn_t.parameters is not None)
        self.assertEqual(eqn_t.parameters['amp'], 1.0)
        self.assertEqual(eqn_t.parameters['midpoint'], 8.0)
        self.assertTrue(eqn_x.parameters is not None)
        self.assertEqual(eqn_x.parameters['amp'], -0.0625)
        self.assertEqual(eqn_x.parameters['midpoint'], 0.0)

        a1 = arrays.FloatArray()
        a1.data = numpy.array([
            20.0,
        ])
        a2 = deepcopy(a1)
        a2.data = numpy.array([
            42.0,
        ])
        self.assertNotEqual(a1.data[0], a2.data[0])

        model1 = ReducedSetHindmarshRose()
        model1.a = numpy.array([
            55.0,
        ])
        model1.number_of_modes = 10

        model2 = ReducedSetHindmarshRose()
        model2.a = numpy.array([42.0])
        model2.number_of_modes = 15
        self.assertNotEqual(model1.number_of_modes, model2.number_of_modes)
        self.assertNotEqual(model1.a[0], model2.a[0])
Exemplo n.º 6
0
 def test_spatiotemporalpattern(self):
     dt = patterns.SpatioTemporalPattern()
     dt.spatial = equations.DoubleGaussian()
     dt.temporal = equations.Gaussian()
     dt.configure_space(numpy.arange(100).reshape((10, 10)))
     dt.configure()
     summary = dt.summary_info()
     assert summary['Type'] == 'SpatioTemporalPattern'
     assert dt.space.shape == (10, 10)
     assert isinstance(dt.spatial, equations.DoubleGaussian)
     assert dt.spatial_pattern.shape == (10, 1)
     assert isinstance(dt.temporal, equations.Gaussian)
     assert dt.temporal_pattern is None
     assert dt.time is None
Exemplo n.º 7
0
 def test_spatiotemporalpattern(self):
     dt = patterns.SpatioTemporalPattern()
     dt.spatial = equations.DoubleGaussian()
     dt.temporal = equations.Gaussian()
     dt.spatial_pattern = numpy.arange(100).reshape((10, 10))
     dt.configure_space(numpy.arange(100).reshape((10, 10)))
     dt.configure()
     summary = dt.summary_info
     self.assertEqual(summary['Type'], 'SpatioTemporalPattern')
     self.assertEqual(dt.space.shape, (10, 10))
     self.assertTrue(isinstance(dt.spatial, equations.DoubleGaussian))
     self.assertEqual(dt.spatial_pattern.shape, (10, 1))
     self.assertTrue(isinstance(dt.temporal, equations.Gaussian))
     self.assertTrue(dt.temporal_pattern is None)
     self.assertTrue(dt.time is None)
Exemplo n.º 8
0
 def test_stimuliregion(self):
     conn = connectivity.Connectivity(load_default=True)
     conn.configure()
     dt = patterns.StimuliRegion()
     dt.connectivity = conn
     dt.spatial = equations.DiscreteEquation()
     dt.temporal = equations.Gaussian()
     dt.weight = [0 for _ in range(conn.number_of_regions)]
     dt.configure_space()
     assert dt.summary_info['Type'] == 'StimuliRegion'
     assert dt.connectivity is not None
     assert dt.space.shape == (76, 1)
     assert dt.spatial_pattern.shape == (76, 1)
     assert isinstance(dt.temporal, equations.Gaussian)
     assert dt.temporal_pattern is None
     assert dt.time is None
Exemplo n.º 9
0
 def test_stimuliregion(self):
     conn = connectivity.Connectivity()
     conn.configure()
     dt = patterns.StimuliRegion()
     dt.connectivity = conn
     dt.spatial = equations.DiscreteEquation()
     dt.temporal = equations.Gaussian()
     dt.weight = [0 for _ in range(conn.number_of_regions)]
     dt.configure_space()
     self.assertEqual(dt.summary_info['Type'], 'StimuliRegion')
     self.assertTrue(dt.connectivity is not None)
     self.assertEqual(dt.space.shape, (74, 1))
     self.assertEqual(dt.spatial_pattern.shape, (74, 1))
     self.assertTrue(isinstance(dt.temporal, equations.Gaussian))
     self.assertTrue(dt.temporal_pattern is None)
     self.assertTrue(dt.time is None)
Exemplo n.º 10
0
 def test_stimulisurface(self):
     srf = surfaces.CorticalSurface.from_file()
     srf.configure()
     dt = patterns.StimuliSurface()
     dt.surface = srf
     dt.spatial = equations.DiscreteEquation()
     dt.temporal = equations.Gaussian()
     dt.focal_points_triangles = numpy.array([0, 1, 2])
     dt.configure()
     dt.configure_space()
     summary = dt.summary_info()
     assert summary['Type'] == "StimuliSurface"
     assert dt.space.shape == (16384, 3)
     assert isinstance(dt.spatial, equations.DiscreteEquation)
     assert dt.spatial_pattern.shape == (16384, 1)
     assert dt.surface is not None
     assert isinstance(dt.temporal, equations.Gaussian)
     assert dt.temporal_pattern is None
     assert dt.time is None
Exemplo n.º 11
0
 def test_stimulisurface(self):
     srf = surfaces.CorticalSurface(load_default=True)
     srf.configure()
     dt = patterns.StimuliSurface()
     dt.surface = srf
     dt.spatial = equations.DiscreteEquation()
     dt.temporal = equations.Gaussian()
     dt.focal_points_surface = [0, 1, 2]
     dt.focal_points_triangles = [0, 1, 2]
     dt.configure()
     dt.configure_space()
     summary = dt.summary_info
     self.assertEqual(summary['Type'], "StimuliSurface")
     self.assertEqual(dt.space.shape, (16384, 3))
     self.assertTrue(isinstance(dt.spatial, equations.DiscreteEquation))
     self.assertEqual(dt.spatial_pattern.shape, (16384, 1))
     self.assertTrue(dt.surface is not None)
     self.assertTrue(isinstance(dt.temporal, equations.Gaussian))
     self.assertTrue(dt.temporal_pattern is None)
     self.assertTrue(dt.time is None)
Exemplo n.º 12
0
class LocalConnectivity(HasTraits):
    """
    A sparse matrix for representing the local connectivity within the Cortex.
    """
    surface = Attr(field_type=surfaces.CorticalSurface, label="Surface")

    matrix = Attr(field_type=scipy.sparse.spmatrix, required=False)

    equation = Attr(
        field_type=equations.FiniteSupportEquation,
        label="Spatial",
        required=False,
        default=equations.Gaussian())

    cutoff = Float(
        label="Cutoff distance (mm)",
        default=40.0,
        doc="Distance at which to truncate the evaluation in mm.")

    # Temporary obj
    matrix_gdist = None

    def compute(self):
        """
        Compute current Matrix.
        """
        self.log.info("Mapping geodesic distance through the LocalConnectivity.")

        # Start with data being geodesic_distance_matrix, then map it through equation
        # Then replace original data with result...
        self.matrix_gdist.data = self.equation.evaluate(self.matrix_gdist.data)

        # Homogenise spatial discretisation effects across the surface
        nv = self.matrix_gdist.shape[0]
        ind = numpy.arange(nv, dtype=int)
        pos_mask = self.matrix_gdist.data > 0.0
        neg_mask = self.matrix_gdist.data < 0.0
        pos_con = self.matrix_gdist.copy()
        neg_con = self.matrix_gdist.copy()
        pos_con.data[neg_mask] = 0.0
        neg_con.data[pos_mask] = 0.0
        pos_contrib = pos_con.sum(axis=1)
        pos_contrib = numpy.array(pos_contrib).squeeze()
        neg_contrib = neg_con.sum(axis=1)
        neg_contrib = numpy.array(neg_contrib).squeeze()
        pos_mean = pos_contrib.mean()
        neg_mean = neg_contrib.mean()
        if ((pos_mean != 0.0 and any(pos_contrib == 0.0)) or
                (neg_mean != 0.0 and any(neg_contrib == 0.0))):
            msg = "Cortical mesh is too coarse for requested LocalConnectivity."
            self.log.warning(msg)
            bad_verts = ()
            if pos_mean != 0.0:
                bad_verts = bad_verts + numpy.nonzero(pos_contrib == 0.0)
            if neg_mean != 0.0:
                bad_verts = bad_verts + numpy.nonzero(neg_contrib == 0.0)
            self.log.debug("Problem vertices are: %s" % str(bad_verts))
        pos_hf = numpy.zeros(shape=pos_contrib.shape)
        pos_hf[pos_contrib != 0] = pos_mean / pos_contrib[pos_contrib != 0]
        neg_hf = numpy.zeros(shape=neg_contrib.shape)
        neg_hf[neg_contrib != 0] = neg_mean / neg_contrib[neg_contrib != 0]
        pos_hf_diag = scipy.sparse.csc_matrix((pos_hf, (ind, ind)), shape=(nv, nv))
        neg_hf_diag = scipy.sparse.csc_matrix((neg_hf, (ind, ind)), shape=(nv, nv))
        homogenious_conn = (pos_hf_diag * pos_con) + (neg_hf_diag * neg_con)

        # Then replace unhomogenised result with the spatially homogeneous one...
        if not homogenious_conn.has_sorted_indices:
            homogenious_conn.sort_indices()

        self.matrix = homogenious_conn

    @staticmethod
    def from_file(source_file="local_connectivity_16384.mat"):

        result = LocalConnectivity()

        source_full_path = try_get_absolute_path("tvb_data.local_connectivity", source_file)
        reader = FileReader(source_full_path)

        result.matrix = reader.read_array(matlab_data_name="LocalCoupling")
        return result

    def summary_info(self):
        """
        Gather scientifically interesting summary information from an instance
        of this datatype.
        """
        _, _, v = scipy.sparse.find(self.matrix)
        return narray_summary_info(v, ar_name='matrix-nonzero')

    def compute_sparse_matrix(self):
        """
        NOTE: Before calling this method, the surface field
        should already be set on the local connectivity.

        Computes the sparse matrix for this local connectivity.
        """
        if self.surface is None:
            raise AttributeError('Require surface to compute local connectivity.')

        self.matrix_gdist = surfaces.gdist.local_gdist_matrix(
            self.surface.vertices.astype(numpy.float64),
            self.surface.triangles.astype(numpy.int32),
            max_distance=self.cutoff)

        self.compute()
        # Avoid having a large data-set in memory.
        self.matrix_gdist = None
Exemplo n.º 13
0
#Initialise an Integrator
heunint = integrators.HeunDeterministic(dt=2**-4)

#Initialise some Monitors with period in physical time
mon_tavg = monitors.TemporalAverage(period=2**-2)
mon_savg = monitors.SpatialAverage(period=2**-2)
mon_eeg = monitors.EEG(period=2**-2)

#Bundle them
what_to_watch = (mon_tavg, mon_savg, mon_eeg)

#Initialise a surface
local_coupling_strength = numpy.array([0.0121])

grey_matter = surfaces.LocalConnectivity(equation=equations.Gaussian(),
                                         cutoff=60.0)
grey_matter.equation.parameters['sigma'] = 10.0
grey_matter.equation.parameters['amp'] = 0.0

default_cortex = surfaces.Cortex(local_connectivity=grey_matter,
                                 coupling_strength=local_coupling_strength)

#Define the stimulus
eqn_t = equations.Gaussian()
eqn_t.parameters["amp"] = 0.0
eqn_t.parameters["midpoint"] = 8.0
eqn_x = equations.Gaussian()

eqn_x.parameters["amp"] = -0.0625
eqn_x.parameters["sigma"] = 28.0
Exemplo n.º 14
0
#Initialise some Monitors with period in physical time
momo = monitors.TemporalAverage(period=1.0)  #1000Hz
mama = monitors.Bold(period=500)  #defaults to one data point every 2s

#Bundle them
what_to_watch = (momo, mama)

#Define the stimulus
#Specify a weighting for regions to receive stimuli...
white_matter.configure()  # Because we want access to number_of_regions
nodes = [0, 7, 13, 33, 42]
weighting = numpy.zeros((white_matter.number_of_regions, ))  #1
weighting[nodes] = numpy.array([2.0**-2, 2.0**-3, 2.0**-4, 2.0**-5,
                                2.0**-6])  # [:, numpy.newaxis]

eqn_t = equations.Gaussian()
eqn_t.parameters["midpoint"] = 15000.0
eqn_t.parameters["sigma"] = 4.0

stimulus = patterns.StimuliRegion(temporal=eqn_t,
                                  connectivity=white_matter,
                                  weight=weighting)

#Initialise Simulator -- Model, Connectivity, Integrator, Monitors, and stimulus.
sim = simulator.Simulator(model=oscilator,
                          connectivity=white_matter,
                          coupling=white_matter_coupling,
                          integrator=heunint,
                          monitors=what_to_watch,
                          stimulus=stimulus)  # surface=default_cortex,
Exemplo n.º 15
0
 def test_gaussian(self):
     t = np.linspace(0,10)
     dt = equations.Gaussian()
     assert dt.parameters == {'amp': 1.0, 'sigma': 1.0, 'midpoint': 0.0, 'offset': 0.0}
     np.testing.assert_allclose( dt.evaluate(t)[10:], dt.evaluate(t[10:]))