def test_nsga2(self): logging.info("\t > Evolution: Testing ALN single node ...") start = time.time() def evaluateSimulation(traj): rid = traj.id logging.info("Running run id {}".format(rid)) model = evolution.getModelFromTraj(traj) model.params["dt"] = 0.2 model.params["duration"] = 2 * 1000.0 model.run() # -------- fitness evaluation here -------- # example: get dominant frequency of activity frs, powers = func.getPowerSpectrum( model.rates_exc[:, -int(1000 / model.params["dt"]):], model.params["dt"], ) domfr = frs[np.argmax(powers)] fitness = abs(domfr - 25) # let's try to find a 25 Hz oscillation fitness_tuple = () fitness_tuple += (fitness, ) # multi objective fitness_tuple += (fitness, ) return fitness_tuple, model.outputs alnModel = ALNModel() alnModel.run(bold=True) pars = ParameterSpace(["mue_ext_mean", "mui_ext_mean"], [[0.0, 4.0], [0.0, 4.0]]) evolution = Evolution( evaluateSimulation, pars, algorithm="nsga2", model=alnModel, weightList=[-1.0, 1.0], POP_INIT_SIZE=4, POP_SIZE=4, NGEN=2, filename="test_nsga2.hdf", ) evolution.run(verbose=False) evolution.info(plot=False) traj = evolution.loadResults() gens, all_scores = evolution.getScoresDuringEvolution() # overview of current population evolution.dfPop # overview of all past individuals evolution.dfEvolution end = time.time() logging.info("\t > Done in {:.2f} s".format(end - start))
def test_sampling_dt_lower_than_duration(self): model = ALNModel() model.params["dt"] = 0.1 # 0.1 ms model.params["duration"] = 10 model.params["sampling_dt"] = 30 with self.assertRaises(AssertionError): model.run()
def test_subsample_aln_chunkwise(self): model = ALNModel(seed=42) model.params["sigma_ou"] = 0.0 model.params["duration"] = 1000 # 1000 ms model.params["dt"] = 0.1 # 0.1 ms # default behaviour should be no subsampling self.assertIs(model.params.get("sampling_dt", None), None) model.run(chunksize=3000) full_output = model.output.copy() # subsample the model (same seed) model = ALNModel(seed=42) model.params["sigma_ou"] = 0.0 model.params["duration"] = 1000 # 1000 ms model.params["dt"] = 0.1 # 0.1 ms model.params["sampling_dt"] = 10.0 # 10 ms model.run(chunksize=3000) subsample_output = model.output.copy() sample_every = int(model.params["sampling_dt"] / model.params["dt"]) self.assertEqual( full_output[:, ::sample_every].shape[1], subsample_output.shape[1] ), "Subsampling returned unexpected output shape" self.assertTrue( (full_output[:, ::sample_every] == subsample_output).all() ), "Subsampling returned unexpected output values"
def test_functional_connectivity(self): # assert log warning was issued root_logger = logging.getLogger() with self.assertLogs(root_logger, level="ERROR") as cm: fcs = self.signal.functional_connectivity() self.assertEqual( cm.output, [ "ERROR:root:Cannot compute functional connectivity from one timeseries." ], ) # should be None when computing on one timeseries self.assertEqual(None, fcs) # now proper example with network - 3D case ds = Dataset("gw") aln = ALNModel(Cmat=ds.Cmat, Dmat=ds.Dmat) # in ms, simulates for 2 minutes aln.params["duration"] = 2 * 1000 aln.run() network_sig = RatesSignal.from_model_output(aln) fcs = network_sig.functional_connectivity() self.assertTrue(isinstance(fcs, xr.DataArray)) correct_shape = (network_sig.shape[0], network_sig.shape[1], network_sig.shape[1]) self.assertTupleEqual(fcs.shape, correct_shape) # 2D case fc = network_sig["rates_exc"].functional_connectivity() self.assertTrue(isinstance(fc, xr.DataArray)) correct_shape = (network_sig.shape[1], network_sig.shape[1]) self.assertTupleEqual(fc.shape, correct_shape)
def setUpClass(cls): np.random.seed(42) aln = ALNModel() # simulate 10 seconds aln.params["duration"] = 10.0 * 1000 aln.params["sigma_ou"] = 0.1 # add some noise aln.run() # init RatesSignal cls.signal = RatesSignal.from_model_output(aln)
def test_single_node(self): logging.info("\t > ALN: Testing single node ...") start = time.time() aln = ALNModel() aln.params["duration"] = 2.0 * 1000 aln.params["sigma_ou"] = 0.1 # add some noise aln.run() end = time.time() logging.info("\t > Done in {:.2f} s".format(end - start))
def setUpClass(cls): ds = Dataset("gw") aln = ALNModel(Cmat=ds.Cmat, Dmat=ds.Dmat) # Resting state fits aln.params["mue_ext_mean"] = 1.57 aln.params["mui_ext_mean"] = 1.6 aln.params["sigma_ou"] = 0.09 aln.params["b"] = 5.0 aln.params["duration"] = 0.2 * 60 * 1000 aln.run(bold=True, chunkwise=True) cls.model = aln cls.ds = Dataset("gw")
def test_single_node(self): logging.info("\t > ALN: Testing single node ...") start = time.time() aln = ALNModel() aln.params["duration"] = 10.0 * 1000 aln.params["sigma_ou"] = 0.1 # add some noise # load new initial parameters aln.run(bold=True) # access outputs aln.xr() aln.xr("BOLD") end = time.time() logging.info("\t > Done in {:.2f} s".format(end - start))
def brainanal(self): print("You're choose Brain Analytics \n") #Frekuensi Brain modelf = ALNModel() modelf.params['sigma_ou'] = 0.5 #Add some noise from brain modelf.run() plotmodel.plot(modelf.t, model.output.T) print("Frekuensi Brain accept some noise \n") #Data activity Brain datasetmodel = DataSet("gw") modelactivity = ALNModel(Cmat=datasetmodel.Cmat, Dmat=datasetmodel.Dmat) modelactivity.params[ 'duration'] = 1 * 60 * 1000 #Time simulation brain activity #One minutes simulation modelactivity.run(bold=True) print("Simulation activity sel on Brain \n")
def test_network(self): logging.info("\t > ALN: Testing brain network (chunkwise integration and BOLD" " simulation) ...") start = time.time() ds = Dataset("gw") aln = ALNModel(Cmat=ds.Cmat, Dmat=ds.Dmat) aln.params["duration"] = 10 * 1000 aln.run(chunkwise=True, bold=True, append_outputs=True) # access outputs aln.xr() aln.xr("BOLD") end = time.time() logging.info("\t > Done in {:.2f} s".format(end - start))
def test_compare_w_neurolib_native_model(self): """ Compare with neurolib's native ALN model. """ # run this model aln_multi = self._create_node() multi_result = aln_multi.run( DURATION, DT, ZeroInput(aln_multi.num_noise_variables).as_array(DURATION, DT), backend="numba" ) # run neurolib's model aln_neurolib = ALNModel(seed=SEED) aln_neurolib.params["duration"] = DURATION aln_neurolib.params["dt"] = DT aln_neurolib.params["mue_ext_mean"] = 0.0 aln_neurolib.params["mui_ext_mean"] = 0.0 aln_neurolib.run() for (var_multi, var_neurolib) in NEUROLIB_VARIABLES_TO_TEST: corr_mat = np.corrcoef(aln_neurolib[var_neurolib], multi_result[var_multi].values.T) self.assertTrue(np.greater(corr_mat, CORR_THRESHOLD).all())
def test_compare_w_neurolib_native_model(self): """ Compare with neurolib's native ALN model. Marked with xfail, since sometimes fail on specific python version on Linux, no idea why, but the model works... """ aln_multi = ALNNetwork(self.SC, self.DELAYS, exc_seed=SEED, inh_seed=SEED) multi_result = aln_multi.run( DURATION, DT, ZeroInput(aln_multi.num_noise_variables).as_array(DURATION, DT), backend="numba") # run neurolib's model aln_neurolib = ALNModel(Cmat=self.SC, Dmat=self.DELAYS, seed=SEED) aln_neurolib.params["duration"] = DURATION aln_neurolib.params["dt"] = DT # there is no "global coupling" parameter in MultiModel aln_neurolib.params["K_gl"] = 1.0 # delays <-> length matrix aln_neurolib.params["signalV"] = 1.0 aln_neurolib.params["sigma_ou"] = 0.0 aln_neurolib.params["mue_ext_mean"] = 0.0 aln_neurolib.params["mui_ext_mean"] = 0.0 # match initial state at least for current - this seems to be enough aln_neurolib.params["mufe_init"] = np.array([ aln_multi[0][0].initial_state[0], aln_multi[1][0].initial_state[0] ]) aln_neurolib.params["mufi_init"] = np.array([ aln_multi[0][1].initial_state[0], aln_multi[1][1].initial_state[0] ]) aln_neurolib.run() for (var_multi, var_neurolib) in NEUROLIB_VARIABLES_TO_TEST: for node_idx in range(len(aln_multi)): corr_mat = np.corrcoef( aln_neurolib[var_neurolib][node_idx, :], multi_result[var_multi].values.T[node_idx, :]) print(corr_mat) self.assertTrue(np.greater(corr_mat, CORR_THRESHOLD).all())
def test_sampling_dt_greater_than_chunksize(self): model = ALNModel() model.params["dt"] = 0.1 # 0.1 ms model.params["sampling_dt"] = 30 with self.assertRaises(AssertionError): model.run(chunksize=210)
def test_sampling_dt_divisible_last_chunksize(self): model = ALNModel() model.params["dt"] = 0.1 # 0.1 ms model.params["sampling_dt"] = 0.21 with self.assertRaises(AssertionError): model.run(chunksize=210)
def test_sampling_dt_invalid(self): model = ALNModel() model.params["sampling_dt"] = -30 with self.assertRaises(ValueError): model.run()
def test_sampling_dt_smaller_than_dt(self): model = ALNModel() model.params["dt"] = 10 # 0.1 ms model.params["sampling_dt"] = 9 with self.assertRaises(AssertionError): model.run()