├── C ├── TVBii.c └── TVBii_update.c ├── LICENSE ├── MATLAB ├── computeGAWs_fast_timescale.m ├── computeGAWs_fast_timescale_agg.m ├── computeGAWs_slow_timescale_agg.m ├── compute_alpha_regressor.m ├── extract_statevars.m ├── generate_artificial_input.m ├── generate_hybrid_model_input.m ├── generate_input_SC.m └── postprocess_simulation_results.m └── README.md /C/TVBii.c: -------------------------------------------------------------------------------- 1 | /***************************************************************************** 2 | TVBii.c 3 | The Virtual Brain 4 | (c) 2017 - Michael Schirner 5 | BrainModes Group 6 | Charité University Medicine Berlin 7 | m.schirner@fu-berlin.de 8 | Licensed under the GNU General Public License 3.0 license. 9 | ******************************************************************************/ 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | struct Xi_p{ 20 | float **Xi_elems; 21 | }; 22 | 23 | struct SC_capS{ 24 | float *cap; 25 | }; 26 | 27 | FILE *FCout, *WFout; 28 | 29 | /* 30 | Open files for writing simulated activity 31 | */ 32 | void openFCoutfile(char *paramset, int myid, char *sub_id){ 33 | char outfilename[1000];memset(outfilename, 0, 1000*sizeof(char)); 34 | char buffer[10];memset(buffer, 0, 10*sizeof(char)); 35 | char underscore[2]; 36 | underscore[0]='_'; 37 | underscore[1]='\0'; 38 | strcpy (outfilename,"output/"); 39 | strcat (outfilename,"/BOLD_"); 40 | strcat (outfilename,sub_id);strcat (outfilename,underscore); 41 | strcat (outfilename,paramset);strcat (outfilename,underscore); 42 | snprintf(buffer, 10, "%d", myid);strcat (outfilename,buffer); 43 | strcat (outfilename,".txt"); 44 | FCout = fopen(outfilename, "w"); 45 | memset(outfilename, 0, 1000*sizeof(char)); 46 | strcpy (outfilename,"output/"); 47 | strcat (outfilename,"/SV_"); 48 | strcat (outfilename,sub_id);strcat (outfilename,underscore); 49 | strcat (outfilename,paramset);strcat (outfilename,underscore); 50 | snprintf(buffer, 10, "%d", myid);strcat (outfilename,buffer); 51 | strcat (outfilename,".txt"); 52 | WFout = fopen(outfilename, "w"); 53 | } 54 | 55 | 56 | /* 57 | Import SC (long-range coupling) and convert into efficient data structure 58 | */ 59 | int importGlobalConnectivity(char *SC_cap_filename, char *SC_dist_filename, char *SC_inputreg_filename, int regions, float **region_activity, struct Xi_p **reg_globinp_p, float global_trans_v, int **n_conn_table, float **n_conn_table_G_NMDA, float G_J_NMDA, struct SC_capS **SC_cap, float **SC_rowsums) 60 | { 61 | 62 | int i,j,k, tmp3, maxdelay=0, tmpint; 63 | float *region_activity_p; 64 | double tmp, tmp2; 65 | struct Xi_p *reg_globinp_pp; 66 | struct SC_capS *SC_capp; 67 | int num_incoming_conn_cap=0, num_incoming_conn_dist=0, num_incoming_conn_inputreg=0; 68 | 69 | // Open SC files 70 | FILE *file_cap, *file_dist, *file_inputreg; 71 | file_cap=fopen(SC_cap_filename, "r"); 72 | file_dist=fopen(SC_dist_filename, "r"); 73 | file_inputreg=fopen(SC_inputreg_filename, "r"); 74 | if (file_cap==NULL || file_dist==NULL || file_inputreg==NULL) 75 | { 76 | printf( "\n ERROR: Could not open SC files. Terminating... \n\n%s\n%s\n%s\n\n", SC_cap_filename, SC_dist_filename, SC_inputreg_filename); 77 | exit(0); 78 | } 79 | 80 | // Read number of regions in header and check whether it's consistent with other specifications 81 | int readSC_cap, readSC_dist, readSC_inp; 82 | if(fscanf(file_cap,"%d",&readSC_cap) == EOF || fscanf(file_dist,"%d",&readSC_dist) == EOF || fscanf(file_inputreg,"%d",&readSC_inp) == EOF){ 83 | printf( "\n ERROR: Unexpected end-of-file in file. File contains less input than expected. Terminating... \n\n"); 84 | exit(0); 85 | } 86 | if (readSC_cap != regions || readSC_dist != regions || readSC_inp != regions) { 87 | printf( "\n ERROR: Inconsistent number of large-scale regions in SC files. Terminating... \n\n"); 88 | fclose(file_dist);fclose(file_inputreg); 89 | exit(0); 90 | } 91 | 92 | // Allocate a counter (to store number of region inputs for each region) and the SCcap array (to store connection weights) 93 | *SC_rowsums = (float *)_mm_malloc(regions*sizeof(float),16); 94 | *n_conn_table = (int *)_mm_malloc(regions*sizeof(int),16); 95 | *n_conn_table_G_NMDA = (float *)_mm_malloc(regions*sizeof(float),16); 96 | *SC_cap = (struct SC_capS *)_mm_malloc(regions*sizeof(struct SC_capS),16); 97 | SC_capp = *SC_cap; 98 | if(*n_conn_table==NULL || *n_conn_table_G_NMDA==NULL || SC_capp==NULL || SC_rowsums==NULL){ 99 | printf("Running out of memory. Terminating.\n");fclose(file_dist);fclose(file_cap);fclose(file_inputreg);exit(2); 100 | } 101 | 102 | // Read the maximal fiber length in header of SCdist-file and compute maxdelay 103 | if(fscanf(file_dist,"%lf",&tmp) == EOF){ 104 | printf( "ERROR: Unexpected end-of-file in file. File contains less input than expected. Terminating... \n"); 105 | exit(0); 106 | } 107 | maxdelay = (int)((tmp/global_trans_v)+0.5); // +0.5 for rounding by casting 108 | if (maxdelay < 1) maxdelay = 1; // Case: no time delays 109 | 110 | // Allocate ringbuffer that contains region activity for each past time-step until maxdelay and another ringbuffer that contains pointers to the first ringbuffer 111 | *region_activity = (float *)_mm_malloc(maxdelay*regions*sizeof(float),16); 112 | region_activity_p = *region_activity; 113 | *reg_globinp_p = (struct Xi_p *)_mm_malloc(maxdelay*regions*sizeof(struct Xi_p),16); 114 | reg_globinp_pp = *reg_globinp_p; 115 | if(region_activity_p==NULL || reg_globinp_p==NULL){ 116 | printf("Running out of memory. Terminating.\n");fclose(file_dist);exit(2); 117 | } 118 | for (j=0; j 0) { 147 | (*n_conn_table_G_NMDA)[i] = G_J_NMDA / num_incoming_conn_inputreg; 148 | //(*n_conn_table_G_NMDA)[i] = G_J_NMDA; 149 | } else{ 150 | (*n_conn_table_G_NMDA)[i] = 0; 151 | } 152 | 153 | 154 | if ((*n_conn_table)[i] > 0) { 155 | // SC strength 156 | SC_capp[i].cap = (float *)_mm_malloc(((*n_conn_table)[i])*sizeof(float),16); 157 | if(SC_capp[i].cap==NULL){ 158 | printf("Running out of memory. Terminating.\n");exit(2); 159 | } 160 | 161 | // Allocate memory for input-region-pointer arrays for each time-step in ringbuffer 162 | for (j=0; j %d. Terminating... \n\n",i,tmp3);exit(0); 178 | } 179 | 180 | //SC_capp[i].cap[j] = (float)tmp * (*n_conn_table_G_NMDA)[i]; 181 | SC_capp[i].cap[j] = (float)tmp * G_J_NMDA; 182 | sum_caps += (float)tmp; 183 | 184 | if (tmp3 >= 0) { 185 | ring_buff_position=maxdelay*regions - tmpint*regions + tmp3; 186 | for (k=0; k (maxdelay*regions-1)) ring_buff_position -= maxdelay*regions; 190 | } 191 | } else { 192 | printf( "\nERROR: Region index is negative: %d -> %d. Terminating... \n\n",i,tmp3);exit(0); 193 | } 194 | 195 | 196 | } else{ 197 | printf( "\n ERROR: Unexpected end-of-file in file %s or %s. File contains less input than expected. Terminating... \n\n", SC_inputreg_filename, SC_dist_filename); 198 | exit(0); 199 | } 200 | 201 | } 202 | if (sum_caps <= 0) { 203 | printf( "\nERROR: Sum of connection strenghts is negative or zero. sum-caps node %d = %f. Terminating... \n\n",i,sum_caps);exit(0); 204 | } 205 | (*SC_rowsums)[i] = sum_caps; 206 | } 207 | } 208 | 209 | fclose(file_dist);fclose(file_inputreg); 210 | return maxdelay; 211 | } 212 | 213 | 214 | 215 | 216 | int main(int argc, char *argv[]) 217 | { 218 | 219 | 220 | /************* 221 | Set up model 222 | *************/ 223 | 224 | int myid=0, i, j, k; 225 | 226 | //Get starting time 227 | time_t start = time(NULL); 228 | 229 | // Check input arguments 230 | if (argc != 4 || atoi(argv[3]) > 8 || atoi(argv[3]) < 0) { 231 | printf( "\n ERROR: Too few/many or wrong arguments. Terminating... \n\n"); 232 | exit(0); 233 | } 234 | 235 | // Open output files and switch between different types of input activity 236 | char outputfolder[100];memset(outputfolder, 0, 100*sizeof(char)); 237 | char subject_file[100];memset(subject_file, 0, 100*sizeof(char)); 238 | strcpy(subject_file,"input/");strcat(subject_file,argv[2]); 239 | switch (atoi(argv[3])) { 240 | case 0: 241 | strcat(subject_file,"_fullextinp1000.txt"); 242 | strcpy(outputfolder,"full"); 243 | break; 244 | case 1: 245 | strcat(subject_file,"_fullextinprandperm1000.txt"); 246 | strcpy(outputfolder,"fullrand"); 247 | break; 248 | case 2: 249 | strcat(subject_file,"_fullextinp_diff1000.txt"); 250 | strcpy(outputfolder,"diff"); 251 | break; 252 | case 3: 253 | strcat(subject_file,"_fullextinprandperm_diff1000.txt"); 254 | strcpy(outputfolder,"diffrand"); 255 | break; 256 | case 4: 257 | strcat(subject_file,"_fullextinp1000.txt"); 258 | strcpy(outputfolder,"testfull"); 259 | break; 260 | case 5: 261 | strcat(subject_file,"_fullextinp_diff1000.txt"); 262 | strcpy(outputfolder,"testdiff"); 263 | break; 264 | case 6: 265 | memset(subject_file, 0, 100*sizeof(char)); 266 | strcpy(subject_file,"input/"); 267 | strcat(subject_file,"artifical_powermod_input.txt"); 268 | strcpy(outputfolder,"testdiff"); 269 | break; 270 | case 7: 271 | memset(subject_file, 0, 100*sizeof(char)); 272 | strcpy(subject_file,"input/"); 273 | strcat(subject_file,"artifical_powermod_input_9Hz.txt"); 274 | strcpy(outputfolder,"testdiff"); 275 | break; 276 | case 8: 277 | memset(subject_file, 0, 100*sizeof(char)); 278 | strcpy(subject_file,"input/"); 279 | strcat(subject_file,"artifical_powermod_input_11Hz.txt"); 280 | strcpy(outputfolder,"testdiff"); 281 | break; 282 | } 283 | openFCoutfile(argv[1], myid, argv[2]); 284 | 285 | 286 | 287 | /* 288 | Global model and integration parameters 289 | */ 290 | float TR = 1.94; // (s) TR of fMRI data 291 | int TR_ts = TR * 1000; // n-th time step for writing out a fMRI data point 292 | const float dt = 0.1; // Integration step length dt = 0.1 ms 293 | const float model_dt = 0.001; // (Hz) Time-step of model (sampling-rate=1000 Hz) 294 | const int vectorization_grade = 4; // depends on CPU Architecture and available intrinsics. 295 | int time_steps = 667*TR*1000; // simulation length: 667 TRs * 1.94 s/TR * 1000 time-steps/s 296 | int time_steps_FIC_burnin = 10*1000; // 10 s as a burn-in for FIC tuning to let model activity stabilized 297 | int time_steps_FIC_fit = time_steps - time_steps_FIC_burnin; 298 | const int nodes = 68; // Number of nodes; must be a multiple of vectorization grade 299 | const int nodes_vec = nodes/vectorization_grade; 300 | const int regions = 68; // Number of large-scale regions (identical to nodes for non-surface simulations) 301 | float global_trans_v = 1.0; // Global transmission velocity (m/s) 302 | float G = 0.5; // Global coupling strength 303 | int FIC_iters = 12; // Number of FIC tuning iterations 304 | const float avg_FR = 3.0631; // (Hz) avg firing rate of an exc. population 305 | const float tuning_factor = 0.005; // parameter for FIC tuning 306 | float adaptive_tuning_factor = tuning_factor; // parameter for FIC tuning 307 | const float meanFRfact = 1.0 / (time_steps_FIC_fit*10); // Factor for averaging firing rates over FIC simulation period 308 | float mean_mean_FR = 0.0; // variable for FIC tuning 309 | float variance_FR = 0.0; // variable for FIC tuning 310 | float tmpglobinput, tmpBOLD; 311 | int ring_buf_pos=0; // Position in ring buffer of past state variables for long-range input 312 | float tmp_exp_E[4] __attribute__((aligned(16))); 313 | float tmp_exp_I[4] __attribute__((aligned(16))); 314 | 315 | 316 | /* 317 | Local model: DMF-Parameters from Deco et al. JNeuro 2014 318 | */ 319 | float w_plus = 1.4; // local excitatory recurrence 320 | //float I_ext = 0; // Additional external stimulation -- not used in hybrid models 321 | //float J_NMDA = 0.15; // (nA) excitatory synaptic coupling 322 | float J_NMDA = 0.0; // J_NMDA is replaced by injected input in hybrid models 323 | //float J_i = 1.0; // Single value for no-FIC models 324 | const float a_E = 310; // (n/C) 325 | const float b_E = 125; // (Hz) 326 | const float d_E = 0.16; // (s) 327 | const float a_I = 615; // (n/C) 328 | const float b_I = 177; // (Hz) 329 | const float d_I = 0.087; // (s) 330 | const float gamma = 0.641/1000.0; // factor 1000 for expressing everything in ms 331 | const float tau_E = 100; // (ms) Time constant of NMDA (excitatory) 332 | const float tau_I = 10; // (ms) Time constant of GABA (inhibitory) 333 | const float I_0 = 0.382; // (nA) overall effective external input 334 | const float w_E = 1.0; // scaling of external input for excitatory pool 335 | const float w_I = 0.7; // scaling of external input for inhibitory pool 336 | const float gamma_I = 1.0/1000.0; // for expressing inhib. pop. in ms 337 | float eIf_e = 1.0; // weighting factor for external input (exc. pop.) 338 | float eIf_i = 1.0; // weighting factor for external input (inh. pop.) 339 | // Derived parameters for more efficient computation 340 | const float min_d_E = -1.0 * d_E; 341 | const float min_d_I = -1.0 * d_I; 342 | const float imintau_E = -1.0 / tau_E; 343 | const float imintau_I = -1.0 / tau_I; 344 | const float w_E__I_0 = w_E * I_0; 345 | const float w_I__I_0 = w_I * I_0; 346 | const float one = 1.0; 347 | const float w_plus__J_NMDA= w_plus * J_NMDA; 348 | 349 | 350 | /* 351 | Allocate and Initialize arrays 352 | */ 353 | // Brain network model arrays 354 | float *ext_input = (float *)_mm_malloc(time_steps*nodes * sizeof(float),16); 355 | double tmp; 356 | float *S_i_E = (float *)_mm_malloc(nodes * sizeof(float),16); 357 | float *S_i_I = (float *)_mm_malloc(nodes * sizeof(float),16); 358 | float *r_i_E = (float *)_mm_malloc(nodes * sizeof(float),16); 359 | float *r_i_I = (float *)_mm_malloc(nodes * sizeof(float),16); 360 | float *EP_selfExc = (float *)_mm_malloc(nodes * sizeof(float),16); 361 | float *EP_globInp = (float *)_mm_malloc(nodes * sizeof(float),16); 362 | float *EP_inhInp = (float *)_mm_malloc(nodes * sizeof(float),16); 363 | float *EP_extInp = (float *)_mm_malloc(nodes * sizeof(float),16); 364 | float *EP_extInpinh = (float *)_mm_malloc(nodes * sizeof(float),16); 365 | float *global_input = (float *)_mm_malloc(nodes * sizeof(float),16); 366 | float *J_i = (float *)_mm_malloc(nodes * sizeof(float),16); // (nA) inhibitory synaptic coupling 367 | float *meanFR = (float *)_mm_malloc(nodes * sizeof(float),16); // summation array for mean firing rate 368 | //Balloon-Windkessel model arrays (see Deco et al. 2014 JNeuro) 369 | int output_ts = time_steps / (TR / model_dt); // Length of BOLD time-series written to HDD 370 | int num_output_ts = 68; // Number of BOLD time-series that are writte to HDD 371 | float *bw_x_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 1 of BW-model (exc. pop.) 372 | float *bw_f_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 2 of BW-model (exc. pop.) 373 | float *bw_nu_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 3 of BW-model (exc. pop.) 374 | float *bw_q_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 4 of BW-model (exc. pop.) 375 | float *bw_x_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 1 of BW-model (inh. pop.) 376 | float *bw_f_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 2 of BW-model (inh. pop.) 377 | float *bw_nu_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 3 of BW-model (inh. pop.) 378 | float *bw_q_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 4 of BW-model (inh. pop.) 379 | if (S_i_E == NULL || S_i_I == NULL || r_i_E == NULL || r_i_I == NULL || global_input == NULL || J_i == NULL || meanFR == NULL || EP_selfExc == NULL || EP_globInp == NULL || EP_inhInp == NULL || EP_extInp == NULL || EP_extInpinh == NULL || ext_input == NULL|| bw_x_ex == NULL|| bw_f_ex == NULL|| bw_nu_ex == NULL|| bw_q_ex == NULL|| bw_q_in == NULL) { 380 | printf( "ERROR: Running out of memory. Aborting... \n"); 381 | _mm_free(S_i_E);_mm_free(S_i_I);_mm_free(global_input);_mm_free(J_i);_mm_free(meanFR); 382 | return 1; 383 | } 384 | 385 | // Initialize model state variables / parameters 386 | for (j = 0; j < nodes; j++) { 387 | S_i_E[j] = 0.001; 388 | S_i_I[j] = 0.001; 389 | global_input[j] = 0.001; 390 | meanFR[j] = 0.0; 391 | J_i[j] = 1.0; 392 | } 393 | 394 | // Initialize Balloon-Windkessel model parameters and arrays 395 | for (j = 0; j < num_output_ts; j++) { 396 | bw_x_ex[j] = 0.0; 397 | bw_f_ex[j] = 1.0; 398 | bw_nu_ex[j] = 1.0; 399 | bw_q_ex[j] = 1.0; 400 | bw_x_in[j] = 0.0; 401 | bw_f_in[j] = 1.0; 402 | bw_nu_in[j] = 1.0; 403 | bw_q_in[j] = 1.0; 404 | } 405 | float BOLD_ex[num_output_ts][output_ts+2]; 406 | float rho = 0.34, alpha = 0.32, tau = 0.98, y = 1.0/0.41, kappa = 1.0/0.65; 407 | float V_0 = 0.02, k1 = 7 * rho, k2 = 2.0, k3 = 2 * rho - 0.2, ialpha = 1.0/alpha, itau = 1.0/tau, oneminrho = (1.0 - rho); 408 | float f_tmp; 409 | int BOLD_offset = 11; 410 | int BOLD_len_i = -1; 411 | 412 | 413 | /* 414 | Load external input -- to be injected into hybrid model 415 | */ 416 | FILE *ext_input_file = fopen(subject_file,"r"); 417 | if (ext_input_file==NULL) { 418 | printf( "\n ERROR: Could not open external input file. Terminating... \n\n"); 419 | exit(0); 420 | } 421 | for (i = 0 ; i < time_steps*nodes; i++){ 422 | if(fscanf(ext_input_file,"%lf",&tmp) != EOF){ 423 | ext_input[i] = (float)tmp; 424 | } else{ 425 | printf( "\n ERROR: Unexpected end-of-file in external input file. File contains less input than expected. Terminating... \n\n"); 426 | exit(0); 427 | } 428 | } 429 | fclose(ext_input_file); 430 | 431 | 432 | 433 | /* 434 | Input-file mode is on: override some parameter-values as specified in additional param-file 435 | */ 436 | float tmpratio = 0.0; 437 | if (argc > 1) { 438 | FILE *file; 439 | file=fopen(argv[1], "r"); 440 | if (file==NULL) 441 | { 442 | printf( "\n ERROR: Could not open file %s. Terminating... \n\n", argv[1]); 443 | exit(0); 444 | } 445 | int skip; 446 | for (skip=-1; skip 0 && is_improved == 0 && maximum_tuning_factor < 0) { 693 | if (avg_previous_Ji_change != 0 && (previous_mean_meanFR - mean_mean_FR) != 0) { 694 | adaptive_tuning_factor = fabsf(avg_previous_Ji_change / (previous_mean_meanFR - mean_mean_FR)); 695 | } else { 696 | adaptive_tuning_factor = tuning_factor; 697 | } 698 | } else if (FIC_iter == 0 && mean_mean_FR <= 2.7){ 699 | for (j = 0; j < nodes; j++){ 700 | J_i[j] = 0.5; 701 | } 702 | } 703 | 704 | if ((fabsf(mean_mean_FR - avg_FR) >= current_best_FRdistance || mean_mean_FR <= 2.7) && is_fine_tuning == -1){ 705 | if (mean_mean_FR <= 2.7 && current_best_FRmean > avg_FR) { 706 | is_improved = 0; 707 | adaptive_tuning_factor = previous_adaptive_tuning_factor / 2; 708 | previous_adaptive_tuning_factor /= 2; 709 | maximum_tuning_factor = previous_adaptive_tuning_factor; 710 | } else{ 711 | is_improved++; 712 | } 713 | 714 | for (j = 0; j < nodes; j++){ 715 | J_i[j] = Ji_save_bestFRdistance[j]; 716 | meanFR[j] = meanFR_save_bestFRdistance[j]; 717 | previous_meanFR[j] = meanFR_save_bestFRdistance[j]; 718 | } 719 | } else{ 720 | is_improved = 0; 721 | if ((is_fine_tuning == 0 && current_best_FR_SD > sqrtf(variance_FR) && fabsf(mean_mean_FR - avg_FR) < 0.3) || is_fine_tuning == -1) { 722 | current_best_FRmean = mean_mean_FR; 723 | current_best_FRdistance = fabsf(mean_mean_FR - avg_FR); 724 | current_best_FR_SD = sqrtf(variance_FR); 725 | for (j = 0; j < nodes; j++){ 726 | Ji_save_bestFRdistance[j] = J_i[j]; 727 | meanFR_save_bestFRdistance[j] = meanFR[j]; 728 | previous_meanFR[j] = meanFR[j]; 729 | } 730 | previous_mean_meanFR = mean_mean_FR; 731 | } else{ 732 | is_fine_tuning = -1; 733 | for (j = 0; j < nodes; j++){ 734 | J_i[j] = Ji_save_bestFRdistance[j]; 735 | meanFR[j] = meanFR_save_bestFRdistance[j]; 736 | previous_meanFR[j] = meanFR_save_bestFRdistance[j]; 737 | } 738 | is_improved++; 739 | } 740 | 741 | } 742 | 743 | if (adaptive_tuning_factor > 3*previous_adaptive_tuning_factor) { 744 | adaptive_tuning_factor = previous_adaptive_tuning_factor*2; 745 | } else if (adaptive_tuning_factor < previous_adaptive_tuning_factor/3){ 746 | adaptive_tuning_factor = previous_adaptive_tuning_factor/2; 747 | } 748 | 749 | avg_previous_Ji_change = 0.0; 750 | float tmpJichange=0.0; 751 | if (is_improved == 0 && current_best_FRdistance >= 0.3) { 752 | for (j = 0; j < nodes; j++){ 753 | tmpJichange = (meanFR[j] - avg_FR)*adaptive_tuning_factor; 754 | J_i[j] += tmpJichange; 755 | avg_previous_Ji_change += (tmpJichange); 756 | //printf("%.4f %.4f %.4f %.4f %.4f %.4f \n", meanFR[j], J_i[j], SC_rowsums[j], G, J_NMDA, eIf_e); 757 | } 758 | avg_previous_Ji_change /= nodes; 759 | is_fine_tuning = -1; 760 | } else{ 761 | if (current_best_FRdistance < 0.3){ 762 | is_fine_tuning = 0; 763 | for (j = 0; j < nodes; j++){ 764 | if (fabsf(meanFR_save_bestFRdistance[j] - avg_FR) > current_best_FR_SD*0.6) J_i[j] += (meanFR_save_bestFRdistance[j] - avg_FR)*adaptive_tuning_factor; 765 | } 766 | } else{ 767 | is_fine_tuning = -1; 768 | if (current_best_FRmean < avg_FR) { 769 | for (j = 0; j < nodes; j++){ 770 | if (meanFR_save_bestFRdistance[j] < (current_best_FRmean - current_best_FR_SD*0.6)) J_i[j] += (meanFR_save_bestFRdistance[j] - current_best_FRmean)*adaptive_tuning_factor; 771 | } 772 | } else{ 773 | for (j = 0; j < nodes; j++){ 774 | if (meanFR_save_bestFRdistance[j] > (current_best_FRmean + current_best_FR_SD*0.6)) J_i[j] += (meanFR_save_bestFRdistance[j] - current_best_FRmean)*adaptive_tuning_factor; 775 | } 776 | } 777 | } 778 | } 779 | } // end: FIC optimization 780 | 781 | // Set J_i to the best values that were found during optimization 782 | for (j = 0; j < nodes; j++){ 783 | J_i[j] = Ji_save_bestFRdistance[j]; 784 | } 785 | 786 | 787 | 788 | 789 | /************************************************ 790 | The actual simulation with fitted J_i parameters 791 | *************************************************/ 792 | int ts_bold=0; 793 | ext_inp_counter=0; 794 | for (ts = 0; ts < time_steps; ts++) { 795 | 796 | // Reset arrays for writing out state variables 797 | for (i_node_vec = 0; i_node_vec < nodes_vec; i_node_vec++) { 798 | _EP_selfExc[i_node_vec] =_zero; 799 | _EP_globInp[i_node_vec] =_zero; 800 | _EP_inhInp[i_node_vec] =_zero; 801 | _EP_extInp[i_node_vec] =_zero; 802 | _EP_extInpinh[i_node_vec] =_zero; 803 | } 804 | 805 | for (int_i = 0; int_i < 10; int_i++) { 806 | /* 807 | Compute long-range coupling 808 | */ 809 | for(j=0; j 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | struct Xi_p{ 20 | float **Xi_elems; 21 | }; 22 | 23 | struct SC_capS{ 24 | float *cap; 25 | }; 26 | 27 | FILE *FCout, *WFout, *Sout; 28 | 29 | /* 30 | Open files for writing simulated activity 31 | */ 32 | void openFCoutfile(char *paramset, int myid, char *sub_id){ 33 | char outfilename[1000];memset(outfilename, 0, 1000*sizeof(char)); 34 | char buffer[10];memset(buffer, 0, 10*sizeof(char)); 35 | char underscore[2]; 36 | underscore[0]='_'; 37 | underscore[1]='\0'; 38 | strcpy (outfilename,"output/"); 39 | strcat (outfilename,"/BOLD_"); 40 | strcat (outfilename,sub_id);strcat (outfilename,underscore); 41 | strcat (outfilename,paramset);strcat (outfilename,underscore); 42 | snprintf(buffer, 10, "%d", myid);strcat (outfilename,buffer); 43 | strcat (outfilename,".txt"); 44 | FCout = fopen(outfilename, "w"); 45 | /* 46 | memset(outfilename, 0, 1000*sizeof(char)); 47 | strcpy (outfilename,"output/"); 48 | strcat (outfilename,"/INP_"); 49 | strcat (outfilename,sub_id);strcat (outfilename,underscore); 50 | strcat (outfilename,paramset);strcat (outfilename,underscore); 51 | snprintf(buffer, 10, "%d", myid);strcat (outfilename,buffer); 52 | strcat (outfilename,".txt"); 53 | WFout = fopen(outfilename, "w"); 54 | memset(outfilename, 0, 1000*sizeof(char)); 55 | strcpy (outfilename,"output/"); 56 | strcat (outfilename,"/S_"); 57 | strcat (outfilename,sub_id);strcat (outfilename,underscore); 58 | strcat (outfilename,paramset);strcat (outfilename,underscore); 59 | snprintf(buffer, 10, "%d", myid);strcat (outfilename,buffer); 60 | strcat (outfilename,".txt"); 61 | Sout = fopen(outfilename, "w"); 62 | */ 63 | } 64 | 65 | 66 | /* 67 | Import SC (long-range coupling) and convert into efficient data structure 68 | */ 69 | int importGlobalConnectivity(char *SC_cap_filename, char *SC_dist_filename, char *SC_inputreg_filename, int regions, float **region_activity, struct Xi_p **reg_globinp_p, float global_trans_v, int **n_conn_table, float **n_conn_table_G_NMDA, float G_J_NMDA, struct SC_capS **SC_cap, float **SC_rowsums) 70 | { 71 | 72 | int i,j,k, tmp3, maxdelay=0, tmpint; 73 | float *region_activity_p; 74 | double tmp, tmp2; 75 | struct Xi_p *reg_globinp_pp; 76 | struct SC_capS *SC_capp; 77 | int num_incoming_conn_cap=0, num_incoming_conn_dist=0, num_incoming_conn_inputreg=0; 78 | 79 | // Open SC files 80 | FILE *file_cap, *file_dist, *file_inputreg; 81 | file_cap=fopen(SC_cap_filename, "r"); 82 | file_dist=fopen(SC_dist_filename, "r"); 83 | file_inputreg=fopen(SC_inputreg_filename, "r"); 84 | if (file_cap==NULL || file_dist==NULL || file_inputreg==NULL) 85 | { 86 | printf( "\n ERROR: Could not open SC files. Terminating... \n\n"); 87 | exit(0); 88 | } 89 | 90 | // Read number of regions in header and check whether it's consistent with other specifications 91 | int readSC_cap, readSC_dist, readSC_inp; 92 | if(fscanf(file_cap,"%d",&readSC_cap) == EOF || fscanf(file_dist,"%d",&readSC_dist) == EOF || fscanf(file_inputreg,"%d",&readSC_inp) == EOF){ 93 | printf( "\n ERROR: Unexpected end-of-file in file. File contains less input than expected. Terminating... \n\n"); 94 | exit(0); 95 | } 96 | if (readSC_cap != regions || readSC_dist != regions || readSC_inp != regions) { 97 | printf( "\n ERROR: Inconsistent number of large-scale regions in SC files. Terminating... \n\n"); 98 | fclose(file_dist);fclose(file_inputreg); 99 | exit(0); 100 | } 101 | 102 | // Allocate a counter (to store number of region inputs for each region) and the SCcap array (to store connection weights) 103 | *SC_rowsums = (float *)_mm_malloc(regions*sizeof(float),16); 104 | *n_conn_table = (int *)_mm_malloc(regions*sizeof(int),16); 105 | *n_conn_table_G_NMDA = (float *)_mm_malloc(regions*sizeof(float),16); 106 | *SC_cap = (struct SC_capS *)_mm_malloc(regions*sizeof(struct SC_capS),16); 107 | SC_capp = *SC_cap; 108 | if(*n_conn_table==NULL || *n_conn_table_G_NMDA==NULL || SC_capp==NULL || SC_rowsums==NULL){ 109 | printf("Running out of memory. Terminating.\n");fclose(file_dist);fclose(file_cap);fclose(file_inputreg);exit(2); 110 | } 111 | 112 | // Read the maximal fiber length in header of SCdist-file and compute maxdelay 113 | if(fscanf(file_dist,"%lf",&tmp) == EOF){ 114 | printf( "ERROR: Unexpected end-of-file in file. File contains less input than expected. Terminating... \n"); 115 | exit(0); 116 | } 117 | maxdelay = (int)((tmp/global_trans_v)+0.5); // +0.5 for rounding by casting 118 | if (maxdelay < 1) maxdelay = 1; // Case: no time delays 119 | 120 | // Allocate ringbuffer that contains region activity for each past time-step until maxdelay and another ringbuffer that contains pointers to the first ringbuffer 121 | *region_activity = (float *)_mm_malloc(maxdelay*regions*sizeof(float),16); 122 | region_activity_p = *region_activity; 123 | *reg_globinp_p = (struct Xi_p *)_mm_malloc(maxdelay*regions*sizeof(struct Xi_p),16); 124 | reg_globinp_pp = *reg_globinp_p; 125 | if(region_activity_p==NULL || reg_globinp_p==NULL){ 126 | printf("Running out of memory. Terminating.\n");fclose(file_dist);exit(2); 127 | } 128 | for (j=0; j 0) { 157 | (*n_conn_table_G_NMDA)[i] = G_J_NMDA / num_incoming_conn_inputreg; 158 | //(*n_conn_table_G_NMDA)[i] = G_J_NMDA; 159 | } else{ 160 | (*n_conn_table_G_NMDA)[i] = 0; 161 | } 162 | 163 | 164 | if ((*n_conn_table)[i] > 0) { 165 | // SC strength 166 | SC_capp[i].cap = (float *)_mm_malloc(((*n_conn_table)[i])*sizeof(float),16); 167 | if(SC_capp[i].cap==NULL){ 168 | printf("Running out of memory. Terminating.\n");exit(2); 169 | } 170 | 171 | // Allocate memory for input-region-pointer arrays for each time-step in ringbuffer 172 | for (j=0; j %d. Terminating... \n\n",i,tmp3);exit(0); 188 | } 189 | 190 | //SC_capp[i].cap[j] = (float)tmp * (*n_conn_table_G_NMDA)[i]; 191 | SC_capp[i].cap[j] = (float)tmp * G_J_NMDA; 192 | sum_caps += (float)tmp; 193 | 194 | if (tmp3 >= 0) { 195 | ring_buff_position=maxdelay*regions - tmpint*regions + tmp3; 196 | for (k=0; k (maxdelay*regions-1)) ring_buff_position -= maxdelay*regions; 200 | } 201 | } else { 202 | printf( "\nERROR: Region index is negative: %d -> %d. Terminating... \n\n",i,tmp3);exit(0); 203 | } 204 | 205 | 206 | } else{ 207 | printf( "\n ERROR: Unexpected end-of-file in file %s or %s. File contains less input than expected. Terminating... \n\n", SC_inputreg_filename, SC_dist_filename); 208 | exit(0); 209 | } 210 | 211 | } 212 | if (sum_caps <= 0) { 213 | printf( "\nERROR: Sum of connection strenghts is negative or zero. sum-caps node %d = %f. Terminating... \n\n",i,sum_caps);exit(0); 214 | } 215 | (*SC_rowsums)[i] = sum_caps; 216 | } 217 | } 218 | 219 | fclose(file_dist);fclose(file_inputreg); 220 | return maxdelay; 221 | } 222 | 223 | 224 | 225 | 226 | int main(int argc, char *argv[]) 227 | { 228 | 229 | 230 | /************* 231 | Set up model 232 | *************/ 233 | 234 | int myid=0, i, j, k; 235 | 236 | //Get starting time 237 | time_t start = time(NULL); 238 | 239 | // Check input arguments 240 | if (argc != 4 || atoi(argv[3]) > 8 || atoi(argv[3]) < 0) { 241 | printf( "\n ERROR: Too few/many or wrong arguments. Terminating... \n\n"); 242 | exit(0); 243 | } 244 | 245 | // Open output files and switch between different types of input activity 246 | char outputfolder[100];memset(outputfolder, 0, 100*sizeof(char)); 247 | char subject_file[100];memset(subject_file, 0, 100*sizeof(char)); 248 | strcpy(subject_file,"input/");strcat(subject_file,argv[2]); 249 | switch (atoi(argv[3])) { 250 | case 0: 251 | strcat(subject_file,"_fullextinp1000.txt"); 252 | strcpy(outputfolder,"full"); 253 | break; 254 | case 1: 255 | strcat(subject_file,"_fullextinprandperm1000.txt"); 256 | strcpy(outputfolder,"fullrand"); 257 | break; 258 | case 2: 259 | strcat(subject_file,"_fullextinp_diff1000.txt"); 260 | strcpy(outputfolder,"diff"); 261 | break; 262 | case 3: 263 | strcat(subject_file,"_fullextinprandperm_diff1000.txt"); 264 | strcpy(outputfolder,"diffrand"); 265 | break; 266 | case 4: 267 | strcat(subject_file,"_fullextinp1000.txt"); 268 | strcpy(outputfolder,"testfull"); 269 | break; 270 | case 5: 271 | strcat(subject_file,"_fullextinp_diff1000.txt"); 272 | strcpy(outputfolder,"testdiff"); 273 | break; 274 | case 6: 275 | memset(subject_file, 0, 100*sizeof(char)); 276 | strcpy(subject_file,"input/"); 277 | strcat(subject_file,"artifical_powermod_input.txt"); 278 | strcpy(outputfolder,"testdiff"); 279 | break; 280 | case 7: 281 | memset(subject_file, 0, 100*sizeof(char)); 282 | strcpy(subject_file,"input/"); 283 | strcat(subject_file,"artifical_powermod_input_9Hz.txt"); 284 | strcpy(outputfolder,"testdiff"); 285 | break; 286 | case 8: 287 | memset(subject_file, 0, 100*sizeof(char)); 288 | strcpy(subject_file,"input/"); 289 | strcat(subject_file,"artifical_powermod_input_11Hz.txt"); 290 | strcpy(outputfolder,"testdiff"); 291 | break; 292 | } 293 | openFCoutfile(argv[1], myid, argv[2]); 294 | 295 | 296 | 297 | /* 298 | Global model and integration parameters 299 | */ 300 | float TR = 1.94; // (s) TR of fMRI data 301 | int TR_ts = TR * 1000; // n-th time step for writing out a fMRI data point 302 | const float dt = 0.1; // Integration step length dt = 0.1 ms 303 | const float model_dt = 0.001; // (Hz) Time-step of model (sampling-rate=1000 Hz) 304 | const int vectorization_grade = 4; // depends on CPU Architecture and available intrinsics. 305 | int time_steps = 667*TR*1000; // simulation length: 667 TRs * 1.94 s/TR * 1000 time-steps/s 306 | int time_steps_FIC_burnin = 10*1000; // 10 s as a burn-in for FIC tuning to let model activity stabilized 307 | int time_steps_FIC_fit = time_steps - time_steps_FIC_burnin; 308 | const int nodes = 68; // Number of nodes; must be a multiple of vectorization grade 309 | const int nodes_vec = nodes/vectorization_grade; 310 | const int regions = 68; // Number of large-scale regions (identical to nodes for non-surface simulations) 311 | float global_trans_v = 1.0; // Global transmission velocity (m/s) 312 | float G = 0.5; // Global coupling strength 313 | int FIC_iters = 12; // Number of FIC tuning iterations 314 | const float avg_FR = 3.0631; // (Hz) avg firing rate of an exc. population 315 | const float tuning_factor = 0.005; // parameter for FIC tuning 316 | float adaptive_tuning_factor = tuning_factor; // parameter for FIC tuning 317 | const float meanFRfact = 1.0 / (time_steps_FIC_fit*10); // Factor for averaging firing rates over FIC simulation period 318 | float mean_mean_FR = 0.0; // variable for FIC tuning 319 | float variance_FR = 0.0; // variable for FIC tuning 320 | float tmpglobinput, tmpBOLD; 321 | int ring_buf_pos=0; // Position in ring buffer of past state variables for long-range input 322 | float tmp_exp_E[4] __attribute__((aligned(16))); 323 | float tmp_exp_I[4] __attribute__((aligned(16))); 324 | float tmp_E[4] __attribute__((aligned(16))); 325 | float tmp_I[4] __attribute__((aligned(16))); 326 | 327 | 328 | /* 329 | Local model: DMF-Parameters from Deco et al. JNeuro 2014 330 | */ 331 | float w_plus = 1.4; // local excitatory recurrence 332 | //float I_ext = 0; // Additional external stimulation -- not used in hybrid models 333 | //float J_NMDA = 0.15; // (nA) excitatory synaptic coupling 334 | float J_NMDA = 0.0; // J_NMDA is replaced by injected input in hybrid models 335 | //float J_i = 1.0; // Single value for no-FIC models 336 | const float a_E = 310; // (n/C) 337 | const float b_E = 125; // (Hz) 338 | const float d_E = 0.16; // (s) 339 | const float a_I = 615; // (n/C) 340 | const float b_I = 177; // (Hz) 341 | const float d_I = 0.087; // (s) 342 | const float gamma = 0.641/1000.0; // factor 1000 for expressing everything in ms 343 | const float tau_E = 100; // (ms) Time constant of NMDA (excitatory) 344 | const float tau_I = 10; // (ms) Time constant of GABA (inhibitory) 345 | const float I_0 = 0.382; // (nA) overall effective external input 346 | const float w_E = 1.0; // scaling of external input for excitatory pool 347 | const float w_I = 0.7; // scaling of external input for inhibitory pool 348 | const float gamma_I = 1.0/1000.0; // for expressing inhib. pop. in ms 349 | float eIf_e = 1.0; // weighting factor for external input (exc. pop.) 350 | float eIf_i = 1.0; // weighting factor for external input (inh. pop.) 351 | // Derived parameters for more efficient computation 352 | const float min_d_E = -1.0 * d_E; 353 | const float min_d_I = -1.0 * d_I; 354 | const float imintau_E = -1.0 / tau_E; 355 | const float imintau_I = -1.0 / tau_I; 356 | const float w_E__I_0 = w_E * I_0; 357 | const float w_I__I_0 = w_I * I_0; 358 | const float one = 1.0; 359 | const float w_plus__J_NMDA= w_plus * J_NMDA; 360 | 361 | 362 | /* 363 | Allocate and Initialize arrays 364 | */ 365 | // Brain network model arrays 366 | float *ext_input = (float *)_mm_malloc(time_steps*nodes * sizeof(float),16); 367 | double tmp; 368 | float *S_i_E = (float *)_mm_malloc(nodes * sizeof(float),16); 369 | float *S_i_I = (float *)_mm_malloc(nodes * sizeof(float),16); 370 | float *r_i_E = (float *)_mm_malloc(nodes * sizeof(float),16); 371 | float *r_i_I = (float *)_mm_malloc(nodes * sizeof(float),16); 372 | float *EP_selfExc = (float *)_mm_malloc(nodes * sizeof(float),16); 373 | float *EP_globInp = (float *)_mm_malloc(nodes * sizeof(float),16); 374 | float *EP_inhInp = (float *)_mm_malloc(nodes * sizeof(float),16); 375 | float *EP_extInp = (float *)_mm_malloc(nodes * sizeof(float),16); 376 | float *EP_extInpinh = (float *)_mm_malloc(nodes * sizeof(float),16); 377 | float *global_input = (float *)_mm_malloc(nodes * sizeof(float),16); 378 | float *J_i = (float *)_mm_malloc(nodes * sizeof(float),16); // (nA) inhibitory synaptic coupling 379 | float *meanFR = (float *)_mm_malloc(nodes * sizeof(float),16); // summation array for mean firing rate 380 | //Balloon-Windkessel model arrays (see Deco et al. 2014 JNeuro) 381 | int output_ts = time_steps / (TR / model_dt); // Length of BOLD time-series written to HDD 382 | int num_output_ts = 68; // Number of BOLD time-series that are writte to HDD 383 | float *bw_x_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 1 of BW-model (exc. pop.) 384 | float *bw_f_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 2 of BW-model (exc. pop.) 385 | float *bw_nu_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 3 of BW-model (exc. pop.) 386 | float *bw_q_ex = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 4 of BW-model (exc. pop.) 387 | float *bw_x_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 1 of BW-model (inh. pop.) 388 | float *bw_f_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 2 of BW-model (inh. pop.) 389 | float *bw_nu_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 3 of BW-model (inh. pop.) 390 | float *bw_q_in = (float *)_mm_malloc(num_output_ts * sizeof(float),16); // State-variable 4 of BW-model (inh. pop.) 391 | if (S_i_E == NULL || S_i_I == NULL || r_i_E == NULL || r_i_I == NULL || global_input == NULL || J_i == NULL || meanFR == NULL || EP_selfExc == NULL || EP_globInp == NULL || EP_inhInp == NULL || EP_extInp == NULL || EP_extInpinh == NULL || ext_input == NULL|| bw_x_ex == NULL|| bw_f_ex == NULL|| bw_nu_ex == NULL|| bw_q_ex == NULL|| bw_q_in == NULL) { 392 | printf( "ERROR: Running out of memory. Aborting... \n"); 393 | _mm_free(S_i_E);_mm_free(S_i_I);_mm_free(global_input);_mm_free(J_i);_mm_free(meanFR); 394 | return 1; 395 | } 396 | 397 | // Initialize model state variables / parameters 398 | for (j = 0; j < nodes; j++) { 399 | S_i_E[j] = 0.001; 400 | S_i_I[j] = 0.001; 401 | global_input[j] = 0.001; 402 | meanFR[j] = 0.0; 403 | J_i[j] = 1.0; 404 | } 405 | 406 | // Initialize Balloon-Windkessel model parameters and arrays 407 | for (j = 0; j < num_output_ts; j++) { 408 | bw_x_ex[j] = 0.0; 409 | bw_f_ex[j] = 1.0; 410 | bw_nu_ex[j] = 1.0; 411 | bw_q_ex[j] = 1.0; 412 | bw_x_in[j] = 0.0; 413 | bw_f_in[j] = 1.0; 414 | bw_nu_in[j] = 1.0; 415 | bw_q_in[j] = 1.0; 416 | } 417 | float BOLD_ex[num_output_ts][output_ts+2]; 418 | float rho = 0.34, alpha = 0.32, tau = 0.98, y = 1.0/0.41, kappa = 1.0/0.65; 419 | float V_0 = 0.02, k1 = 7 * rho, k2 = 2.0, k3 = 2 * rho - 0.2, ialpha = 1.0/alpha, itau = 1.0/tau, oneminrho = (1.0 - rho); 420 | float f_tmp; 421 | int BOLD_offset = 11; 422 | int BOLD_len_i = -1; 423 | 424 | 425 | /* 426 | Load external input -- to be injected into hybrid model 427 | */ 428 | FILE *ext_input_file = fopen(subject_file,"r"); 429 | if (ext_input_file==NULL) { 430 | printf( "\n ERROR: Could not open external input file. Terminating... \n\n"); 431 | exit(0); 432 | } 433 | for (i = 0 ; i < time_steps*nodes; i++){ 434 | if(fscanf(ext_input_file,"%lf",&tmp) != EOF){ 435 | ext_input[i] = (float)tmp; 436 | } else{ 437 | printf( "\n ERROR: Unexpected end-of-file in external input file. File contains less input than expected. Terminating... \n\n"); 438 | exit(0); 439 | } 440 | } 441 | fclose(ext_input_file); 442 | 443 | 444 | 445 | /* 446 | Input-file mode is on: override some parameter-values as specified in additional param-file 447 | */ 448 | float tmpratio = 0.0; 449 | if (argc > 1) { 450 | FILE *file; 451 | file=fopen(argv[1], "r"); 452 | if (file==NULL) 453 | { 454 | printf( "\n ERROR: Could not open file %s. Terminating... \n\n", argv[1]); 455 | exit(0); 456 | } 457 | int skip; 458 | for (skip=-1; skip 0 ? S_i_E[j] : 0; 644 | S_i_I[j] = S_i_I[j] < 1 ? S_i_I[j] : 1; 645 | S_i_I[j] = S_i_I[j] > 0 ? S_i_I[j] : 0; 646 | } 647 | 648 | 649 | ext_inp_counter -= nodes_vec; 650 | memcpy(®ion_activity[ring_buf_pos], S_i_E, regions*sizeof( float )); 651 | // Shift ring-buff-pos 652 | ring_buf_pos = ring_buf_pos<(reg_act_size-regions) ? (ring_buf_pos+regions) : 0; 653 | 654 | /* 655 | if (FIC_iter == 4) { 656 | for (j = 0; j < nodes; j++){ 657 | fprintf(WFout, "%.3f ",r_i_E[j]); 658 | } 659 | for (j = 0; j < nodes; j++){ 660 | fprintf(WFout, "%.3f ",r_i_I[j]); 661 | } 662 | fprintf(WFout, "\n"); 663 | } 664 | */ 665 | } 666 | ext_inp_counter += nodes_vec; 667 | } 668 | /* 669 | if (FIC_iter == 4) { 670 | exit(0); 671 | } 672 | */ 673 | /* 674 | Phase II: Simulate full time series and compute mean firing rate for each node 675 | */ 676 | for (; ts < time_steps; ts++) { 677 | for (int_i = 0; int_i < 10; int_i++) { 678 | 679 | /* 680 | Compute long-range coupling 681 | */ 682 | for(j=0; j 0 ? S_i_E[j] : 0; 731 | S_i_I[j] = S_i_I[j] < 1 ? S_i_I[j] : 1; 732 | S_i_I[j] = S_i_I[j] > 0 ? S_i_I[j] : 0; 733 | } 734 | 735 | ext_inp_counter -= nodes_vec; 736 | memcpy(®ion_activity[ring_buf_pos], S_i_E, regions*sizeof( float )); 737 | // Shift ring-buff-pos 738 | ring_buf_pos = ring_buf_pos<(reg_act_size-regions) ? (ring_buf_pos+regions) : 0; 739 | 740 | 741 | } 742 | ext_inp_counter += nodes_vec; 743 | } 744 | 745 | 746 | /* 747 | Phase III: Evaluate mean FR and adapt J_i 748 | */ 749 | float tmpFR=0.0; 750 | mean_mean_FR = 0.0; 751 | avg_previous_FR_change = 0.0; 752 | for (j = 0; j < nodes; j++){ 753 | tmpFR = meanFR[j]*meanFRfact; 754 | meanFR[j] = tmpFR; 755 | mean_mean_FR += meanFR[j]; 756 | avg_previous_FR_change += fabsf(tmpFR - previous_meanFR[j]); 757 | previous_meanFR[j] = tmpFR; 758 | } 759 | avg_previous_FR_change /= nodes; 760 | mean_mean_FR /= nodes; 761 | 762 | printf("%d %f\n",FIC_iter, mean_mean_FR); 763 | 764 | variance_FR = 0.0; 765 | for (j = 0; j < nodes; j++){ 766 | variance_FR += (meanFR[j] - mean_mean_FR)*(meanFR[j] - mean_mean_FR); 767 | } 768 | variance_FR /= (nodes - 1); 769 | 770 | if (fabsf(mean_mean_FR - avg_FR) < current_best_FRdistance && maximum_tuning_factor < 0){ 771 | previous_adaptive_tuning_factor = adaptive_tuning_factor; 772 | } 773 | if (FIC_iter > 0 && is_improved == 0 && maximum_tuning_factor < 0) { 774 | if (avg_previous_Ji_change != 0 && (previous_mean_meanFR - mean_mean_FR) != 0) { 775 | adaptive_tuning_factor = fabsf(avg_previous_Ji_change / (previous_mean_meanFR - mean_mean_FR)); 776 | } else { 777 | adaptive_tuning_factor = tuning_factor; 778 | } 779 | } else if (FIC_iter == 0 && mean_mean_FR <= 2.7){ 780 | for (j = 0; j < nodes; j++){ 781 | J_i[j] = 0.5; 782 | } 783 | } 784 | 785 | if ((fabsf(mean_mean_FR - avg_FR) >= current_best_FRdistance || mean_mean_FR <= 2.7) && is_fine_tuning == -1){ 786 | if (mean_mean_FR <= 2.7 && current_best_FRmean > avg_FR) { 787 | is_improved = 0; 788 | adaptive_tuning_factor = previous_adaptive_tuning_factor / 2; 789 | previous_adaptive_tuning_factor /= 2; 790 | maximum_tuning_factor = previous_adaptive_tuning_factor; 791 | } else{ 792 | is_improved++; 793 | } 794 | 795 | for (j = 0; j < nodes; j++){ 796 | J_i[j] = Ji_save_bestFRdistance[j]; 797 | meanFR[j] = meanFR_save_bestFRdistance[j]; 798 | previous_meanFR[j] = meanFR_save_bestFRdistance[j]; 799 | } 800 | } else{ 801 | is_improved = 0; 802 | if ((is_fine_tuning == 0 && current_best_FR_SD > sqrtf(variance_FR) && fabsf(mean_mean_FR - avg_FR) < 0.3) || is_fine_tuning == -1) { 803 | current_best_FRmean = mean_mean_FR; 804 | current_best_FRdistance = fabsf(mean_mean_FR - avg_FR); 805 | current_best_FR_SD = sqrtf(variance_FR); 806 | for (j = 0; j < nodes; j++){ 807 | Ji_save_bestFRdistance[j] = J_i[j]; 808 | meanFR_save_bestFRdistance[j] = meanFR[j]; 809 | previous_meanFR[j] = meanFR[j]; 810 | } 811 | previous_mean_meanFR = mean_mean_FR; 812 | } else{ 813 | is_fine_tuning = -1; 814 | for (j = 0; j < nodes; j++){ 815 | J_i[j] = Ji_save_bestFRdistance[j]; 816 | meanFR[j] = meanFR_save_bestFRdistance[j]; 817 | previous_meanFR[j] = meanFR_save_bestFRdistance[j]; 818 | } 819 | is_improved++; 820 | } 821 | 822 | } 823 | 824 | if (adaptive_tuning_factor > 3*previous_adaptive_tuning_factor) { 825 | adaptive_tuning_factor = previous_adaptive_tuning_factor*2; 826 | } else if (adaptive_tuning_factor < previous_adaptive_tuning_factor/3){ 827 | adaptive_tuning_factor = previous_adaptive_tuning_factor/2; 828 | } 829 | 830 | avg_previous_Ji_change = 0.0; 831 | float tmpJichange=0.0; 832 | if (is_improved == 0 && current_best_FRdistance >= 0.3) { 833 | for (j = 0; j < nodes; j++){ 834 | tmpJichange = (meanFR[j] - avg_FR)*adaptive_tuning_factor; 835 | // if (J_i[j] + tmpJichange > 3) { 836 | // tmpJichange = 3 - J_i[j]; 837 | // } 838 | J_i[j] += tmpJichange; 839 | avg_previous_Ji_change += (tmpJichange); 840 | //printf("%.4f %.4f %.4f %.4f %.4f %.4f \n", meanFR[j], J_i[j], SC_rowsums[j], G, J_NMDA, eIf_e); 841 | } 842 | avg_previous_Ji_change /= nodes; 843 | is_fine_tuning = -1; 844 | } else{ 845 | if (current_best_FRdistance < 0.3){ 846 | is_fine_tuning = 0; 847 | for (j = 0; j < nodes; j++){ 848 | if (fabsf(meanFR_save_bestFRdistance[j] - avg_FR) > current_best_FR_SD*0.6) J_i[j] += (meanFR_save_bestFRdistance[j] - avg_FR)*adaptive_tuning_factor; 849 | } 850 | } else{ 851 | is_fine_tuning = -1; 852 | if (current_best_FRmean < avg_FR) { 853 | for (j = 0; j < nodes; j++){ 854 | if (meanFR_save_bestFRdistance[j] < (current_best_FRmean - current_best_FR_SD*0.6)) J_i[j] += (meanFR_save_bestFRdistance[j] - current_best_FRmean)*adaptive_tuning_factor; 855 | } 856 | } else{ 857 | for (j = 0; j < nodes; j++){ 858 | if (meanFR_save_bestFRdistance[j] > (current_best_FRmean + current_best_FR_SD*0.6)) J_i[j] += (meanFR_save_bestFRdistance[j] - current_best_FRmean)*adaptive_tuning_factor; 859 | } 860 | } 861 | } 862 | } 863 | } // end: FIC optimization 864 | 865 | // Set J_i to the best values that were found during optimization 866 | for (j = 0; j < nodes; j++){ 867 | J_i[j] = Ji_save_bestFRdistance[j]; 868 | } 869 | 870 | 871 | 872 | 873 | /************************************************ 874 | The actual simulation with fitted J_i parameters 875 | *************************************************/ 876 | int ts_bold=0; 877 | ext_inp_counter=0; 878 | for (ts = 0; ts < time_steps; ts++) { 879 | 880 | // Reset arrays for writing out state variables 881 | for (i_node_vec = 0; i_node_vec < nodes_vec; i_node_vec++) { 882 | _EP_selfExc[i_node_vec] =_zero; 883 | _EP_globInp[i_node_vec] =_zero; 884 | _EP_inhInp[i_node_vec] =_zero; 885 | _EP_extInp[i_node_vec] =_zero; 886 | _EP_extInpinh[i_node_vec] =_zero; 887 | } 888 | 889 | for (int_i = 0; int_i < 10; int_i++) { 890 | /* 891 | Compute long-range coupling 892 | */ 893 | for(j=0; j 0 ? S_i_E[j] : 0; 952 | S_i_I[j] = S_i_I[j] < 1 ? S_i_I[j] : 1; 953 | S_i_I[j] = S_i_I[j] > 0 ? S_i_I[j] : 0; 954 | } 955 | 956 | ext_inp_counter -= nodes_vec; 957 | memcpy(®ion_activity[ring_buf_pos], S_i_E, regions*sizeof( float )); 958 | // Shift ring-buff-pos 959 | ring_buf_pos = ring_buf_pos<(reg_act_size-regions) ? (ring_buf_pos+regions) : 0; 960 | } 961 | ext_inp_counter += nodes_vec; 962 | 963 | /* 964 | Compute BOLD for that time-step (subsampled to 1 ms) 965 | */ 966 | for (j = 0; j < num_output_ts; j++) { 967 | // Excitatory populations 968 | bw_x_ex[j] = bw_x_ex[j] + model_dt * (S_i_E[j] - kappa * bw_x_ex[j] - y * (bw_f_ex[j] - 1.0)); 969 | f_tmp = bw_f_ex[j] + model_dt * bw_x_ex[j]; 970 | bw_nu_ex[j] = bw_nu_ex[j] + model_dt * itau * (bw_f_ex[j] - powf(bw_nu_ex[j], ialpha)); 971 | bw_q_ex[j] = bw_q_ex[j] + model_dt * itau * (bw_f_ex[j] * (1.0 - powf(oneminrho,(1.0/bw_f_ex[j]))) / rho - powf(bw_nu_ex[j],ialpha) * bw_q_ex[j] / bw_nu_ex[j]); 972 | bw_f_ex[j] = f_tmp; 973 | 974 | /* 975 | // Inhibitory populations 976 | bw_x_in[j] = bw_x_in[j] + model_dt * (S_i_I[j] - kappa * bw_x_in[j] - y * (bw_f_in[j] - 1.0)); 977 | f_tmp = bw_f_in[j] + model_dt * bw_x_in[j]; 978 | bw_nu_in[j] = bw_nu_in[j] + model_dt * itau * (bw_f_in[j] - powf(bw_nu_in[j], ialpha)); 979 | bw_q_in[j] = bw_q_in[j] + model_dt * itau * (bw_f_in[j] * (1.0 - powf(oneminrho,(1.0/bw_f_in[j]))) / rho - powf(bw_nu_in[j],ialpha) * bw_q_in[j] / bw_nu_in[j]); 980 | bw_f_in[j] = f_tmp; 981 | */ 982 | } 983 | 984 | 985 | // Write out state variables as columns and time-steps as rows 986 | /* 987 | for (j = 0; j < num_output_ts; j++) { 988 | fprintf(Sout, "%.5f ",S_i_E[j]); 989 | } 990 | fprintf(Sout, "\n"); // End of output line 991 | */ 992 | /* 993 | for (j = 0; j < num_output_ts; j++) { 994 | fprintf(WFout, "%.4f ",S_i_I[j]); 995 | } 996 | 997 | for (j = 0; j < num_output_ts; j++) { 998 | fprintf(WFout, "%.2f ",r_i_E[j]); 999 | } 1000 | 1001 | for (j = 0; j < num_output_ts; j++) { 1002 | fprintf(WFout, "%.2f ",r_i_I[j]); 1003 | } 1004 | */ 1005 | // divide by 10 to get sampling rate of 10 Hz 1006 | for (i_node_vec = 0; i_node_vec < nodes_vec; i_node_vec++) { 1007 | _EP_selfExc[i_node_vec]=_mm_mul_ps(_EP_selfExc[i_node_vec], _pone); 1008 | _EP_globInp[i_node_vec]=_mm_mul_ps(_EP_globInp[i_node_vec], _pone); 1009 | _EP_inhInp[i_node_vec] =_mm_mul_ps(_EP_inhInp[i_node_vec], _pone); 1010 | _EP_extInp[i_node_vec] =_mm_mul_ps(_EP_extInp[i_node_vec], _pone); 1011 | _EP_extInpinh[i_node_vec] =_mm_mul_ps(_EP_extInpinh[i_node_vec], _pone); 1012 | } 1013 | /* 1014 | for (j = 0; j < num_output_ts; j++) { 1015 | fprintf(WFout, "%.3f ",EP_selfExc[j]); 1016 | } 1017 | for (j = 0; j < num_output_ts; j++) { 1018 | fprintf(WFout, "%.3f ",EP_globInp[j]); 1019 | } 1020 | for (j = 0; j < num_output_ts; j++) { 1021 | fprintf(WFout, "%.3f ",EP_inhInp[j]); 1022 | } 1023 | for (j = 0; j < num_output_ts; j++) { 1024 | fprintf(WFout, "%.3f ",EP_extInp[j]); 1025 | } 1026 | for (j = 0; j < num_output_ts; j++) { 1027 | fprintf(WFout, "%.3f ",EP_extInpinh[j]); 1028 | } 1029 | */ 1030 | /* 1031 | for (j = 0; j < num_output_ts; j++) { 1032 | fprintf(WFout, "%.5f ",(EP_selfExc[j]+EP_globInp[j]+EP_extInp[j])); 1033 | } 1034 | fprintf(WFout, "\n"); // End of output line 1035 | */ 1036 | // Excitatory populations' BOLD 1037 | // for (j = 0; j < num_output_ts; j++) { 1038 | // tmpBOLD = 100 / rho * V_0 * (k1 * (1 - bw_q_ex[j]) + k2 * (1 - bw_q_ex[j]/bw_nu_ex[j]) + k3 * (1 - bw_nu_ex[j])); 1039 | // fprintf(WFout, "%.3f ",tmpBOLD); 1040 | // } 1041 | 1042 | // Inhibitory populations' BOLD 1043 | /* 1044 | for (j = 0; j < num_output_ts; j++) { 1045 | tmpBOLD = 100 / rho * V_0 * (k1 * (1 - bw_q_in[j]) + k2 * (1 - bw_q_in[j]/bw_nu_in[j]) + k3 * (1 - bw_nu_in[j])); 1046 | fprintf(WFout, "%.3f ",tmpBOLD); 1047 | } 1048 | */ 1049 | 1050 | 1051 | 1052 | if (ts_bold % TR_ts == 0) { 1053 | BOLD_len_i++; 1054 | 1055 | for (j = 0; j < num_output_ts; j++) { 1056 | BOLD_ex[j][BOLD_len_i] = 100 / rho * V_0 * (k1 * (1 - bw_q_ex[j]) + k2 * (1 - bw_q_ex[j]/bw_nu_ex[j]) + k3 * (1 - bw_nu_ex[j])); 1057 | //BOLD_in[BOLD_len_i * num_output_ts + j] = 100 / rho * V_0 * (k1 * (1 - bw_q_ex[j]) + k2 * (1 - bw_q_ex[j]/bw_nu_ex[j]) + k3 * (1 - bw_nu_ex[j])); 1058 | } 1059 | } 1060 | ts_bold++; 1061 | 1062 | } 1063 | 1064 | //fprintf(FCout, "%.10f %.10f %.10f %.10f %.10f %.2f \n\n", G,w_plus, J_NMDA, eIf_e, eIf_i, current_best_FRmean); 1065 | for (i=0; i<(BOLD_len_i-BOLD_offset); i++) { 1066 | for (j=0; j 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MATLAB/computeGAWs_fast_timescale.m: -------------------------------------------------------------------------------- 1 | % Compute grand average waveforms (GAW) on fast time scale time-locked to 2 | % alpha phase fluctuation 3 | % 4 | % USAGE: 5 | % GAWnode = computeGAWnode_fast_timescale(waveform_file, node) 6 | % 7 | % INPUTS: 8 | % waveform_file - String that contains the filename of the ..txtwf 9 | % waveform file output by the hybrid model C code 10 | % node - Scalar integer that specifies the brain network model 11 | % node for which GAWnode should be computed 12 | % OUTPUTS: 13 | % GAWnode - struct that contains grand average waveforms for node 14 | % 15 | % COMMENTS: 16 | % This function sums and aggregates alpha cycles for one node. The actual 17 | % grand average and grand standard deviations are then computed in the 18 | % script computeGAWnode_fast_timescale_agg.m. This is necessary b/c: the data 19 | % size is too large for a standard computer to have the GAW computed over 20 | % all nodes in one run. 21 | 22 | 23 | function GAWnode = computeGAWs_fast_timescale(waveform_file, node) 24 | 25 | % Read waveform file 26 | fid = fopen(waveform_file,'r'); 27 | data = fscanf(fid,'%f'); 28 | fclose(fid); 29 | data = reshape(data,68*10,length(data)/(68*10))'; 30 | 31 | 32 | %{ 33 | Pre-allocate arrays 34 | %} 35 | num_guess = 4500; % Initial guess 36 | 37 | % cycle length of alpha wave to get sharp GAW profiles 38 | cycle_lens = [95 105]; 39 | 40 | % Arrays to store average 41 | GAWnode.grand_avg_alpha = zeros(cycle_lens(2),1); 42 | GAWnode.grand_avg_inhib = zeros(cycle_lens(2),1); 43 | GAWnode.grand_avg_FR_exc = zeros(cycle_lens(2),1); 44 | GAWnode.grand_avg_FR_inh = zeros(cycle_lens(2),1); 45 | GAWnode.grand_avg_Extern = zeros(cycle_lens(2),1); 46 | GAWnode.grand_avg_ExternInh = zeros(cycle_lens(2),1); 47 | GAWnode.grand_avg_Recurrent = zeros(cycle_lens(2),1); 48 | GAWnode.grand_avg_input = zeros(cycle_lens(2),1); 49 | GAWnode.grand_avg_inputInh = zeros(cycle_lens(2),1); 50 | GAWnode.grand_avg_ExcSyn = zeros(cycle_lens(2),1); 51 | GAWnode.grand_avg_InhSyn = zeros(cycle_lens(2),1); 52 | GAWnode.grand_avg_Global = zeros(cycle_lens(2),1); 53 | GAWnode.grand_avg_BOLDexc = zeros(cycle_lens(2),1); 54 | 55 | % Arrays to store standard deviation 56 | GAWnode.grand_avg_alphaSD = zeros(num_guess,cycle_lens(2)); 57 | GAWnode.grand_avg_inhibSD = zeros(num_guess,cycle_lens(2)); 58 | GAWnode.grand_avg_FR_excSD = zeros(num_guess,cycle_lens(2)); 59 | GAWnode.grand_avg_FR_inhSD = zeros(num_guess,cycle_lens(2)); 60 | GAWnode.grand_avg_ExternSD = zeros(num_guess,cycle_lens(2)); 61 | GAWnode.grand_avg_ExternInhSD = zeros(num_guess,cycle_lens(2)); 62 | GAWnode.grand_avg_RecurrentSD = zeros(num_guess,cycle_lens(2)); 63 | GAWnode.grand_avg_inputSD = zeros(num_guess,cycle_lens(2)); 64 | GAWnode.grand_avg_inputInhSD = zeros(num_guess,cycle_lens(2)); 65 | GAWnode.grand_avg_ExcSynSD = zeros(num_guess,cycle_lens(2)); 66 | GAWnode.grand_avg_InhSynSD = zeros(num_guess,cycle_lens(2)); 67 | GAWnode.grand_avg_GlobalSD = zeros(num_guess,cycle_lens(2)); 68 | GAWnode.grand_avg_BOLDexcSD = zeros(num_guess,cycle_lens(2)); 69 | 70 | % Binned alpha power histogramm 71 | GAWnode.bin1 = zeros(num_guess,1); 72 | GAWnode.bin2 = zeros(num_guess,1); 73 | GAWnode.bin3 = zeros(num_guess,1); 74 | GAWnode.bin4 = zeros(num_guess,1); 75 | GAWnode.bin5 = zeros(num_guess,1); 76 | GAWnode.bin6 = zeros(num_guess,1); 77 | 78 | 79 | %{ 80 | Extract full waveforms 81 | %} 82 | 83 | % Butterworth band-pass filter in alpha range 84 | [b,a] = butter(1, [8 12]/(1000/2)); 85 | 86 | % Extract and filter injected input 87 | extern_inp = data(:,node+68*7); 88 | extern_inp_filt = filtfilt(b,a,extern_inp); 89 | 90 | % Compute instantaneous amplitude (ongoing alpha power) 91 | extern_inp_filt_hilbert = hilbert(extern_inp_filt); 92 | inst_ampl = abs(extern_inp_filt_hilbert); 93 | GAWnode.alphapower = inst_ampl; 94 | 95 | % Firing rate of exc. pop. 96 | FR_exc = data(:,node+68*2); 97 | % Firing rate of inh. pop. 98 | FR_inh = data(:,node+68*3); 99 | % Synaptic gating of exc. pop. 100 | Syn_exc = data(:,node); 101 | % Synaptic gating of inh. pop. 102 | Syn_inh = data(:,node+68); 103 | % Injected input exc. pop. 104 | externinp = data(:,node+68*7); 105 | % Injected input inh. pop. (scaled version of inj. inp. to exc. pop.) 106 | externinpinh = data(:,node+68*8); 107 | % Long-range input 108 | Global_inp = data(:,node+68*5); 109 | % Feedback inhibition 110 | Inhib_inp = data(:,node+68*6); 111 | % Recurrent excitation 112 | Exc_inp = data(:,node+68*4); 113 | % Sum of all inputs to exc. pop. 114 | Input_ExcPop = externinp + 0.382 - Inhib_inp + Global_inp; 115 | % Sum of all inputs to inh. pop. 116 | Input_InhPop = 0.7*0.382 - Syn_inh + externinpinh; 117 | % fMRI 118 | bold_exc = data(:,node+68*9); 119 | 120 | 121 | 122 | %{ 123 | Compute grand average waveforms time-locked to alpha phase fluctuation 124 | %} 125 | 126 | counter = 0; 127 | previous_cycle_start = -1; 128 | 129 | % Scan through alpha wave 130 | % Edges are ignored to avoid edge artifacts 131 | for ii = 1000*50*1.94:length(extern_inp_filt)-1000*50*1.94, 132 | 133 | % Zero-crossing of alpha wave marks the beginning of an alpha wave 134 | if extern_inp_filt(ii-1) < 0 && extern_inp_filt(ii) >= 0, 135 | if previous_cycle_start == -1, 136 | previous_cycle_start = ii; 137 | else 138 | % Compute length of current alpha cycle 139 | cycle_length = ii-1 - previous_cycle_start + 1; 140 | 141 | % Only use for GAW computation if length is in prescribed 142 | % boundaries (to get sharp GAW profiles) 143 | if cycle_length > cycle_lens(1) && cycle_length < cycle_lens(2) 144 | 145 | counter=counter+1; 146 | 147 | % Mean firing rate of current cycle 148 | avg_FR_curr_cycle = mean(FR_exc(previous_cycle_start:(ii-1))); 149 | 150 | % Divide cycle into six sub-epochs, compute mean firing 151 | % rate during each epoch 152 | GAWnode.bin1(counter) = mean(FR_exc(previous_cycle_start: (previous_cycle_start + round(cycle_length/6) - 1)))./avg_FR_curr_cycle; 153 | GAWnode.bin2(counter) = mean(FR_exc((previous_cycle_start + round(1*cycle_length/6)) : (previous_cycle_start + round(2*cycle_length/6) - 1)))./avg_FR_curr_cycle; 154 | GAWnode.bin3(counter) = mean(FR_exc((previous_cycle_start + round(2*cycle_length/6)) : (previous_cycle_start + round(3*cycle_length/6) - 1)))./avg_FR_curr_cycle; 155 | GAWnode.bin4(counter) = mean(FR_exc((previous_cycle_start + round(3*cycle_length/6)) : (previous_cycle_start + round(4*cycle_length/6) - 1)))./avg_FR_curr_cycle; 156 | GAWnode.bin5(counter) = mean(FR_exc((previous_cycle_start + round(4*cycle_length/6)) : (previous_cycle_start + round(5*cycle_length/6) - 1)))./avg_FR_curr_cycle; 157 | GAWnode.bin6(counter) = mean(FR_exc((previous_cycle_start + round(5*cycle_length/6)) : (previous_cycle_start + round(6*cycle_length/6) - 1)))./avg_FR_curr_cycle; 158 | 159 | % Sum waveforms to compute average for each time step 160 | % later (during aggregation step) 161 | GAWnode.grand_avg_alpha = GAWnode.grand_avg_alpha + extern_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 162 | GAWnode.grand_avg_inhib = GAWnode.grand_avg_inhib - Inhib_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 163 | GAWnode.grand_avg_InhSyn = GAWnode.grand_avg_InhSyn + Syn_inh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 164 | GAWnode.grand_avg_FR_exc = GAWnode.grand_avg_FR_exc + FR_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 165 | GAWnode.grand_avg_FR_inh = GAWnode.grand_avg_FR_inh + FR_inh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 166 | GAWnode.grand_avg_Extern = GAWnode.grand_avg_Extern + externinp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 167 | GAWnode.grand_avg_ExternInh = GAWnode.grand_avg_ExternInh + externinpinh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 168 | GAWnode.grand_avg_Recurrent = GAWnode.grand_avg_Recurrent + Exc_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 169 | GAWnode.grand_avg_input = GAWnode.grand_avg_input + Input_ExcPop(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 170 | GAWnode.grand_avg_inputInh = GAWnode.grand_avg_inputInh + Input_InhPop(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 171 | GAWnode.grand_avg_ExcSyn = GAWnode.grand_avg_ExcSyn + Syn_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 172 | GAWnode.grand_avg_Global = GAWnode.grand_avg_Global + Global_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 173 | GAWnode.grand_avg_BOLDexc = GAWnode.grand_avg_BOLDexc + bold_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 174 | 175 | % Store waveforms to compute SD for each time step 176 | % later (during aggregation step) 177 | GAWnode.grand_avg_alphaSD(counter,:) = extern_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 178 | GAWnode.grand_avg_inhibSD(counter,:) = -Inhib_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 179 | GAWnode.grand_avg_FR_excSD(counter,:) = FR_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 180 | GAWnode.grand_avg_FR_inhSD(counter,:) = FR_inh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 181 | GAWnode.grand_avg_ExternSD(counter,:) = externinp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 182 | GAWnode.grand_avg_ExternInhSD(counter,:) = externinpinh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 183 | GAWnode.grand_avg_RecurrentSD(counter,:) = Exc_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 184 | GAWnode.grand_avg_inputSD(counter,:) = Input_ExcPop(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 185 | GAWnode.grand_avg_inputInhSD(counter,:) = Input_InhPop(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 186 | GAWnode.grand_avg_ExcSynSD(counter,:) = Syn_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 187 | GAWnode.grand_avg_InhSynSD(counter,:) = Syn_inh(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 188 | GAWnode.grand_avg_GlobalSD(counter,:) = Global_inp(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 189 | GAWnode.grand_avg_BOLDexcSD(counter,:) = bold_exc(previous_cycle_start:previous_cycle_start+cycle_lens(2)-1); 190 | end 191 | 192 | % Time step of the end/beginning of this/next cycle 193 | previous_cycle_start = ii; 194 | end 195 | end 196 | end 197 | 198 | % Store results in output struct (cut off empty parts of arrays) 199 | GAWnode.bin1 = bin1(1:counter); 200 | GAWnode.bin2 = bin2(1:counter); 201 | GAWnode.bin3 = bin3(1:counter); 202 | GAWnode.bin4 = bin4(1:counter); 203 | GAWnode.bin5 = bin5(1:counter); 204 | GAWnode.bin6 = bin6(1:counter); 205 | GAWnode.grand_avg_alphaSD = GAWnode.grand_avg_alphaSD(1:counter,:); 206 | GAWnode.grand_avg_inhibSD = GAWnode.grand_avg_inhibSD(1:counter,:); 207 | GAWnode.grand_avg_FRSD = GAWnode.grand_avg_FR_excSD(1:counter,:); 208 | GAWnode.grand_avg_ExternSD = GAWnode.grand_avg_ExternSD(1:counter,:); 209 | GAWnode.grand_avg_ExternInhSD = GAWnode.grand_avg_ExternInhSD(1:counter,:); 210 | GAWnode.grand_avg_RecurrentSD = GAWnode.grand_avg_RecurrentSD(1:counter,:); 211 | GAWnode.grand_avg_inputSD = GAWnode.grand_avg_inputSD(1:counter,:); 212 | GAWnode.grand_avg_inputInhSD = GAWnode.grand_avg_inputInhSD(1:counter,:); 213 | GAWnode.grand_avg_ExcSynSD = GAWnode.grand_avg_ExcSynSD(1:counter,:); 214 | GAWnode.grand_avg_GlobalSD = GAWnode.grand_avg_GlobalSD(1:counter,:); 215 | GAWnode.grand_avg_InhSynSD = GAWnode.grand_avg_InhSynSD(1:counter,:); 216 | GAWnode.grand_avg_FR_inhSD = GAWnode.grand_avg_FR_inhSD(1:counter,:); 217 | GAWnode.grand_avg_BOLDexcSD = GAWnode.grand_avg_BOLDexcSD(1:counter,:); 218 | GAWnode.counter = counter; 219 | 220 | end 221 | 222 | 223 | -------------------------------------------------------------------------------- /MATLAB/computeGAWs_fast_timescale_agg.m: -------------------------------------------------------------------------------- 1 | % Aggregates grand average waveform (GAW) results over all nodes and 2 | % subjects 3 | % 4 | % USAGE: 5 | % GAW = computeGAWs_fast_timescale_agg(GAWnode_filenames) 6 | % 7 | % INPUTS: 8 | % GAWnode_filenames - cell array that contains filenames for results from 9 | % computeGAWs_fast_timescale.m. 10 | % 11 | % OUTPUTS: 12 | % GAW - grand average waveform over all nodes and subjects 13 | % 14 | % COMMENTS: 15 | % This function computes the average over all individual GAWnode results 16 | % for each subject and node output by computeGAWs_fast_timescale.m. 17 | 18 | function GAW = computeGAWs_fast_timescale_agg(GAWnode_filenames) 19 | 20 | % Initialize arrays 21 | GAW.grand_avg_alphaSDc = zeros(1,105); 22 | GAW.grand_avg_inhibSDc = zeros(1,105); 23 | GAW.grand_avg_FRSDc = zeros(1,105); 24 | GAW.grand_avg_ExternSDc = zeros(1,105); 25 | GAW.grand_avg_ExternInhSDc = zeros(1,105); 26 | GAW.grand_avg_RecurrentSDc = zeros(1,105); 27 | GAW.grand_avg_inputSDc = zeros(1,105); 28 | GAW.grand_avg_inputInhSDc = zeros(1,105); 29 | GAW.grand_avg_ExcSynSDc = zeros(1,105); 30 | GAW.grand_avg_GlobalSDc = zeros(1,105); 31 | GAW.grand_avg_InhSynSDc = zeros(1,105); 32 | GAW.grand_avg_FR_inhSDc = zeros(1,105); 33 | GAW.grand_avg_BOLDexcSDc = zeros(1,105); 34 | GAW.bin1 = zeros(1,105); 35 | GAW.bin2 = zeros(1,105); 36 | GAW.bin3 = zeros(1,105); 37 | GAW.bin4 = zeros(1,105); 38 | GAW.bin5 = zeros(1,105); 39 | GAW.bin6 = zeros(1,105); 40 | SD_GAW.grand_avg_alphaSDc = zeros(1,105); 41 | SD_GAW.grand_avg_inhibSDc = zeros(1,105); 42 | SD_GAW.grand_avg_FRSDc = zeros(1,105); 43 | SD_GAW.grand_avg_ExternSDc = zeros(1,105); 44 | SD_GAW.grand_avg_ExternInhSDc = zeros(1,105); 45 | SD_GAW.grand_avg_RecurrentSDc = zeros(1,105); 46 | SD_GAW.grand_avg_inputSDc = zeros(1,105); 47 | SD_GAW.grand_avg_inputInhSDc = zeros(1,105); 48 | SD_GAW.grand_avg_ExcSynSDc = zeros(1,105); 49 | SD_GAW.grand_avg_GlobalSDc = zeros(1,105); 50 | SD_GAW.grand_avg_InhSynSDc = zeros(1,105); 51 | SD_GAW.grand_avg_FR_inhSDc = zeros(1,105); 52 | SD_GAW.grand_avg_BOLDexcSDc = zeros(1,105); 53 | SD_GAW.bin1 = zeros(1,105); 54 | SD_GAW.bin2 = zeros(1,105); 55 | SD_GAW.bin3 = zeros(1,105); 56 | SD_GAW.bin4 = zeros(1,105); 57 | SD_GAW.bin5 = zeros(1,105); 58 | SD_GAW.bin6 = zeros(1,105); 59 | 60 | % Initialize element counters for each bin 61 | lenb1 = 0; 62 | lenb2 = 0; 63 | lenb3 = 0; 64 | lenb4 = 0; 65 | lenb5 = 0; 66 | lenb6 = 0; 67 | 68 | % Sum up all node-wise GAW results 69 | total_alpha_cycles = 0; 70 | for ii = 1:length(GAWnode_filenames) 71 | 72 | % Load GAWnode file 73 | load(GAWnode_filenames{ii}); 74 | 75 | % Sum waveforms to compute average waveform 76 | GAW.grand_avg_alphaSDc = GAW.grand_avg_alphaSDc + sum( GAWnode.grand_avg_alphaSDc ); 77 | GAW.grand_avg_inhibSDc = GAW.grand_avg_inhibSDc + sum( GAWnode.grand_avg_inhibSDc ); 78 | GAW.grand_avg_FRSDc = GAW.grand_avg_FRSDc + sum( GAWnode.grand_avg_FRSDc ); 79 | GAW.grand_avg_ExternSDc = GAW.grand_avg_ExternSDc + sum( GAWnode.grand_avg_ExternSDc ); 80 | GAW.grand_avg_ExternInhSDc = GAW.grand_avg_ExternInhSDc + sum( GAWnode.grand_avg_ExternInhSDc); 81 | GAW.grand_avg_RecurrentSDc = GAW.grand_avg_RecurrentSDc + sum( GAWnode.grand_avg_RecurrentSDc); 82 | GAW.grand_avg_inputSDc = GAW.grand_avg_inputSDc + sum( GAWnode.grand_avg_inputSDc ); 83 | GAW.grand_avg_inputInhSDc = GAW.grand_avg_inputInhSDc + sum( GAWnode.grand_avg_inputInhSDc ); 84 | GAW.grand_avg_ExcSynSDc = GAW.grand_avg_ExcSynSDc + sum( GAWnode.grand_avg_ExcSynSDc ); 85 | GAW.grand_avg_GlobalSDc = GAW.grand_avg_GlobalSDc + sum( GAWnode.grand_avg_GlobalSDc ); 86 | GAW.grand_avg_InhSynSDc = GAW.grand_avg_InhSynSDc + sum( GAWnode.grand_avg_InhSynSDc ); 87 | GAW.grand_avg_FR_inhSDc = GAW.grand_avg_FR_inhSDc + sum( GAWnode.grand_avg_FR_inhSDc ); 88 | GAW.grand_avg_BOLDexcSDc = GAW.grand_avg_BOLDexcSDc + sum( GAWnode.grand_avg_BOLDexcSDc ); 89 | 90 | % Sum up number of elements for each bin 91 | lenb1 = lenb1 + length( GAWnode.bin1 ); 92 | lenb2 = lenb2 + length( GAWnode.bin2 ); 93 | lenb3 = lenb3 + length( GAWnode.bin3 ); 94 | lenb4 = lenb4 + length( GAWnode.bin4 ); 95 | lenb5 = lenb5 + length( GAWnode.bin5 ); 96 | lenb6 = lenb6 + length( GAWnode.bin6 ); 97 | 98 | % Sum up firing rates in each bin 99 | GAW.bin1 = GAW.bin1 + sum( GAWnode.bin1 ); 100 | GAW.bin2 = GAW.bin2 + sum( GAWnode.bin2 ); 101 | GAW.bin3 = GAW.bin3 + sum( GAWnode.bin3 ); 102 | GAW.bin4 = GAW.bin4 + sum( GAWnode.bin4 ); 103 | GAW.bin5 = GAW.bin5 + sum( GAWnode.bin5 ); 104 | GAW.bin6 = GAW.bin6 + sum( GAWnode.bin6 ); 105 | 106 | % Sum up number of alpha cycles 107 | total_alpha_cycles = total_alpha_cycles + GAWnode.counter ; 108 | end 109 | 110 | 111 | % Compute average waveforms by dividing each time step by number of alpha 112 | % cycles 113 | GAW.grand_avg_alphaSDc = GAW.grand_avg_alphaSDc / total_alpha_cycles; 114 | GAW.grand_avg_inhibSDc = GAW.grand_avg_inhibSDc / total_alpha_cycles; 115 | GAW.grand_avg_FRSDc = GAW.grand_avg_FRSDc / total_alpha_cycles; 116 | GAW.grand_avg_ExternSDc = GAW.grand_avg_ExternSDc / total_alpha_cycles; 117 | GAW.grand_avg_ExternInhSDc = GAW.grand_avg_ExternInhSDc / total_alpha_cycles; 118 | GAW.grand_avg_RecurrentSDc = GAW.grand_avg_RecurrentSDc / total_alpha_cycles; 119 | GAW.grand_avg_inputSDc = GAW.grand_avg_inputSDc / total_alpha_cycles; 120 | GAW.grand_avg_inputInhSDc = GAW.grand_avg_inputInhSDc / total_alpha_cycles; 121 | GAW.grand_avg_ExcSynSDc = GAW.grand_avg_ExcSynSDc / total_alpha_cycles; 122 | GAW.grand_avg_GlobalSDc = GAW.grand_avg_GlobalSDc / total_alpha_cycles; 123 | GAW.grand_avg_InhSynSDc = GAW.grand_avg_InhSynSDc / total_alpha_cycles; 124 | GAW.grand_avg_FR_inhSDc = GAW.grand_avg_FR_inhSDc / total_alpha_cycles; 125 | GAW.grand_avg_BOLDexcSDc = GAW.grand_avg_BOLDexcSDc / total_alpha_cycles; 126 | GAW.bin1 = GAW.bin1 / lenb1; 127 | GAW.bin2 = GAW.bin2 / lenb2; 128 | GAW.bin3 = GAW.bin3 / lenb3; 129 | GAW.bin4 = GAW.bin4 / lenb4; 130 | GAW.bin5 = GAW.bin5 / lenb5; 131 | GAW.bin6 = GAW.bin6 / lenb6; 132 | 133 | 134 | % Iterate again over all GAWnode files to compute squared deviation 135 | % from mean 136 | for ii = 1:length(GAWnode_filenames) 137 | 138 | % Load GAWnode file 139 | load(GAWnode_filenames{ii}); 140 | 141 | % Compute squared deviation from mean 142 | SD_GAW.grand_avg_alphaSDc = SD_GAW.grand_avg_alphaSDc + sum(( GAWnode.grand_avg_alphaSDc - GAW.grand_avg_alphaSDc ).^2); 143 | SD_GAW.grand_avg_inhibSDc = SD_GAW.grand_avg_inhibSDc + sum(( GAWnode.grand_avg_inhibSDc - GAW.grand_avg_inhibSDc ).^2); 144 | SD_GAW.grand_avg_FRSDc = SD_GAW.grand_avg_FRSDc + sum(( GAWnode.grand_avg_FRSDc - GAW.grand_avg_FRSDc ).^2); 145 | SD_GAW.grand_avg_ExternSDc = SD_GAW.grand_avg_ExternSDc + sum(( GAWnode.grand_avg_ExternSDc - GAW.grand_avg_ExternSDc ).^2); 146 | SD_GAW.grand_avg_ExternInhSDc = SD_GAW.grand_avg_ExternInhSDc + sum(( GAWnode.grand_avg_ExternInhSDc - GAW.grand_avg_ExternInhSDc).^2); 147 | SD_GAW.grand_avg_RecurrentSDc = SD_GAW.grand_avg_RecurrentSDc + sum(( GAWnode.grand_avg_RecurrentSDc - GAW.grand_avg_RecurrentSDc).^2); 148 | SD_GAW.grand_avg_inputSDc = SD_GAW.grand_avg_inputSDc + sum(( GAWnode.grand_avg_inputSDc - GAW.grand_avg_inputSDc ).^2); 149 | SD_GAW.grand_avg_inputInhSDc = SD_GAW.grand_avg_inputInhSDc + sum(( GAWnode.grand_avg_inputInhSDc - GAW.grand_avg_inputInhSDc ).^2); 150 | SD_GAW.grand_avg_ExcSynSDc = SD_GAW.grand_avg_ExcSynSDc + sum(( GAWnode.grand_avg_ExcSynSDc - GAW.grand_avg_ExcSynSDc ).^2); 151 | SD_GAW.grand_avg_GlobalSDc = SD_GAW.grand_avg_GlobalSDc + sum(( GAWnode.grand_avg_GlobalSDc - GAW.grand_avg_GlobalSDc ).^2); 152 | SD_GAW.grand_avg_InhSynSDc = SD_GAW.grand_avg_InhSynSDc + sum(( GAWnode.grand_avg_InhSynSDc - GAW.grand_avg_InhSynSDc ).^2); 153 | SD_GAW.grand_avg_FR_inhSDc = SD_GAW.grand_avg_FR_inhSDc + sum(( GAWnode.grand_avg_FR_inhSDc - GAW.grand_avg_FR_inhSDc ).^2); 154 | SD_GAW.grand_avg_BOLDexcSDc = SD_GAW.grand_avg_BOLDexcSDc + sum(( GAWnode.grand_avg_BOLDexcSDc - GAW.grand_avg_BOLDexcSDc ).^2); 155 | SD_GAW.bin1 = SD_GAW.bin1 + sum(( GAWnode.bin1 - GAW.bin1 ).^2); 156 | SD_GAW.bin2 = SD_GAW.bin2 + sum(( GAWnode.bin2 - GAW.bin2 ).^2); 157 | SD_GAW.bin3 = SD_GAW.bin3 + sum(( GAWnode.bin3 - GAW.bin3 ).^2); 158 | SD_GAW.bin4 = SD_GAW.bin4 + sum(( GAWnode.bin4 - GAW.bin4 ).^2); 159 | SD_GAW.bin5 = SD_GAW.bin5 + sum(( GAWnode.bin5 - GAW.bin5 ).^2); 160 | SD_GAW.bin6 = SD_GAW.bin6 + sum(( GAWnode.bin6 - GAW.bin6 ).^2); 161 | 162 | end 163 | 164 | % Compute standard deviation 165 | SD_GAW.grand_avg_alphaSDc = sqrt(SD_GAW.grand_avg_alphaSDc / (total_alpha_cycles - 1) ); 166 | SD_GAW.grand_avg_inhibSDc = sqrt(SD_GAW.grand_avg_inhibSDc / (total_alpha_cycles - 1) ); 167 | SD_GAW.grand_avg_FRSDc = sqrt(SD_GAW.grand_avg_FRSDc / (total_alpha_cycles - 1) ); 168 | SD_GAW.grand_avg_ExternSDc = sqrt(SD_GAW.grand_avg_ExternSDc / (total_alpha_cycles - 1) ); 169 | SD_GAW.grand_avg_ExternInhSDc = sqrt(SD_GAW.grand_avg_ExternInhSDc/ (total_alpha_cycles - 1) ); 170 | SD_GAW.grand_avg_RecurrentSDc = sqrt(SD_GAW.grand_avg_RecurrentSDc/ (total_alpha_cycles - 1) ); 171 | SD_GAW.grand_avg_inputSDc = sqrt(SD_GAW.grand_avg_inputSDc / (total_alpha_cycles - 1) ); 172 | SD_GAW.grand_avg_inputInhSDc = sqrt(SD_GAW.grand_avg_inputInhSDc / (total_alpha_cycles - 1) ); 173 | SD_GAW.grand_avg_ExcSynSDc = sqrt(SD_GAW.grand_avg_ExcSynSDc / (total_alpha_cycles - 1) ); 174 | SD_GAW.grand_avg_GlobalSDc = sqrt(SD_GAW.grand_avg_GlobalSDc / (total_alpha_cycles - 1) ); 175 | SD_GAW.grand_avg_InhSynSDc = sqrt(SD_GAW.grand_avg_InhSynSDc / (total_alpha_cycles - 1) ); 176 | SD_GAW.grand_avg_FR_inhSDc = sqrt(SD_GAW.grand_avg_FR_inhSDc / (total_alpha_cycles - 1) ); 177 | SD_GAW.grand_avg_BOLDexcSDc = sqrt(SD_GAW.grand_avg_BOLDexcSDc / (total_alpha_cycles - 1) ); 178 | SD_GAW.bin1 = sqrt(SD_GAW.bin1 / (total_alpha_cycles - 1) ); 179 | SD_GAW.bin2 = sqrt(SD_GAW.bin2 / (total_alpha_cycles - 1) ); 180 | SD_GAW.bin3 = sqrt(SD_GAW.bin3 / (total_alpha_cycles - 1) ); 181 | SD_GAW.bin4 = sqrt(SD_GAW.bin4 / (total_alpha_cycles - 1) ); 182 | SD_GAW.bin5 = sqrt(SD_GAW.bin5 / (total_alpha_cycles - 1) ); 183 | SD_GAW.bin6 = sqrt(SD_GAW.bin6 / (total_alpha_cycles - 1) ); 184 | 185 | 186 | % Compute standard error of the mean 187 | GAW.inhibSD = SD_GAW.grand_avg_inhibSDc / sqrt(total_alpha_cycles); 188 | GAW.RecurrentSD = SD_GAW.grand_avg_RecurrentSDc / sqrt(total_alpha_cycles); 189 | GAW.GlobalSD = SD_GAW.grand_avg_GlobalSDc / sqrt(total_alpha_cycles); 190 | GAW.fmriexcSD = SD_GAW.grand_avg_BOLDexcSDc / sqrt(total_alpha_cycles); 191 | GAW.alphaSD = SD_GAW.grand_avg_alphaSDc / sqrt(total_alpha_cycles); 192 | GAW.excSynSD = SD_GAW.grand_avg_ExcSynSDc / sqrt(total_alpha_cycles); 193 | GAW.inhSynSD = SD_GAW.grand_avg_InhSynSDc / sqrt(total_alpha_cycles); 194 | GAW.extSD = SD_GAW.grand_avg_ExternSDc / sqrt(total_alpha_cycles); 195 | GAW.extinhSD = SD_GAW.grand_avg_ExternInhSDc / sqrt(total_alpha_cycles); 196 | GAW.inhSD = SD_GAW.grand_avg_InhSynSDc / sqrt(total_alpha_cycles); 197 | GAW.excSD = SD_GAW.grand_avg_RecurrentSDc / sqrt(total_alpha_cycles); 198 | GAW.inpExcSD = SD_GAW.grand_avg_inputSDc / sqrt(total_alpha_cycles); 199 | GAW.inpInhSD = SD_GAW.grand_avg_inputInhSDc / sqrt(total_alpha_cycles)/1.4; 200 | GAW.FRExcSD = SD_GAW.grand_avg_FRSDc / sqrt(total_alpha_cycles); 201 | GAW.FRInhSD = SD_GAW.grand_avg_FR_inhSDc / sqrt(total_alpha_cycles); 202 | GAW.bin1SD = SD_GAW.bin1 / sqrt(lenb1); 203 | GAW.bin2SD = SD_GAW.bin2 / sqrt(lenb2); 204 | GAW.bin3SD = SD_GAW.bin3 / sqrt(lenb3); 205 | GAW.bin4SD = SD_GAW.bin4 / sqrt(lenb4); 206 | GAW.bin5SD = SD_GAW.bin5 / sqrt(lenb5); 207 | GAW.bin6SD = SD_GAW.bin6 / sqrt(lenb6); 208 | 209 | end 210 | -------------------------------------------------------------------------------- /MATLAB/computeGAWs_slow_timescale_agg.m: -------------------------------------------------------------------------------- 1 | % Aggregates grand average waveform (GAW) results over all nodes and 2 | % subjects for activity on a slow time scale (< 0.1 Hz) 3 | % 4 | % USAGE: 5 | % GAW = computeGAWs_fast_timescale_agg(GAWnode_filenames) 6 | % 7 | % INPUTS: 8 | % GAWnode_filenames - cell array that contains filenames for results from 9 | % extract_statevars.m (68 regions for 15 subjects) 10 | % 11 | % OUTPUTS: 12 | % GAW - grand average waveform over all nodes and subjects 13 | 14 | 15 | 16 | function GAW = computeGAWs_slow_timescale_agg(GAWnode_filenames) 17 | 18 | % Initialize arrays 19 | GAW.EPSC = zeros(129398,1); 20 | GAW.EPSCinh = zeros(129398,1); 21 | GAW.SynINH = zeros(129398,1); 22 | GAW.SynEXC = zeros(129398,1); 23 | GAW.IPSC = zeros(129398,1); 24 | GAW.FRexc = zeros(129398,1); 25 | GAW.FRinh = zeros(129398,1); 26 | GAW.GlobaI = zeros(129398,1); 27 | GAW.BOLD = zeros(129398,1); 28 | GAW.INPexc = zeros(129398,1); 29 | GAW.INPinh = zeros(129398,1); 30 | 31 | % Iterate over all GAW result files and compute sum of waveforms 32 | for ii = length(GAWnode_filenames) 33 | load(GAWnode_filenames{ii}); 34 | GAW.EPSC = GAW.EPSC + sum(statevars.externinp')'; 35 | GAW.EPSCinh = GAW.EPSCinh + sum(statevars.externinpinh')'; 36 | GAW.SynINH = GAW.SynINH + sum(statevars.Syn_inh_ts')'; 37 | GAW.SynEXC = GAW.SynEXC + sum(statevars.Syn_exc')'; 38 | GAW.IPSC = GAW.IPSC + sum(statevars.Inhib_inp')'; 39 | GAW.FRexc = GAW.FRexc + sum(statevars.FR_exc')'; 40 | GAW.FRinh = GAW.FRinh + sum(statevars.FR_inh')'; 41 | GAW.GlobaI = GAW.GlobaI + sum(statevars.Global_inp')'; 42 | GAW.BOLD = GAW.BOLD + sum(statevars.bold_exc')'; 43 | GAW.INPexc = GAW.INPexc + sum(statevars.Input_ExcPop')'; 44 | GAW.INPinh = GAW.INPinh + sum(statevars.Input_InhPop')'; 45 | end 46 | 47 | % Compute average waveform 48 | GAW.EPSC = GAW.EPSC / (68*15) ; 49 | GAW.EPSCinh = GAW.EPSCinh / (68*15) ; 50 | GAW.SynINH = GAW.SynINH / (68*15) ; 51 | GAW.SynEXC = GAW.SynEXC / (68*15) ; 52 | GAW.IPSC = GAW.-1*IPSC / (68*15) ; 53 | GAW.FRexc = GAW.FRexc / (68*15) ; 54 | GAW.FRinh = GAW.FRinh / (68*15) ; 55 | GAW.GlobaI = GAW.GlobaI / (68*15) ; 56 | GAW.BOLD = GAW.BOLD / (68*15) ; 57 | GAW.INPexc = GAW.INPexc / (68*15) ; 58 | GAW.INPinh = GAW.INPinh / (68*15) ; 59 | 60 | % Compute moving averages 61 | movavg_window = 50; 62 | GAW.movavgFR_exc = nan(size(FRexc,1),1); 63 | GAW.movavgFR_inh = nan(size(FRinh,1),1); 64 | for p = (movavg_window + 1) : size(FRexc,1) - movavg_window, 65 | GAW.movavgFR_exc(p) = mean(FRexc(p-movavg_window:p+movavg_window)); 66 | GAW.movavgFR_inh(p) = mean(FRinh(p-movavg_window:p+movavg_window)); 67 | end 68 | 69 | end 70 | -------------------------------------------------------------------------------- /MATLAB/compute_alpha_regressor.m: -------------------------------------------------------------------------------- 1 | % Compute alpha regressor from EEG source activity 2 | % 3 | % USAGE: 4 | % alpha_reg = compute_alpha_regressor(source_activity, regionsMap, HRF_resEEG) 5 | % 6 | % INPUTS: 7 | % source_activity - [68 x 259184] matrix containing EEG source activity for 8 | % 68 regions and 259184 time points (200 Hz sampling rate) 9 | % (data/empirical_source_activity/source_activity.mat) 10 | % regionsMap - [68 x 1] vector that contains the region sorting of source 11 | % activity as outputted by Brainstorm 12 | % (data/regionsMap.mat) 13 | % HRF_resEEG - [1 x 6498] vector that contains the hemodynamic 14 | % response function sampled at 200 Hz 15 | % (data/HRF_200Hz.mat) 16 | % 17 | % OUTPUTS: 18 | % alpha_reg - struct that contains alpha regressor and filtered 19 | % alpha regressor (edges are discarded due to edge 20 | % effects from filtering and from convolution with HRF) 21 | 22 | 23 | 24 | function alpha_reg = compute_alpha_regressor(source_activity, regionsMap, HRF_resEEG) 25 | % Sorting of Desikan-Killiany atlas regions in SC matrices 26 | SCmat_sorting=[1001:1003,1005:1035,2001:2003,2005:2035]; 27 | 28 | % Generate butterworth filter for alpha range and for resting-state 29 | % slow oscillations range 30 | [b_hi,a_hi] = butter(1, [8 12]/(200/2)); 31 | [b_lo,a_lo] = butter(1, [0.1]/((1/1.94)/2)); 32 | 33 | 34 | % Initialize output arrays (shorter than full fMRI time series to 35 | % discard edge effects from filtering and convolution with HRF) 36 | alpha_reg = zeros(651,68); 37 | alpha_reg_filt = zeros(651,68); 38 | 39 | % Iterate over regions 40 | for ii = 1:68, 41 | % Get SC matrix sorting 42 | regindSAC = find(regionsMap==SCmat_sorting(ii)); 43 | region_ts = source_activity(regindSAC,:); 44 | 45 | % Filter in alpha range 46 | region_ts_filt = filtfilt(b_hi,a_hi,region_ts); 47 | 48 | % Hilbert transform to get instantaneous amplitude 49 | region_ts_filt_hilb = hilbert(region_ts_filt); 50 | inst_ampl = abs(region_ts_filt_hilb); 51 | 52 | % Convolution with HRF 53 | inst_ampl_HRF = conv(inst_ampl(100:end-100),HRF_resEEG,'valid'); 54 | 55 | % Downsample to BOLD sampling rate (TR = 1.94 s) 56 | alpha_reg(:,ii) = downsample(inst_ampl_HRF(100:end-100),388); 57 | alpha_reg_filt(:,ii)= filtfilt(b_lo,a_lo,alpha_reg(:,ii)); 58 | end 59 | 60 | % Fill output struct 61 | alpha_reg.alpha_reg = alpha_reg; 62 | alpha_reg.alpha_reg_filt = alpha_reg_filt; 63 | 64 | end 65 | -------------------------------------------------------------------------------- /MATLAB/extract_statevars.m: -------------------------------------------------------------------------------- 1 | % Extract and downsample state variables from simulation results 2 | % 3 | % USAGE: 4 | % statevars = extract_statevars(waveform_file) 5 | % 6 | % INPUTS: 7 | % waveform_file - String that contains the filename of the ..txtwf 8 | % waveform file output by the hybrid model C code 9 | % 10 | % OUTPUTS: 11 | % statevars - struct that contains state variables of the hybrid 12 | % model 13 | 14 | 15 | 16 | function statevars = extract_statevars(waveform_file) 17 | 18 | % Read waveform file 19 | fid = fopen(waveform_file,'r'); 20 | data = fscanf(fid,'%f'); 21 | fclose(fid); 22 | data = reshape(data,68*10,length(data)/(68*10))'; 23 | 24 | %{ 25 | Downsample to 100 Hz, fill output structure 26 | %} 27 | nodes = (1:68); 28 | 29 | % Firing rate of excitatory population 30 | statevars.FR_exc = downsample(data(:,nodes+68*2),10); 31 | 32 | % Firing rate of inhibitory population 33 | statevars.FR_inh = downsample(data(:,nodes+68*3),10); 34 | 35 | % Synaptic gating of excitatory population 36 | statevars.Syn_exc = downsample(data(:,nodes),10); 37 | 38 | % Synaptic gating of inhibitory population 39 | statevars.Syn_inh = downsample(data(:,nodes+68),10); 40 | 41 | % Source activity injected into exc. pop. 42 | statevars.externinp = downsample(data(:,nodes+68*7),10); 43 | 44 | % Source activity injected into inh. pop. (different scaling than into 45 | % exc. pop.) 46 | statevars.externinpinh = downsample(data(:,nodes+68*8),10); 47 | 48 | % Long-range input 49 | statevars.Global_inp = downsample(data(:,nodes+68*5),10); 50 | 51 | % Feedback inhibition 52 | statevars.Inhib_inp = downsample(data(:,nodes+68*6),10); 53 | 54 | % Recurrent excitation 55 | statevars.Exc_inp = downsample(data(:,nodes+68*4),10); 56 | 57 | % Sum of all inputs to exc. pop. 58 | statevars.Input_ExcPop = statevars.unfexterninp + 0.382 - statevars.unfInhib_inp + statevars.unfGlobal_inp; 59 | 60 | % Sum of all inputs to inh. pop. 61 | statevars.Input_InhPop = 0.7*0.382 - statevars.unfSyn_inh_ts + statevars.unfexterninpinh; 62 | 63 | % fMRI of exc. pop. 64 | statevars.bold_exc = downsample(data(:,nodes+68*9),10); 65 | 66 | end 67 | 68 | 69 | -------------------------------------------------------------------------------- /MATLAB/generate_artificial_input.m: -------------------------------------------------------------------------------- 1 | % Compute artificial alpha input (10 Hz sine wave) 2 | % First part: ~10 minutes of activity with short alpha burst 3 | % Second part: ~10 minutes of activity with slow power 4 | % modulation (0.01 - 0.03 Hz) 5 | 6 | 7 | function generate_artificial_input() 8 | 9 | %{ 10 | Generate first part: 10 minutes with short alpha burst 11 | %} 12 | 13 | % Generate one alpha cycle @10000 Hz 14 | sp = linspace(0,2*pi,1001); 15 | onecycle = sin(sp); 16 | onecycle = zscore(onecycle(1:end-1)); 17 | 18 | % Generate four seconds of alpha activity 19 | tinsec = 4; 20 | inp = []; 21 | for i = 1:10*tinsec 22 | inp = [inp onecycle]; 23 | end 24 | 25 | % Generate a slow modulator of the power of the 10 Hz sine wave 26 | tslen = 5000; 27 | mod1 = linspace(0.005,0.4,tslen); 28 | mod2 = linspace(0.4,0.001,tslen); 29 | hcyc0 = linspace(pi,2*pi,tslen+1); 30 | hcyc1 = linspace(pi,2*pi,tslen+1); 31 | hcyc2 = linspace(2*pi,3*pi,tslen+1); 32 | hcyc0 = ones(1,length(hcyc0)-1)*0.02; 33 | hcyc1 = zscore(cos(hcyc1(1:end-1))) * std(mod1) + mean(mod1); 34 | hcyc2 = zscore(cos(hcyc2(1:end-1))) * std(mod2) + mean(mod2); 35 | osc_modulator = [hcyc0 hcyc0 hcyc0 hcyc1 hcyc2 hcyc0 hcyc0 hcyc0]; 36 | 37 | % Compute alpha burst 38 | ext_input = zscore(inp(10000:30000).*osc_modulator(10000:30000)); 39 | 40 | % Generate 10 minutes of 10 Hz sine wave with the power burst in the middle 41 | ext_input = [repmat(ext_input(1:1000),1,5*60*10) ext_input repmat(ext_input(1:1000),1,5*60*10)]; 42 | cut_sig = downsample(repmat(ext_input(1:1000),1,10*60*10),10); 43 | 44 | % downsample to 1000 Hz 45 | ext_input = downsample(ext_input,10); 46 | 47 | 48 | 49 | %{ 50 | Generate second part: 10 minutes with slow power modulation 51 | %} 52 | 53 | % Generate 310 TRs of a 10 Hz sine wave (1 TR = 1.94 sec) 54 | tinsec = 1.94*310; 55 | sp = linspace(0,2*pi*tinsec*10,tinsec*1000); 56 | alphawave = sin(sp); 57 | 58 | % Generate power modulators at different frequencies 59 | sp2_p01 = linspace(0,2*pi,1000/0.01); 60 | sp2_p02 = linspace(0,2*pi,1000/0.02); 61 | sp2_p03 = linspace(0,2*pi,1000/0.03); 62 | sp2_p015 = linspace(0,2*pi,1000/0.015); 63 | sp2_p025 = linspace(0,2*pi,1000/0.025); 64 | modulator = cos([sp2_p01 sp2_p02 sp2_p03 sp2_p03 sp2_p01 sp2_p025 sp2_p025 sp2_p015 sp2_p01 sp2_p03 sp2_p03]); 65 | modulator = modulator + -1*min(modulator); 66 | inp_seg2 = zscore(alphawave.*modulator(1:length(alphawave))); 67 | 68 | % Concat first and second part 69 | ext_input = [ext_input inp_seg2]; 70 | 71 | % Fill up edges to get 668 TRs of activity (to match length of 72 | % empirical data) 73 | missing = 668*1.94*1000 - length(ext_input); 74 | ext_input = [cut_sig(1:round(missing/2)) ext_input cut_sig(1:round(missing/2)+1000)]; 75 | 76 | % Copy for all 68 nodes of model 77 | output = repmat(ext_input',1,68); 78 | 79 | dlmwrite('Arificial_input.txt',output,'delimiter',' ','precision','%.4f'); 80 | end 81 | 82 | -------------------------------------------------------------------------------- /MATLAB/generate_hybrid_model_input.m: -------------------------------------------------------------------------------- 1 | % Generate hybrid model input from EEG source activity 2 | % 3 | % USAGE: 4 | % preprocess_external_input(output_fileid, source_activity, regionsMap) 5 | % 6 | % INPUTS: 7 | % output_fileid - String that contains the filestem for the output textfile 8 | % source_activity - [68 x 259184] matrix containing EEG source activity for 9 | % 68 regions and 259184 time points (200 Hz sampling rate) 10 | % (stored in data/empirical_source_activity/source_activity.mat) 11 | % regionsMap - [68 x 1] vector that contains the region sorting of source 12 | % activity as outputted by Brainstorm 13 | % 14 | % 15 | % OUTPUTS: 16 | % [output_fileid '.txt'] - hybrid model input activity 17 | % [output_fileid '_randperm.txt'] - random permutation of input activity 18 | % 19 | % COMMENTS: 20 | % Region-wise source imaging results from Brainstorm are re-sorted to match 21 | % the region-sorting of SC matrices and upsampled to 1000 Hz 22 | 23 | function generate_hybrid_model_input(output_fileid, source_activity, regionsMap) 24 | 25 | % Sorting of Desikan-Killiany atlas regions in SC matrices 26 | SCmat_sorting = [1001:1003,1005:1035,2001:2003,2005:2035]; 27 | 28 | % Sampling rate of model input activity (Hz) 29 | srate = 1000; 30 | 31 | % Number of TRs in source activity (1 TR = 1.94 s) 32 | numscans = 668; 33 | 34 | % Original and interpolated time points 35 | x = 1:(srate/200):(srate*1.94*numscans); 36 | xi = 1:(srate*1.94*numscans); 37 | 38 | % Initialize output arrays 39 | sorted_sac = zeros(length(xi),68); 40 | sorted_sacrand = zeros(length(xi),68); 41 | 42 | % Re-sort and upsample source activity; generate random permutation 43 | for ii = 1:68, 44 | regindSAC = find(regionsMap==SCmat_sorting(ii)); 45 | ts = zscore(source_activity(regindSAC,:)); 46 | sorted_sac(:,ii) = interp1(x,ts,xi,'spline','extrap'); 47 | sorted_sacrand(:,ii)= sorted_sac(randperm(size(sorted_sac,1)),ii); 48 | end 49 | 50 | % Write output 51 | dlmwrite([output_fileid '.txt'],sorted_sac,'delimiter',' ','precision','%.4f'); 52 | dlmwrite([output_fileid '_randperm.txt'],sorted_sac,'delimiter',' ','precision','%.4f'); 53 | 54 | end 55 | -------------------------------------------------------------------------------- /MATLAB/generate_input_SC.m: -------------------------------------------------------------------------------- 1 | % Converts MATLAB format SC files into a txt file format that can be read 2 | % by the hybrid brain network model implementation 3 | % 4 | % USAGE: 5 | % generate_input_SC(SC, output_filestem) 6 | % 7 | % INPUTS: 8 | % SC - [N,N] array that contains connection weights for all 9 | % NxN region pairs 10 | % output_filestem - String that becomes the prefix of the three output 11 | % files 12 | % 13 | % OUTPUTS: 14 | % The hybrid brain network model implementation needs three input text 15 | % files. All three filenames must contain identical prefixes and this 16 | % prefix must be supplied as an argument for the brain model. 17 | % Suffix _SC_strengths.txt: contains connection weights, 18 | % suffix _SC_distances.txt: contains connection distances, 19 | % suffix _SC_regionids.txt: contains the region numbers of the source and 20 | % target regions for each region of the brain model 21 | 22 | 23 | function generate_input_SC(SC, output_filestem) 24 | 25 | % Normalize SC by dividing through maximum value 26 | SC = SC ./ max(SC(:)); 27 | SCsize = size(SC,1); 28 | 29 | % OPTIONAL: Set low coupling values to zero 30 | %sumSC = sum(SC); 31 | %for ii = 1:SCsize 32 | % SC(ii, find(SC(ii,:) < sumSC(ii)*0.05) ) = 0; 33 | %end 34 | 35 | % Generate filenames 36 | sc_cap_file = [output_filestem '_SC_strengths.txt']; 37 | sc_dist_file = [output_filestem '_SC_distances.txt']; 38 | sc_id_file = [output_filestem '_SC_regionids.txt']; 39 | 40 | % Write number of nodes as header line into SC files 41 | dlmwrite(sc_cap_file, SCsize); 42 | dlmwrite(sc_dist_file, SCsize); 43 | dlmwrite(sc_id_file, SCsize); 44 | 45 | % Write maximum distance as 2nd header line into dist file 46 | % Time-delays are turned off, max-distance is set to 1 47 | maxdist = 1; 48 | dlmwrite(sc_dist_file,maxdist,'delimiter',' ','-append'); 49 | 50 | % Write connection weights, distances and input-region IDs 51 | for ii = 1:SCsize, 52 | % Select all non-zero connections 53 | inpregs = find(SC(ii,:)>0); 54 | inpcaps = SC(ii,inpregs); 55 | inpdists = sc_dist(ii,inpregs); 56 | 57 | % Write connectivity description for each node 58 | % Convert from Matlab-style 1-based numbering to C-style 0-based 59 | % numbering 60 | inpregs = inpregs-1; 61 | cap_line = [(ii-1) length(inpregs)]; 62 | dist_line = [(ii-1) length(inpregs)]; 63 | inp_line = [(ii-1) length(inpregs)]; 64 | dlmwrite(sc_cap_file, cap_line,'delimiter',' ','-append'); 65 | dlmwrite(sc_dist_file, dist_line,'delimiter',' ','-append'); 66 | dlmwrite(sc_id_file, inp_line,'delimiter',' ','-append'); 67 | 68 | % Write actual connectivity information 69 | dlmwrite(sc_cap_file, inpcaps,'delimiter',' ','-append','precision','%.8f'); 70 | dlmwrite(sc_dist_file, inpdists,'delimiter',' ','-append','precision','%.8f'); 71 | dlmwrite(sc_id_file, inpregs,'delimiter',' ','-append'); 72 | end 73 | 74 | end 75 | -------------------------------------------------------------------------------- /MATLAB/postprocess_simulation_results.m: -------------------------------------------------------------------------------- 1 | % Reads simulation results, computes correlation between empirical and 2 | % simulated time series and functional connectivities 3 | % 4 | % USAGE: 5 | % sim_res = postprocess_simulation_results(simulated_fMRI, empirical_fMRI) 6 | % 7 | % INPUTS: 8 | % simulated_fMRI - string that contains filename of hybrid model 9 | % fMRI simulation results for subject 10 | % empirical_fMRI - [N,M] array containing N time points and M regions of 11 | % empirical fMRI activity for subject 12 | % (empirical_fMRI.mat) 13 | % RSN - [N,K] array containing N time points and K empirical 14 | % RSN temporal modes for subject (GroupICA_results.mat) 15 | % RSNroi - struct that contains mapping between RSNs and BNM 16 | % regions (RSN_to_region.mat) 17 | % 18 | % OUTPUTS: 19 | % sim_res - struct that contains correlations between simulated 20 | % and empirical time series and functional connectivity 21 | 22 | function sim_res = postprocess_simulation_results(simulated_fMRI, empirical_fMRI, RSN, RSNroi) 23 | 24 | % logical array to map RSNs to BNM regions 25 | RSNidx_loose = zeros(68,10); 26 | for ii = 1:10 27 | RSNidx_loose(RSNroi(ii).SCrois_loose,ii) = 1; 28 | end 29 | RSNidx_loose = logical(RSNidx_loose); 30 | 31 | 32 | % Compute low-pass filtered versions of fMRI/RSN activity 33 | [b,a] = butter(1, [0.1]/((1/1.94)/2)); 34 | for ii = 1:68, 35 | empirical_fMRI_filt(:,ii) = filtfilt(b,a,empirical_fMRI(:,ii)); 36 | end 37 | for ii = 1:10, 38 | RSN_filt(:,ii) = filtfilt(b,a,RSN(:,ii)); 39 | end 40 | 41 | % Compute functional connectivity 42 | static_FCemp = corr(empirical_fMRI(1+5+7:640+5+7,:)); 43 | static_FCemp_filt = corr(empirical_fMRI_filt(1+5+7:640+5+7,:)); 44 | Isubdiag = find(tril(ones(68),-1)); % Indexes of all the values below the diagonal. 45 | 46 | 47 | % Read simulated fMRI 48 | fid = fopen(simulated_fMRI,'r'); 49 | data = fscanf(fid,'%f'); 50 | fclose(fid); 51 | 52 | 53 | % Pre-allocate result arrays 54 | ts_cc = zeros(length(data)/(6+655*68),12); 55 | ts_cc_filt = zeros(length(data)/(6+655*68),12); 56 | static_FC_cc = zeros(length(data)/(6+655*68),2); 57 | static_FC_cc_filt = zeros(length(data)/(6+655*68),2); 58 | 59 | 60 | % Loop over all parameter sets 61 | for ii = 0:length(data)/(6+655*68)-1, 62 | 63 | % Store simulation parameters / metadata 64 | ts_cc(ii+1,1:6) = data(1+ii*6+ii*655*68:6+ii*6+ii*655*68); 65 | 66 | % Extract simulated fMRI for parameter set 67 | sim_ts = reshape(data(7+ii*6+ii*655*68:7+ii*6+(ii+1)*655*68-1),68,655)'; 68 | 69 | % Compute low-pass filtered version of simulated fMRI 70 | for node = 1:68, 71 | simts_filt(:,node) = filtfilt(b,a,sim_ts(:,node)); 72 | end 73 | 74 | % Compute average fMRI time series correlations over all 68 simulated and 75 | % empirical region-pairs for time shifts to account for lag of HRF. 76 | % Leave offset for edge effects of filtering. 77 | clear tmp_res 78 | for shift = 0:15 79 | tmp_tmp_res = diag(corr(sim_ts(6:645,:),empirical_fMRI(6+shift:645+shift,:))); 80 | tmp_res(shift+1) = mean(tmp_tmp_res(~isnan(tmp_tmp_res))); 81 | end 82 | [ts_cc(ii+1,7), ts_cc(ii+1,8)] = max(tmp_res); 83 | 84 | % same for filtered data 85 | clear tmp_res 86 | for shift = 0:15 87 | tmp_tmp_res = diag(corr(simts_filt(6:645,:),empirical_fMRI_filt(6+shift:645+shift,:))); 88 | tmp_res(shift+1) = mean(tmp_tmp_res(~isnan(tmp_tmp_res))); 89 | end 90 | [ts_cc_filt(ii+1,7), ts_cc_filt(ii+1,8)] = max(tmp_res); 91 | 92 | 93 | % Compute average RSN time series correlations using all correlations 94 | % between all 9 empirical RSNs and their corresponding simulated 95 | % regions (cerebellar RSN is excluded) 96 | clear tmp_res 97 | for shift = 0:15 98 | tmp_tmp_res = corr(sim_ts(1+5:640+5,:),RSN(1+shift+5:640+shift+5,:)); 99 | tmp_res(shift+1,:) = [mean(tmp_tmp_res(RSNidx_loose(:,1),1)) mean(tmp_tmp_res(RSNidx_loose(:,2),2)) mean(tmp_tmp_res(RSNidx_loose(:,3),3)) mean(tmp_tmp_res(RSNidx_loose(:,4),4)) mean(tmp_tmp_res(RSNidx_loose(:,6),6)) mean(tmp_tmp_res(RSNidx_loose(:,7),7)) mean(tmp_tmp_res(RSNidx_loose(:,8),8)) mean(tmp_tmp_res(RSNidx_loose(:,9),9)) mean(tmp_tmp_res(RSNidx_loose(:,10),10))]; 100 | end 101 | ts_cc(ii+1,9) = max(tmp_res(:)); 102 | ts_cc(ii+1,10) = max(mean(tmp_res')); 103 | 104 | % same for filtered data 105 | clear tmp_res 106 | for shift = 0:15 107 | tmp_tmp_res = corr(simts_filt(1+5:640+5,:),RSN_filt(1+shift+5:640+shift+5,:)); 108 | tmp_res(shift+1,:) = [mean(tmp_tmp_res(RSNidx_loose(:,1),1)) mean(tmp_tmp_res(RSNidx_loose(:,2),2)) mean(tmp_tmp_res(RSNidx_loose(:,3),3)) mean(tmp_tmp_res(RSNidx_loose(:,4),4)) mean(tmp_tmp_res(RSNidx_loose(:,6),6)) mean(tmp_tmp_res(RSNidx_loose(:,7),7)) mean(tmp_tmp_res(RSNidx_loose(:,8),8)) mean(tmp_tmp_res(RSNidx_loose(:,9),9)) mean(tmp_tmp_res(RSNidx_loose(:,10),10))]; 109 | end 110 | ts_cc_filt(ii+1,9) = max(tmp_res(:)); 111 | ts_cc_filt(ii+1,10) = max(mean(tmp_res')); 112 | 113 | 114 | % Correlation between simulated and empirical FC 115 | static_FC_sim = corr(sim_ts(1+5:640+5,:)); 116 | static_FC_cc(ii+1,1) = corr(static_FC_sim(Isubdiag),static_FCemp(Isubdiag)); 117 | 118 | % same for filtered data 119 | static_FC_sim_filt = corr(simts_filt(1+5:640+5,:)); 120 | static_FC_cc_filt(ii+1,1) = corr(static_FC_sim_filt(Isubdiag),static_FCemp_filt(Isubdiag)); 121 | 122 | end 123 | 124 | sim_res.ts_cc = ts_cc; 125 | sim_res.ts_cc_filt = ts_cc_filt; 126 | sim_res.static_FC_cc = static_FC_cc; 127 | sim_res.static_FC_cc_filt = static_FC_cc_filt; 128 | 129 | 130 | end 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The-Hybrid-Virtual-Brain 2 | 3 | # Update: Please use updated version TVBii_update.c to address numerical instability leading to accumulation of machine precision errors on some machines. In the updated version simple checks were added that re-set the state of synaptic gating back to its plausible range between 0 and 1 if it leaves this range. 4 | 5 | 6 | Quick instructions 7 | 8 | 1. Compile the C code with a compiler with support for SSE instructions enabled. I found the following combination of flags yields good performance (in terms of simulation speed) with the GNU C compiler 9 | 10 | gcc -Wall -std=c99 -msse2 -O3 -ftree-vectorize -ffast-math -funroll-loops -fomit-frame-pointer -m64 -lm TVBii.c -o tvb 11 | 12 | 13 | 2. Create a folder “input” and a folder “output” in the folder where the newly created program binary is stored. 14 | 15 | 16 | 3. Create input files for each subject-specific brain model using the MATLAB script 'generate_input_SC.m' and store them in the folder 'input'. For each subject three input files are required. They contain (i) connection strengths, (ii) connection lengths (unit: mm), and (iii) the node-ids of the connected nodes in files (i) and (ii). The MATLAB script converts structural connectivity from a matrix representation (strengths matrix and delay matrix) into a list format that can be read by the hybrid model program. In addition, the user needs to supply a file of floating point values separated by whitespaces that contains the time series (sampled at 1000 Hz, format: regions x time steps [rows x columns]) that are to be injected into the model populations. These files must also be stored in the folder 'input'. To compute the input time series, the provided [empirical EEG source activity](https://osf.io/mndt8/), which is sampled at 200 Hz, must be upsampled to 1000 Hz using the script [generate_hybrid_model_input.m](https://github.com/BrainModes/The-Hybrid-Virtual-Brain/blob/master/MATLAB/generate_hybrid_model_input.m). Different types of input were considered during the experimental phase of the project (EEG source activity, randomly permutated EEG source activity inputs, temporal differences of source activity, artificial alpha, etc.), for an overwiew see the different cases beginning at line 239 of TVBii.c. The different modes can be switched with the argument shown in the next step. The standard case for source activity injection is case "0" and it expects a file of the format \_fullextinp1000.txt in the 'input' folder. 17 | 18 | 19 | 4. Run the program in the folder from a terminal. The program expects three arguments: 20 | 21 | ./tvb 22 | 23 | : filename of a simple text file (stored in the same folder as ) that contains a sequence of three floating point numbers that specify (in this order). Note that all three floating point values must be written into the first line, each one separated by one whitespace. 24 | * long-range coupling strength parameter G 25 | * inhibitory population input scaling parameter w_BG^I 26 | * and the ratio of inhibitory to excitatory input strengths w_BG^I / w_BG^E (“optimal” ratios w_BG^I / w_BG^E found during parameter space exploration were >1) 27 | 28 | : a string that specifies the prefix of all subject-specific input files (stored in folder ‘./input’ relative to program folder) 29 | 30 | : switches between eight different input files and output folders, see lines 239f of the code. It basically just adds a suffix to the input filename output path folder, for example 31 | 32 | 'input/_fullextinp1000.txt' 33 | 34 | 35 | 5. Outputs are stored in the folder 'output'. Files with prefix 'BOLD_' contain simulated fMRI time series (time x nodes)- Files with prefix 'SV_' contain state variables (time x n * state_variable). Please refer to lines 885 to 923 of the C code for the sorting of state variables. If you perform a large number of simulations, consider commenting out these lines, as the produced state variable files will be very large (several GB per file depending on simulated time). 36 | 37 | 38 | 39 | Questions? michael.schirner@charite.de or petra.ritter@charite.de 40 | --------------------------------------------------------------------------------