├── .gitignore ├── Doxyfile ├── ForExtCurrent ├── Adam_stimulus_mean_curr.m └── ImageProcess_DOG.m ├── LICENSE.md ├── README.md ├── configure.ac ├── cpp.supp ├── cpp_sources ├── ChemSyn.cpp ├── ChemSyn.h ├── MyIO.cpp ├── MyIO.h ├── NeuroNet.cpp ├── NeuroNet.h ├── NeuroPop.cpp ├── NeuroPop.h ├── SimuInterface.cpp ├── SimuInterface.h ├── main.cpp └── mpi_stuff │ ├── mpi_pseudocode │ └── toymodel_mpi.cpp ├── documentation ├── SpikeNet_Documentation.bib ├── SpikeNet_Documentation.pdf ├── SpikeNet_Documentation.tex ├── work_flow.png └── work_flow_white.png ├── m4 ├── ax_cxx_compile_stdcxx.m4 └── ax_lib_hdf5.m4 ├── main_demo.m ├── makefile.in ├── matlab_interface ├── DiscardTransientData.m ├── ReadH5.m ├── ReadYG.m ├── Read_and_save_YGSamp.m ├── ReduceResolution.m ├── ReformatSpikeHistory.m ├── SaveRYG.m ├── appendThisMatlabFileHDF5_example.m ├── new_ygin_files_and_randseedHDF5.m ├── read_syn_h5.m ├── read_ygin_syn.m ├── shuffle_K_common_neighbour.m ├── try_h5read.m ├── writeBasicParaHDF5.m ├── writeChemicalConnectionHDF5.m ├── writeELIFNeuronModelHDF5.m ├── writeExplVarHDF5.m ├── writeExtConductanceSettingsHDF5.m ├── writeExtConductanceTimeVariantSettingsHDF5.m ├── writeExtCurrentPopHDF5.m ├── writeExtCurrentSettingsHDF5.m ├── writeExtCurrentTimeVariantSettingsHDF5.m ├── writeExtCurrentTimeVariantSettingsMultiGroupHDF5.m ├── writeExtInitVHDF5.m ├── writeExtSpikeSettingsHDF5.m ├── writeExtSpikeTinvSettingsHDF5.m ├── writeHeterSpikeFreqAdptHDF5.m ├── writeInhSTDPHDF5.m ├── writeInitCondHDF5.m ├── writeInitVHDF5.m ├── writeJHLearnDirectionHDF5.m ├── writeJHLearnHDF5.m ├── writeLFPRecordHDF5.m ├── writeNeuronSamplingHDF5.m ├── writePerturbationHDF5.m ├── writePoissonPopHDF5.m ├── writePopCovRecordHDF5.m ├── writePopParaHDF5.m ├── writePopSeedHDF5.m ├── writePopStatsRecordHDF5.m ├── writeRealTimeCOMHDF5.m ├── writeRunawayKillerHDF5.m ├── writeSTDHDF5.m ├── writeSpikeFileInputPopHDF5.m ├── writeSpikeFreqAdptHDF5.m ├── writeSynCovRecordHDF5.m ├── writeSynParaHDF5.m ├── writeSynSamplingHDF5.m ├── writeSynStatsRecordHDF5.m └── writeSynapseModelChoiceHDF5.m ├── models ├── generate_learning_config.m ├── main_Chen_and_Gong_2019.m ├── main_Chen_and_Gong_2021.m ├── main_GU_et_al_2018.m ├── main_Keane_and_Gong_2015.m └── main_Qi_and_Gong_2022.m ├── post_processing ├── AnalyseGC_ELIF.m ├── AnalyseYG.m ├── CorrCoefYG.m ├── GCplotSpike_onegrid.m ├── GCplotV_onegrid.m ├── PostProcessGC_ELIF.m ├── PostProcessYG.m ├── RasterGC_ELIF.m ├── SpikeNet2SpikeGrid_spikehist.m ├── SpikeTrainConvolve.m ├── convolve2.m ├── fit_bayesian_bump_2_spikes_circular.m ├── fminsearchbnd.m ├── fminsearchcon.m ├── g_EPSP_conversion.m ├── g_pool_generator.m ├── generate_comments.m ├── generate_commentsGC_ELIF.m ├── get_CC_network.m ├── get_CC_pop.m ├── get_CN_prob.m ├── get_ISI.m ├── get_combinedSpikeHist.m ├── get_g_spike_triggered.m ├── get_grid_firing_centre.m ├── get_initialV.m ├── get_motif.m ├── get_rate.m ├── get_rate_spon_evoked.m ├── get_rich_club.m ├── get_rich_club_stPR_coupling.m ├── get_seg.m ├── get_stPR.m ├── get_stru_var_decomp.m ├── get_structural_variance.m ├── get_susceptibility.m ├── get_triplet_sequence.m ├── get_triplet_sequence_no_latency.m ├── get_up_and_down.m ├── my_logn_rand.m ├── num_spikes_plot.m ├── pairs_sample_from_network.m ├── peak_height_requirement.m ├── persistence_requirement.m ├── raster_marginals_shuffling.m ├── raster_plot.m ├── seq_postprocess.m ├── seq_postprocess_p3.m ├── spike_train_kernel_YG.m └── window_spike_hist_compressed.m ├── shell_scripts ├── GC_all_in_one.sh ├── YG_all_in_one.sh ├── all_in_one.sh.bak ├── ppmat.sh.bak └── repeat_simulations.sh.bak └── simu_config_tools ├── ARBITRARY_DEGREE_NEWMAN.m ├── ARBITRARY_DEGREE_NEWMAN_PRE_POST.m ├── Brian_connectivity_toolbox ├── Koetter_chapter_modified.pdf ├── Measurements │ ├── Modularity │ │ ├── modularity_finetune_dir.m │ │ ├── modularity_finetune_und.m │ │ ├── modularity_louvain_dir.m │ │ ├── modularity_louvain_und.m │ │ ├── modularity_newman_dir.m │ │ └── modularity_newman_und.m │ ├── assortativity_wei.m │ ├── charpath.m │ ├── clustering_coef_wd.m │ ├── degrees_dir.m │ ├── density_dir.m │ ├── distance_wei.m │ ├── jdegree.m │ ├── make_motif34lib.m │ ├── motif3struct_bin.m │ ├── motif3struct_wei.m │ ├── motif4struct_wei.m │ ├── rich_club_wd.m │ └── strengths_dir.m ├── Node Reorder │ ├── align_matrices.m │ ├── reorderMAT.m │ ├── reorder_matrix.m │ └── reorder_mod.m ├── backbone_wu.m ├── breadth.m ├── grid_communities.m ├── makefractalCIJ.m ├── makerandCIJdegreesfixed.m └── rich_club_bd.m ├── GenerateAjacencyMatrix.m ├── GridDM.m ├── Lattice2Lattice.m ├── MIT_Network_Toolbox ├── documentational │ ├── MIT Network toolbox.htm │ └── MIT Network toolbox_files │ │ ├── NGexample.png │ │ ├── circle_draw_example.png │ │ ├── continentalUS.png │ │ ├── dot_matrix_example.png │ │ ├── ga.js │ │ ├── header04.jpg │ │ ├── hexlattice.jpg │ │ ├── logo.gif │ │ ├── radial_plot_example.jpg │ │ ├── random_modular_graph.png │ │ ├── spectral_partitioning_example.png │ │ └── style.css └── original code │ ├── BFS.m │ ├── DoddsWattsSabel.m │ ├── PriceModel.m │ ├── add_edge_weights.m │ ├── adj2adjL.m │ ├── adj2dl.m │ ├── adj2edgeL.m │ ├── adj2inc.m │ ├── adj2pajek.m │ ├── adj2simple.m │ ├── adj2str.m │ ├── adjL2adj.m │ ├── adjL2edgeL.m │ ├── algebraic_connectivity.m │ ├── ave_neighbor_deg.m │ ├── ave_path_length.m │ ├── average_degree.m │ ├── build_smax_graph.m │ ├── canonical_nets.m │ ├── closeness.m │ ├── clust_coeff.m │ ├── degrees.m │ ├── diameter.m │ ├── dijkstra.m │ ├── distance_distribution.m │ ├── dot_matrix_plot.m │ ├── draw_circ_graph.m │ ├── edgeL2adj.m │ ├── edgeL2adjL.m │ ├── edgeL2cyto.m │ ├── edgeL2pajek.m │ ├── edgeL2simple.m │ ├── edge_betweenness.m │ ├── edgelist2dl.m │ ├── eigencentrality.m │ ├── el2geom.m │ ├── exponential_growth_model.m │ ├── fabrikant_model.m │ ├── fiedler_vector.m │ ├── find_conn_comp.m │ ├── forestFireModel.m │ ├── getEdges.m │ ├── getNodes.m │ ├── giant_component.m │ ├── graph_complement.m │ ├── graph_dual.m │ ├── graph_energy.m │ ├── graph_from_degree_sequence.m │ ├── graph_radius.m │ ├── graph_similarity.m │ ├── graph_spectrum.m │ ├── inc2adj.m │ ├── inc2edgeL.m │ ├── isbipartite.m │ ├── iscomplete.m │ ├── isconnected.m │ ├── isdirected.m │ ├── iseulerian.m │ ├── isgraphic.m │ ├── isregular.m │ ├── issimple.m │ ├── istree.m │ ├── isweighted.m │ ├── kmin_neighbors.m │ ├── kneighbors.m │ ├── kregular.m │ ├── laplacian_matrix.m │ ├── leaf_edges.m │ ├── leaf_nodes.m │ ├── license.txt │ ├── link_density.m │ ├── loops3.m │ ├── loops4.m │ ├── louvain_community_finding.m │ ├── master_equation_growth_model.m │ ├── min_span_tree.m │ ├── modularity_metric.m │ ├── multiedges.m │ ├── nested_hierarchies_model.m │ ├── newman_comm_fast.m │ ├── newman_eigenvector_method.m │ ├── newmangastner.m │ ├── newmangirvan.m │ ├── node_betweenness_faster.m │ ├── node_betweenness_slow.m │ ├── num_conn_comp.m │ ├── num_conn_triples.m │ ├── num_loops.m │ ├── num_star_motifs.m │ ├── numedges.m │ ├── numnodes.m │ ├── pajek2adj.m │ ├── pajek2edgeL.m │ ├── pajek2xyz.m │ ├── pdf_cdf_rank.m │ ├── pearson.m │ ├── preferential_attachment.m │ ├── purge.m │ ├── radial_plot.m │ ├── random_directed_graph.m │ ├── random_graph.m │ ├── random_modular_graph.m │ ├── rewire.m │ ├── rewire_assort.m │ ├── rewire_disassort.m │ ├── rich_club_metric.m │ ├── s_metric.m │ ├── selfloops.m │ ├── shortest_pathDP.m │ ├── simple_dijkstra.m │ ├── simple_spectral_partitioning.m │ ├── smooth_diameter.m │ ├── sort_nodes_by_max_neighbor_degree.m │ ├── sort_nodes_by_sum_neighbor_degrees.m │ ├── str2adj.m │ ├── subgraph.m │ ├── symmetrize.m │ ├── symmetrize_edgeL.m │ ├── tarjan.m │ ├── test_all_functions.m │ ├── vertex_eccentricity.m │ └── weighted_clust_coeff.m ├── MyRandomGraphGenerator.m ├── degree2stub.m ├── dirclustercoeffs.m ├── generate_IJ_2D.m ├── generate_graph_given_in_out_degree.m ├── hybrid_degree.m ├── inverse_pool.m ├── lattice_nD.m ├── lattice_nD_find_dist.m ├── poissrnd_2D.m ├── quasi_lattice_2D.m ├── rand_unique_pairs.m └── uni_bi_connect_prob.m /.gitignore: -------------------------------------------------------------------------------- 1 | 2 2 | *.asv 3 | *.mat 4 | makefile 5 | *.o 6 | *~ 7 | documentation/ 8 | *.7z 9 | *.dmg 10 | *.gz 11 | *.iso 12 | *.jar 13 | *.rar 14 | *.tar 15 | *.zip 16 | .DS_Store 17 | 18 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_INIT() 2 | 3 | dnl Switch to a C++ compiler, and check if it works. 4 | AC_LANG(C++) 5 | AC_PROG_CXX 6 | 7 | dnl Neet to check std=c++11 8 | dnl Check for HDF5 support 9 | AC_CONFIG_MACRO_DIR([m4]) 10 | m4_include([m4/ax_lib_hdf5.m4]) 11 | AX_LIB_HDF5([serial]) 12 | if test "$with_hdf5" = "no"; then 13 | AC_MSG_ERROR([Unable to find HDF5, we need serial HDF5.]) 14 | fi 15 | 16 | dnl TEST_AND_SET_CXXFLAG(flag, [program]) 17 | dnl 18 | dnl This attempts to compile a program with a certain compiler flag. 19 | dnl If no program is given, then the minimal C++ program is compiled, and 20 | dnl this tests just the validity of the compiler flag. 21 | dnl 22 | define([TEST_AND_SET_CXXFLAG],[ 23 | AC_MSG_CHECKING([if compiler flag $1 works]) 24 | 25 | dnl Store the current CXXFLAGS 26 | save_CXXFLAGS="$CXXFLAGS" 27 | 28 | dnl Append the flag of interest 29 | CXXFLAGS="$CXXFLAGS $1" 30 | 31 | dnl Create an M4 macro, "prog", which expands to a C++ program. 32 | dnl This should either be a default one or the one specified. 33 | dnl Note that macros are not local, but there is a stack so push 34 | dnl the definition on to the stack to prevent clobbering a definition 35 | dnl that might already exist. 36 | m4_if([$2],[],[pushdef(prog, [int main(){}])], [pushdef(prog, [$2])]) 37 | 38 | flag_test=0 39 | 40 | dnl See if the compiler runs 41 | AC_COMPILE_IFELSE([AC_LANG_SOURCE([prog])], [flag_test=1],[flag_test=0]) 42 | 43 | dnl De-clobber the "prog" macro 44 | popdef([prog]) 45 | 46 | if test $flag_test = 1 47 | then 48 | AC_MSG_RESULT(yes) 49 | else 50 | AC_MSG_RESULT(no) 51 | dnl The flag doesn't work, so restore the old CXXFLAGS 52 | CXXFLAGS="$save_CXXFLAGS" 53 | fi 54 | ]) 55 | 56 | TEST_AND_SET_CXXFLAG(-Wall) 57 | TEST_AND_SET_CXXFLAG(-Wextra) 58 | TEST_AND_SET_CXXFLAG(-W) 59 | TEST_AND_SET_CXXFLAG(-O3) 60 | TEST_AND_SET_CXXFLAG(-g) 61 | 62 | dnl Process Makefile.in to create Makefile 63 | AC_CONFIG_FILES([makefile]) 64 | AC_OUTPUT 65 | 66 | -------------------------------------------------------------------------------- /cpp.supp: -------------------------------------------------------------------------------- 1 | { 2 | 3 | Memcheck:Cond 4 | fun:_platform_memchr$VARIANT$Haswell 5 | fun:__sfvwrite 6 | fun:fwrite 7 | fun:_ZNSt3__111__stdoutbufIcE8overflowEi 8 | fun:_ZNSt3__115basic_streambufIcNS_11char_traitsIcEEE6xsputnEPKcl 9 | fun:_ZNSt3__116__pad_and_outputIcNS_11char_traitsIcEEEENS_19ostreambuf_iteratorIT_T0_EES6_PKS4_S8_S8_RNS_8ios_baseES4_ 10 | fun:_ZNSt3__124__put_character_sequenceIcNS_11char_traitsIcEEEERNS_13basic_ostreamIT_T0_EES7_PKS4_m 11 | fun:_ZNSt3__1lsINS_11char_traitsIcEEEERNS_13basic_ostreamIcT_EES6_PKc 12 | fun:main 13 | } 14 | -------------------------------------------------------------------------------- /cpp_sources/NeuroNet.h: -------------------------------------------------------------------------------- 1 | // header guard at start of header file 2 | #ifndef NEURONET_H 3 | #define NEURONET_H 4 | 5 | #include "ChemSyn.h" 6 | 7 | 8 | using namespace std; 9 | 10 | class NeuroNet{ 11 | public: 12 | NeuroNet(); 13 | NeuroNet(vector N_array, double dt, int step_tot); // parameterised constructor for heterogeneous coupling 14 | 15 | vector N_array; // number of neurons in each pupolation 16 | double dt; // (ms) 17 | int step_tot; // total number of simulation steps 18 | int Num_pop; // number of populations 19 | 20 | vector NeuroPopArray; // array of neuron populations 21 | vector ChemSynArray; // array of chemical synapses: inter-/intra-population connections 22 | 23 | bool runaway_killed; 24 | int step_killed; // initialised as -1 25 | 26 | void update(int step_current); // update the network to current time step, use "virtual" if want override by derived class 27 | 28 | void import_restart(H5File & file, string out_filename); 29 | void export_restart(H5File& file_HDF5, int restart_no); 30 | void output_results(H5File& file_HDF5); 31 | 32 | 33 | 34 | }; 35 | 36 | inline NeuroNet::NeuroNet(){}; 37 | #endif // End guard at bottom of header file 38 | 39 | -------------------------------------------------------------------------------- /cpp_sources/SimuInterface.h: -------------------------------------------------------------------------------- 1 | #ifndef SIMUINTERFACE_H 2 | #define SIMUINTERFACE_H 3 | 4 | #include // stringstream is input and output 5 | 6 | 7 | #include "NeuroNet.h" 8 | 9 | using namespace std; 10 | 11 | class SimuInterface{ 12 | public: 13 | SimuInterface(); 14 | NeuroNet network; // use container? 15 | 16 | // Import Network Setup Data 17 | string in_filename; // path+name 18 | ifstream inputfile; // current input file (.ygin or .ygin_syn) 19 | 20 | void simulate(); 21 | 22 | // output data 23 | string output_suffix; // output filename extension (.ygout) 24 | string out_filename; // without suffix 25 | string gen_out_filename(); // generate unique file name using time stamp 26 | 27 | 28 | bool import_restart_HDF5(string in_filename_input); 29 | void export_restart_HDF5(); 30 | // string gen_restart_filename(); 31 | 32 | void output_results_HDF5(); 33 | bool import_HDF5(string in_filename); 34 | 35 | }; 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /cpp_sources/main.cpp: -------------------------------------------------------------------------------- 1 | #include "SimuInterface.h" 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char* argv[]){// arguments should be input file path 6 | cout << "Number of input files: " << argc-1 << endl; 7 | for (int i = 1; i < argc; ++i){ 8 | cout << "Processing input file No." << i << " out of " << argc-1 << "..." << endl; 9 | SimuInterface simulator; 10 | bool success = false; 11 | 12 | string filename = string(argv[i]); 13 | if(filename.substr(filename.find_last_of(".") + 1) == "h5") 14 | { 15 | if(filename.find("restart") != string::npos){ 16 | success = simulator.import_restart_HDF5(argv[i]); 17 | } 18 | else{ 19 | success = simulator.import_HDF5(argv[i]); 20 | } 21 | } 22 | else 23 | { 24 | cout << "Unrecogized input filename extension. " << endl; 25 | } 26 | 27 | if (success){ // return true if import is successful 28 | simulator.simulate(); 29 | cout << "Input file No." << i << " out of " << argc-1 << " processed." << endl; 30 | } 31 | } 32 | cout << "The planet earth is blue and there's nothing I can do." << endl; 33 | return 0; 34 | }; 35 | -------------------------------------------------------------------------------- /documentation/SpikeNet_Documentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/documentation/SpikeNet_Documentation.pdf -------------------------------------------------------------------------------- /documentation/work_flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/documentation/work_flow.png -------------------------------------------------------------------------------- /documentation/work_flow_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/documentation/work_flow_white.png -------------------------------------------------------------------------------- /matlab_interface/ReduceResolution.m: -------------------------------------------------------------------------------- 1 | function Data = ReduceResolution(Data, reduced_step_length) 2 | % Re-format the raw spike history data into natural structure with 3 | % reduced resolution 4 | % Dump relevant fields 5 | Num_pop = Data.Num_pop; 6 | step_tot = Data.step_tot; 7 | N = Data.N; 8 | dt = Data.dt; 9 | spike_hist_compressed = Data.spike_hist_compressed; 10 | num_spikes = Data.num_spikes; 11 | num_ref = Data.num_ref; 12 | 13 | if nargin == 1 14 | reduced_step_length = 10; % (ms) 15 | end 16 | reduced_dt = reduced_step_length*dt; 17 | reduced_step_tot = ceil(step_tot/reduced_step_length); 18 | reduced_spike_hist = cell(Num_pop,1); 19 | reduced_num_spikes = cell(Num_pop,1); 20 | reduced_num_ref = cell(Num_pop,1); 21 | 22 | for pop_ind = 1:Num_pop 23 | %if nnz(num_spikes{pop_ind}) > 0 24 | reduced_num_spikes_temp = [num_spikes{pop_ind} zeros(1, reduced_step_tot*reduced_step_length-step_tot)]; % padding 25 | reduced_num_spikes_temp = sum(reshape(reduced_num_spikes_temp, reduced_step_length, reduced_step_tot),1); 26 | reduced_T_ind_full = cell2mat(arrayfun(@(x, y) repmat(x, [1 y]), 1:reduced_step_tot, reduced_num_spikes_temp, 'UniformOutput', false)); 27 | reduced_spike_hist{pop_ind} = sparse(spike_hist_compressed{pop_ind}, reduced_T_ind_full, true(size(reduced_T_ind_full)), N(pop_ind), reduced_step_tot); 28 | reduced_num_spikes{pop_ind} = full(sum(reduced_spike_hist{pop_ind},1)); 29 | reduced_num_ref{pop_ind} = num_ref{pop_ind}(round(linspace(1,step_tot,reduced_step_tot))); % down-sampling 30 | %end 31 | end 32 | 33 | Data.reduced.dt = reduced_dt; 34 | Data.reduced.step_tot = reduced_step_tot; 35 | Data.reduced.spike_hist = reduced_spike_hist; 36 | Data.reduced.num_spikes = reduced_num_spikes; 37 | Data.reduced.num_ref = reduced_num_ref; 38 | 39 | end -------------------------------------------------------------------------------- /matlab_interface/ReformatSpikeHistory.m: -------------------------------------------------------------------------------- 1 | function Data = ReformatSpikeHistory(Data) 2 | % Re-format the raw (compressed) spike history data into natural structure 3 | % (logical sparse matrix) 4 | % Dump relevant fields 5 | Num_pop = Data.Num_pop; 6 | step_tot = Data.step_tot; 7 | N = Data.N; 8 | spike_hist = Data.spike_hist; 9 | num_spikes = Data.num_spikes; 10 | 11 | % Re-format the raw spike history data into natural structure 12 | spike_hist_natural = cell(Num_pop,1); 13 | for pop_ind = 1:Num_pop 14 | if nnz(num_spikes{pop_ind}) > 0 15 | T_ind_full = cell2mat(arrayfun(@(x, y) repmat(x, [1 y]), 1:step_tot, num_spikes{pop_ind}, 'UniformOutput', false)); 16 | spike_hist_natural{pop_ind} = sparse(spike_hist{pop_ind}, T_ind_full, true(size(T_ind_full)), N(pop_ind), step_tot); 17 | else 18 | spike_hist_natural{pop_ind} = sparse(false(N(pop_ind), step_tot)); 19 | end 20 | end 21 | Data.spike_hist_compressed = Data.spike_hist; 22 | Data.spike_hist = spike_hist_natural; % overwrite spike history data (logical sparse matrix) 23 | end -------------------------------------------------------------------------------- /matlab_interface/SaveRYG.m: -------------------------------------------------------------------------------- 1 | function SaveRYG( Result_cell ) 2 | %This function saves Result_cell as explanatory and response 3 | %variables to .mat file 4 | % Detailed explanation goes here 5 | 6 | Result_num = length(Result_cell); 7 | for r_num = 1:Result_num 8 | R_temp = Result_cell{r_num}; 9 | name_temp = strcat( Result_cell{r_num}.stamp, '_RYG.mat'); 10 | fprintf('Saving results into file %s...\n', name_temp); 11 | save(name_temp, '-struct', 'R_temp', '-v7.3'); % -v7.3 for >2GB 12 | end 13 | disp('Saving done.') 14 | 15 | end 16 | 17 | -------------------------------------------------------------------------------- /matlab_interface/appendThisMatlabFileHDF5_example.m: -------------------------------------------------------------------------------- 1 | function appendThisMatlabFileHDF5_example(FID) 2 | 3 | % % need to coopy and past the following code into the file to be appended! 4 | % text = fileread([mfilename('fullpath'),'.m']); 5 | % hdf5write(FID,['/config/MATLAB/config.m'],text,'WriteMode','append'); 6 | 7 | end -------------------------------------------------------------------------------- /matlab_interface/new_ygin_files_and_randseedHDF5.m: -------------------------------------------------------------------------------- 1 | function [name] = new_ygin_files_and_randseedHDF5(loop_num) 2 | 3 | 4 | % Creat ygin file 5 | % using loop_num in filename to ensure unique naming! 6 | % Otherwise overwriting may occur when using PBS. 7 | date_now = datestr(now,'yyyymmddHHMM-SSFFF'); 8 | name = [ sprintf('%04g-', loop_num), date_now ]; 9 | name=[name,'_in.h5']; 10 | 11 | fprintf('Data file name is: \n%s\n', name ); % write the file name to stdout and use "grep ygin" to extract it 12 | 13 | % seed the matlab rand function! The seed is global. 14 | % Be very careful about that!!!!!!!!!!! 15 | scan_temp = textscan(date_now,'%s','Delimiter','-'); 16 | rand_seed = loop_num*10^5+eval(scan_temp{1}{2}); % scan_temp{1}{2} is the SSFFF part 17 | alg='twister'; 18 | rng(rand_seed,alg); % Note that this effect is global! 19 | %NOTE: MATLAB has new h5create and h5write functions but they are less capable (e.g. can't 20 | %write strings, need to create the dataset before writing) so for now use 21 | %the more capable hdf5write function though it may be removed in future 22 | %versions 23 | hdf5write(name,'Original_filename',name); 24 | hdf5write(name,'/MATLAB/rng_seed',rand_seed,'WriteMode','append'); 25 | hdf5write(name,'/MATLAB/rng_alg',alg,'WriteMode','append'); 26 | % h5create(name,'/MATLAB/rand_alg',1,alg); 27 | 28 | fprintf('Random number generator seed is: %f\n', rand_seed ); 29 | 30 | end -------------------------------------------------------------------------------- /matlab_interface/read_syn_h5.m: -------------------------------------------------------------------------------- 1 | function [syn_cell] = read_syn_h5(FID, pop_ind_pre, pop_ind_post, syn_type) 2 | % refer to the function writeChemicalConnectionHDF5 3 | 4 | 5 | % find match 6 | pop_ind_pre = pop_ind_pre - 1; % from matlab to c++ index 7 | pop_ind_post = pop_ind_post - 1; 8 | syn_type = syn_type - 1; 9 | 10 | n_syns = h5read(FID,'/config/syns/n_syns'); 11 | n_match = NaN; 12 | for n = (1:n_syns)-1 13 | try 14 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 15 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 16 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 17 | 18 | if pop_ind_pre == i_pre && pop_ind_post == j_post && syn_type == type 19 | n_match = n; 20 | end 21 | catch ME 22 | end 23 | end 24 | 25 | % read data 26 | if isnan(n_match) 27 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post and syn_type!') 28 | else 29 | syn.I = try_h5read(FID,['/config/syns/syn',num2str(n_match),'/INIT006/I']) + 1; 30 | syn.J = try_h5read(FID,['/config/syns/syn',num2str(n_match),'/INIT006/J']) + 1; 31 | syn.K = try_h5read(FID,['/config/syns/syn',num2str(n_match),'/INIT006/K']); 32 | syn.D = try_h5read(FID,['/config/syns/syn',num2str(n_match),'/INIT006/D']); 33 | end 34 | 35 | syn_cell = {syn}; 36 | 37 | end -------------------------------------------------------------------------------- /matlab_interface/read_ygin_syn.m: -------------------------------------------------------------------------------- 1 | function [syn_cell] = read_ygin_syn(filename, pop_pre, pop_post) 2 | % refer to the function writeChemicalConnection 3 | 4 | syn_cell = {}; 5 | 6 | FID = fopen(filename,'r'); 7 | 8 | while ~feof(FID) 9 | tline = fgetl(FID); 10 | if isempty(tline) 11 | continue; 12 | elseif strcmp(tline(1), '>') 13 | 14 | if strfind(tline,'INIT006') % fprintf(FID, '%s\n', '> INIT006'); 15 | tline = fgetl(FID); 16 | scan_temp = textscan(tline,'%f','Delimiter',','); 17 | syn.type = scan_temp{1}(1)+1; % be careful here! 18 | syn.pop_pre = scan_temp{1}(2)+1; % be careful here! 19 | syn.pop_post = scan_temp{1}(3)+1; % be careful here! 20 | 21 | if syn.pop_pre == pop_pre && syn.pop_post == pop_post 22 | fprintf('\t Reading connectivity from pop %d to pop %d...\n', syn.pop_pre, syn.pop_post); 23 | 24 | tline = fgetl(FID); 25 | scan_temp = textscan(tline,'%f','Delimiter',','); 26 | syn.I = scan_temp{1} + 1; 27 | 28 | tline = fgetl(FID); 29 | scan_temp = textscan(tline,'%f','Delimiter',','); 30 | syn.J = scan_temp{1} + 1; 31 | 32 | tline = fgetl(FID); 33 | scan_temp = textscan(tline,'%f','Delimiter',','); 34 | syn.K = scan_temp{1}; 35 | 36 | tline = fgetl(FID); 37 | scan_temp = textscan(tline,'%f','Delimiter',','); 38 | syn.D = scan_temp{1}; 39 | 40 | if isempty(syn_cell) 41 | syn_cell = {syn}; 42 | else 43 | syn_cell = [syn_cell, syn]; 44 | end 45 | 46 | end 47 | 48 | 49 | end 50 | 51 | end 52 | end 53 | 54 | fclose(FID); 55 | 56 | 57 | end -------------------------------------------------------------------------------- /matlab_interface/try_h5read.m: -------------------------------------------------------------------------------- 1 | 2 | function r = try_h5read(file, dataset_name) 3 | r = []; 4 | try 5 | r = h5read(file, dataset_name); 6 | catch ME 7 | switch ME.identifier 8 | case 'MATLAB:imagesci:h5read:libraryError' 9 | otherwise 10 | rethrow(ME) 11 | end 12 | 13 | end 14 | end -------------------------------------------------------------------------------- /matlab_interface/writeBasicParaHDF5.m: -------------------------------------------------------------------------------- 1 | function writeBasicParaHDF5(FID, dt, step_tot, N, modify) 2 | % write basic parameters 3 | % FID: file id for writing data 4 | % dt: time step size in ms 5 | % step_tot: total number of simulation steps 6 | % N: vector for number of neurons in each population 7 | 8 | 9 | if nargin == 4 10 | modify = 0; 11 | end 12 | 13 | if modify == 0 14 | h5create(FID,'/config/Net/INIT001/N', length(N)); 15 | h5create(FID,'/config/Net/INIT002/dt', 1); 16 | h5create(FID,'/config/Net/INIT002/step_tot', 1); 17 | end 18 | 19 | % hdf5write(FID,'/config/Net/INIT001/N', N, 'WriteMode', 'append'); 20 | % hdf5write(FID,'/config/Net/INIT002/dt',dt, 'WriteMode', 'append'); 21 | % hdf5write(FID,'/config/Net/INIT002/step_tot', step_tot, 'WriteMode', 'append'); 22 | 23 | h5write(FID,'/config/Net/INIT001/N', N); 24 | h5write(FID,'/config/Net/INIT002/dt', dt); 25 | h5write(FID,'/config/Net/INIT002/step_tot', step_tot); 26 | 27 | 28 | 29 | 30 | 31 | end 32 | 33 | -------------------------------------------------------------------------------- /matlab_interface/writeELIFNeuronModelHDF5.m: -------------------------------------------------------------------------------- 1 | function writeELIFNeuronModelHDF5(FID,pop,ELIF_VT,ELIF_delT) 2 | % FID: file id for writing data 3 | % pop: the population number 4 | % type: type of neuron model (0=LIF, 1 = Exponential LIF) 5 | % ELIF_VT: Exponential integrate and Fire threshold 6 | % ELIF_delT: Exponential integrate and FIre spiking slope factor 7 | 8 | 9 | 10 | type=1; %this specifies elif 11 | 12 | 13 | hdf5write(FID,['/config/pops/pop',num2str(pop-1),'/neuron_model'],int32(type),'WriteMode','append'); 14 | 15 | if type==1 16 | hdf5write(FID,['/config/pops/pop',num2str(pop-1),'/ELIF/ELIF_VT'],ELIF_VT,'WriteMode','append'); 17 | hdf5write(FID,['/config/pops/pop',num2str(pop-1),'/ELIF/ELIF_delT'],ELIF_delT,'WriteMode','append'); 18 | end 19 | 20 | -------------------------------------------------------------------------------- /matlab_interface/writeExplVarHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExplVarHDF5(FID, varargin) 2 | 3 | % check input 4 | var_num = length(varargin)/2; 5 | if mod(var_num,1) ~= 0 6 | disp('wrong PopPara input format!\n') 7 | disp('var_num: ');disp(var_num); 8 | else 9 | 10 | para_str = []; 11 | for i = 1:var_num 12 | para_str = [para_str, varargin{i*2-1}, ',' , num2str(varargin{i*2}), ',']; %#ok 13 | end 14 | 15 | hdf5write(FID,'/config/explanatory_variables', para_str,'WriteMode','append'); 16 | end 17 | 18 | end 19 | 20 | -------------------------------------------------------------------------------- /matlab_interface/writeExtConductanceSettingsHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtConductanceSettingsHDF5(FID, pop_ind, mean, std, modify) 2 | % write external Conductance settings 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % mean: mean value for Gaussian conductance (uS) for each neuron 6 | % std: std for Gaussian conductance (uS) for each neuron 7 | 8 | if length(mean) == 1 || length(std) == 1 9 | warning('INIT012: MEAN and STD must be specified for each neuron.') 10 | end 11 | 12 | pop_ind = pop_ind - 1; 13 | 14 | if nargin == 4 15 | modify = 0; 16 | end 17 | 18 | if modify == 0 19 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT012/mean'],length(mean)); 20 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT012/std'],length(std)); 21 | end 22 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT012/mean'],mean); 23 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT012/std'],std); 24 | end 25 | 26 | -------------------------------------------------------------------------------- /matlab_interface/writeExtConductanceTimeVariantSettingsHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtConductanceTimeVariantSettingsHDF5(FID, pop_ind, mean, std, mean_TV, std_TV, modify) 2 | % write external Conductance settings 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % mean: mean value for Gaussian conductance (uS) for each neuron 6 | % std: std for Gaussian conductance (uS) for each neuron 7 | % mean_TV: a time-variant factor multiplied to the mean value for Gaussian currents (nA) for each neuron 8 | % mean_std: a time-variant factor multiplied to the std value for Gaussrian currents for each neuron 9 | % modify: whether this is for modifying existing HDF5 file content or not 10 | % 11 | % Explanation: For neuron i, at time step t, the external conductance will be a Gaussian random number with a mean of mean[i]*mean_TV[t] and a std of std[i]*std_TV[t] 12 | 13 | if length(mean) == 1 || length(std) == 1 14 | warning('INIT004 has been updated. MEAN and STD must be specified for each neuron.') 15 | end 16 | 17 | pop_ind = pop_ind - 1; 18 | 19 | if nargin == 6 20 | modify = 0; 21 | end 22 | 23 | if modify == 0 24 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/mean'],length(mean)); 25 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/std'],length(std)); 26 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/mean_TV'],length(mean_TV)); 27 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/std_TV'],length(std_TV)); 28 | end 29 | 30 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/mean'],mean); 31 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/std'],std); 32 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/mean_TV'],mean_TV); 33 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT018/std_TV'],std_TV); 34 | 35 | end 36 | 37 | -------------------------------------------------------------------------------- /matlab_interface/writeExtCurrentSettingsHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtCurrentSettingsHDF5(FID, pop_ind, mean, std, modify) 2 | % write external current settings 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % mean: mean value for Gaussian currents (nA) for each neuron 6 | % std: std for Gaussrian currents for each neuron 7 | 8 | if length(mean) == 1 || length(std) == 1 9 | warning('INIT004 has been updated. MEAN and STD must be specified for each neuron.') 10 | end 11 | 12 | pop_ind = pop_ind - 1; 13 | 14 | if nargin == 4 15 | modify = 0; 16 | end 17 | 18 | if modify == 0 19 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT004/mean'],length(mean)); 20 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT004/std'],length(std)); 21 | end 22 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT004/mean'],mean); 23 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT004/std'],std); 24 | 25 | end 26 | 27 | -------------------------------------------------------------------------------- /matlab_interface/writeExtCurrentTimeVariantSettingsHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtCurrentTimeVariantSettingsHDF5(FID, pop_ind, mean, std, mean_TV, std_TV, modify) 2 | % write external current settings with time-variant factors 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % mean: mean value for Gaussian currents (nA) for each neuron 6 | % std: std for Gaussrian currents for each neuron 7 | % mean_TV: a time-variant factor multiplied to the mean value for Gaussian currents (nA) for each neuron 8 | % std_TV: a time-variant factor multiplied to the std value for Gaussrian currents for each neuron 9 | % modify: whether this is for modifying existing HDF5 file content or not 10 | % 11 | % Explanation: For neuron i, at time step t, the external current will be a Gaussian random number with a mean of mean[i]*mean_TV[t] and a std of std[i]*std_TV[t] 12 | 13 | if length(mean) == 1 || length(std) == 1 14 | warning('INIT004 has been updated. MEAN and STD must be specified for each neuron.') 15 | end 16 | 17 | pop_ind = pop_ind - 1; 18 | 19 | if nargin == 6 20 | modify = 0; 21 | end 22 | 23 | if modify == 0 24 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/mean'],length(mean)); 25 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/std'],length(std)); 26 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/mean_TV'],length(mean_TV)); 27 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/std_TV'],length(std_TV)); 28 | end 29 | 30 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/mean'],mean); 31 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/std'],std); 32 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/mean_TV'],mean_TV); 33 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT014/std_TV'],std_TV); 34 | 35 | end 36 | -------------------------------------------------------------------------------- /matlab_interface/writeExtCurrentTimeVariantSettingsMultiGroupHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtCurrentTimeVariantSettingsMultiGroupHDF5(FID, pop_ind, mean, std, mean_TV, std_TV, TV_group) 2 | % write external current settings with time-variant factors 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % mean: mean value for Gaussian currents (nA) for each neuron 6 | % std: std for Gaussrian currents for each neuron 7 | % mean_TV: a time-variant factor multiplied to the mean value for 8 | % Gaussian currents (nA) for each neuron, 9 | % size: number_of_groups-by-number_of_time_steps 10 | % std_TV: a time-variant factor multiplied to the std value for 11 | % Gaussrian currents for each neuron 12 | % size: number_of_groups-by-number_of_time_steps 13 | % TV_group: the group number of each neuron (for choosing the row in mean_TV and std_TV) 14 | % 15 | % Explanation: For neuron i, at time step t, the external current will be a 16 | % Gaussian random number with a mean of mean[i]*mean_TV[TV_group[i],t] and a std of std[i]*std_TV[TV_group[i],t] 17 | 18 | pop_ind = pop_ind - 1; 19 | if min(TV_group) == 0 20 | error('Group number must start from 1 (matlab indexing).') 21 | end 22 | TV_group = TV_group - 1; 23 | 24 | [n_group, step_tot] = size(mean_TV); 25 | if n_group > step_tot % if the size is not right 26 | error('For multiple groups, use multiple rows.') 27 | else 28 | mean_TV = mean_TV'; % columns 29 | std_TV = std_TV'; % columns 30 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT019/mean_TV'],mean_TV,'WriteMode','append'); 31 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT019/std_TV'],std_TV,'WriteMode','append'); 32 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT019/mean'],mean,'WriteMode','append'); 33 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT019/std'],std,'WriteMode','append'); 34 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT019/TV_group'],TV_group,'WriteMode','append'); 35 | 36 | end 37 | -------------------------------------------------------------------------------- /matlab_interface/writeExtInitVHDF5.m: -------------------------------------------------------------------------------- 1 | function writeExtInitVHDF5(FID,pop,external_init_V, modify) 2 | % write initial condition for membrane potential 3 | % FID: file id for writing data 4 | % pop: is the number of population 5 | % external_init_V: is the vector of initial membrane potential for all neurons 6 | % of this population 7 | 8 | if nargin == 3 9 | modify = 0; 10 | end 11 | 12 | if modify == 0 13 | h5create(FID,['/config/pops/pop',num2str(pop-1),'/SETINITV/external_init_V'], length(external_init_V)); 14 | end 15 | 16 | h5write(FID,['/config/pops/pop',num2str(pop-1),'/SETINITV/external_init_V'],external_init_V); 17 | 18 | end 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /matlab_interface/writeHeterSpikeFreqAdptHDF5.m: -------------------------------------------------------------------------------- 1 | function writeHeterSpikeFreqAdptHDF5(FID, pop_ind, dg_K_heter, start_step, end_step, dg_K) 2 | % write heterogeneous spike-frequency adaptation (SFA) setting for specific 3 | % duration: start_step:end_step 4 | % ref: Alessandro Treves, 1993, Mean-field analysis of neuronal spike dynamics 5 | % FID: file id for writing data 6 | % pop_ind: 7 | % dg_K_heter: heterogeneous dg_K for all neurons (uS=miuSiemens) 8 | %start_step, end_step: the heterogeneous SFA works from start step to end step. 9 | % dg_K: the normal SFA's delta g_k (default value: 0.01 uS) 10 | 11 | % for C/C++ index convetion 12 | pop_ind = pop_ind-1; 13 | start_step = start_step - 1; 14 | end_step = end_step - 1; 15 | 16 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 17 | '/INIT010/spike_freq_adpt'],1,'WriteMode','append'); 18 | 19 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 20 | '/INIT010/dg_K_heter'],dg_K_heter,'WriteMode','append'); 21 | 22 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 23 | '/INIT010/start_step'],start_step,'WriteMode','append'); 24 | 25 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 26 | '/INIT010/end_step'],end_step,'WriteMode','append'); 27 | 28 | if nargin == 6 29 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 30 | '/INIT010/dg_K'],dg_K,'WriteMode','append'); 31 | end 32 | end -------------------------------------------------------------------------------- /matlab_interface/writeInhSTDPHDF5.m: -------------------------------------------------------------------------------- 1 | function writeInhSTDPHDF5(FID, pop_ind_pre, pop_ind_post, inh_STDP_step) 2 | % add inhibitory STDP to connection 3 | % FID: file id for writing data 4 | % pop_ind: 5 | 6 | pop_ind_pre = pop_ind_pre - 1; % from matlab to c++ index 7 | pop_ind_post = pop_ind_post - 1; 8 | 9 | syn_type = 1; % GABA 10 | 11 | n_syns = h5read(FID,'/config/syns/n_syns'); 12 | n_match = NaN; 13 | for n = (1:n_syns)-1 14 | try 15 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 16 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 17 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 18 | 19 | if pop_ind_pre == i_pre && pop_ind_post == j_post && syn_type == type 20 | n_match = n; 21 | end 22 | catch ME 23 | end 24 | end 25 | 26 | 27 | if isnan(n_match) 28 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post and syn_type = GABA!') 29 | else 30 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/INIT009/inh_STDP_on_step'], inh_STDP_step,'WriteMode','append'); 31 | end 32 | 33 | 34 | end 35 | 36 | -------------------------------------------------------------------------------- /matlab_interface/writeInitCondHDF5.m: -------------------------------------------------------------------------------- 1 | function writeInitCondHDF5(FID, r_V0, p_fire) 2 | % write initial condition for membrane potential distribution and firing 3 | % FID: file id for writing data 4 | % r_V0: set init V distribution to be [V_rt, V_rt + (V_th-V_rt)*r_V0] 5 | % p_fire: init firing probability 6 | % 7 | % Note that both r_V0 and p_fire should be a vector (defined for all the 8 | % populations). 9 | 10 | if max(r_V0) > 1 || max(p_fire) > 1 || min(r_V0) < 0 || min(p_fire) < 0 11 | error('r_V0 and p_fire must be within 0 and 1!') 12 | else 13 | for i=1:length(r_V0) 14 | hdf5write(FID,['/config/pops/pop',num2str(i-1),'/INIT011/r_V0'],r_V0(i),'WriteMode','append'); 15 | hdf5write(FID,['/config/pops/pop',num2str(i-1),'/INIT011/p_fire'],p_fire(i),'WriteMode','append'); 16 | end 17 | end 18 | end 19 | 20 | -------------------------------------------------------------------------------- /matlab_interface/writeInitVHDF5.m: -------------------------------------------------------------------------------- 1 | function writeInitVHDF5(FID, p_fire) 2 | % write initial condition for membrane potential distribution 3 | % FID: file id for writing data 4 | % p_fire: initial firing rate for each population (vector, value 0~1) 5 | % 6 | % Note that the membrane potential distributions are uniform and decided by 7 | % the given p_fire 8 | 9 | for i=1:length(p_fire) 10 | hdf5write(FID,['/config/pops/pop',num2str(i-1),'/INIT003/p_fire'],p_fire(i),'WriteMode','append') 11 | end 12 | 13 | end 14 | 15 | -------------------------------------------------------------------------------- /matlab_interface/writeJHLearnDirectionHDF5.m: -------------------------------------------------------------------------------- 1 | function writeJHLearnDirectionHDF5(FID, pop_ind_pre, pop_ind_post, direction) 2 | % add inhibitory STDP to connection 3 | % FID: file id for writing data 4 | % pop_ind: 5 | 6 | pop_ind_pre = pop_ind_pre - 1; % from matlab to c++ index 7 | pop_ind_post = pop_ind_post - 1; 8 | 9 | n_syns = h5read(FID,'/config/syns/n_syns'); 10 | n_match = NaN; 11 | for n = (1:n_syns)-1 12 | try 13 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 14 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 15 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 16 | 17 | if pop_ind_pre == i_pre && pop_ind_post == j_post 18 | n_match = n; 19 | end 20 | catch ME 21 | end 22 | end 23 | 24 | 25 | if isnan(n_match) 26 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post!') 27 | else 28 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/INIT016/direction'],int32(direction),'WriteMode','append'); 29 | 30 | end 31 | 32 | 33 | 34 | end 35 | 36 | -------------------------------------------------------------------------------- /matlab_interface/writeLFPRecordHDF5.m: -------------------------------------------------------------------------------- 1 | function writeLFPRecordHDF5(FID, pop_ind, LFP_neurons) 2 | % write data recording for local field potential 3 | % FID: file id for writing data 4 | % pop_ind: 5 | % LFP_neurons: logical vector that specifies which neurons contribute the 6 | % LFP measure. For multiple LFP measures, use multiple rows. 7 | 8 | 9 | % for C/C++ index convetion 10 | pop_ind = pop_ind-1; 11 | 12 | % write 13 | [n_LFP, N] = size(LFP_neurons); 14 | if n_LFP > N % if the size is not right 15 | warning('For multiple LFP measures, use multiple rows.') 16 | else 17 | LFP_neurons = LFP_neurons'; % columns 18 | % LFP_neurons = LFP_neurons(:); % vectorization 19 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP005/LFP_neurons'],LFP_neurons,'WriteMode','append'); 20 | end 21 | 22 | end -------------------------------------------------------------------------------- /matlab_interface/writePerturbationHDF5.m: -------------------------------------------------------------------------------- 1 | function writePerturbationHDF5(FID, pop_ind, step_perturb) 2 | % write perturbation setting 3 | % FID: file id for writing data 4 | % pop_ind: 5 | % step_perturb: the step where one spike is removed (if there is no spike at this step, then the next step) 6 | 7 | 8 | % for C/C++ index convetion 9 | pop_ind = pop_ind-1; 10 | 11 | % write 12 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/INIT007/step_perturb'],step_perturb,'WriteMode','append'); 13 | 14 | end 15 | 16 | -------------------------------------------------------------------------------- /matlab_interface/writePoissonPopHDF5.m: -------------------------------------------------------------------------------- 1 | function writePoissonPopHDF5(FID, pop_ind, rate) 2 | % This function sets the population pop_ind to be a population 3 | % where each neuron generates a Poisson spike train 4 | % rate is assumed to be in units of spikes per second 5 | 6 | 7 | pop_ind = pop_ind - 1; % from matlab to c++ index 8 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/poisson_pop/rate'],rate,'WriteMode','append'); 9 | 10 | end 11 | 12 | -------------------------------------------------------------------------------- /matlab_interface/writePopCovRecordHDF5.m: -------------------------------------------------------------------------------- 1 | function writePopCovRecordHDF5(FID, pop_ind, time_start, time_end) 2 | 3 | % for C/C++ index convetion 4 | pop_ind = pop_ind-1; 5 | time_start = time_start - 1; 6 | time_end = time_end - 1; 7 | 8 | % write 9 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP103/time_start'],time_start,'WriteMode','append'); 10 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP103/time_end'],time_end,'WriteMode','append'); 11 | 12 | end -------------------------------------------------------------------------------- /matlab_interface/writePopParaHDF5.m: -------------------------------------------------------------------------------- 1 | function writePopParaHDF5(FID, pop_ind, varargin) 2 | % write non-default neuron model parameters 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % varargin: var_name1, var_value1, var_name2, var_value2, ... 6 | % 7 | % For example, writePopPara(FID, 1, "Cm", 1.0, "tau_ref", 3.0) 8 | % 9 | % defualt parameters (using coherent units: msec+mV+nF+miuS+nA) 10 | % Cm = 0.25; % nF 11 | % tau_ref = 2.0; % absolute refractory time (ms), 3.0 12 | % % Potential constants (mV) 13 | % V_rt = -60.0; % Reset, usually same as leak reversal, use -75.0 to model relative refractory period?? 14 | % V_lk = -70.0; % Leak reversal, -70.0 15 | % V_th = -50.0; % Threshold // -55.0 16 | % % Leak conductance 17 | % g_lk = 0.0167; % (miuS), time constants=Cm/gL=15 ms! 18 | % % Reversal potential for external currents 19 | % V_ext = 0.0; % mV 20 | 21 | 22 | % for C/C++ index convetion 23 | pop_ind = pop_ind-1; 24 | 25 | % check input 26 | var_num = length(varargin)/2; 27 | if mod(var_num,1) ~= 0 28 | disp('wrong PopPara input format!\n') 29 | disp('var_num: ');disp(var_num); 30 | else 31 | 32 | para_str = []; 33 | for i = 1:var_num 34 | if strcmp(varargin{i*2-1}, 'V_ext') 35 | warning('Unless you know what you are doing, V_ext should usually be identical to V_ex in SynPara!') 36 | end 37 | para_str = [para_str, varargin{i*2-1}, ',' , num2str(varargin{i*2}), ',']; %#ok 38 | end 39 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/PARA001/para_str_ascii'], double(para_str),'WriteMode','append'); 40 | end 41 | 42 | end 43 | -------------------------------------------------------------------------------- /matlab_interface/writePopSeedHDF5.m: -------------------------------------------------------------------------------- 1 | function writePopSeedHDF5(FID, pop_ind, seed, modify) 2 | % manualy seed RNG seed for this neuron popluation 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % seed: positive integer 6 | % 7 | % For example, writePopPara(FID, 1, 1234) 8 | 9 | if nargin == 3 10 | modify = 0; 11 | end 12 | 13 | % for C/C++ index convetion 14 | pop_ind = pop_ind-1; 15 | 16 | % check input 17 | if mod(seed,1) ~= 0 || seed < 0 18 | disp('The seed should be a positive integer!\n') 19 | else 20 | if modify == 0 21 | h5create(FID,['/config/pops/pop',num2str(pop_ind),'/SEED001/seed'], 1); 22 | end 23 | h5write(FID,['/config/pops/pop',num2str(pop_ind),'/SEED001/seed'], seed); 24 | end 25 | 26 | end 27 | -------------------------------------------------------------------------------- /matlab_interface/writePopStatsRecordHDF5.m: -------------------------------------------------------------------------------- 1 | function writePopStatsRecordHDF5(FID, pop_ind) 2 | 3 | % for C/C++ index convetion 4 | pop_ind = pop_ind-1; 5 | % write 6 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP003/record'],1,'WriteMode','append'); 7 | 8 | end -------------------------------------------------------------------------------- /matlab_interface/writeRealTimeCOMHDF5.m: -------------------------------------------------------------------------------- 1 | function writeRealTimeCOMHDF5(FID, pop_ind, data_type, time_index) 2 | % write real-time center-of-mass recording settings for specific time points 3 | % FID: file id for writing data 4 | % pop_ind: neuron population index 5 | % data_type: logical vector for [V,I] 6 | % time_index: logical vector to define time points to be sampled 7 | % 8 | % For example, if V and I are needed, use data_type = [1,1] 9 | % 10 | % Note that time_index should have the length of total simulation steps. 11 | % For example, if step_tot = 10 and the last half time points are to be 12 | % sampled, use time_index = [0,0,0,0,0,1,1,1,1,1,0] 13 | % 4,000 neurons x 10,000 time points will be 300MB data 14 | 15 | 16 | % if sum((time_index ~= 0) & (time_index ~= 1)) ~= 0 17 | % error('sample_time_index must be logical vectors: '); 18 | % end 19 | 20 | % for C/C++ index convetion 21 | pop_ind = pop_ind-1; 22 | if sum((data_type ~= 0) & (data_type ~= 1)) ~= 0 23 | error('Data_type must be logical vectors: '); 24 | end 25 | 26 | if length(data_type) < 2 27 | error('data_type must have a length of at least 2.') 28 | end 29 | 30 | % sampling frequency check 31 | dt = hdf5read(FID,'/config/Net/INIT002/dt'); 32 | freq_s = 1000 / (mode(diff(find(time_index)))*dt); 33 | if freq_s < 1000 34 | warning('You are assuming the Nyquist frequency of the system is lower than %g Hz. /n', freq_s); 35 | end 36 | 37 | % write 38 | % fprintf(FID, '%s\n', '# neuronal membrane potential and currents sampling setting // pop_ind;sample_ind'); 39 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP006/data_type/V_flag'],data_type(1),'WriteMode','append'); 40 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP006/data_type/I_flag'],data_type(2),'WriteMode','append'); 41 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/SAMP006/time_points'],time_index,'WriteMode','append'); 42 | end 43 | -------------------------------------------------------------------------------- /matlab_interface/writeRunawayKillerHDF5.m: -------------------------------------------------------------------------------- 1 | function writeRunawayKillerHDF5(FID, pop_ind, min_ms, runaway_Hz, Hz_ms) 2 | % write runaway activity killer 3 | % FID: file id for writing data 4 | % min_ms: minimum simulation time before it can be killed 5 | % runaway_Hz: the threshold defines runaway activity 6 | % Hz_ms: the time window over which the populational firing rate 7 | % is estimated and compared with runaway_Hz 8 | % 9 | % So if any neuron population's activity exceeds the threshold define by 10 | % (runaway_Hz,Hz_ms), the simulation will be killed. 11 | % Note that only those populations with (by defualt) >100 neurons will be 12 | % considered. 13 | 14 | % for C/C++ index convetion 15 | pop_ind = pop_ind-1; 16 | 17 | 18 | %fprintf(FID, '%s\n', '# runaway killer setting //runaway_steps, runaway_mean_num_ref(0~1),'); 19 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/KILL001/min_ms'],min_ms,'WriteMode','append'); 20 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/KILL001/runaway_Hz'],runaway_Hz,'WriteMode','append'); 21 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),'/KILL001/Hz_ms'],Hz_ms,'WriteMode','append'); 22 | end -------------------------------------------------------------------------------- /matlab_interface/writeSTDHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSTDHDF5(FID, pre_pop_ind, post_pop_ind, STD_step) 2 | % add STD to connection 3 | % FID: file id for writing data 4 | % pop_ind: 5 | 6 | pre_pop_ind = pre_pop_ind - 1; % from matlab to c++ index 7 | post_pop_ind = post_pop_ind - 1; 8 | 9 | syn_type = 0; % AMPA 10 | 11 | 12 | n_syns = h5read(FID,'/config/syns/n_syns'); 13 | n_match = NaN; 14 | for n = (1:n_syns)-1 % c++ index 15 | try 16 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 17 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 18 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 19 | 20 | if pre_pop_ind == i_pre && post_pop_ind == j_post && syn_type == type 21 | n_match = n; 22 | end 23 | catch ME 24 | end 25 | end 26 | 27 | 28 | if isnan(n_match) 29 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post and syn_type == AMPA!') 30 | else 31 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/INIT008/STD_on_step'], STD_step,'WriteMode','append'); 32 | end 33 | 34 | end 35 | 36 | -------------------------------------------------------------------------------- /matlab_interface/writeSpikeFreqAdptHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSpikeFreqAdptHDF5(FID, pop_ind, dg_K) 2 | % write spike-frequency adaptation setting 3 | % ref: Alessandro Treves, 1993, Mean-field analysis of neuronal spike dynamics 4 | % FID: file id for writing data 5 | % pop_ind: 6 | % dg_K: default value 0.01 (uS=miuSiemens) 7 | 8 | % for C/C++ index convetion 9 | pop_ind = pop_ind-1; 10 | 11 | 12 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 13 | '/INIT010/spike_freq_adpt'],1,'WriteMode','append'); 14 | 15 | if nargin == 3 16 | hdf5write(FID,['/config/pops/pop',num2str(pop_ind),... 17 | '/INIT010/dg_K'],dg_K,'WriteMode','append'); 18 | end 19 | 20 | end 21 | 22 | -------------------------------------------------------------------------------- /matlab_interface/writeSynCovRecordHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSynCovRecordHDF5(FID, pop_ind_pre, pop_ind_post, syn_type, time_start, time_end) 2 | 3 | % for C/C++ index convetion 4 | pop_ind_pre = pop_ind_pre-1; 5 | pop_ind_post = pop_ind_post-1; 6 | syn_type = syn_type-1; 7 | 8 | n_syns = h5read(FID,'/config/syns/n_syns'); 9 | n_match = NaN; 10 | for n = (1:n_syns)-1 11 | try 12 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 13 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 14 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 15 | 16 | if pop_ind_pre == i_pre && pop_ind_post == j_post && syn_type == type 17 | n_match = n; 18 | end 19 | catch ME 20 | end 21 | end 22 | 23 | if isnan(n_match) 24 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post and syn_type!') 25 | else 26 | time_start = time_start - 1; 27 | time_end = time_end - 1; 28 | % write 29 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/SAMP104/time_start'],time_start,'WriteMode','append'); 30 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/SAMP104/time_end'],time_end,'WriteMode','append'); 31 | 32 | end 33 | 34 | end -------------------------------------------------------------------------------- /matlab_interface/writeSynParaHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSynParaHDF5(FID, varargin) 2 | % write non-default synapse parameters 3 | % FID: file id for writing data 4 | % varargin: var_name1, var_value1, var_name2, var_value2, ... 5 | % 6 | % For example, writeSynPara(FID, "V_ex", 1.0, "V_in", -85.0) 7 | % 8 | % defualt parameters (using coherent units: msec+mV+nF+miuS+nA) 9 | % % Potential constants (mV) 10 | % V_ex = 0.0; % Excitatory reversal, 0.0 11 | % V_in = -80.0; % Inhibitory reversal, -80.0 12 | % % time-evolution of post-synaptic conductance change 13 | % Dt_trans_AMPA = 1.0; % 0.5 14 | % Dt_trans_GABA = 1.0; % 1.0 15 | % Dt_trans_NMDA = 5.0; % 5.0 16 | % tau_decay_AMPA = 5.0; % 3.0 17 | % tau_decay_GABA = 5.0; % 7.0 18 | % tau_decay_NMDA = 80.0; % 80.0 19 | 20 | 21 | % check input 22 | var_num = length(varargin)/2; 23 | if mod(var_num,1) ~= 0 24 | disp('wrong SynPara input format!\n') 25 | disp('var_num: ');disp(var_num); 26 | else 27 | 28 | para_str = []; 29 | for i = 1:var_num 30 | if strcmp(varargin{i*2-1}, 'V_ex') 31 | warning('Unless you know what you are doing, V_ex should usually be identical to V_ext in PopPara!') 32 | end 33 | para_str = [para_str, varargin{i*2-1}, ',' , num2str(varargin{i*2}), ',']; %#ok 34 | end 35 | hdf5write(FID,'/config/syns/PARA002/para_str_ascii', double(para_str),'WriteMode','append'); 36 | end 37 | 38 | 39 | end 40 | -------------------------------------------------------------------------------- /matlab_interface/writeSynStatsRecordHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSynStatsRecordHDF5(FID, pop_ind_pre, pop_ind_post, syn_type) 2 | 3 | % for C/C++ index convetion 4 | pop_ind_pre = pop_ind_pre-1; 5 | pop_ind_post = pop_ind_post-1; 6 | syn_type = syn_type-1; 7 | 8 | n_syns = h5read(FID,'/config/syns/n_syns'); 9 | n_match = NaN; 10 | for n = (1:n_syns)-1 11 | try 12 | type = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/type']); 13 | i_pre = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/i_pre']); 14 | j_post = hdf5read(FID,['/config/syns/syn',num2str(n),'/INIT006/j_post']); 15 | 16 | if pop_ind_pre == i_pre && pop_ind_post == j_post && syn_type == type 17 | n_match = n; 18 | end 19 | catch ME 20 | end 21 | end 22 | 23 | if isnan(n_match) 24 | error('Cannot find syn with identical pop_ind_pre, pop_ind_post and syn_type!') 25 | else 26 | hdf5write(FID,['/config/syns/syn',num2str(n_match),'/SAMP004/record'], 1,'WriteMode','append'); 27 | end 28 | 29 | end -------------------------------------------------------------------------------- /matlab_interface/writeSynapseModelChoiceHDF5.m: -------------------------------------------------------------------------------- 1 | function writeSynapseModelChoiceHDF5(FID, model_choice) 2 | % writeSynapseModelChoice(FID, model_choice) 3 | % model_choice = 1: See Gu, Yifan, Gong, Pulin, 2016, The dynamics of 4 | % memory retrieval in hierarchical networks: a modeling study 5 | % model_choice = 2: See Keane, A., Gong, P., 2015, Propagating Waves Can 6 | % Explain Irregular Neural Dynamics 7 | 8 | 9 | if model_choice <= 0 || mod(model_choice, 1) ~= 0 10 | warning('model_choise must be an positive integer!') 11 | elseif model_choice ~= 1 % 1 is default, no need to change it 12 | model_choice = model_choice-1; % for C/C++ index convetion 13 | hdf5write(FID,'/config/syns/INIT013/model_choice',model_choice,'WriteMode','append'); 14 | end 15 | 16 | end -------------------------------------------------------------------------------- /post_processing/CorrCoefYG.m: -------------------------------------------------------------------------------- 1 | function [ CC, RateA, RateB ] = CorrCoefYG( SpikeTrainA, SpikeTrainB, kernel, time_series ) 2 | %UNTITLED Summary of this function goes here 3 | % Detailed explanation goes here 4 | % 5 | % SpikeTrainA/B is two sparse logical row vectors, coloumn index is time step 6 | % [0 0 1 1 1 0 1 0 0 0; 7 | % 1 0 0 0 0 0 1 0 0 0] 8 | % 9 | % Kernel is row vector, column index is time step, e.g. 10 | % [0.1 0.2 0.4 0.2 0.1] 11 | % -2dt -dt 0 +dt +2dt 12 | % 13 | % TestCorrCoefYG.m: 14 | % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 15 | % SpikeLength = 10^6; 16 | % SpikeNum = 10^2; 17 | % kernelLength = 10^2; 18 | % 19 | % SpikeTrainA = sparse(1, SpikeLength); 20 | % SpikeTrainA(randperm(SpikeLength,SpikeNum)) = true; 21 | % 22 | % SpikeTrainB = sparse(1, SpikeLength); 23 | % SpikeTrainB(randperm(SpikeLength,SpikeNum)) = true; 24 | % 25 | % kernel = ones(1,kernelLength)/kernelLength; 26 | % 27 | % tic; 28 | % [ CC ] = CorrCoefYG( SpikeTrainA, SpikeTrainB, kernel ) 29 | % toc; 30 | % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 31 | 32 | kernel = kernel(:)'; % row vector 33 | 34 | if length(kernel) == 1 && kernel(1) == 0 % no kernel required 35 | RateA = SpikeTrainA; 36 | RateB = SpikeTrainB; 37 | else 38 | RateA = SpikeTrainConvolve(SpikeTrainA, kernel); 39 | RateB = SpikeTrainConvolve(SpikeTrainB, kernel); 40 | end 41 | 42 | 43 | 44 | if nargin == 3 || (nargin == 4 && time_series == 0) % 45 | CC = COV(RateA,RateB)/sqrt(COV(RateA,RateA)*COV(RateB,RateB)); 46 | % CC_matlab = corrcoef([RateA(:) RateB(:)]) 47 | elseif nargin == 4 && time_series == 1 % return the time series 48 | CC = (RateA-mean(RateA)).*(RateB-mean(RateB))/sqrt(COV(RateA,RateA)*COV(RateB,RateB)); 49 | end 50 | 51 | 52 | end 53 | 54 | % Covariance 55 | function out = COV(V1,V2) 56 | out = mean(V1.*V2)-mean(V1)*mean(V2); 57 | % note that cov(x,x) = std(x)^2 = variance(x) 58 | end 59 | -------------------------------------------------------------------------------- /post_processing/GCplotSpike_onegrid.m: -------------------------------------------------------------------------------- 1 | function GCplotSpike_onegrid(Result_cell) 2 | 3 | % record the video of membrane potential dynamics 4 | disp('GCplotSpike...'); 5 | Result_num = length(Result_cell); 6 | for r_num = 1:Result_num 7 | R = Result_cell{r_num}; 8 | Num_neu = R.N; 9 | % Num_pop = R.Num_pop; 10 | spike_hist = R.Analysis.spike_hist_combined; 11 | file_name = R.stamp(1:end-3); 12 | gridsize = sqrt(sum(Num_neu)); 13 | 14 | % set the figure invisible, so one can run it without GUI 15 | figure('NumberTitle', 'off','Name','membrane potential', 'visible', 'off'); 16 | clf 17 | % hold off 18 | video1 = VideoWriter([file_name,'_S.avi'],'Motion JPEG AVI'); 19 | video1.FrameRate = 15; 20 | video1.Quality = 50; 21 | open(video1); 22 | % input_file = h5read([R.stamp(1:end-18),'.h5'],'/config/pops/pop0/file_current_input/fname'); 23 | % start_step = h5read(input_file,'start_step')-200; 24 | % end_step = h5read(input_file,'start_step')+200; 25 | start_step = 10000; 26 | end_step = 22000; 27 | step = 10; 28 | for i=start_step:step:end_step 29 | grid = reshape(spike_hist(:,i),gridsize,gridsize); 30 | [y,x] = find(grid); 31 | scatter(x,abs(gridsize-y),'k.'); 32 | axis equal 33 | axis tight 34 | axis([1,gridsize,1,gridsize]); 35 | title(sprintf('Time: %f ms', (start_step + (i-start_step)*step)*R.dt)) 36 | drawnow 37 | vframe = getframe(gcf); 38 | writeVideo(video1,vframe); 39 | % pause(0.5) 40 | % waitforbuttonpress 41 | end 42 | 43 | close(video1); 44 | 45 | end 46 | end 47 | 48 | -------------------------------------------------------------------------------- /post_processing/PostProcessGC_ELIF.m: -------------------------------------------------------------------------------- 1 | function PostProcessGC_ELIF(stdin) 2 | % stdin is paths of input files in unix-style, i.e., separated by spaces 3 | % If given no argument, it searches for matches under CURRENT directory 4 | 5 | 6 | % Prepare files 7 | if nargin == 0 8 | dir_strut = dir('*out.h5'); 9 | num_files = length(dir_strut); 10 | files = cell(1,num_files); 11 | for id_out = 1:num_files 12 | files{id_out} = dir_strut(id_out).name; 13 | end 14 | else 15 | % stdin, i.e., file pathes and names separated by space 16 | sfiles = textscan(stdin,'%s'); % cell array of file path+names 17 | num_files = size(sfiles{1},1); 18 | for i = 1:num_files 19 | files{i} = cell2mat(sfiles{1}(i,:)); 20 | end 21 | end 22 | 23 | % save figures 24 | save_fig = 1; % -1 for no figure, 0 for displaying figure, 1 for saving figure 25 | % Start processing 26 | for id_out = 1:num_files 27 | % start from .ygout files 28 | fprintf('Processing output file No.%d out of %d...\n', id_out, num_files); 29 | fprintf('\t File name: %s\n', files{id_out}); 30 | R = ReadH5( files(id_out) ); % read .ygout file into matlab data struct 31 | R = AnalyseGC_ELIF(R); % do some simple analysis 32 | SaveRYG(R); 33 | disp('Done'); 34 | RasterGC_ELIF(R, save_fig); % generate raster plot for spiking history 35 | 36 | GCplotV_onegrid(R); % record the video of V combing E and I 37 | 38 | GCplotSpike_onegrid(R); % record the video of spike 39 | 40 | %get_initialV(R,R{1}.step_tot/50); % get the last V for external setting V of initial conditions 41 | end 42 | 43 | end 44 | 45 | -------------------------------------------------------------------------------- /post_processing/SpikeNet2SpikeGrid_spikehist.m: -------------------------------------------------------------------------------- 1 | function R = SpikeNet2SpikeGrid_spikehist(R) 2 | % transfer the spike history's data format from SpikeNet to SpikeGrid 3 | disp('SpikeNet2SpikeGrid, spike history...'); 4 | tic; 5 | Num_neu = R.N; 6 | gsize = sqrt(sum(Num_neu));%sqrt(Num_neu); 7 | if floor(gsize)==gsize 8 | spike_hist = R.spike_hist; 9 | MemP = false(gsize); 10 | MemP(2:2:gsize,2:2:gsize) = 1; 11 | ind_E = MemP == 0; 12 | ind_I = MemP == 1; 13 | [~,end_step] = size(spike_hist{1}); 14 | S = false(gsize^2,end_step); 15 | for i=1:1:end_step 16 | MemP(ind_E) = spike_hist{1}(:,i); 17 | MemP(ind_I) = spike_hist{2}(:,i); 18 | S(:,i) = MemP(:); 19 | end 20 | % if one want save memory, S can be convert to sparse matrix but slower 21 | R.Analysis.spike_hist_combined = sparse(S); 22 | toc; 23 | else % no-square, should be specified manually 24 | spike_hist = R.spike_hist; 25 | gsizex=30; 26 | gsizey=180; 27 | MemP = false(gsizex,gsizey); 28 | MemP(2:2:gsizex,2:2:gsizey) = 1; 29 | ind_E = MemP == 0; 30 | ind_I = MemP == 1; 31 | [~,end_step] = size(spike_hist{1}); 32 | S = false(gsizex*gsizey,end_step); 33 | for i=1:1:end_step 34 | MemP(ind_E) = spike_hist{1}(:,i); 35 | MemP(ind_I) = spike_hist{2}(:,i); 36 | S(:,i) = MemP(:); 37 | end 38 | % if one want save memory, S can be convert to sparse matrix but slower 39 | R.Analysis.spike_hist_combined = sparse(S); 40 | toc; 41 | end 42 | end 43 | 44 | -------------------------------------------------------------------------------- /post_processing/SpikeTrainConvolve.m: -------------------------------------------------------------------------------- 1 | function [ Y ] = SpikeTrainConvolve(SpikeTrain, kernel) 2 | % SpikeTrain is (sparse) row vectors, coloumn index is time step, e.g 3 | % 4 | % [0 0 1 1 1 0 1 0 0 0; for single neuron spike train 5 | % [0 0 1 2 1 9 0 0 9 0] for neuron-cluster spike train 6 | % 7 | % Kernel is row vector, column index is time step, e.g. 8 | % [0.1 0.2 0.4 0.2 0.1] 9 | % -2dt -dt 0 +dt +2dt 10 | 11 | if mod(length(kernel),2) == 0 12 | kernel = [kernel 0]; 13 | end 14 | kernel_length = length(kernel); 15 | kernel_half_length = (kernel_length-1)/2; 16 | kernel_t = -kernel_half_length:kernel_half_length; 17 | 18 | [num, q] = size(SpikeTrain); 19 | Y = zeros(num,q); 20 | 21 | 22 | 23 | % if nnz(SpikeTrain) > 0.1*num*q % ??? 24 | % 25 | % SpikeTrain = double(full(SpikeTrain)); 26 | % for n = 1:num 27 | % Y(n,:) = conv( SpikeTrain(n,:), kernel_t, 'same'); 28 | % end 29 | % 30 | % else 31 | RatePadded = zeros(1,q+2*kernel_half_length);% padding 32 | for n = 1:num 33 | [~,timing,num_spikes] = find(SpikeTrain(n,:)); 34 | if ~isempty(timing) 35 | for i = 1:kernel_length 36 | RatePadded(1, timing+kernel_half_length+kernel_t(i)) = RatePadded(1, timing+kernel_half_length+kernel_t(i))+num_spikes*kernel(i); 37 | end 38 | end 39 | Y(n,:) = RatePadded((kernel_half_length+1):(end-kernel_half_length)); 40 | end 41 | % end 42 | 43 | 44 | end 45 | 46 | -------------------------------------------------------------------------------- /post_processing/generate_comments.m: -------------------------------------------------------------------------------- 1 | 2 | function [R] = generate_comments(R) 3 | 4 | fprintf('\t Gennerating auto comments...\n'); 5 | % comment line length 6 | cmt_llength = 100; 7 | % dump field 8 | ExplVar = R.ExplVar; 9 | step_killed = R.step_killed; 10 | Hz = []; 11 | for pop = 1:length(R.N) 12 | Hz = [Hz mean(R.Analysis.rate{pop}) ]; 13 | end 14 | 15 | % Comments 16 | comments = ' '; 17 | if step_killed >= 0 18 | comments = sprintf('Runaway killed at step %g, ', step_killed); 19 | end 20 | comments = [comments 'Mean firing rate (Hz) ', sprintf('%.4g, ', Hz)]; 21 | % Expl variables 22 | if ~isempty(ExplVar) 23 | fname_cell = fieldnames(ExplVar); 24 | for f = 1:length(fname_cell) 25 | fn = fname_cell{f}; 26 | if isnumeric(ExplVar.(fn)) 27 | comments = [comments sprintf('%s = %.4g, ', fn, ExplVar.(fn)) ]; 28 | else 29 | comments = [comments sprintf('%s = %s, ', fn, ExplVar.(fn)) ]; 30 | end 31 | end 32 | end 33 | % break comments into multiple lines if too long 34 | line_num = ceil(length(comments) / cmt_llength); 35 | if line_num > 1 36 | comments = [comments repmat(' ', 1, line_num*cmt_llength-length(comments)) ]; % pad with white space 37 | comment_lines = cell(0,1); 38 | for ll = 1:line_num 39 | comment_lines{ll} = comments((ll-1)*cmt_llength+1:ll*cmt_llength); 40 | end 41 | comments = comment_lines; 42 | end 43 | % record results 44 | R.comments = comments; 45 | 46 | end 47 | 48 | -------------------------------------------------------------------------------- /post_processing/generate_commentsGC_ELIF.m: -------------------------------------------------------------------------------- 1 | 2 | function [R] = generate_commentsGC_ELIF(R) 3 | 4 | fprintf('\t Gennerating auto comments...\n'); 5 | % comment line length 6 | cmt_llength = 100; 7 | % dump field 8 | ExplVar = R.ExplVar; 9 | step_killed = R.step_killed; 10 | 11 | 12 | Hz = []; 13 | Hz_sp = []; 14 | Hz_evo = []; 15 | 16 | for pop = 1:length(R.N) 17 | Hz = [Hz mean(R.Analysis.rate{pop}) ]; 18 | try 19 | Hz_sp = [Hz_sp mean(R.Analysis.rate_spon{pop})]; 20 | Hz_evo = [Hz_evo mean(R.Analysis.rate_evoked{pop})]; 21 | catch 22 | end 23 | end 24 | 25 | % Comments 26 | comments = ' '; 27 | if step_killed >= 0 28 | comments = sprintf('Runaway killed at step %g, ', step_killed); 29 | end 30 | comments = [comments 'Mean firing rate (Hz) ', sprintf('%.4g, ', Hz),... 31 | 'Mean firing rate of spontaneous activity (Hz) ', sprintf('%.4g, ', Hz_sp),... 32 | 'Mean firing rate of evoked activity (Hz) ', sprintf('%.4g, ', Hz_evo)]; 33 | 34 | % % Expl variables 35 | % if ~isempty(ExplVar) 36 | % fname_cell = fieldnames(ExplVar); 37 | % for f = 1:length(fname_cell) 38 | % fn = fname_cell{f}; 39 | % if isnumeric(ExplVar.(fn)) 40 | % comments = [comments sprintf('%s = %.4g, ', fn, ExplVar.(fn)) ]; 41 | % else 42 | % comments = [comments sprintf('%s = %s, ', fn, ExplVar.(fn)) ]; 43 | % end 44 | % end 45 | % end 46 | 47 | % break comments into multiple lines if too long 48 | line_num = ceil(length(comments) / cmt_llength); 49 | if line_num > 1 50 | comments = [comments repmat(' ', 1, line_num*cmt_llength-length(comments)) ]; % pad with white space 51 | comment_lines = cell(0,1); 52 | for ll = 1:line_num 53 | comment_lines{ll} = comments((ll-1)*cmt_llength+1:ll*cmt_llength); 54 | end 55 | comments = comment_lines; 56 | end 57 | % record results 58 | R.comments = comments; 59 | 60 | end 61 | 62 | -------------------------------------------------------------------------------- /post_processing/get_CC_network.m: -------------------------------------------------------------------------------- 1 | function [R] = get_CC_network(R) 2 | fprintf('\t Getting correlation coefficient distribution (network-wide sampling)...\n'); 3 | corrcoef_sample_num = 10^3; %10^4; % number of sampling pairs 4 | CC_kernel_width = 40; % ms, kernel length 5 | 6 | % Dumpe fields 7 | N = R.N; 8 | spike_hist = R.reduced.spike_hist; 9 | dt = R.reduced.dt; 10 | Num_pop = R.Num_pop; 11 | num_spikes = R.num_spikes; 12 | 13 | % Define kernel 14 | kernel_type = 'square'; 15 | CC_kernel = spike_train_kernel_YG(CC_kernel_width, dt, kernel_type); 16 | 17 | % sample pairs from entire network (all the populations) 18 | NNZ_product = 1; 19 | for pop_ind = 1:Num_pop 20 | NNZ_product = NNZ_product * nnz(num_spikes{pop_ind}); % if any one of them is zero 21 | end 22 | 23 | if NNZ_product > 0 24 | [popA, indA, popB, indB] = pairs_sample_from_network(N,corrcoef_sample_num); 25 | corrcoef_sample_num = length(popA); % Note that length(popA) <= corrcoef_sample_num !!!!!!!!!!!!! 26 | % Calculate pair-wise corrcoef 27 | CC_sample = zeros(1,corrcoef_sample_num); 28 | for i = 1:corrcoef_sample_num 29 | CC_sample(i) = CorrCoefYG(spike_hist{popA(i)}(indA(i),:), spike_hist{popB(i)}(indB(i),:), CC_kernel); 30 | % display progress 31 | if i > 1 32 | fprintf(repmat('\b',1,10)); 33 | end 34 | if i < corrcoef_sample_num 35 | fprintf('%10g',i); 36 | end 37 | end 38 | % Record results 39 | R.Analysis.CC_network_kernel_type = kernel_type; 40 | R.Analysis.CC_network_kernel_width = CC_kernel_width; 41 | R.Analysis.CC_network = CC_sample; 42 | end 43 | end 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /post_processing/get_CC_pop.m: -------------------------------------------------------------------------------- 1 | function [R] = get_CC_pop(R, pops) 2 | 3 | fprintf('\t Getting correlation coefficient distribution for specified population(s)...\n'); 4 | 5 | corrcoef_sample_num = 10^4; % number of sampling pairs 6 | CC_kernel_width = 40; % ms, kernel length 7 | 8 | % Dumpe fields 9 | N = R.N; 10 | spike_hist = R.reduced.spike_hist; 11 | dt = R.reduced.dt; 12 | Num_pop = R.Num_pop; 13 | num_spikes = R.num_spikes; 14 | 15 | % Define kernel 16 | kernel_type = 'square_Hz'; 17 | CC_kernel = spike_train_kernel_YG(CC_kernel_width, dt, kernel_type); 18 | 19 | % corrcoef within each population 20 | CC_pop = cell(Num_pop,1); 21 | CC_pop_pairs = cell(Num_pop,1); 22 | 23 | if nargin == 1 24 | pops = 1:Num_pop; 25 | end 26 | 27 | for pop_ind = pops 28 | if nnz(num_spikes{pop_ind}) > 0 29 | 30 | pairs = rand_unique_pairs( N(pop_ind), corrcoef_sample_num ); 31 | CC_pop_pairs{pop_ind} = pairs; 32 | % Calculate pair-wise corrcoef 33 | for i = 1:corrcoef_sample_num 34 | CC_pop{pop_ind}(1,i) = CorrCoefYG(spike_hist{pop_ind}(pairs(1,i),:), spike_hist{pop_ind}(pairs(2,i),:), CC_kernel); 35 | % display progress 36 | 37 | % if i > 1 38 | % fprintf(repmat('\b',1,10)); 39 | % end 40 | % if i < corrcoef_sample_num 41 | % fprintf('%10g',i); 42 | % end 43 | end 44 | 45 | end 46 | end 47 | 48 | % Record results 49 | R.Analysis.CC_pop_kernel_type = kernel_type; 50 | R.Analysis.CC_pop_kernel_width = CC_kernel_width; 51 | R.Analysis.CC_pop = CC_pop; 52 | R.Analysis.CC_pop_pairs = CC_pop_pairs; 53 | 54 | end 55 | 56 | 57 | -------------------------------------------------------------------------------- /post_processing/get_CN_prob.m: -------------------------------------------------------------------------------- 1 | function [R] = get_CN_prob(R,varargin) 2 | 3 | n_sample = 2000; 4 | % 12-neuron 5 | n_samp = 2000; 6 | s_samp = 12; 7 | 8 | 9 | for i = 1:length(varargin)/2 10 | var_name = varargin{2*i-1}; 11 | var_value = varargin{2*i}; 12 | if isnumeric(var_value) 13 | eval([var_name, '=', num2str(var_value), ';']); 14 | else 15 | eval([var_name, '=''', var_value, ''';']); 16 | end 17 | end 18 | 19 | s = strsplit(R.stamp,'_'); 20 | FID = [s{1},'_in.h5']; 21 | [syn_cell] = read_syn_h5(FID, 1, 1, 1); 22 | 23 | L = lattice_nD(2, 31); 24 | I_sample = find( L(:,1).^2+L(:,2).^2 <= n_sample/pi ); 25 | 26 | I = syn_cell{1}.I; 27 | J = syn_cell{1}.J; 28 | K = syn_cell{1}.K; 29 | clear syn_cell; 30 | W = full(sparse(I,J,K, 63^2, 63^2)); 31 | A = W(I_sample, I_sample); 32 | A = double(A>0); 33 | clear I J K W; 34 | 35 | 36 | cn_tot = []; 37 | A_tot = []; 38 | cn_p = zeros(1,5); 39 | for n = 1:n_samp 40 | i_samp = randperm(length(I_sample), s_samp); 41 | A_samp = A(i_samp, i_samp); 42 | cn = A_samp'* A_samp; % A * A' gives common post-synaptic neighbours, note that cn is symmetric 43 | 44 | A_samp(logical(eye(size(A_samp)))) = NaN; 45 | A_samp = A_samp(:); 46 | A_samp(isnan(A_samp)) = []; 47 | A_tot = [A_tot; A_samp(:)]; 48 | 49 | cn(logical(eye(size(cn)))) = NaN; 50 | cn = cn(:); 51 | cn(isnan(cn)) = []; 52 | 53 | cn_tot = [cn_tot; cn(:)]; %#ok<*AGROW> 54 | end 55 | [c,bin] = histc(cn_tot,-0.5:1:4.5); 56 | 57 | for n = 1:5 58 | cn_p(n) = cn_p(n) + sum(A_tot(bin == n)); 59 | end 60 | cn_p = cn_p./c(1:5)'; 61 | 62 | R.CN_prob.cn_p = cn_p; 63 | R.CN_prob.I_sample = I_sample; 64 | R.CN_prob.n_samp = n_samp; 65 | R.CN_prob.s_samp = s_samp; 66 | 67 | end -------------------------------------------------------------------------------- /post_processing/get_ISI.m: -------------------------------------------------------------------------------- 1 | function [R] = get_ISI(R) 2 | 3 | minimum_spikes = 5; % 3? 5? for CV^2 calculation 4 | % dump fields 5 | dt = R.dt; 6 | N = R.N; 7 | Num_pop = R.Num_pop; 8 | num_spikes = R.num_spikes; 9 | spike_hist = R.spike_hist; 10 | 11 | % 12 | fprintf('\t Getting ISI distribution and CV^2 of ISI...\n'); 13 | ISI_lumped = cell(Num_pop,1); % ISI 14 | ISI_lumped_ind = cell(Num_pop,1); % neuron index 15 | CV2_ISI = cell(Num_pop,1);% CV2_ISI = (STD[ISI]/MEAN[ISI])^2, squared coefficient of variation (note that STD = sqrt(VAR) ) 16 | 17 | for pop_ind = 1:Num_pop 18 | if nnz(num_spikes{pop_ind}) > 0 19 | 20 | % warning for insufficient data for CV^2 of ISI 21 | CV2_ISI{pop_ind} = zeros(N(pop_ind),1); 22 | spike_tot = sum(num_spikes{pop_ind},2); 23 | if min(spike_tot) < minimum_spikes; 24 | warning('insufficient data for estimating CV_ISI for each neuron!'); 25 | end 26 | 27 | 28 | for i = 1:N(pop_ind) 29 | spike_temp = find(spike_hist{pop_ind}(i,:)); % in time step in lieu of ms!!! 30 | % get ISI 31 | if length(spike_temp) >= 2 32 | ISI_temp = (spike_temp(2:end)-spike_temp(1:end-1))*dt; % in ms 33 | ISI_lumped{pop_ind} = [ISI_lumped{pop_ind} ISI_temp]; 34 | ISI_lumped_ind{pop_ind} = [ISI_lumped_ind{pop_ind} i*ones(size(ISI_temp)) ]; 35 | end 36 | % get CV^2 of ISI 37 | if length(spike_temp) >= minimum_spikes 38 | ISI_temp = (spike_temp(2:end)-spike_temp(1:end-1))*dt; % in ms 39 | CV2_ISI{pop_ind}(i) = (std(ISI_temp)/mean(ISI_temp))^2;% CV^2 40 | else 41 | CV2_ISI{pop_ind}(i) = NaN; 42 | end 43 | end 44 | end 45 | end 46 | 47 | % record results 48 | R.Analysis.ISI_lumped = ISI_lumped; 49 | R.Analysis.ISI_lumped_ind = ISI_lumped_ind; 50 | R.Analysis.CV2_ISI = CV2_ISI; 51 | 52 | 53 | 54 | end -------------------------------------------------------------------------------- /post_processing/get_combinedSpikeHist.m: -------------------------------------------------------------------------------- 1 | function get_combinedSpikeHist(Result_cell) 2 | % save combined spike history for Adam's model 3 | disp('Saving combined spike history for Adam ELIF model...'); 4 | Result_num = length(Result_cell); 5 | for r_num = 1:Result_num 6 | R = Result_cell{r_num}; 7 | spikehist = sparse(R.Analysis.spike_hist_combined); 8 | save([R.stamp(1:end-3),'ComSpikeHis.mat'],'spikehist','-v7.3') 9 | end -------------------------------------------------------------------------------- /post_processing/get_initialV.m: -------------------------------------------------------------------------------- 1 | function Vini = get_initialV(Result_cell,varargin) 2 | 3 | % Get initial membrane potential 4 | % please make sure the main function sampled the initial V 5 | disp('Get initial membrane potential...'); 6 | 7 | Result_num = length(Result_cell); 8 | 9 | if nargin == 1 10 | T = 1; 11 | else 12 | T = varargin{1}; 13 | end 14 | 15 | for r_num = 1:Result_num 16 | R = Result_cell{r_num}; 17 | % R = Result_cell; 18 | Num_pop = R.Num_pop; 19 | Vini = cell(Num_pop,1); 20 | 21 | for pop=1:Num_pop 22 | file_name = [R.stamp(1:end-3), num2str(pop-1), '_neurosamp.mat']; 23 | R_samp = load(file_name); 24 | Vini{pop}=R_samp.V(:,T); 25 | end 26 | V=Vini{1}; 27 | save([R.stamp(1:4),'_init_V_1.mat'],'V') 28 | V=Vini{2}; 29 | save([R.stamp(1:4),'_init_V_2.mat'],'V') 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /post_processing/get_motif.m: -------------------------------------------------------------------------------- 1 | function R = get_motif(R) 2 | 3 | disp('Getting motif...') 4 | warning('Lots of hard coded numbers here.') 5 | 6 | n_sub = 100; % number of substitute network 7 | n_sample = 1000; 8 | 9 | L = lattice_nD(2, 31); 10 | I_sample = find( L(:,1).^2+L(:,2).^2 <= n_sample/pi ); 11 | N_sample = length(I_sample); 12 | 13 | s = strsplit(R.stamp,'_'); 14 | FID = [s{1},'_in.h5']; 15 | [syn_cell] = read_syn_h5(FID, 1, 1, 1); 16 | 17 | I = syn_cell{1}.I; 18 | J = syn_cell{1}.J; 19 | K = syn_cell{1}.K; 20 | clear syn_cell; 21 | W = full(sparse(I,J,ones(size(K)), 63^2, 63^2)); % binary 22 | W = W(I_sample, I_sample); % downsample 23 | clear I J ; 24 | 25 | 26 | [p, bi_p, uni_p, z_bi, z_uni] = uni_bi_connect_prob(W); 27 | 28 | f = get_motif_quadruple(W); 29 | 30 | f_sub = zeros(13,1); 31 | for i = 1:n_sub 32 | 33 | W_sub = MyRandomGraphGenerator('E_R_uni_bi','N', N_sample, 'uni_p', uni_p, 'bi_p', bi_p); 34 | f_sub_tmp = get_motif_quadruple(W_sub); 35 | f_sub = f_sub + f_sub_tmp; 36 | end 37 | f_sub = f_sub / n_sub; 38 | 39 | R.motif.bi_p = bi_p; 40 | R.motif.uni_p = uni_p; 41 | R.motif.z_bi = z_bi; 42 | R.motif.z_uni = z_uni; 43 | R.motif.f = f; 44 | R.motif.f_sub = f_sub; 45 | 46 | 47 | 48 | end 49 | 50 | function f = get_motif_quadruple(W) 51 | n_sample = 1000; 52 | [~, n] = size(W); 53 | f = zeros(13,1); 54 | for i = 1:n_sample 55 | s = randperm(n, 4); 56 | f_tmp = motif3struct_bin(W(s,s)); 57 | f = f + f_tmp; 58 | end 59 | f = f / n_sample; 60 | end 61 | 62 | 63 | -------------------------------------------------------------------------------- /post_processing/get_rate.m: -------------------------------------------------------------------------------- 1 | function [R] = get_rate(R) 2 | fprintf('\t Getting firing rate...\n'); 3 | % dump fields 4 | dt = R.dt; 5 | step_tot = R.step_tot; 6 | N = R.N; 7 | Num_pop = R.Num_pop; 8 | num_spikes = R.num_spikes; 9 | spike_hist = R.spike_hist; 10 | % 11 | 12 | % kernel for instantaneous rate estimation 13 | CC_kernel_width = 50; % ms, kernel length 14 | choice = 'gaussian_Hz'; 15 | kernel = spike_train_kernel_YG(CC_kernel_width, dt, choice); 16 | 17 | rate = cell(Num_pop,1); % Initialise individual neuron average firing rate 18 | Hz_t = cell(Num_pop,1); % population instantaneous rate estimation 19 | Hz_overall = 0; % Network-wide average firing rate in Hz over simulation 20 | for pop = 1:Num_pop 21 | if nnz(num_spikes{pop}) > 0 22 | rate{pop} = full(sum(spike_hist{pop},2))/(dt/1000*step_tot); 23 | Hz_t{pop} = SpikeTrainConvolve( sum(spike_hist{pop}, 1)/N(pop), kernel ); 24 | Hz_overall = Hz_overall + sum(rate{pop})/sum(N); 25 | end 26 | end 27 | % Record results 28 | R.Analysis.Hz_overall = Hz_overall; 29 | R.Analysis.Hz_t = Hz_t; 30 | R.Analysis.rate = rate; 31 | end 32 | -------------------------------------------------------------------------------- /post_processing/get_rich_club.m: -------------------------------------------------------------------------------- 1 | function R = get_rich_club(R) 2 | 3 | disp('Getting rich club...') 4 | 5 | n_sub = 100; 6 | n_sample = 2000; 7 | 8 | L = lattice_nD(2, 31); 9 | I_sample = find( L(:,1).^2+L(:,2).^2 <= n_sample/pi ); 10 | N_sample = length(I_sample); 11 | 12 | 13 | s = strsplit(R.stamp,'_'); 14 | FID = [s{1},'_in.h5']; 15 | [syn_cell] = read_syn_h5(FID, 1, 1, 1); 16 | 17 | I = syn_cell{1}.I; 18 | J = syn_cell{1}.J; 19 | K = syn_cell{1}.K; 20 | clear syn_cell; 21 | W = full(sparse(I,J,K, 63^2, 63^2)); 22 | W = W(I_sample, I_sample); 23 | clear I J K; 24 | 25 | % topological rich club 26 | in_degree = sum(W > 0,1); 27 | out_degree = sum(W > 0,2); 28 | Rw_t = rich_club_bd( double(W > 0) ); 29 | % 30 | Rw_t_sub = []; 31 | for i = 1:n_sub 32 | i 33 | [cij,flag] = makerandCIJdegreesfixed(in_degree(:),out_degree(:)); 34 | Rw_sub_tmp = rich_club_bd( double(cij > 0) ); 35 | Rw_t_sub = [Rw_t_sub; Rw_sub_tmp(:)']; %#ok 36 | end 37 | 38 | 39 | % weight rich club 40 | Rw_w = rich_club_wd( W ); 41 | [I,J,K] = find(W); 42 | clear W; 43 | % 44 | Rw_w_sub = []; 45 | for i = 1:n_sub 46 | i 47 | W_sub = full(sparse(I, J, K(randperm(length(K))), 63^2, 63^2)); 48 | Rw_sub_tmp = rich_club_wd( W_sub ); 49 | Rw_w_sub = [Rw_w_sub; Rw_sub_tmp(:)']; %#ok 50 | end 51 | 52 | R.rich_club.Rw_t = Rw_t; 53 | R.rich_club.Rw_t_sub = mean(Rw_t_sub); 54 | R.rich_club.Rw_w = Rw_w; 55 | R.rich_club.Rw_w_sub = mean(Rw_w_sub); 56 | 57 | end 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /post_processing/get_rich_club_stPR_coupling.m: -------------------------------------------------------------------------------- 1 | cd ../SWR_reference_100sec_10runs/ 2 | 3 | rc_rate_z = cell(1,0); 4 | rc_stPR_z = cell(1,0); 5 | k = 300:25:600; 6 | for kk = k 7 | rc_rate_z{end+1} = []; %#ok<*SAGROW> 8 | rc_stPR_z{end+1} = []; 9 | 10 | for i = 1:10 11 | loop = sprintf('%04g',i); 12 | 13 | n = dir([loop '*RYG.mat']); 14 | R = load(n.name); 15 | 16 | s = strsplit(R.stamp,'_'); 17 | FID = [s{1},'_in.h5']; 18 | [syn_cell] = read_syn_h5(FID, 1, 1, 1); 19 | 20 | n_sample = 2000; 21 | 22 | L = lattice_nD(2, 31); 23 | I_sample = find( L(:,1).^2+L(:,2).^2 <= n_sample/pi ); 24 | 25 | I = syn_cell{1}.I; 26 | J = syn_cell{1}.J; 27 | K = syn_cell{1}.K; 28 | clear syn_cell; 29 | W = full(sparse(I,J,K, 63^2, 63^2)); 30 | CIJ = W(I_sample, I_sample); 31 | clear I J K W; 32 | 33 | % definition of "degree" as used for RC coefficients 34 | % degree is taken to be the sum of incoming and outgoing connectons 35 | [~,~,degree] = degrees_dir(CIJ); 36 | 37 | SmallNodes=find(degree<=kk); %get 'small nodes' with degree <=k 38 | % 39 | I_rc = I_sample; 40 | I_rc(SmallNodes) = []; 41 | rc_rate_z{end} = [rc_rate_z{end}(:); (R.Analysis.rate{1}(I_rc) - mean(R.Analysis.rate{1})) / std(R.Analysis.rate{1})]; %#ok<*NOPTS> 42 | 43 | for ii = 1:R.stPR.n_trials 44 | ind_trial = (ii-1)*66+(1:66); 45 | [I_check_stPR, ~, I_stPR] = intersect(I_rc, R.stPR.sample_ind(ind_trial)); 46 | c_tmp = R.stPR.c_norm(ind_trial); 47 | rc_stPR_z{end} =[ rc_stPR_z{end}(:); (c_tmp(I_stPR) - mean(c_tmp)) / std(c_tmp)]; 48 | end 49 | 50 | end 51 | end 52 | 53 | save('rich_club_stPR_analysis.mat','rc_rate_z','rc_stPR_z','k') -------------------------------------------------------------------------------- /post_processing/get_seg.m: -------------------------------------------------------------------------------- 1 | function seg_ind = get_seg(step_tot, seg_size, seg) 2 | 3 | seg_num = ceil(step_tot/seg_size); 4 | if seg < seg_num 5 | seg_ind = ((seg-1)*seg_size+1):(seg*seg_size); 6 | else 7 | seg_ind = ((seg-1)*seg_size+1):(step_tot); 8 | end 9 | 10 | end -------------------------------------------------------------------------------- /post_processing/get_susceptibility.m: -------------------------------------------------------------------------------- 1 | function R = get_susceptibility( R ) 2 | % Griffiths phase and long-range correlations in a biologically motivated 3 | % visual cortex model 4 | 5 | rho = R.reduced.num_spikes{1}/R.N(1); 6 | 7 | susceptibility = R.N(1) * ( mean(rho.^2) - mean(rho)^2) / mean(rho); 8 | 9 | % output resultss 10 | R.susceptibility = susceptibility; 11 | 12 | end 13 | 14 | 15 | -------------------------------------------------------------------------------- /post_processing/my_logn_rand.m: -------------------------------------------------------------------------------- 1 | function [ X ] = my_logn_rand( Mu, Sigma, CorrMat_log, N, mu_sigma_mode ) 2 | %[ X ] = my_logn_rand( Mu, Sigma, CorrMat_log, N, mu_sigma_mode ) 3 | % 'mu_sigma_mode' specifies whether the input Mu and Sigma are for the 4 | % pre-exponentiated normal distribution ('mu_sigma_norm') or for the 5 | % post-exponentiated lognormal distritbution ('mu_sigma_norm') 6 | % 7 | % 8 | % Code tested. 9 | 10 | % For more information see: Aggregration of Correlated Risk Portfolios: 11 | % Models and Algorithms; Shaun S. Wang, Phd. Casualty Actuarial Society 12 | % Proceedings Volume LXXXV www.casact.org 13 | % 14 | % Author: Stephen Lienhard 15 | 16 | 17 | switch lower(mu_sigma_mode) 18 | case 'mu_sigma_log' 19 | Mu_norm = log((Mu.^2)./sqrt(Sigma.^2+Mu.^2)); 20 | Sigma_norm = sqrt(log(Sigma.^2./(Mu.^2)+1)); 21 | case 'mu_sigma_norm' 22 | Mu_norm = Mu; 23 | Sigma_norm = Sigma; 24 | end 25 | % The inverse transformation of the above one is lognstat 26 | 27 | % Calculate the covariance structure 28 | sigma_down = repmat( Sigma_norm(:)' , numel(Sigma_norm(:)), 1 ); 29 | sigma_acrs = repmat( Sigma_norm(:) , 1 , numel(Sigma_norm(:)) ); 30 | covv = log( CorrMat_log .* sqrt(exp(sigma_down.^2)-1) .* ... 31 | sqrt(exp(sigma_acrs.^2)-1) + 1 ); 32 | 33 | % error check 34 | min_error = 0.1; % percent 35 | error = 1; 36 | max_loop = 100; 37 | loop = 0; 38 | if length(Mu) == 2 39 | while error > min_error 40 | loop = loop + 1; 41 | if loop > max_loop 42 | X = []; 43 | break; 44 | end 45 | % The Simulation 46 | X = exp( mvnrnd( Mu_norm(:) , covv , N )); 47 | % error 48 | X_c = corrcoef(X); 49 | error = abs( (X_c(1,2)-CorrMat_log(1,2) ) / CorrMat_log(1,2) ); 50 | end 51 | else 52 | disp('length(Mu) ~= 2, error check skipped.') 53 | end 54 | 55 | 56 | end 57 | 58 | -------------------------------------------------------------------------------- /post_processing/num_spikes_plot.m: -------------------------------------------------------------------------------- 1 | function num_spikes_plot(R, pop_ind, seg, seg_size) 2 | 3 | % Input check and default values 4 | if nargin < 4 5 | seg_size = 4*10^4; % 2*10^4 for 2-pop, segmentation size for each plot 6 | end 7 | if nargin < 3 8 | seg = 1; 9 | end 10 | 11 | % Default line color 12 | Color = [255 30 30]/255; 13 | 14 | % Dump fields 15 | dt = R.reduced.dt; 16 | step_tot = R.reduced.step_tot; 17 | N = R.N; 18 | 19 | % 20 | dt = dt/1000; % sec 21 | 22 | % Segmetation 23 | seg_ind = get_seg(step_tot, seg_size, seg); 24 | 25 | % Dump fields 26 | num_spikes = R.reduced.num_spikes{pop_ind}(seg_ind); 27 | T = seg_ind*dt; 28 | 29 | % Plot number of spikes 30 | line([T; T], [zeros(1, length(T)); num_spikes/N(pop_ind)*100], 'Color', Color); 31 | 32 | 33 | ylabel('% Firing'); 34 | set(gca, 'TickDir','out'); 35 | xlabel('t (sec)'); 36 | 37 | end -------------------------------------------------------------------------------- /post_processing/pairs_sample_from_network.m: -------------------------------------------------------------------------------- 1 | function [popA, indA, popB, indB] = pairs_sample_from_network(N, sample_num) 2 | % e.g. 3 | % N = [4000, 1000]; sample_num = 10^4 4 | % popA = [1 2 1 1 1 2 1 2 ....] (10^4 elements) 5 | % indA = [1 1 2 3 4 1000 4000 8 ...] (10^4 elements) 6 | 7 | N_tot = sum(N); 8 | ind_tot2pop = []; % total index to pop id 1:Num_pop 9 | ind_tot2ind = []; % total index to pop index 1:N(i) 10 | 11 | for i = 1:length(N) 12 | ind_tot2pop = [ind_tot2pop i*ones(1,N(i))]; 13 | ind_tot2ind = [ind_tot2ind 1:N(i)]; 14 | end 15 | 16 | [pairs] = rand_unique_pairs(N_tot, sample_num); 17 | 18 | popA = ind_tot2pop(pairs(1,:)); % population index of neuron A 19 | indA = ind_tot2ind(pairs(1,:)); % neuron index of neuron A 20 | popB = ind_tot2pop(pairs(2,:)); % population index of neuron B 21 | indB = ind_tot2ind(pairs(2,:)); % neuron index of neuron B 22 | 23 | end -------------------------------------------------------------------------------- /post_processing/peak_height_requirement.m: -------------------------------------------------------------------------------- 1 | function [ seq ] = peak_height_requirement( seq, data, peak_min ) 2 | %UNTITLED Summary of this function goes here 3 | % Detailed explanation goes here 4 | 5 | cutoff = 1; 6 | [~, one_du, ~, one_start, ~] = seq_postprocess(seq, 1, cutoff); 7 | 8 | for i = 1:length(one_du) 9 | if max(data(one_start(i):one_start(i)+one_du(i)-1)) < peak_min 10 | seq(one_start(i):one_start(i)+one_du(i)-1) = 0; 11 | end 12 | end 13 | end 14 | 15 | -------------------------------------------------------------------------------- /post_processing/raster_marginals_shuffling.m: -------------------------------------------------------------------------------- 1 | function spike_hist_shuffle = raster_marginals_shuffling(spike_hist) 2 | %%%%%%%%%%%%%% shuffling 3 | % Implementation of the Raster Marginals Model, as introduced in 4 | % "Population rate dynamics and multineuron firing patterns in 5 | % sensory cortex", Journal of Neuroscience. 6 | % 7 | % Basically, the shuffling preserves the average firing rate of each neuron 8 | % the temporal population firing rate. 9 | % In other words, the so-called raster marginals model is a 0/1 matrices 10 | % with given marginals. 11 | % 12 | sample_num = length(spike_hist(:,1)); 13 | if sample_num > 100 14 | error('Sample is too large for shuffling!') 15 | end 16 | spike_hist_shuffle = spike_hist'; 17 | shuffle_num = 100*nchoosek(sample_num,2); 18 | c = ceil(rand(shuffle_num,2)*sample_num); % two randomly selected columns 19 | for i = 1:shuffle_num 20 | I = spike_hist_shuffle(:,c(i,1)) + spike_hist_shuffle(:,c(i,2)) == 1; % where the 2 columns don't coincide 21 | cA = spike_hist_shuffle(I,[c(i,1) c(i,2)]); % a copy of the part that matters, to make it run faster 22 | i01 = find(cA(:,1) == 0); 23 | i10 = find(cA(:,1) == 1); 24 | toFlip = ceil(min(length(i01), length(i10))/2); % how many 01s & 10s to flip 25 | i01 = i01(randperm(length(i01))); 26 | i01 = i01(1:toFlip); 27 | i10 = i10(randperm(length(i10))); 28 | i10 = i10(1:toFlip); 29 | % the flip itself: 30 | cA(i01,1) = true; cA(i01,2) = false; 31 | cA(i10,1) = false; cA(i10,2) = true; 32 | spike_hist_shuffle(I,[c(i,1) c(i,2)]) = cA; 33 | end; 34 | spike_hist_shuffle = spike_hist_shuffle'; % the shuffled spike history 35 | end 36 | -------------------------------------------------------------------------------- /post_processing/spike_train_kernel_YG.m: -------------------------------------------------------------------------------- 1 | 2 | function [ Kernel ] = spike_train_kernel_YG( width, dt, choice ) 3 | %UNTITLED2 Summary of this function goes here 4 | % width and dt in msec 5 | % convolution estimates instantaneous firing rates (Hz) 6 | 7 | switch lower(choice) 8 | % Square kernel 9 | case 'square_hz' % so that convolution estimates instantaneous firing rates (Hz) 10 | square_width = width; 11 | SquareKernelLength = round(square_width/dt); 12 | UnitSquareKernel = ones(1,SquareKernelLength)/SquareKernelLength; 13 | Square_kernel = UnitSquareKernel * (SquareKernelLength/(square_width/1000)); 14 | Kernel = Square_kernel; 15 | 16 | % Gaussian filter 17 | case 'gaussian_hz' % so that convolution estimates instantaneous firing rates (Hz) 18 | sigma_gaussian = width; % ms, width here is std of Gaussian function! 19 | num_sigma_gaussian = 4; % 3? 20 | sigma_gaussian_steps = round(sigma_gaussian/dt); 21 | t_k = -num_sigma_gaussian*sigma_gaussian_steps:num_sigma_gaussian*sigma_gaussian_steps; 22 | unitkernel = 1/(sqrt(2*pi)*sigma_gaussian_steps)*exp(-t_k.^2/(2*sigma_gaussian_steps^2)); 23 | Gaussian_kernel = unitkernel * (length(t_k)/(2*num_sigma_gaussian*sigma_gaussian/1000)); % someting may be wrong here!!! 24 | Kernel = Gaussian_kernel; 25 | 26 | % Gaussian filter 27 | case 'gaussian_unit' 28 | sigma_gaussian = width; % ms, width here is std of Gaussian function! 29 | num_sigma_gaussian = 4; % 3? 30 | sigma_gaussian_steps = round(sigma_gaussian/dt); 31 | t_k = -num_sigma_gaussian*sigma_gaussian_steps:num_sigma_gaussian*sigma_gaussian_steps; 32 | unitkernel = 1/(sqrt(2*pi)*sigma_gaussian_steps)*exp(-t_k.^2/(2*sigma_gaussian_steps^2)); 33 | unitkernel = unitkernel /sum(unitkernel); 34 | Kernel = unitkernel; 35 | 36 | 37 | end 38 | 39 | end 40 | 41 | -------------------------------------------------------------------------------- /post_processing/window_spike_hist_compressed.m: -------------------------------------------------------------------------------- 1 | function [ t_mid, ind_ab, num_spikes_win, t_ab_vec ] = window_spike_hist_compressed( R, win_len, win_gap, pop_ind ) 2 | % [ t_mid, ind_ab, num_spikes_win ] = window_spike_hist_compressed( R, win_len, win_gap, pop_ind ) 3 | %This function returns ind_ab = [ind_a; ind_b] so that 4 | %spike_hist_compressed{pop_ind}(ind_a(i):ind_b(i)) gives the indices of the 5 | %neurons that spiked during the i-th window as defined by win_len and 6 | %win_gap (unit: steps). t_mid is the centre of the windows. 7 | 8 | 9 | if nargin == 3 10 | pop_ind = 1; 11 | end 12 | 13 | 14 | %%%% get window-ed index range for spike_hist_compressed 15 | t_a_vec = []; 16 | t_b_vec = []; 17 | ind_a_vec = []; 18 | ind_b_vec = []; 19 | num_spikes_win = []; 20 | 21 | t_a = 1; 22 | t_b = win_len; 23 | ind_a = 1; 24 | while t_b < R.step_tot 25 | t_a_vec = [t_a_vec t_a];%#ok 26 | t_b_vec = [t_b_vec t_b];%#ok 27 | 28 | num_spikes_win_tmp = sum(R.num_spikes{pop_ind}(t_a:t_b)); 29 | num_spikes_win = [num_spikes_win num_spikes_win_tmp];%#ok 30 | ind_b = ind_a + num_spikes_win_tmp - 1; 31 | 32 | ind_a_vec = [ind_a_vec ind_a];%#ok 33 | ind_b_vec = [ind_b_vec ind_b];%#ok 34 | 35 | num_spikes_win_gap = sum(R.num_spikes{pop_ind}(t_a:(t_a+win_gap-1))); 36 | ind_a = ind_a + num_spikes_win_gap; 37 | 38 | t_a = t_a + win_gap; 39 | t_b = t_b + win_gap; 40 | end 41 | t_ab_vec = [t_a_vec(:) t_b_vec(:)]; 42 | t_mid = round( (t_a_vec+t_b_vec)/2 ); 43 | ind_ab = [ind_a_vec; ind_b_vec]; 44 | 45 | % % The above code has been tested using the following code 46 | % t_s = 1234; 47 | % nnz(R.spike_hist{pop_ind}(:,t_a_vec(t_s):t_b_vec(t_s))) 48 | % num_spikes_win(t_s) 49 | % nnz(R.spike_hist_compressed{pop_ind}(ind_a_vec(t_s):ind_b_vec(t_s))) 50 | 51 | 52 | end 53 | 54 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Koetter_chapter_modified.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/Brian_connectivity_toolbox/Koetter_chapter_modified.pdf -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/assortativity_wei.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/Brian_connectivity_toolbox/Measurements/assortativity_wei.m -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/charpath.m: -------------------------------------------------------------------------------- 1 | function [lambda,efficiency,ecc,radius,diameter] = charpath(D) 2 | %CHARPATH Characteristic path length, global efficiency and related statistics 3 | % 4 | % lambda = charpath(D); 5 | % [lambda,efficiency] = charpath(D); 6 | % [lambda,ecc,radius,diameter] = charpath(D); 7 | % 8 | % The characteristic path length is the average shortest path length in 9 | % the network. The global efficiency is the average inverse shortest path 10 | % length in the network. 11 | % 12 | % Input: D, distance matrix 13 | % 14 | % Outputs: lambda, characteristic path length 15 | % efficiency, global efficiency 16 | % ecc, eccentricity (for each vertex) 17 | % radius, radius of graph 18 | % diameter, diameter of graph 19 | % 20 | % Notes: 21 | % The input distance matrix may be obtained with any of the distance 22 | % functions, e.g. distance_bin, distance_wei. 23 | % Characteristic path length is calculated as the global mean of 24 | % the distance matrix D, excludings any 'Infs' but including distances on 25 | % the main diagonal. 26 | % 27 | % 28 | % Olaf Sporns, Indiana University, 2002/2007/2008 29 | 30 | % Modification, 2010 (Mika Rubinov): incorporation of global efficiency 31 | 32 | % Mean of finite entries of D(G) 33 | lambda = sum(sum(D(D~=Inf)))/length(nonzeros(D~=Inf)); 34 | 35 | % Eccentricity for each vertex (note: ignore 'Inf') 36 | ecc = max(D.*(D~=Inf),[],2); 37 | 38 | % Radius of graph 39 | radius = min(ecc); % but what about zeros? 40 | 41 | % Diameter of graph 42 | diameter = max(ecc); 43 | 44 | % Efficiency: mean of inverse entries of D(G) 45 | n = size(D,1); 46 | D = 1./D; %invert distance 47 | D(1:n+1:end) = 0; %set diagonal to 0 48 | efficiency = sum(D(:))/(n*(n-1)); %compute global efficiency 49 | 50 | end -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/clustering_coef_wd.m: -------------------------------------------------------------------------------- 1 | function C=clustering_coef_wd(W) 2 | %CLUSTERING_COEF_WD Clustering coefficient 3 | % 4 | % C = clustering_coef_wd(W); 5 | % 6 | % The weighted clustering coefficient is the average "intensity" of 7 | % triangles around a node. 8 | % 9 | % Input: W, weighted directed connection matrix 10 | % 11 | % Output: C, clustering coefficient vector 12 | % 13 | % Reference: Fagiolo (2007) Phys Rev E 76:026107. 14 | % 15 | % 16 | % Mika Rubinov, UNSW, 2007-2010 17 | 18 | 19 | %Methodological note (also see clustering_coef_bd) 20 | %The weighted modification is as follows: 21 | %- The numerator: adjacency matrix is replaced with weights matrix ^ 1/3 22 | %- The denominator: no changes from the binary version 23 | % 24 | %The above reduces to symmetric and/or binary versions of the clustering 25 | %coefficient for respective graphs. 26 | 27 | A=W~=0; %adjacency matrix 28 | S=W.^(1/3)+(W.').^(1/3); %symmetrized weights matrix ^1/3 29 | clear W; 30 | K=sum(A+A.',2); %total degree (in + out) 31 | cyc3=diag(S^3)/2; %number of 3-cycles (ie. directed triangles) 32 | K(cyc3==0)=inf; %if no 3-cycles exist, make C=0 (via K=inf) 33 | CYC3=K.*(K-1)-2*diag(A^2); %number of all possible 3-cycles 34 | clear A K; 35 | C=cyc3./CYC3; %clustering coefficient 36 | 37 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/degrees_dir.m: -------------------------------------------------------------------------------- 1 | function [id,od,deg] = degrees_dir(CIJ) 2 | %DEGREES_DIR Indegree and outdegree 3 | % 4 | % [id,od,deg] = degrees_dir(CIJ); 5 | % 6 | % Node degree is the number of links connected to the node. The indegree 7 | % is the number of inward links and the outdegree is the number of 8 | % outward links. 9 | % 10 | % Input: CIJ, directed (binary/weighted) connection matrix 11 | % 12 | % Output: id, node indegree 13 | % od, node outdegree 14 | % deg, node degree (indegree + outdegree) 15 | % 16 | % Notes: Inputs are assumed to be on the columns of the CIJ matrix. 17 | % Weight information is discarded. 18 | % 19 | % 20 | % Olaf Sporns, Indiana University, 2002/2006/2008 21 | 22 | 23 | % ensure CIJ is binary... 24 | CIJ = double(CIJ~=0); 25 | 26 | % compute degrees 27 | id = sum(CIJ,1); % indegree = column sum of CIJ 28 | od = sum(CIJ,2)'; % outdegree = row sum of CIJ 29 | deg = id+od; % degree = indegree+outdegree 30 | 31 | 32 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/density_dir.m: -------------------------------------------------------------------------------- 1 | function [kden,N,K] = density_dir(CIJ) 2 | %DENSITY Density 3 | % 4 | % kden = density_dir(CIJ); 5 | % [kden,N,K] = density_dir(CIJ); 6 | % 7 | % Density is the fraction of present connections to possible connections. 8 | % 9 | % Input: CIJ, directed (weighted/binary) connection matrix 10 | % 11 | % Output: kden, density 12 | % N, number of vertices 13 | % K, number of edges 14 | % 15 | % Notes: Assumes CIJ is directed and has no self-connections. 16 | % Weight information is discarded. 17 | % 18 | % 19 | % Olaf Sporns, Indiana University, 2002/2007/2008 20 | 21 | N = size(CIJ,1); 22 | K = nnz(CIJ); 23 | kden = K/(N^2-N); 24 | end 25 | 26 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/jdegree.m: -------------------------------------------------------------------------------- 1 | function [J,J_od,J_id,J_bl] = jdegree(CIJ) 2 | %JDEGREE Joint degree distribution 3 | % 4 | % [J,J_od,J_id,J_bl] = jdegree(CIJ); 5 | % 6 | % This function returns a matrix in which the value of each element (u,v) 7 | % corresponds to the number of nodes that have u outgoing connections 8 | % and v incoming connections. 9 | % 10 | % Input: CIJ, directed (weighted/binary) connection matrix 11 | % 12 | % Outputs: J, joint degree distribution matrix (shifted by one) 13 | % J_od, number of vertices with od>id. 14 | % J_id, number of vertices with id>od. 15 | % J_bl, number of vertices with id=od. 16 | % 17 | % Note: Weights are discarded. 18 | % 19 | % 20 | % Olaf Sporns, Indiana University, 2002/2006/2008 21 | 22 | 23 | % ensure CIJ is binary... 24 | CIJ = double(CIJ~=0); 25 | 26 | N = size(CIJ,1); 27 | 28 | id = sum(CIJ,1); % indegree = column sum of CIJ 29 | od = sum(CIJ,2)'; % outdegree = row sum of CIJ 30 | 31 | % Create the joint degree distribution matrix 32 | % Note: the matrix is shifted by one, to accomodate zero id and od in the first row/column. 33 | % Upper triangular part of the matrix has vertices with an excess of 34 | % outgoing edges (od>id) 35 | % Lower triangular part of the matrix has vertices with an excess of 36 | % outgoing edges (id>od) 37 | % Main diagonal has units with id=od 38 | 39 | szJ = max(max(id,od))+1; 40 | J = zeros(szJ); 41 | 42 | for i=1:N 43 | J(id(i)+1,od(i)+1) = J(id(i)+1,od(i)+1) + 1; 44 | end; 45 | 46 | J_od = sum(sum(triu(J,1))); 47 | J_id = sum(sum(tril(J,-1))); 48 | J_bl = sum(diag(J)); 49 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/motif3struct_wei.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/Brian_connectivity_toolbox/Measurements/motif3struct_wei.m -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Measurements/strengths_dir.m: -------------------------------------------------------------------------------- 1 | function [is,os,str] = strengths_dir(CIJ) 2 | %STRENGTHS_DIR Instrength and outstrength 3 | % 4 | % [is,os,str] = strengths_dir(CIJ); 5 | % 6 | % Node strength is the sum of weights of links connected to the node. The 7 | % instrength is the sum of inward link weights and the outstrength is the 8 | % sum of outward link weights. 9 | % 10 | % Input: CIJ, directed weighted connection matrix 11 | % 12 | % Output: is, node instrength 13 | % os, node outstrength 14 | % str, node strength (instrength + outstrength) 15 | % 16 | % Notes: Inputs are assumed to be on the columns of the CIJ matrix. 17 | % 18 | % 19 | % Olaf Sporns, Indiana University, 2002/2006/2008 20 | 21 | 22 | % compute strengths 23 | is = sum(CIJ,1); % instrength = column sum of CIJ 24 | os = sum(CIJ,2)'; % outstrength = row sum of CIJ 25 | str = is+os; % strength = instrength+outstrength 26 | 27 | 28 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/Node Reorder/reorderMAT.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/Brian_connectivity_toolbox/Node Reorder/reorderMAT.m -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/breadth.m: -------------------------------------------------------------------------------- 1 | function [distance,branch] = breadth(CIJ,source) 2 | %BREADTH Auxiliary function for breadthdist.m 3 | % 4 | % [distance,branch] = breadth(CIJ,source); 5 | % 6 | % Implementation of breadth-first search. 7 | % 8 | % Input: CIJ, binary (directed/undirected) connection matrix 9 | % source, source vertex 10 | % 11 | % Outputs: distance, distance between 'source' and i'th vertex 12 | % (0 for source vertex) 13 | % branch, vertex that precedes i in the breadth-first search tree 14 | % (-1 for source vertex) 15 | % 16 | % Notes: Breadth-first search tree does not contain all paths (or all 17 | % shortest paths), but allows the determination of at least one path with 18 | % minimum distance. The entire graph is explored, starting from source 19 | % vertex 'source'. 20 | % 21 | % 22 | % Olaf Sporns, Indiana University, 2002/2007/2008 23 | 24 | N = size(CIJ,1); 25 | 26 | % colors: white, gray, black 27 | white = 0; 28 | gray = 1; 29 | black = 2; 30 | 31 | % initialize colors 32 | color = zeros(1,N); 33 | % initialize distances 34 | distance = inf*ones(1,N); 35 | % initialize branches 36 | branch = zeros(1,N); 37 | 38 | % start on vertex 'source' 39 | color(source) = gray; 40 | distance(source) = 0; 41 | branch(source) = -1; 42 | Q = source; 43 | 44 | % keep going until the entire graph is explored 45 | while ~isempty(Q) 46 | u = Q(1); 47 | ns = find(CIJ(u,:)); 48 | for v=ns 49 | % this allows the 'source' distance to itself to be recorded 50 | if (distance(v)==0) 51 | distance(v) = distance(u)+1; 52 | end; 53 | if (color(v)==white) 54 | color(v) = gray; 55 | distance(v) = distance(u)+1; 56 | branch(v) = u; 57 | Q = [Q v]; 58 | end; 59 | end; 60 | Q = Q(2:length(Q)); 61 | color(u) = black; 62 | end 63 | -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/grid_communities.m: -------------------------------------------------------------------------------- 1 | function [X Y indsort] = grid_communities(c) 2 | %GRID_COMMUNITIES outline communities along diagonal 3 | % 4 | % [X Y INDSORT] = GRID_COMMUNITIES(C) takes a vector of community 5 | % assignments C and returns three output arguments for visualizing the 6 | % communities. The third is INDSORT, which is an ordering of the vertices 7 | % so that nodes with the same community assignment are next to one 8 | % another. The first two arguments are vectors that, when overlaid on the 9 | % adjacency matrix using the PLOT function, highlight the communities. 10 | % 11 | % Example: 12 | % 13 | % >> load AIJ; % load adjacency matrix 14 | % >> [C,Q] = modularity_louvain_und(AIJ); % get community assignments 15 | % >> [X,Y,INDSORT] = fcn_grid_communities(C); % call function 16 | % >> imagesc(AIJ(INDSORT,INDSORT)); % plot ordered adjacency matrix 17 | % >> hold on; % hold on to overlay community visualization 18 | % >> plot(X,Y,'r','linewidth',2); % plot community boundaries 19 | % 20 | % Inputs: C, community assignments 21 | % 22 | % Outputs: X, x coor 23 | % Y, y coor 24 | % INDSORT, indices 25 | % 26 | % Richard Betzel, Indiana University, 2012 27 | % 28 | 29 | nc = max(c); 30 | [c,indsort] = sort(c); 31 | 32 | X = []; 33 | Y = []; 34 | for i = 1:nc 35 | ind = find(c == i); 36 | if ~isempty(ind) 37 | mn = min(ind) - 0.5; 38 | mx = max(ind) + 0.5; 39 | x = [mn mn mx mx mn NaN]; 40 | y = [mn mx mx mn mn NaN]; 41 | X = [X, x]; 42 | Y = [Y, y]; 43 | end 44 | end -------------------------------------------------------------------------------- /simu_config_tools/Brian_connectivity_toolbox/makefractalCIJ.m: -------------------------------------------------------------------------------- 1 | function [CIJ,K] = makefractalCIJ(mx_lvl,E,sz_cl) 2 | %MAKEFRACTALCIJ Synthetic hierarchical modular network 3 | % 4 | % [CIJ,K] = makefractalCIJ(mx_lvl,E,sz_cl); 5 | % 6 | % This function generates a directed network with a hierarchical modular 7 | % organization. All modules are fully connected and connection density 8 | % decays as 1/(E^n), with n = index of hierarchical level. 9 | % 10 | % Inputs: mx_lvl, number of hierarchical levels, N = 2^mx_lvl 11 | % E, connection density fall-off per level 12 | % sz_cl, size of clusters (power of 2) 13 | % 14 | % Outputs: CIJ, connection matrix 15 | % K, number of connections present in the output CIJ 16 | % 17 | % 18 | % Olaf Sporns, Indiana University, 2005/2007 19 | 20 | % make a little template 21 | t = ones(2).*2; 22 | 23 | % compute N and cluster size 24 | N = 2^mx_lvl; 25 | sz_cl = sz_cl-1; 26 | 27 | n = [0 0 0:mx_lvl-3]; 28 | 29 | for lvl=1:mx_lvl-1 30 | CIJ = ones(2^(lvl+1),2^(lvl+1)); 31 | group1 = [1:size(CIJ,1)/2]; 32 | group2 = [size(CIJ,1)/2+1:size(CIJ,1)]; 33 | CIJ(group1,group1) = t; 34 | CIJ(group2,group2) = t; 35 | CIJ = CIJ+ones(size(CIJ,1),size(CIJ,1)); 36 | t = CIJ; 37 | end; 38 | s = size(CIJ,1); 39 | CIJ = CIJ-ones(s,s)-mx_lvl.*eye(s); 40 | 41 | % assign connection probablities 42 | ee = mx_lvl-CIJ-sz_cl; 43 | ee = (ee>0).*ee; 44 | prob = (1./(E.^ee)).*(ones(s,s)-eye(s)); 45 | CIJ = (prob>rand(N)); 46 | 47 | % count connections 48 | K = sum(sum(CIJ)); 49 | 50 | -------------------------------------------------------------------------------- /simu_config_tools/GridDM.m: -------------------------------------------------------------------------------- 1 | function DM=GridDM(InGrid, OutGrid, pbc) 2 | % Calculates the distance between all pairs of points from one grid to 3 | % another. 4 | % Grid is a vector of [ no rows, no columns, grid step size] 5 | NoIn=InGrid(1)*InGrid(2); 6 | NoOut=OutGrid(2)*OutGrid(2); 7 | 8 | DM=zeros(NoIn,NoOut); 9 | 10 | for i=0:NoIn-1 11 | % Convert 1D index to 2D spat coords 12 | yi=floor(i/InGrid(1)); 13 | xi=i-yi*InGrid(1); 14 | 15 | % Scale for grid step size 16 | yi=yi*InGrid(3); 17 | xi=xi*InGrid(3); 18 | 19 | for j=0:NoOut-1 20 | % Convert 1D index to 2D spat coords 21 | yj=floor(j/OutGrid(1)); 22 | xj=j-yj*OutGrid(1); 23 | 24 | % Scale for grid step size 25 | yj=yj*OutGrid(3); 26 | xj=xj*OutGrid(3); 27 | 28 | delx=abs(xi-xj); 29 | dely=abs(yi-yj); 30 | 31 | if pbc 32 | %If grid has periodic boundaries then check to see which 33 | % distance is shortest (i.e via the periodic boundary or not 34 | delx=min([delx,abs(InGrid(2)*InGrid(3)-delx)]); 35 | dely=min([dely,abs(InGrid(1)*InGrid(3)-dely)]); 36 | end 37 | 38 | DM(i+1,j+1)=sqrt(delx^2+dely^2); 39 | 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /simu_config_tools/Lattice2Lattice.m: -------------------------------------------------------------------------------- 1 | function [ I,J ] = Lattice2Lattice( L_pre, L_post, hw, tau_c, p0, dist_cutoff ) 2 | %UNTITLED5 Summary of this function goes here 3 | % Detailed explanation goes here 4 | 5 | 6 | N_pre = length(L_pre(:,1)); 7 | N_post = length(L_post(:,1)); 8 | I = []; 9 | J = []; 10 | for i = 1:N_pre 11 | 12 | dist = lattice_nD_find_dist(L_post, hw, L_pre(i,1), L_pre(i,2) ); 13 | dist_factor = exp(-dist/tau_c); 14 | % distance cutoff 15 | if nargin == 6 16 | dist_factor(dist > dist_cutoff) = NaN; 17 | end 18 | 19 | [~, ind] = sort( rand(N_post,1)./dist_factor, 'ascend' ); 20 | chosen_j = ind(1:poissrnd(N_post*p0)); 21 | I = [I; i*ones(size(chosen_j))]; %#ok 22 | J = [J; chosen_j]; %#ok 23 | end 24 | 25 | end 26 | 27 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/NGexample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/NGexample.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/circle_draw_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/circle_draw_example.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/continentalUS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/continentalUS.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/dot_matrix_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/dot_matrix_example.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/header04.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/header04.jpg -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/hexlattice.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/hexlattice.jpg -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/logo.gif -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/radial_plot_example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/radial_plot_example.jpg -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/random_modular_graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/random_modular_graph.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/spectral_partitioning_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrainDynamicsUSYD/SpikeNet/a22db63b8f62ab76411118077814c048957fc989/simu_config_tools/MIT_Network_Toolbox/documentational/MIT Network toolbox_files/spectral_partitioning_example.png -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/BFS.m: -------------------------------------------------------------------------------- 1 | % Implementation of breadth-first-search of a graph 2 | % INPUTs: adjacency list, starting node index 3 | % OUTPUTs: BFS tree, in adjacency list format (directed) 4 | 5 | function T=BFS(adjL,i0) 6 | 7 | discovered=[i0]; 8 | q=[i0]; 9 | T=cell(length(adjL),1); 10 | 11 | while not(isempty(q)) 12 | j=q(1); q=q(2:length(q)); % pop the front 13 | neigh=adjL{j}; 14 | for nn=1:length(neigh) 15 | if isempty(find(discovered==neigh(nn))) 16 | T{j}=[T{j}, neigh(nn)]; 17 | discovered=[discovered, neigh(nn)]; 18 | q=[q, neigh(nn)]; 19 | end 20 | end 21 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/PriceModel.m: -------------------------------------------------------------------------------- 1 | % Routine implementing the Price model for network growth 2 | % Notes: 3 | % p_k - fraction of vertices with degree k 4 | % probability a new vertex attaches to any of the degree-k vertices is 5 | % (k+1)p_k/(m+1), where m - mean number of new citations per vertex 6 | % Source: "The Structure and Function of Complex Networks", M.E.J. Newman 7 | % INPUTs: n - final number of vertices 8 | % OUTPUTs: adjacency matrix, directed 9 | % GB, Last modified: March 18, 2006 10 | 11 | function adj = PriceModel(n) 12 | 13 | adj = zeros(n); 14 | adj(1,1) = 1; 15 | vertices = 1; 16 | 17 | while vertices < n 18 | % attach new vertex 19 | vertices = vertices + 1; 20 | adj(vertices,vertices) = 1; 21 | 22 | indeg = sum(adj); % get indegree values 23 | m = 0; % mean in-degree (per vertex) 24 | for k=1:vertices 25 | pk(k) = numel(find(indeg==k))/vertices; 26 | m = m + pk(k)*k; 27 | end 28 | 29 | % attach new edges with probability (k+1)pk/(m+1) 30 | for k=1:vertices 31 | if rand < (k+1)*pk(k)/(m+1); adj(vertices,k)=adj(vertices,k)+1; end 32 | end 33 | 34 | end 35 | 36 | adj=adj-diag(diag(adj)); % remove self-loops -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/add_edge_weights.m: -------------------------------------------------------------------------------- 1 | % Add multiple edges in an edgelist 2 | % INPUTS: original (non-compact) edgelist 3 | % OUTPUTS: final compact edgelist (no row repetitions) 4 | % GB, Last updated: October 7, 2009 5 | 6 | function elc=add_edge_weights(el) 7 | 8 | el2=[el(:,1), el(:,2)]; % make the edge list searchable w/o the weights 9 | visited=[]; % mark visited edges 10 | 11 | elc=[]; 12 | for e=1:size(el,1) 13 | if sum(ismember(visited,el2(e,:),'rows'))==0 % if not visited yet 14 | ind=ismember(el2,el2(e,:),'rows'); 15 | ind=find(ind==1); % these are all the ocurrences of el(e,:) 16 | elc=[elc; el(e,1), el(e,2), sum(el(ind,3))]; 17 | visited=[visited; el2(e,:)]; 18 | end 19 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adj2adjL.m: -------------------------------------------------------------------------------- 1 | % Converts an adjacency graph representation to an adjacency list 2 | % Valid for a general (directed, not simple) network model, but edge 3 | % weights get lost in the conversion. 4 | % INPUT: an adjacency matrix, NxN, N - # of nodes 5 | % OUTPUT: cell structure for adjacency list: x{i_1}=[j_1,j_2 ...] 6 | % GB, October 1, 2009 7 | 8 | function L = adj2adjL(adj) 9 | 10 | L=cell(length(adj),1); 11 | 12 | for i=1:length(adj); L{i}=find(adj(i,:)>0); end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adj2dl.m: -------------------------------------------------------------------------------- 1 | function []=adj2dl(adj,filename) 2 | 3 | % function to convert adjacency matrix to UCINET dl format 4 | % D Whitney Nov 29, 2010 5 | 6 | adj=full(adj'); 7 | n=size(adj,1); 8 | fid=fopen(filename,'w'); 9 | fprintf(fid,'dl n %1u format=fm diagonal=present \n',n'); 10 | fprintf(fid,'labels: \n'); 11 | labels=[1:n]; 12 | fprintf(fid,'%u \n',labels); 13 | fprintf(fid,'data: \n'); 14 | b=[]; 15 | for i = 1:n 16 | b=strcat(b,'%4u'); 17 | end 18 | fprintf(fid,strcat(b,'\n'),adj'); 19 | fclose(fid); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adj2edgeL.m: -------------------------------------------------------------------------------- 1 | % Converts adjacency matrix (nxn) to edge list (mx3) 2 | % INPUTS: adjacency matrix: nxn 3 | % OUTPUTS: edge list: mx3 4 | % GB, Last updated: October 2, 2009 5 | 6 | function el=adj2edgeL(adj) 7 | 8 | n=length(adj); % number of nodes 9 | edges=find(adj>0); % indices of all edges 10 | 11 | el=[]; 12 | for e=1:length(edges) 13 | [i,j]=ind2sub([n,n],edges(e)); % node indices of edge e 14 | el=[el; i j adj(i,j)]; 15 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adj2inc.m: -------------------------------------------------------------------------------- 1 | % Convert adjacency matrix to an incidence matrix 2 | % Valid for directed/undirected, simple/not simple graph 3 | % INPUTs: adjacency matrix, NxN, N - number of nodes 4 | % OUTPUTs: incidence matrix: N x number of edges 5 | % Other routines used: isdirected.m 6 | % GB, Last Updated: July 10, 2011 7 | 8 | function inc = adj2inc(adj) 9 | 10 | n=length(adj); % number of nodes 11 | 12 | inc=[]; % initialize incidence matrix 13 | 14 | if isdirected(adj) 15 | 16 | for i=1:n 17 | for j=1:n 18 | 19 | % handle selfloops 20 | if i==j; for x=1:adj(i,j); inc=[inc; zeros(1,length(1:i-1)), 1,zeros(1,length(i+1:n))]; end; continue; end 21 | 22 | for x=1:adj(i,j) % add multiple edges if any 23 | if i0; % make all edges weight 1 10 | adj = adj - diag(diag(adj)); % clear the diagonal (selfloops) -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adj2str.m: -------------------------------------------------------------------------------- 1 | % Converts an adjacency matrix to a one-line string representation 2 | % INPUTS: adjacency matrix, nxn 3 | % OUTPUTS: string 4 | % The nomenclature used to construct the string is arbitrary. Here we use 5 | % .i1.j1.k1,.i2.j2.k2,.... 6 | % Other routines used: kneighbors.m 7 | % GB, Last updated: October 6, 2009 8 | 9 | function str=adj2str(adj) 10 | 11 | % in '.i1.j1.k1,.i2.j2.k2,....', dot: signifies new neighbor, comma: next node 12 | str=''; 13 | n=length(adj); 14 | 15 | for i=1:n 16 | neigh=kneighbors(adj,i,1); 17 | for k=1:length(neigh); str=strcat(str,'.',num2str(neigh(k))); end 18 | str=strcat(str,','); % close this node's neighbors list 19 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adjL2adj.m: -------------------------------------------------------------------------------- 1 | % Convert an adjacency list to an adjacency matrix 2 | % INPUTS: adjacency list: {n} 3 | % OUTPUTS: adjacency matrix nxn 4 | % Note: Assume that if node i has no neighbours, L{i}=[]; 5 | % GB, Last updated: October 6, 2009 6 | 7 | function adj=adjL2adj(adjL) 8 | 9 | adj = zeros(length(adjL)); 10 | 11 | for i=1:length(adjL) 12 | for j=1:length(adjL{i}); adj(i,adjL{i}(j))=1; end 13 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/adjL2edgeL.m: -------------------------------------------------------------------------------- 1 | % Converts adjacency list to an edge list 2 | % INPUTS: adjacency list 3 | % OUTPUTS: edge list 4 | % GB, Last Updated: October 6, 2009 5 | 6 | function el = adjL2edgeL(adjL) 7 | 8 | el = []; % initialize edgelist 9 | for i=1:length(adjL) 10 | for j=1:length(adjL{i}); el=[el; i, adjL{i}(j), 1]; end 11 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/algebraic_connectivity.m: -------------------------------------------------------------------------------- 1 | % The algebraic connectivity of a graph: the second smallest eigenvalue of the Laplacian 2 | % INPUTs: adjacency matrix 3 | % OUTPUTs: algebraic connectivity 4 | 5 | function a=algebraic_connectivity(adj) 6 | 7 | s=graph_spectrum(adj); 8 | a=s(length(s)-1); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/ave_neighbor_deg.m: -------------------------------------------------------------------------------- 1 | % Computes the average degree of neighboring nodes for every vertex 2 | % Note: Works for weighted degrees also 3 | % INPUTs: adjacency matrix 4 | % OUTPUTs: average neighbor degree vector nx1 5 | % Other routines used: degrees.m, kneighbors.m 6 | % GB, Last updated: May 21, 2010 7 | 8 | function ave_n_deg=ave_neighbor_deg(adj) 9 | 10 | ave_n_deg=zeros(1,length(adj)); % initialize output vector 11 | [deg,~,~]=degrees(adj); 12 | 13 | for i=1:length(adj) % across all nodes 14 | 15 | neigh=kneighbors(adj,i,1); % neighbors of i, one link away 16 | if isempty(neigh); ave_n_deg(i)=0; continue; end 17 | ave_n_deg(i)=sum(deg(neigh))/deg(i); 18 | 19 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/ave_path_length.m: -------------------------------------------------------------------------------- 1 | % Compute average path length for a network - the average shortest path 2 | % INPUTS: adjL - matrix of weights/distances between nodes 3 | % OUTPUTS: average path length: the average of the shortest paths between every two edges 4 | % Note: works for directed/undirected networks 5 | % GB, December 8, 2005 6 | 7 | function l = ave_path_length(adj) 8 | 9 | n=size(adj,1); 10 | 11 | dij = []; 12 | 13 | for i=1:n; dij=[dij; simple_dijkstra(adj,i) ]; end 14 | 15 | l = sum(sum(dij))/(n^2-n); % sum and average across everything but the diagonal -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/average_degree.m: -------------------------------------------------------------------------------- 1 | % Computes the average degree of a node in a graph, defined as 2*num_edges 2 | % divided by the num_nodes (every edge is counted in degrees twice). 3 | % Other routines used: numnodes.m, numedges.m 4 | % GB, Last Update: October 1, 2009 5 | 6 | function k=average_degree(adj) 7 | 8 | k=2*numedges(adj)/numnodes(adj); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/closeness.m: -------------------------------------------------------------------------------- 1 | % Computes the closeness centrality for every vertex: 1/sum(dist to all other nodes) 2 | % For disconnected graphs can use: sum_over_t(2^-d(i,t)), idea Dangalchev (2006) 3 | % C(i)=sum(2.^(-d)) if graph is disconnected, but sum w/o d(i) 4 | % INPUTs: graph representation (adjacency matrix nxn) 5 | % OUTPUTs: vector of centralities, nx1 6 | % Source: social networks literature 7 | % Other routines used: simple_dijkstra.m 8 | % GB, Last updated: October 9, 2009 9 | 10 | function C=closeness(adj) 11 | 12 | C=zeros(length(adj),1); % initialize closeness vector 13 | 14 | for i=1:length(adj); C(i)=1/sum( simple_dijkstra(adj,i) ); end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/clust_coeff.m: -------------------------------------------------------------------------------- 1 | % Computes clustering coefficient, based on triangle motifs count and local clustering 2 | % C1 = num triangle loops / num connected triples 3 | % C2 = the average local clustering, where Ci = (num triangles connected to i) / (num triples centered on i) 4 | % Ref: M. E. J. Newman, "The structure and function of complex networks" 5 | % Valid for directed and undirected graphs 6 | % INPUT: adjacency matrix representation of a graph 7 | % OUTPUT: graph average clustering coefficient and clustering coefficient 8 | % Other routines used: degrees.m, isdirected.m, kneighbors.m, numedges.m, subgraph.m, loops3.m, num_conn_triples.m 9 | % GB, October 9, 2009 10 | 11 | function [C1,C2,C] = clust_coeff(adj) 12 | 13 | n = length(adj); 14 | adj = adj>0; % no multiple edges 15 | [deg,~,~] = degrees(adj); 16 | C=zeros(n,1); % initialize clustering coefficient 17 | 18 | % multiplication change in the clust coeff formula 19 | coeff = 2; 20 | if isdirected(adj); coeff=1; end 21 | 22 | for i=1:n 23 | 24 | if deg(i)==1 | deg(i)==0; C(i)=0; continue; end 25 | 26 | neigh=kneighbors(adj,i,1); 27 | edges_s=numedges(subgraph(adj,neigh)); 28 | 29 | C(i)=coeff*edges_s/deg(i)/(deg(i)-1); 30 | 31 | end 32 | 33 | C1=loops3(adj)/num_conn_triples(adj); 34 | C2=sum(C)/n; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/degrees.m: -------------------------------------------------------------------------------- 1 | % Compute the total degree, in-degree and out-degree of a graph based on 2 | % the adjacency matrix; should produce weighted degrees, if the input matrix is weighted 3 | % INPUTS: adjacency matrix 4 | % OUTPUTS: degree, indegree and outdegree sequences 5 | % GB, Last Updated: October 2, 2009 6 | 7 | function [deg,indeg,outdeg]=degrees(adj) 8 | 9 | indeg = sum(adj); 10 | outdeg = sum(adj'); 11 | 12 | if isdirected(adj) 13 | deg = indeg + outdeg; % total degree 14 | 15 | else % undirected graph: indeg=outdeg 16 | deg = indeg + diag(adj)'; % add self-loops twice, if any 17 | 18 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/diameter.m: -------------------------------------------------------------------------------- 1 | % The longest shortest path between any two nodes nodes in the network 2 | % INPUTS: adjacency matrix, adj 3 | % OUTPUTS: network diameter, diam 4 | % Other routines used: simple_dijkstra.m 5 | % GB, Last updated: June 8, 2010 6 | 7 | function diam = diameter(adj) 8 | 9 | diam=0; 10 | for i=1:size(adj,1) 11 | d=simple_dijkstra(adj,i); 12 | diam = max([max(d),diam]); 13 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/dijkstra.m: -------------------------------------------------------------------------------- 1 | % INPUTS: adj - adjacency matrix, s - source node, target - target node 2 | % OUTPUTS: distance, d and path, P (from s to target) 3 | % Note: if target==[], then dist and P include all distances and paths from s 4 | % Other routines used: adj2adjL.m, purge.m 5 | % GB, Last Updated: Dec 22, 2009 6 | 7 | function [dist,P]=dijkstra(adj,s,target) 8 | 9 | % initialize distances ========================== 10 | n=length(adj); % number of nodes 11 | adjL=adj2adjL(adj); % list of neighbors 12 | 13 | dist=inf(1,n); 14 | dist(s)=0; 15 | 16 | previous=[1:n; inf(1,n)]'; % {i: inf}, i=1:n, inf -> not assigned 17 | S=cell(1,n); % shortest path sequence 18 | 19 | 20 | Q=[1:n]; % all unvisited vertices, entire graph 21 | while length(Q)>0 % while not empty 22 | % get min dist member among unvisited vertices 23 | [mindist,min_ind]=min(dist(Q)); 24 | u=Q(min_ind); 25 | 26 | % termination condition - save source-u path 27 | S{u}=[]; 28 | t=u; 29 | while not(isempty(find(previous(:,1)==t))) % t in previous.keys(): 30 | % insert u at the beginning of S 31 | S{u}=[t S{u}]; 32 | t=previous(t,2); 33 | end 34 | if length(target)>0 & u==target 35 | dist=dist(u); P=S{u}; 36 | return 37 | end 38 | 39 | % ========================================= 40 | Q=purge(Q,u); % remove u from Q 41 | for v=1:length(adjL{u}) % across all neighbors of u 42 | v=adjL{u}(v); 43 | alt=dist(u)+adj(u,v); 44 | if alt < dist(v) 45 | dist(v)=alt; 46 | previous(v,2)=u; 47 | end 48 | end 49 | end 50 | 51 | P=S; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/distance_distribution.m: -------------------------------------------------------------------------------- 1 | % The number of pairs of nodes at a distance x, divided by the total number of pairs n(n-1) 2 | % Source: Mahadevan et al, "Systematic Topology Analysis and Generation Using Degree Correlations" 3 | % Note: The cumulative distance distribution (hop-plot) can be obtained by using ddist(i)=length(find(dij<=i)); in line 18 instead. 4 | % INPUTS: adjacency matrix, (nxn) 5 | % OUTPUTS: distribution vector ((n-1)x1): {k_i} where k_i is the # of pairs at a distance i, normalized 6 | % Other routines used: simple_dijkstra.m 7 | 8 | function ddist=distance_distribution(adj) 9 | 10 | n=size(adj,1); 11 | 12 | dij=[]; 13 | for i=1:n; dij=[dij; simple_dijkstra(adj,i) ]; end 14 | 15 | dij(find(dij==0))=inf; % not considering (i-i) node pairs/loops, 16 | % otherwise divide ddist by n^2 17 | 18 | for i=1:n-1; ddist(i)=length(find(dij==i)) / (n*(n-1)); end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/draw_circ_graph.m: -------------------------------------------------------------------------------- 1 | % Draw a circular graph with links and nodes in order of degree 2 | % Strategy: position vertices in a regular n-polygon 3 | % INPUTs: adj - adjacency matrix 4 | % OUTPUTs: a figure 5 | % Other routines used: degrees.m 6 | % GB, February 21, 2006 7 | 8 | function [] = draw_circ_graph(adj) 9 | 10 | n = size(adj,1); % number of nodes 11 | [degs,~,~]=degrees(adj); 12 | [~, Y] = sort(degs); % Y - sorted nodal indices 13 | angl = 2*pi/n; % rotation angle 14 | 15 | for k=1:n 16 | x(Y(k)) = real(exp(angl*(k-1)*i)); 17 | y(Y(k)) = imag(exp(angl*(k-1)*i)); 18 | end 19 | 20 | for k=1:n 21 | plot(x(k),y(k),'ko') 22 | text(1.1*x(k),1.1*y(k),strcat('v',num2str(k))); 23 | hold off; hold on; 24 | end 25 | 26 | edges=find(adj>0); 27 | set(gcf,'Color',[1,1,1]) 28 | 29 | for e=1:length(edges) 30 | [ii,jj]=ind2sub([n,n],edges(e)); 31 | line([x(ii) x(jj)],[y(ii) y(jj)],'Color','k'); 32 | hold off; hold on; 33 | end 34 | axis off; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgeL2adj.m: -------------------------------------------------------------------------------- 1 | % Converts edge list to adjacency matrix 2 | % INPUTS: edgelist: mx3 3 | % OUTPUTS: adjacency matrix nxn 4 | % Note: information about nodes is lost: indices only (i1,...in) remain 5 | % GB, Last updated: October 6, 2009 6 | 7 | function adj=edgeL2adj(el) 8 | 9 | nodes=sort(unique([el(:,1) el(:,2)])); % get all nodes, sorted 10 | adj=zeros(numel(nodes)); % initialize adjacency matrix 11 | 12 | % across all edges 13 | for i=1:size(el,1); adj(find(nodes==el(i,1)),find(nodes==el(i,2)))=el(i,3); end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgeL2adjL.m: -------------------------------------------------------------------------------- 1 | % Converts an edgelist to an adjacency list 2 | % INPUTS: edgelist, (mx3) 3 | % OUTPUTS: adjacency list 4 | % GB, Last updated: October 13, 2006 5 | 6 | function adjL = edgeL2adjL(el) 7 | 8 | nodes = unique([el(:,1)' el(:,2)']); 9 | adjL=cell(numel(nodes),1); 10 | 11 | for e=1:size(el,1); adjL{el(e,1)}=[adjL{el(e,1)},el(e,2)]; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgeL2cyto.m: -------------------------------------------------------------------------------- 1 | % Write an edgelist structure m x [node 1, node 2, link] to Cytoscape input format (.txt or any text extension works) 2 | % In Cytoscape the column separator option is semi-colon ";". If desired, this is easy to change below in line 15. 3 | % INPUTs: edgelist - mx3 matrix, m = number of edges, file name string 4 | % OUTPUTs: text file in Cytoscape format with a semicolon column separator 5 | 6 | function []=edgeL2cyto(el,filename) 7 | 8 | nodes=unique([el(:,1)', el(:,2)']); 9 | n=length(nodes); % number of nodes 10 | m = size(el,1); % number of edges 11 | 12 | fid = fopen(filename,'wt','native'); 13 | 14 | for i=1:m 15 | fprintf(fid,' %4i ; %4i ; %3.6f\n',el(i,1),el(i,2),el(i,3)); 16 | end 17 | 18 | fclose(fid); 19 | 20 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgeL2pajek.m: -------------------------------------------------------------------------------- 1 | % Converts an edgelist matrix representation to a Pajek .net readable format 2 | % INPUT: an edgelist matrix, [mx3], a filename, [string] 3 | % OUTPUT: text format of Pajek readable .net file 4 | % See also: adj2pajek.m 5 | % Other routines used: edgeL2adj.m, issymmetric.m 6 | % EXAMPLE 7 | % *Vertices 4 8 | % 1 "14" 0.1000 0.5000 0.5000 9 | % 2 "31" 0.1000 0.4975 0.5000 10 | % 3 "46" 0.1000 0.4950 0.5000 11 | % 4 "51" 0.1001 0.4925 0.5000 12 | % *Edges 13 | % 14 31 1 14 | % 46 51 1 15 | % 51 60 1 16 | % GB, Last updated: October 7, 2009 17 | 18 | function []=edgeL2pajek(el,filename) 19 | 20 | nodes=unique([el(:,1)', el(:,2)']); 21 | n=length(nodes); % number of nodes 22 | m = size(el,1); % number of edges 23 | 24 | fid = fopen(filename,'wt','native'); 25 | 26 | fprintf(fid,'*Vertices %6i\n',n); 27 | 28 | for i=1:n 29 | fprintf(fid,' %3i %s %1.4f %1.4f %1.4f\n',i,strcat('"v',num2str(nodes(i)),'"'),rand,rand,0); 30 | end 31 | 32 | adj = edgeL2adj(el); 33 | if issymmetric(adj); fprintf(fid,'*Edges\n'); end; % undirected version 34 | if not(issymmetric(adj)); fprintf(fid,'*Arcs\n'); end; % directed version 35 | for i=1:m 36 | fprintf(fid,' %4i %4i %2i\n',el(i,1),el(i,2),el(i,3)); 37 | end 38 | 39 | fclose(fid); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgeL2simple.m: -------------------------------------------------------------------------------- 1 | % Convert an edge list of a general graph to the edge list of a simple 2 | % graph (no loops, no double edges) - great for quick data clean up 3 | % INPUTS: edgelist (mx3), m - number of edges 4 | % OUTPUTs: edge list of the corresponding simple graph 5 | % Note: Assumes all node pairs [n1,n2,x] occur once; if else see add_edge_weights.m 6 | % GB, Last updated: October 4, 2009 7 | 8 | function el=edgeL2simple(el) 9 | 10 | el(:,3)=ones(size(el,1),1); % make all edge weights 1 11 | 12 | ind=find(not(el(:,1)-el(:,2)==0)); % indices of the "non-self-loops" 13 | el=el(ind,:); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/edgelist2dl.m: -------------------------------------------------------------------------------- 1 | function []=edgelist2dl(edgelistt,filename) 2 | 3 | % function to convert two-way edgelist to UCINET dl format 4 | % D Whitney Nov 29, 2010 5 | % example filename is 'filename.txt' 6 | 7 | numnodes=max(max(edgelistt)) 8 | n=numnodes; 9 | fid=fopen(filename,'w'); 10 | fprintf(fid,'dl n %1u format=el1 \n',n); 11 | fprintf(fid,'labels: \n'); 12 | labels=[1:n]; 13 | fprintf(fid,'%u \n',labels); 14 | fprintf(fid,'data: \n'); 15 | fprintf(fid,'%3u %3u \n', edgelistt); 16 | fclose(fid); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/eigencentrality.m: -------------------------------------------------------------------------------- 1 | % The ith component of the eigenvector corresponding to the greatest 2 | % eigenvalue gives the centrality score of the ith node in the network. 3 | % INPUTs: adjacency matrix 4 | % OUTPUTs: eigen(-centrality) vector 5 | % GB, Last Updated: October 14, 2009 6 | 7 | function x=eigencentrality(adj) 8 | 9 | [V,D]=eig(adj); 10 | [max_eig,ind]=max(diag(D)); 11 | x=V(:,ind); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/el2geom.m: -------------------------------------------------------------------------------- 1 | % Plot geometry based on extended edgelist 2 | % INPUTS: extended edgelist el[i,:]=[n1 n2 m x1 y1 x2 y2] 3 | % OUTPUTS: geometry plot, higher-weight links are thicker and lighter 4 | % Note 1: m - edge weight; (x1,y1) are the Euclidean coordinates of n1, (x2,y2) - n2 resp. 5 | % Note 2: Easy to change colors and corresponding edge weight coloring 6 | % Example input: 7 | % [el,p] = newmangastner(1000,0.5); 8 | % elnew = []; 9 | % for e=1:size(el,1) 10 | % elnew = [elnew; el(e,1), el(e,2), randi(8), p(el(e,1),1), p(el(e,1),2), p(el(e,2),1), p(el(e,2),2)]; 11 | % end 12 | % el2geom(elnew) 13 | % GB, last updated: april 24, 2007 14 | 15 | function []=el2geom(el) 16 | 17 | set(gcf,'Color',[1 1 1]) 18 | map=colormap('hot'); 19 | 20 | for i=1:size(el,1) 21 | 22 | % plot line between two nodes 23 | x1=el(i,4); y1=el(i,5); 24 | x2=el(i,6); y2=el(i,7); 25 | 26 | % edge weights ============== 27 | if el(i,3)<2 28 | color=map(8,:); 29 | linew=1; 30 | elseif el(i,3)>=2 & el(i,3)<3 31 | color=map(2*8,:); 32 | linew=2; 33 | elseif el(i,3)>=3 & el(i,3)<4 34 | color=map(3*8,:); 35 | linew=3; 36 | elseif el(i,3)>=4 & el(i,3)<5 37 | color=map(4*8,:); 38 | linew=4; 39 | elseif el(i,3)>=5 & el(i,3)<6 40 | color=map(5*8,:); 41 | linew=5; 42 | elseif el(i,3)>=6 & el(i,3)<7 43 | color=map(6*8,:); 44 | linew=6; 45 | elseif el(i,3)>=7 & el(i,3)<8 46 | color=map(7*8,:); 47 | linew=7; 48 | elseif el(i,3)>=8 49 | color=map(8*8,:); 50 | linew=8; 51 | end 52 | line([x1 x2],[y1 y2],'LineWidth',linew,'Color',color) 53 | 54 | hold off; hold on; 55 | 56 | end 57 | axis equal -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/exponential_growth_model.m: -------------------------------------------------------------------------------- 1 | % Grow a network exponentially 2 | % Probability of node s having k links at time t: p(k,s,t)=1/t*p(k-1,s,t-1)+(1-1/t)*p(k,s,t-1) 3 | % INPUTS: number of time-steps, t 4 | % OUTPUTs: edgelist, mx3 5 | % GB, Last Updated: May 7, 2007 6 | 7 | function el=exponential_growth_model(t) 8 | 9 | el=[1 2 1; 2 1 1]; % initialize with two connected nodes 10 | 11 | % for all remaining time t 12 | for i=3:t; r = randi(i-1); el=[el; i r 1; r i 1]; end 13 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/fabrikant_model.m: -------------------------------------------------------------------------------- 1 | % Implements the Fabrikant model of internet growth 2 | % Source: Fabrikant et al, "Heuristically Optimized Trade-offs: A New Paradigm for Power Laws in the Internet" 3 | % Note: Assume the first point to be the center - easy to change by setting p(1,:) = [x0,y0] 4 | % INPUTS: n - number of points, parameter alpha, [0,inf), plt='on'/'off', if [], then 'off' is default 5 | % OUTPUTS: generated network (adjacency matrix) and plot [optional] 6 | % Other functions used: simple_dijkstra.m 7 | % GB, Last Updated: November 26, 2006 8 | 9 | 10 | function [adj,p]=fabrikant_model(n,alpha,plt) 11 | 12 | 13 | % create random point (polar) coordinates 14 | p = zeros(n-1,2); 15 | rad = rand(1,n-1); 16 | theta = 2*pi*rand(1,n-1); 17 | for i=1:n-1; p(i,:) = rad(i)*[cos(theta(i)),sin(theta(i))]; end 18 | p=[[0 0]; p]; % add zero 19 | 20 | h=zeros(n,1); % initialize centrality function 21 | adj=zeros(n); % initialize adjacency matrix 22 | 23 | 24 | for i=2:n % a new point arrives at each iteration 25 | 26 | % compute min weight across all existing points 27 | d=[]; 28 | for j=1:i-1; d=[d; alpha*norm(p(i,:)-p(j,:)) + h(j)]; end 29 | [~,indmin]=min(d); 30 | adj(i,indmin)=1; adj(indmin,i)=1; 31 | 32 | % compute centrality function for new point 33 | adjL = pdist2(p,p,'euclidean'); 34 | h = simple_dijkstra(adjL,1); 35 | 36 | end 37 | 38 | if nargin<=2 | not(strcmp(plt,'on')); return; end 39 | 40 | set(gcf,'color',[1,1,1]) 41 | for i=1:n 42 | axis off 43 | drawnow 44 | %plot(p(i,1),p(i,2),'.','Color',[0.5,0.5,0.5]); hold off; hold on; % plot the new point 45 | for j=i+1:n 46 | if adj(i,j)>0 47 | line([p(i,1) p(j,1)],[p(i,2) p(j,2)],'Color',[0.5,0.5,0.5]) 48 | hold off; hold on; 49 | end 50 | end 51 | end 52 | 53 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/fiedler_vector.m: -------------------------------------------------------------------------------- 1 | % The vector corresponding to the second smallest eigenvalue of the Laplacian matrix 2 | % INPUTs: adjacency matrix (nxn) 3 | % OUTPUTs: fiedler vector (nx1) 4 | 5 | function fv=fiedler_vector(adj) 6 | 7 | [V,D]=eig(laplacian_matrix(adj)); 8 | [ds,Y]=sort(diag(D)); 9 | fv=V(:,Y(2)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/find_conn_comp.m: -------------------------------------------------------------------------------- 1 | % Algorithm for finding connected components in a graph 2 | % Valid for undirected graphs only 3 | % INPUTS: adj - adjacency matrix 4 | % OUTPUTS: a list of the components comp{i}=[j1,j2,...jk} 5 | % Other routines used: find_conn_compI.m (embedded), degrees.m, kneighbors.m 6 | % GB, Last updated: October 2, 2009 7 | 8 | 9 | function comp_mat = find_conn_comp(adj) 10 | 11 | [deg,~,~]=degrees(adj); % degrees 12 | comp_mat={}; % initialize components matrix 13 | 14 | for i=1:length(deg) 15 | if deg(i)>0 16 | done=0; 17 | for x=1:length(comp_mat) 18 | if length(find(comp_mat{x}==i))>0 % i in comp_mat(x).mat 19 | done=1; 20 | break 21 | end 22 | end 23 | if not(done) 24 | comp=find_conn_compI(adj,i); 25 | comp_mat{length(comp_mat)+1}=comp; 26 | end 27 | 28 | elseif deg(i)==0 29 | comp_mat{length(comp_mat)+1}=[i]; 30 | end 31 | end 32 | 33 | 34 | function comp=find_conn_compI(adj,i) 35 | % heuristic for finding the conn component to which "i" belongs to 36 | % works well in practice for large datasets 37 | % INPUTS: adjacency matrix and index of the key node 38 | % OUTPUTS: all node indices of the nodes to which "i" belongs to 39 | 40 | neigh1=kneighbors(adj,i,1); 41 | neigh1=unique([neigh1 i]); % add i to its own component 42 | 43 | while 1 44 | len0=length(neigh1); 45 | for j=1:len0 46 | neigh2=kneighbors(adj,neigh1(j),1); 47 | neigh1=unique([neigh1, neigh2]); 48 | end 49 | if len0==length(neigh1) 50 | comp=neigh1; 51 | return 52 | end 53 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/getEdges.m: -------------------------------------------------------------------------------- 1 | % Return the list of edges for varying representation types 2 | % Inputs: graph structure (matrix or cell or struct) and type of structure (string) 3 | % Outputs: edge list 4 | % 'type' can be: 'adj','edgelist','adjlist' (neighbor list),'inc' (incidence matrix) 5 | % Note: symmetric edges will both twice, also in undirected graphs, (i.e. [n1,n2] and [n2,n1]) 6 | % Other routines used: adj2edgeL.m, adjL2edgeL.m, inc2edgeL.m 7 | 8 | function edges = getEdges(graph,type) 9 | 10 | if strcmp(type,'adj') 11 | edges=adj2edgeL(graph); 12 | 13 | elseif strcmp(type,'edgelist') 14 | edges=graph; % the graph structure is the edge list 15 | 16 | elseif strcmp(type,'adjlist') 17 | edges=adjL2edgeL(graph); 18 | 19 | elseif strcmp(type,'inc') 20 | edges=inc2edgeL(graph); 21 | else 22 | fprintf('"type" input can only be "adj" (adjacency, nxn matrix), "edgelist" (mx3 matrix)\n, "adjlist" (neighbor list, nx1 cell) and "inc" incidence (nxm matrix)\n') 23 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/getNodes.m: -------------------------------------------------------------------------------- 1 | % return the list of nodes for varying representation types 2 | % inputs: graph structure (matrix or cell or struct) and type of structure 3 | % (string) 4 | % 'type' can be: 'adj','edgelist','adjlist' (neighbor list),'inc' (incidence matrix) 5 | % Note 1: only the edge list allows/returns non-consecutive node indexing 6 | % Note 2: no build-in error check for graph structure - type matching 7 | 8 | function nodes = getNodes(graph,type) 9 | 10 | if strcmp(type,'adj') | strcmp(type,'adjlist') 11 | nodes=[1:max([size(graph,1) size(graph,2)])]; 12 | 13 | elseif strcmp(type,'edgelist') 14 | nodes=unique([graph(:,1)' graph(:,2)']); 15 | 16 | elseif strcmp(type,'inc') 17 | nodes=[1:size(graph,1)]; 18 | else 19 | fprintf('"type" input can only be "adj" (adjacency, nxn matrix), "edgelist" (mx3 matrix)\n, "adjlist" (neighbor list, nx1 cell) and "inc" incidence (nxm matrix)\n') 20 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/giant_component.m: -------------------------------------------------------------------------------- 1 | % extract giant component from a network 2 | % INPUTS: adjacency matrix 3 | % OUTPUTS: giant comp matrix and node indeces 4 | % Other routines used: find_conn_comp.m, subgraph.m 5 | % GB, Last Updated: October 2, 2009 6 | 7 | 8 | function [GC,gc_nodes]=giant_component(adj) 9 | 10 | comps=find_conn_comp(adj); 11 | 12 | L=[]; 13 | for k=1:length(comps); L=[L, length(comps{k})]; end 14 | [maxL,ind_max]=max(L); 15 | 16 | gc_nodes=comps{ind_max}; 17 | GC=subgraph(adj,gc_nodes); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_complement.m: -------------------------------------------------------------------------------- 1 | % Returns the complement of a graph 2 | % INPUTs: adj - original graph adjacency matrix 3 | % OUTPUTs: complement graph adjacency matrix 4 | % Note: Assumes no multiedges 5 | % GB, February 2, 2006 6 | 7 | function adj_c = graph_complement(adj) 8 | 9 | adj_c=ones(size(adj))-adj; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_dual.m: -------------------------------------------------------------------------------- 1 | % Finds the dual of a graph; a dual is the inverted nodes-edges graph 2 | % This is also called the line graph, adjoint graph or the edges adjacency 3 | % INPUTs: adjacency (neighbor) list representation of the graph (see adj2adjL.m) 4 | % OUTPUTs: adj (neighbor) list of the corresponding dual graph and cell array of edges 5 | % Note: this routine only works for undirected, simple graphs 6 | % GB, March 26, 2011 7 | 8 | function [dL,edge_array] = graph_dual(L) 9 | 10 | dL={}; % initialize 11 | for i=1:length(L) 12 | for j=1:length(L{i}) 13 | 14 | if i<=L{i}(j); dL{length(dL)+1}=[]; end 15 | 16 | end 17 | end 18 | 19 | edge_array={}; 20 | 21 | for i=1:length(L) 22 | 23 | for j=1:length(L{i}) % add i,L{i}j to list of nodes 24 | if i<=L{i}(j); edge_array{length(edge_array)+1}= strcat(num2str(i),'-',num2str(L{i}(j))); end 25 | end 26 | 27 | for j=1:length(L{i}) % add i - L{i}j to list of edges 28 | for k=j+1:length(L{i}) 29 | edge1=strcat(num2str(min([i,L{i}(j)])),'-',num2str(max([i,L{i}(j)]))); 30 | edge2=strcat(num2str(min([i,L{i}(k)])),'-',num2str(max([i,L{i}(k)]))); 31 | 32 | ind_edge1=find(ismember(edge_array, edge1)==1); 33 | ind_edge2=find(ismember(edge_array, edge2)==1); 34 | 35 | dL{ind_edge1}=unique([dL{ind_edge1},ind_edge2]); 36 | dL{ind_edge2}=unique([dL{ind_edge2},ind_edge1]); 37 | end 38 | end 39 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_energy.m: -------------------------------------------------------------------------------- 1 | % Graph energy defined as: the sum of the absolute values of the real components of the eigenvalues 2 | % Source: Gutman, The energy of a graph, Ber. Math. Statist. Sekt. Forsch-ungszentram Graz. 103 (1978) 1?22. 3 | % INPUTs: adjacency matrix (nxn) 4 | % OUTPUTs: graph energy 5 | 6 | function G=graph_energy(adj) 7 | 8 | [~,e]=eig(adj); % e are the eigenvalues 9 | G=sum(abs(real(diag(e)))); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_from_degree_sequence.m: -------------------------------------------------------------------------------- 1 | % Constructing a graph from a given degree sequence: deterministic 2 | % This is the Havel-Hakimi algorithm 3 | % Inputs: a graphic degree sequence, [d1,d2, ... dn], where di is the degree of the ith node 4 | % Outputs: adjacency matrix, nxn 5 | 6 | function adj = graph_from_degree_sequence(seq) 7 | 8 | adj = zeros(length(seq)); 9 | 10 | while sum(seq)>0 % while there are still stubs to connect 11 | 12 | % order stubs by decreasing number of degrees left 13 | [sorted,I] = sort(-seq); 14 | n1 = I(1); 15 | for x=1:-sorted(1) 16 | n2 = I(x+1); 17 | adj(n1,n2)= adj(n1,n2)+1; 18 | adj(n2,n1)= adj(n2,n1)+1; 19 | seq(n1) = seq(n1)-1; 20 | seq(n2) = seq(n2)-1; 21 | end 22 | 23 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_radius.m: -------------------------------------------------------------------------------- 1 | % The minimum vertex eccentricity is the graph radius 2 | % Inputs: adjacency matrix (nxn) 3 | % Outputs: graph radius 4 | % Other routines used: vertex_eccentricity.m 5 | 6 | function Rg=graph_radius(adj) 7 | 8 | Rg=min( vertex_eccentricity(adj) ); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_similarity.m: -------------------------------------------------------------------------------- 1 | % Computes the similarity matrix between two graphs 2 | % Ref: "A measure of similarity between graph vertices: 3 | % applications to synomym extraction and web searching" 4 | % Blondel, SIAM Review, Vol. 46, No. 4, pp. 647-666 5 | % Inputs: A, B - two graphs adjacency matrices, mxm and nxn 6 | % Outputs: S - similarity matrix, mxn 7 | % Last updated: December 11, 2006 8 | 9 | function S=graph_similarity(A,B) 10 | 11 | m=size(A,1); n=size(B,1); 12 | S=zeros(n,m); S_new=ones(n,m); % initialize S: 13 | 14 | while norm(S_new-S,'fro')>0.001 15 | S=S_new; 16 | % do an iteration twice 17 | S_new=(B*S*transpose(A)+transpose(B)*S*A)/norm(B*S*transpose(A)+transpose(B)*S*A,'fro'); 18 | S_new=(B*S_new*transpose(A)+transpose(B)*S_new*A)/norm(B*S_new*transpose(A)+transpose(B)*S_new*A,'fro'); 19 | end 20 | 21 | S=S_new; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/graph_spectrum.m: -------------------------------------------------------------------------------- 1 | % The eigenvalues of the Laplacian of the graph 2 | % INPUTs: adjacency matrix 3 | % OUTPUTs: laplacian eigenvalues, sorted 4 | 5 | function s=graph_spectrum(adj) 6 | 7 | [v,D]=eig(laplacian_matrix(adj)); 8 | s=-sort(-diag(D)); % sort in decreasing order -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/inc2adj.m: -------------------------------------------------------------------------------- 1 | % Converts an incidence matrix representation to an adjacency 2 | % matrix representation for an arbitrary graph 3 | % INPUTs: incidence matrix, nxm 4 | % OUTPUTs: adjacency matrix, nxn 5 | % GB, October 5, 2009 6 | 7 | function adj = inc2adj(inc) 8 | 9 | m = size(inc,2); % number of edges 10 | adj = zeros(size(inc,1)); % initialize adjacency matrix 11 | 12 | if isempty(find(inc==-1)) % undirected graph 13 | 14 | for e=1:m 15 | ind=find(inc(:,e)==1); 16 | if length(ind)==2 17 | adj(ind(1),ind(2))=1; 18 | adj(ind(2),ind(1))=1; 19 | elseif length(ind)==1 % selfloop 20 | adj(ind,ind)=1; 21 | else 22 | 'invalid incidence matrix' 23 | return 24 | end 25 | end 26 | 27 | else % directed graph 28 | 29 | for e=1:m 30 | ind1=find(inc(:,e)==1); 31 | indm1=find(inc(:,e)==-1); 32 | if isempty(indm1) & length(ind1)==1 % selfloop 33 | adj(ind1,ind1)=1; 34 | elseif length(indm1)==1 & length(ind1)==1 35 | adj(indm1,ind1)=1; 36 | else 37 | 'invalid incidence matrix' 38 | return 39 | end 40 | end 41 | 42 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/inc2edgeL.m: -------------------------------------------------------------------------------- 1 | % Converts an incidence matrix to an edgelist 2 | % inputs: inc - incidence matrix nxm 3 | % outputs: edgelist - mx3 4 | % GB, Last Updated: June 9, 2006 5 | 6 | function el = inc2edgeL(inc) 7 | 8 | m = size(inc,2); % number of edges 9 | el = zeros(m,3); % initialize edgelist [n1, n2, weight] 10 | 11 | for e=1:m 12 | ind_m1 = find(inc(:,e)==-1); 13 | ind_p1 = find(inc(:,e)==1); 14 | 15 | if numel(ind_m1)==0 & numel(ind_p1)==1 % undirected, self-loop 16 | el(e,:) = [ind_p1 ind_p1 1]; 17 | 18 | elseif numel(ind_m1)==0 & numel(ind_p1)==2 % undirected 19 | el(e,:) = [ind_p1(1) ind_p1(2) 1]; 20 | el=[el; ind_p1(2) ind_p1(1) 1]; 21 | 22 | elseif numel(ind_m1)==1 & numel(ind_p1)==1 % directed 23 | el(e,:) = [ind_m1 ind_p1 1]; 24 | 25 | end 26 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/isbipartite.m: -------------------------------------------------------------------------------- 1 | % Test whether a graph is bipartite, if yes, return the two vertex sets 2 | % Inputs: graph in the form of adjancency list (neighbor list, see adj2adjL.m) 3 | % Outputs: True/False (boolean), empty set (if False) or two sets of vertices 4 | % Note: This only works for undirected graphs 5 | % Last updated: April 28, 2011 6 | 7 | function [isit,A,B]=isbipartite(L) 8 | 9 | isit=true; % default 10 | A=[]; B=[]; 11 | 12 | queue=[1]; % initialize to first vertex arbitrarily 13 | visited=[]; % initilize to empty 14 | A=[1]; % put the first node on the queue in A, arbitrarily 15 | 16 | while not(isempty(queue)) 17 | 18 | i=queue(1); 19 | visited=[visited, i]; 20 | 21 | if length(find(A==i))>0 22 | for j=1:length(L{i}) 23 | B=[B,L{i}(j)]; 24 | if length(find(visited==L{i}(j)))==0; queue=[queue, L{i}(j)]; end 25 | end 26 | 27 | elseif length(find(B==i))>0 28 | 29 | for j=1:length(L{i}) 30 | A=[A,L{i}(j)]; 31 | if length(find(visited==L{i}(j)))==0; queue=[queue, L{i}(j)]; end 32 | end 33 | 34 | end 35 | 36 | queue=queue(2:length(queue)); % remove the visited node 37 | 38 | % if A and B overlap, return false, [],[] ==== 39 | A=unique(A); B=unique(B); 40 | if not(isempty(intersect(A,B))); isit=false; A=[]; B=[]; return; end 41 | % ============================================ 42 | 43 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/iscomplete.m: -------------------------------------------------------------------------------- 1 | % Checks whether a (sub)graph is complete, i.e. whether every node is 2 | % linked to every other node. Only defined for unweighted graphs. 3 | % INPUTS: adjacency matrix, adj, nxn 4 | % OUTPUTS: Boolean variable, true/false 5 | % GB, Last Updated: October 1, 2009 6 | 7 | function S=iscomplete(adj) 8 | 9 | S=false; % default 10 | 11 | adj=adj>0; % remove weights 12 | n=length(adj); 13 | 14 | % all degrees "n-1" or "n" or w/ n selfloops 15 | if sum(adj)==ones(1,n)*(n-1) | sum(adj)==ones(1,n)*n; S=true; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/isdirected.m: -------------------------------------------------------------------------------- 1 | % Using the matrix transpose function 2 | % INPUTS: adjacency matrix 3 | % OUTPUTS: boolean variable 4 | % GB, Last updated: October 1, 2009 5 | 6 | function S=isdirected(adj) 7 | 8 | S = true; 9 | if adj==transpose(adj); S = false; end 10 | 11 | % one-liner alternative: S=not(issymmetric(adj)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/iseulerian.m: -------------------------------------------------------------------------------- 1 | % Check if a graph is Eulerian, i.e. it has an Eulerian circuit 2 | % "A connected undirected graph is Eulerian if and only if every graph vertex has an even degree." 3 | % "A connected directed graph is Eulerian if and only if every graph vertex has equal in- and out- degree." 4 | % Note: Assume that the graph is connected. 5 | % INPUTS: adjacency matrix 6 | % OUTPUTS: Boolean variable 7 | % Other routines used: degrees.m, isdirected.m 8 | % GB, Last Updated: October 2, 2009 9 | 10 | 11 | function S=iseulerian(adj) 12 | 13 | S=false; 14 | 15 | [degs,indeg,outdeg]=degrees(adj); 16 | odd=find(mod(degs,2)==1); 17 | 18 | if not(isdirected(adj)) & isempty(odd) % if undirected and all degrees are even 19 | S=true; 20 | 21 | elseif isdirected(adj) & indeg==outdeg % directed and in-degrees equal out-degrees 22 | S=true; 23 | 24 | elseif numel(odd)==2 25 | fprintf('there is an Eulerian trail from node %2i to node %2i\n',odd(1),odd(2)); 26 | 27 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/isgraphic.m: -------------------------------------------------------------------------------- 1 | % Check whether a sequence of number is graphical, i.e. a graph with this degree sequence exists 2 | % INPUTs: a sequence (vector) of numbers 3 | % OUTPUTs: boolean, true or false 4 | % Note: not generalized to directed graph degree sequences 5 | % Source: Erdős, P. and Gallai, T. "Graphs with Prescribed Degrees of Vertices" [Hungarian]. Mat. Lapok. 11, 264-274, 1960. 6 | 7 | function B = isgraphic(seq) 8 | 9 | if not(isempty(find(seq<=0))) | mod(sum(seq),2)==1 10 | % there are non-positive degrees or their sum is odd 11 | B = false; return; 12 | end 13 | 14 | n=length(seq); 15 | seq=-sort(-seq); % sort in decreasing order 16 | 17 | for k=1:n-1 18 | sum_dk = sum(seq(1:k)); 19 | sum_dk1 = sum(min([k*ones(1,n-k);seq(k+1:n)])); 20 | 21 | if sum_dk > k*(k-1) + sum_dk1; B = false; return; end 22 | 23 | end 24 | 25 | B = true; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/isregular.m: -------------------------------------------------------------------------------- 1 | % Checks whether a graph is regular, i.e. every node has the same degree. 2 | % Note: Defined for unweighted graphs only. 3 | % INPUTS: adjacency matrix nxn 4 | % OUTPUTS: Boolean, yes/no 5 | % GB, Last updated: October 1, 2009 6 | 7 | function S=isregular(adj) 8 | 9 | S=false; 10 | 11 | degs=sum(adj>0); % remove weights and sum columns 12 | 13 | if degs == degs(1)*ones(size(degs)); S = true; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/issimple.m: -------------------------------------------------------------------------------- 1 | % Checks whether a graph is simple (no self-loops, no multiple edges) 2 | % INPUTs: adj - adjacency matrix 3 | % OUTPUTs: S - a Boolean variable 4 | % Other routines used: selfloops.m, multiedges.m 5 | % GB, Last updated: October 1, 2009 6 | 7 | function S = issimple(adj) 8 | 9 | S=true; 10 | 11 | % check for self-loops or double edges 12 | if selfloops(adj)>0 | multiedges(adj)>0; S=false; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/istree.m: -------------------------------------------------------------------------------- 1 | % Check whether a graph is a tree 2 | % Source: "Intro to Graph Theory" by Bela Bollobas 3 | % INPUTS: adjacency matrix 4 | % OUTPUTS: Boolean variable 5 | % Other routines used: isconnected.m, numedges.m, numnodes.m 6 | % GB, Last Updated: June 19, 2007 7 | 8 | function S=istree(adj) 9 | 10 | S=false; 11 | 12 | if isconnected(adj) & numedges(adj)==numnodes(adj)-1; S=true; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/isweighted.m: -------------------------------------------------------------------------------- 1 | % Check whether a graph is weighted, i.e not all edges are 0,1. 2 | % INPUTS: edge list, m x 3, m: number of edges, [node 1, node 2, edge weight] 3 | % OUTPUTS: Boolean variable, yes/no 4 | % GB, Last updated: October 1, 2009 5 | 6 | function S=isweighted(el) 7 | 8 | S=true; 9 | 10 | if numel( find(el(:,3)==1) ) == size(el,1); S=false; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/kmin_neighbors.m: -------------------------------------------------------------------------------- 1 | % Finds the number of "kmin"-neighbors (k links away at a minimum) for every node 2 | % If nodes are k-links away due to loops (so they appear as m-neighbours, m0)]; 14 | adjk = adjk*adj; 15 | end 16 | 17 | kneigh = setdiff(find(adjk(ind,:)>0),[close_neighbors ind]); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/kneighbors.m: -------------------------------------------------------------------------------- 1 | % Finds the number of k-neighbors (k links away) for every node 2 | % INPUTS: adjacency matrix, node index, k - number of links 3 | % OUTPUTS: vector of k-neighbors indices 4 | % GB, May 3, 2006 5 | 6 | function kneigh = kneighbors(adj,ind,k) 7 | 8 | adjk = adj; 9 | for i=1:k-1; adjk = adjk*adj; end; 10 | 11 | kneigh = find(adjk(ind,:)>0); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/kregular.m: -------------------------------------------------------------------------------- 1 | % Create a k-regular graph 2 | % INPUTs: n - # nodes, k - degree of each vertex 3 | % OUTPUTs: el - edge list of the k-regular undirected graph 4 | % GB, Last updated: January 12, 2011 5 | 6 | function eln = kregular(n,k) 7 | 8 | el={}; 9 | 10 | if k>n-1; fprintf('a simple graph with n nodes and k>n-1 does not exist\n'); return; end 11 | if mod(k,2)==1 & mod(n,2)==1; fprintf('no solution for this case\n'); return; end 12 | 13 | 14 | half_degree=floor(k/2); % k/2 if k even, else (k-1)/2 15 | 16 | 17 | for node=1:n 18 | for kk=1:half_degree 19 | 20 | node_f=mod(node+kk,n); 21 | if node_f==0; node_f=n; end 22 | edge_f=strcat(num2str(node),'+',num2str(node_f)); 23 | 24 | node_b=mod(node-kk,n); 25 | if node_b==0; node_b=n; end 26 | edge_b=strcat(num2str(node),'+',num2str(node_b)); 27 | 28 | if sum(ismember(el,edge_f))==0 29 | el{length(el)+1}=edge_f; 30 | end 31 | if sum(ismember(el,edge_b))==0 32 | el{length(el)+1}=edge_b; 33 | end 34 | 35 | end 36 | end 37 | 38 | if mod(k,2)==1 & mod(n,2)==0 39 | % connect mirror nodes 40 | for node=1:n/2 41 | 42 | node_m=mod(node+n/2,n); 43 | if node_m==0; node_m=n; end 44 | edge_m=strcat(num2str(node),'+',num2str(node_m)); 45 | 46 | if sum(ismember(el,edge_m))==0 47 | el{length(el)+1}=edge_m; 48 | end 49 | 50 | end 51 | end 52 | 53 | 54 | eln=[]; 55 | for edge=1:length(el) 56 | edge=el{edge}; 57 | plus=find(edge=='+'); 58 | eln=[eln; str2num(edge(1:plus-1)), str2num(edge(plus+1:length(edge))), 1]; 59 | end 60 | eln=symmetrize_edgeL(eln); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/laplacian_matrix.m: -------------------------------------------------------------------------------- 1 | % The Laplacian matrix defined for a *simple* graph 2 | % (the difference b/w the diagonal degree and the adjacency matrices) 3 | % Note: This is not the normalized Laplacian 4 | % INPUTS: adjacency matrix 5 | % OUTPUTs: Laplacian matrix 6 | 7 | function L=laplacian_matrix(adj) 8 | 9 | L=diag(sum(adj))-adj; 10 | 11 | 12 | % NORMALIZED Laplacian ============= 13 | 14 | % n=length(adj); 15 | % deg = sum(adj); % for other than simple graphs, use [deg,~,~]=degrees(adj); 16 | 17 | % L=zeros(n); 18 | % edges=find(adj>0); 19 | % 20 | % for e=1:length(edges) 21 | % [ii,jj]=ind2sub([n,n],edges(e)) 22 | % if ii==jj; L(ii,ii)=1; continue; end 23 | % L(ii,jj)=-1/sqrt(deg(ii)*deg(jj)); 24 | % end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/leaf_edges.m: -------------------------------------------------------------------------------- 1 | % Return the leaf edges of the graph: edges with one adjacent edge only 2 | % Leaf edges have only one associated leaf node, otherwise they are single floating disconnected edges. 3 | % Assumptions: 4 | % Note 1: For a directed graph, leaf edges are those that "flow into" the leaf node 5 | % Note 2: There could be other definitions of leaves ex: farthest away from a given root node 6 | % Note 3: Edges that are self-loops are not considered leaf edges. 7 | % Input: adjacency matrix 8 | % Output: set of leaf edges: a (num edges x 2) matrix where every row containts the leaf edge nodal indices 9 | % Last updated: June 27, 2011, by GB 10 | 11 | 12 | function edges=leaf_edges(adj) 13 | 14 | adj=int8(adj>0); 15 | 16 | lves=find(sum(adj)==1); % same as leaf_nodes.m 17 | 18 | edges=[]; 19 | 20 | for i=1:length(lves); edges=[edges; find(adj(:,lves(i))==1),lves(i)]; end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/leaf_nodes.m: -------------------------------------------------------------------------------- 1 | % Return the leaf nodes of the graph - degree 1 nodes 2 | % Note: For a directed graph, leaf nodes are those with a single incoming edge 3 | % Note 2: There could be other definitions of leaves ex: farthest away from a given root node 4 | % Note 3: Nodes with self-loops are not considered leaf nodes. 5 | % Input: adjacency matrix 6 | % Output: indexes of leaf nodes 7 | % Last updated: Mar 25, 2011, by GB 8 | 9 | function leaves=leaf_nodes(adj) 10 | 11 | adj=int8(adj>0); 12 | 13 | leaves=find(sum(adj)==1); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2011, Massachusetts Institute of Technology. 2 | All rights reserved. 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 7 | - Neither the name of the Massachusetts Institute of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 8 | 9 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 10 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/link_density.m: -------------------------------------------------------------------------------- 1 | % Computes the link density of a graph, defined as num_edges divided by 2 | % num_nodes(num_nodes-1)/2 where the latter is the max possible num edges. 3 | % The graph needs to be non-trivial (more than 1 node). 4 | % Other routines used: numnodes.m, numedges.m 5 | % GB, Last Update: October 1, 2009 6 | 7 | function d=link_density(adj) 8 | 9 | n = numnodes(adj); 10 | d = 2*numedges(adj)/(n*(n-1)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/loops3.m: -------------------------------------------------------------------------------- 1 | % Calculates number of loops of length 3 2 | % INPUTs: adj - adjacency matrix 3 | % OUTPUTs: L3 - number of triangles (loops of length 3) 4 | % Valid for an undirected network 5 | % GB, April 6, 2006 6 | 7 | function L3 = loops3(adj) 8 | 9 | L3 = trace(adj^3)/6; % trace(adj^3)/3! -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/loops4.m: -------------------------------------------------------------------------------- 1 | % Finds loops of length 4 in a graph; Note: Quite basic and slow, but works 2 | % INPUTs: adj - adjacency matrix of graph 3 | % OUTPUTs: number of loops of size 4 4 | % Note: assumes undirected graph 5 | % Other functions used: adj2adjL.m 6 | % Last Updated: May 25, 2010, originally April 2006 7 | 8 | function l4 = loops4(adj) 9 | 10 | n = size(adj,1); % number of nodes 11 | L = adj2adjL(adj); % adjacency list or list of neighbors 12 | 13 | l4 = {}; % initialize loops of size 4 14 | 15 | for i=1:n-1 16 | for j=i+1:n 17 | 18 | int=intersect(L{i},L{j}); 19 | int=setdiff(int,[i j]); 20 | 21 | if length(int)>=2 22 | % enumerate pairs in the intersection 23 | for ii=1:length(int)-1 24 | for jj=ii+1:length(int) 25 | loop4=sort([i,j,int(ii),int(jj)]); 26 | loop4=strcat(num2str(loop4(1)),'-',num2str(loop4(2)),'-',num2str(loop4(3)),'-',num2str(loop4(4))); 27 | 28 | if sum(ismember(l4,loop4))>0; continue; end 29 | l4{length(l4)+1}=loop4; 30 | 31 | end 32 | end 33 | end 34 | 35 | 36 | end 37 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/master_equation_growth_model.m: -------------------------------------------------------------------------------- 1 | % "Master equation" growth model, as in "Evolution of Networks" by Dorogovtsev, Mendez 2 | % Note: probability of attachment: (q(i)+ma)/((1+a)mt), q(i)-indegree of i, a=const, t - time step (# nodes) 3 | % INPUTS: number of nodes n, m - # links to add at each step, a=constant 4 | % OUTPUTS: adjacency matrix, nxn 5 | % Last updated by GB: May 18, 2007 6 | 7 | function adj=master_equation_growth_model(n,m,a) 8 | 9 | adj=zeros(n); adj(1,2)=2; adj(2,1)=2; % initial condition 10 | vertices = 2; 11 | if nargin==2 | a==[]; a = 2; end % pick a constant 12 | 13 | while vertices < n 14 | 15 | t = vertices; 16 | q=sum(adj); % indegrees 17 | 18 | % compute the probability of attachment 19 | pk = zeros(1,t); 20 | for k=1:t; pk(k)=(q(k)+m*a)/((1+a)*m*t); end 21 | 22 | r = randsample([1:t],m,true,pk); 23 | if length(unique(r))~=length(r) 24 | r = randsample([1:t],m,true,pk); 25 | end 26 | 27 | vertices=vertices+1; % add vertex 28 | 29 | % add m links 30 | for node=1:length(r) 31 | adj(vertices,r(node))=1; 32 | adj(r(node),vertices)=1; 33 | end 34 | 35 | adj(vertices,vertices)=1; % for the purposes of non-zero probability of attachment 36 | 37 | end 38 | 39 | adj = adj>0; 40 | adj=adj-diag(diag(adj)); % remove self-loops -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/min_span_tree.m: -------------------------------------------------------------------------------- 1 | % Prim's minimal spanning tree algorithm 2 | % Prim's alg idea: 3 | % start at any node, find closest neighbor and mark edges 4 | % for all remaining nodes, find closest to previous cluster, mark edge 5 | % continue until no nodes remain 6 | % INPUTS: graph defined by adjacency matrix 7 | % OUTPUTS: matrix specifying minimum spanning tree (subgraph) 8 | % Other routines used: isconnected.m 9 | % GB, March 14, 2005 10 | 11 | function tr = min_span_tree(adj) 12 | 13 | % check if graph is connected: 14 | if not(isconnected(adj)); fprintf('the graph is not connected, no spanning tree exists\n'); return; end 15 | 16 | n = length(adj); % number of nodes 17 | tr = zeros(n); % initialize tree 18 | 19 | adj(find(adj==0))=inf; % set all zeros in the matrix to inf 20 | 21 | conn_nodes = 1; % nodes part of the min-span-tree 22 | rem_nodes = [2:n]; % remaining nodes 23 | 24 | while length(rem_nodes)>0 25 | [minlink]=min(min(adj(conn_nodes,rem_nodes))); 26 | ind=find(adj(conn_nodes,rem_nodes)==minlink); 27 | 28 | [ind_i,ind_j] = ind2sub([length(conn_nodes),length(rem_nodes)],ind(1)); 29 | 30 | i=conn_nodes(ind_i); j=rem_nodes(ind_j); % gets back to adj indices 31 | tr(i,j)=1; tr(j,i)=1; 32 | conn_nodes = [conn_nodes j]; 33 | rem_nodes = setdiff(rem_nodes,j); 34 | 35 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/modularity_metric.m: -------------------------------------------------------------------------------- 1 | % Computing the modularity for a given module/commnunity break-down 2 | % Defined as: Q=sum_over_modules_i (eii-ai^2) (eq 5) in Newman and Girvan. 3 | % eij = fraction of edges that connect community i to community j, ai=sum_j (eij) 4 | % Source: Newman, M.E.J., Girvan, M., "Finding and evaluating community structure in networks" 5 | % Also: "Fast algorithm for detecting community structure in networks", Mark Newman 6 | % Inputs: adjacency matrix and set modules as cell array of vectors, ex: {[1,2,3],[4,5,6]} 7 | % Outputs: modularity metric, in [-1,1] 8 | % Other functions used: numedges.m 9 | % Last updated: June 13, 2011 10 | 11 | function Q=modularity_metric(modules,adj) 12 | 13 | nedges=numedges(adj); % total number of edges 14 | 15 | Q = 0; 16 | for m=1:length(modules) 17 | 18 | e_mm=numedges(adj(modules{m},modules{m}))/nedges; 19 | a_m=sum(sum(adj(modules{m},:)))/(2*nedges); 20 | Q = Q + (e_mm - a_m^2); 21 | 22 | end 23 | 24 | 25 | % $$$ % alternative: Q = sum_ij { 1/2m [Aij-kikj/2m]delta(ci,cj) } = 26 | % $$$ % = sum_ij Aij/2m delta(ci,cj) - sum_ij kikj/4m^2 delta(ci,cj) = 27 | % $$$ % = sum_modules e_mm - sum_modules (kikj/4m^2) = 28 | % $$$ % = sum_modules (e_mm - ((sum_i ki)/2m)^2) 29 | % $$$ 30 | % $$$ n = numnodes(adj); 31 | % $$$ m = numedges(adj); 32 | % $$$ 33 | % $$$ mod={}; 34 | % $$$ for mm=1:length(modules) 35 | % $$$ for ii=1:length(modules{mm}) 36 | % $$$ mod{modules{mm}(ii)}=modules{mm}; 37 | % $$$ end 38 | % $$$ end 39 | % $$$ 40 | % $$$ Q = 0; 41 | % $$$ 42 | % $$$ for i=1:n 43 | % $$$ for j=1:n 44 | % $$$ 45 | % $$$ if not(isequal(mod(i),mod(j))) 46 | % $$$ continue 47 | % $$$ end 48 | % $$$ 49 | % $$$ Q = Q + (adj(i,j) - sum(adj(i,:))*sum(adj(j,:))/(2*m))/(2*m); 50 | % $$$ 51 | % $$$ end 52 | % $$$ end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/multiedges.m: -------------------------------------------------------------------------------- 1 | % counts the number of multiple edges in the graph 2 | % INPUT: adjacency matrix 3 | % OUTPUT: interger, number of multiple edges 4 | % Last Updated: GB, October 1, 2009 5 | 6 | function mE=multiedges(adj) 7 | 8 | mE=length(find(adj>1)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/newmangastner.m: -------------------------------------------------------------------------------- 1 | % Implements the Newman-Gastner model for spatially distributed networks 2 | % Source: Newman, Gastner, "Shape and efficiency in spatial distribution networks" 3 | % Note 1: minimize: wij = dij + beta x (dj0) 4 | % Note 2: easy to change to input point coordinates, instead of generate randomly 5 | % Inputs: n - number of points/nodes, beta - parameter [0,1], plt - 'on'/'off' 6 | % Outputs: graph (edgelist), point coordinates and plot [optional] 7 | % GB, Last Updated: May 23, 2007 8 | 9 | function [el,points]=newmangastner(n,beta,plt) 10 | 11 | % create random point coordinates 12 | points = zeros(n-1,2); 13 | rad = rand(1,n-1); 14 | theta = 2*pi*rand(1,n-1); 15 | for i=1:n-1; points(i,:) = rad(i)*[cos(theta(i)),sin(theta(i))]; end 16 | points=[[0 0]; points]; % add zero 17 | 18 | % order points in closeness to 0 19 | for i=1:n; normp(i)=norm(points(i,:)); end 20 | [normps,ind]=sort(normp); 21 | points=points(ind,:); 22 | 23 | % calculate distances between all points (can also use pdist) 24 | L=zeros(n); 25 | for i=1:n 26 | for j=i+1:n 27 | L(i,j)=norm(points(i,:)-points(j,:)); 28 | L(j,i)=L(i,j); 29 | end 30 | L(i,i)=Inf; 31 | end 32 | 33 | if nargin>2 & strcmp(plt,'on') % if plot is 'on' 34 | set(gcf,'Color',[1 1 1]) 35 | plot(points(:,1),points(:,2),'.','Color',[1,1,1]) 36 | hold off; hold on; 37 | axis off 38 | end 39 | 40 | % connect points consequtively 41 | el=[]; 42 | for i=2:n 43 | % current node is "i" 44 | w=L(i,1:i-1)+beta*normps(1:i-1); 45 | [minv,minj]=min(w); 46 | el=[el; i minj 1]; 47 | 48 | if nargin>2 & strcmp(plt,'on') % if plot is 'on' 49 | line([points(i,1) points(minj,1)],[points(i,2) points(minj,2)],'Color',[0.5,0.5,0.5]) 50 | hold off; hold on; 51 | drawnow 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/node_betweenness_faster.m: -------------------------------------------------------------------------------- 1 | % Betweenness centrality measure: number of shortest paths running though a vertex 2 | % Compute for all vertices, using Dijkstra's algorithm, using 'number of shortest paths through a node' definition 3 | % Note: Valid for a general (connected) graph. 4 | % INPUTS: adjacency (distances) matrix (nxn) 5 | % OUTPUTS: betweeness vector for all vertices (nx1) 6 | % Other routines used: dijkstra.m 7 | % GB, December 22, 2009 8 | 9 | function betw = node_betweenness_faster(adj) 10 | 11 | n = length(adj); 12 | spaths=inf(n,n); 13 | adjk = adj; 14 | 15 | % calculate number of shortest paths 16 | for k=1:n-1 17 | 18 | for i=1:n 19 | for j=1:n 20 | 21 | if adjk(i,j)>0; spaths(i,j)=min([spaths(i,j) adjk(i,j)]); end 22 | 23 | end 24 | end 25 | 26 | adjk=adjk*adj; 27 | 28 | end 29 | 30 | 31 | betw = zeros(1,n); 32 | for i=1:n 33 | [dist,P]=dijkstra(adj,i,[]); 34 | for j=1:n 35 | 36 | if dist(j)<=1; continue; end % either i=j or i,j are 1 edge apart 37 | betw(P{j}(2:dist(j))) = betw(P{j}(2:dist(j))) + 1/spaths(i,j); 38 | 39 | end 40 | end 41 | 42 | betw=betw/nchoosek(n,2); % further normalize by the number of all node pairs -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/node_betweenness_slow.m: -------------------------------------------------------------------------------- 1 | % Betweenness centrality measure: number of shortest paths running though a 2 | 3 | % vertex. Compute for all vertices. 4 | 5 | % Note: Valid for a general graph. Using 'number of shortest paths through a node' definition 6 | 7 | % INPUTS: adjacency (distances) matrix (nxn) 8 | 9 | % OUTPUTS: betweeness vector for all vertices (nx1) 10 | 11 | % 12 | 13 | % GB, October 13, 2009 14 | 15 | 16 | 17 | function betw = node_betweenness_slow(adj) 18 | 19 | 20 | 21 | n = numnodes(adj); 22 | 23 | spaths=inf(n,n); 24 | 25 | 26 | 27 | % calculate number of shortest paths 28 | 29 | for k=1:n-1 30 | 31 | adjk=adj^k; 32 | 33 | for i=1:n 34 | 35 | for j=1:n 36 | 37 | if adjk(i,j)>0 38 | 39 | spaths(i,j)=min([spaths(i,j) adjk(i,j)]); 40 | 41 | end 42 | 43 | end 44 | 45 | end 46 | 47 | end 48 | 49 | 50 | 51 | betw = zeros(1,n); 52 | 53 | for i=1:n 54 | 55 | [J_st,route_st,J,route]=shortest_pathDP(adj,i,i,n); 56 | 57 | for j=1:n 58 | 59 | if i==j 60 | 61 | continue 62 | 63 | end 64 | 65 | %[J_st,route_st]=shortest_pathDP(adj,i,j,n); 66 | 67 | [J_ji,step_ind] = min(J(:,j)); 68 | 69 | route_ji = [j, route(step_ind,j).path]; 70 | 71 | betw(route_ji(2:length(route_ji)-1)) = betw(route_ji(2:length(route_ji)-1)) + 1/spaths(j,i); 72 | 73 | end 74 | 75 | end 76 | 77 | 78 | 79 | betw=betw/nchoosek(n,2); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/num_conn_comp.m: -------------------------------------------------------------------------------- 1 | % Calculate the number of connected components using the Laplacian 2 | % eigenvalues - counting the number of zeros 3 | % INPUTS: adjacency matrix 4 | % OUTPUTs: positive integer - number of connected components 5 | % Other routines used: graph_spectrum.m 6 | % GB, Last updated: October 22, 2009 7 | 8 | function nc=num_conn_comp(adj) 9 | 10 | s=graph_spectrum(adj); 11 | nc=numel(find(s<10^(-5))); % zero eigenvalues are sometimes close to zeros numerically in matlab -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/num_conn_triples.m: -------------------------------------------------------------------------------- 1 | % Counts the number of connected triples in a graph 2 | % INPUTs: adjacency matrix 3 | % OUTPUTs: integer - num conn triples 4 | % Other routines used: kneighbors.m, loops3.m 5 | % Note: works for undirected graphs only 6 | % GB, Last updated: October 9, 2009 7 | 8 | function c=num_conn_triples(adj) 9 | 10 | c=0; % initialize 11 | 12 | for i=1:length(adj) 13 | neigh=kneighbors(adj,i,1); 14 | if length(neigh)<2; continue; end % handle leaves, no triple here 15 | c=c+nchoosek(length(neigh),2); 16 | end 17 | 18 | c=c-2*loops3(adj); % due to the symmetry triangles repeat 3 times in the nchoosek count -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/num_loops.m: -------------------------------------------------------------------------------- 1 | % Calculate the number of independent loops (use G=m-n+c) 2 | % where G = num loops, m - num edges, n - num nodes, c - num_connected_components 3 | % This is also known as the "cyclomatic number" or the number of edges that need to be removed so that the graph cannot have cycles. 4 | % INPUTS: adjacency matrix 5 | % OUTPUTs: number of independent loops (or cyclomatic number) 6 | % Other routines used: numnodes.m, numedges.m, find_conn_comp.m 7 | 8 | function G = num_loops(adj) 9 | 10 | n=numnodes(adj); 11 | m=numedges(adj); 12 | comp_mat = find_conn_comp(adj); 13 | 14 | G=m-n+length(comp_mat); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/num_star_motifs.m: -------------------------------------------------------------------------------- 1 | % Calculates the number of star motifs of given (subgraph) size 2 | % Easily extendible to return the actual stars as k-tuples of nodes 3 | % INPUTs: adjacency matrix of original graph, k - size of the star motif 4 | % OUTPUTs: number of stars with k nodes (k-1 spokes) 5 | % Other routines used: degrees.m 6 | % Note: star of size 1 is the trivial case of a single node 7 | 8 | function num = num_star_motifs(adj,k) 9 | 10 | [deg,~,~]=degrees(adj); 11 | 12 | num=0; 13 | 14 | for i=1:length(deg) 15 | if deg(i)>=(k-1); num=num+nchoosek(deg(i),k-1); end 16 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/numedges.m: -------------------------------------------------------------------------------- 1 | % Returns the total number of edges given the adjacency matrix 2 | % Valid for both directed and undirected, simple or general graph 3 | % INPUTs: adjacency matrix 4 | % OUTPUTs: m - total number of edges/links 5 | % Other routines used: selfloops.m, issymmetric.m 6 | % GB, Last Updated: October 1, 2009 7 | 8 | function m = numedges(adj) 9 | 10 | sl=selfloops(adj); % counting the number of self-loops 11 | 12 | if issymmetric(adj) & sl==0 % undirected simple graph 13 | m=sum(sum(adj))/2; 14 | return 15 | elseif issymmetric(adj) & sl>0 16 | sl=selfloops(adj); 17 | m=(sum(sum(adj))-sl)/2+sl; % counting the self-loops only once 18 | return 19 | elseif not(issymmetric(adj)) % directed graph (not necessarily simple) 20 | m=sum(sum(adj)); 21 | return 22 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/numnodes.m: -------------------------------------------------------------------------------- 1 | % Returns the number of nodes, given an adjacency list 2 | % also works for an adjacency matrix 3 | % INPUTs: adjacency list: {i:j_1,j_2 ..} 4 | % OUTPUTs: number of nodes 5 | % GB, February 19, 2006 6 | 7 | function n = numnodes(L) 8 | 9 | n = length(L); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/pajek2adj.m: -------------------------------------------------------------------------------- 1 | % This program extracts an adjacency matrix from a pajek text (.net) file 2 | % INPUT .net text filename, n - number of nodes in the graph 3 | % OUTPUT: adjacency matrix, nxn, n - # nodes 4 | % Other routines used: pajek2edgeL.m, edgeL2adj.m 5 | % GB, October 7, 2009 6 | 7 | function adj = pajek2adj(filename,n) 8 | 9 | el=pajek2edgeL(filename,n); 10 | adj=edgeL2adj(el); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/pajek2edgeL.m: -------------------------------------------------------------------------------- 1 | % This program extracts an edge list from a pajek text (.net) file 2 | % INPUT: .net (or .txt) filename, n - number of nodes in the graph 3 | % OUTPUT: edge list, mx3, m - # edges 4 | % GB, October 7, 2009 5 | 6 | function el=pajek2edgeL(filename,n) 7 | 8 | [e1,e2,e3] = textread(filename,'%6d%6d%6d','headerlines',n+2); 9 | el=[e1,e2,e3]; 10 | 11 | % ALTERNATIVE: Not using the number of nodes as an input: 12 | % f=fopen(filename,'r'); 13 | % C = textscan(f, '%s'); 14 | % c=C{1}; 15 | % ind_edges=find(ismember(c, '*Edges')==1); 16 | % 17 | % e1=[]; e2=[]; e3=[]; 18 | % for cc=ind_edges:length(c) 19 | % % two indices are edges, one is weight and again 20 | % if mod(ind_edges,3)==mod(cc,3) % this is edge weight 21 | % e3=[e3, str2num(c{cc})]; 22 | % elseif mod(ind_edges,3)==mod(cc-1,3) % this is node 1 23 | % e1=[e1, str2num(c{cc})]; 24 | % elseif mod(ind_edges,3)==mod(cc-2,3) % this is node 2 25 | % e2=[e2, str2num(c{cc})]; 26 | % end 27 | % end 28 | % 29 | % el=[e1',e2',e3']; -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/pajek2xyz.m: -------------------------------------------------------------------------------- 1 | % Read x,y,z node coordinates from a pajek .net file - useful for plotting in Matlab 2 | % INPUTS: filename, string format 3 | % OUTPUTS: x,y,z coordinate vectors 4 | % GB, Last updated: October 7, 2009 5 | 6 | function [x,y,z]=pajek2xyz(filename) 7 | 8 | f=fopen(filename,'r'); 9 | C = textscan(f, '%s'); 10 | c=C{1}; 11 | 12 | ind_edges=find(ismember(c, '*Edges')==1); 13 | if isempty(ind_edges); ind_edges=find(ismember(c, '*Arcs')==1); end 14 | 15 | % c{1}='*Vertices', n=str2num(c{2}); % number of nodes 16 | % c{3},c{8},c{13},...c{5k+3} are node indices 17 | % c{4},c{9},c{14},...c{5k+4} are 'vi', between them are coordinates 18 | 19 | x=[]; y=[]; z=[]; % initialize coordinates 20 | 21 | for cc=3:ind_edges-1 22 | if mod(cc,5)==4 23 | x=[x, str2num(c{cc+1})]; 24 | y=[y, str2num(c{cc+2})]; 25 | z=[z, str2num(c{cc+3})]; 26 | end 27 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/pdf_cdf_rank.m: -------------------------------------------------------------------------------- 1 | % Compute the pdf, cdf and rank distributions for a sequence of values 2 | % INPUTS: sequence of values: x, size 1xn, 'plot' - 'on' or 'off' 3 | % OUTPUTS: pdf, cdf and rank distribution values 4 | % Note: pdf = frequency, cdf = cumulative frequency, rank = log-log scale of the sorted sequence 5 | % GB, Last Updated: June 27, 2007 6 | 7 | function [xpdf,ypdf,xcdf,ycdf,logk,logx]=pdf_cdf_rank(x,plt) 8 | 9 | xx=unique(x); 10 | 11 | bin = 100; % arbitrary, change if xx has few values 12 | if length(xx)<100; bin = 10; end; 13 | 14 | 15 | for ii=1:numel(xx) 16 | xcdf(ii) = xx(ii); ycdf(ii) = length(find(x<=xx(ii)))/numel(x); 17 | 18 | % how many x's fall in the interval [xx(ii)-0.5*numel(xx)/bin,xx(ii)+0.5*numel(xx)/bin] 19 | xpdf(ii) = xx(ii); ypdf(ii) = length(find(abs(xx(ii)-x)<=0.5*numel(xx)/bin))/numel(x); 20 | end 21 | 22 | x=-sort(-x); 23 | logk=log(1:length(x)); 24 | logx=log(x); 25 | 26 | if strcmp(plt,'on') 27 | set(gcf,'color',[1,1,1]) 28 | subplot(1,3,1) 29 | plot(xpdf,ypdf,'k.') 30 | title('pdf') 31 | axis('tight') 32 | subplot(1,3,2) 33 | plot(xcdf,ycdf,'k.') 34 | title('cdf') 35 | axis('tight') 36 | subplot(1,3,3) 37 | plot(logk,logx,'k.') 38 | title('rank') 39 | axis('tight') 40 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/pearson.m: -------------------------------------------------------------------------------- 1 | % Calculating the Pearson coefficient for a degree sequence 2 | % INPUTs: M - matrix, square 3 | % OUTPUTs: r - Pearson coefficient 4 | % Courtesy: Dr. Daniel Whitney, circa 2006 5 | 6 | function prs = pearson(M) 7 | 8 | %calculates pearson degree correlation of M 9 | [rows,colms]=size(M); 10 | won=ones(rows,1); 11 | k=won'*M; 12 | ksum=won'*k'; 13 | ksqsum=k*k'; 14 | xbar=ksqsum/ksum; 15 | num=(won'*M-won'*xbar)*M*(M*won-xbar*won); 16 | M*(M*won-xbar*won); 17 | kkk=(k'-xbar*won).*(k'.^.5); 18 | denom=kkk'*kkk; 19 | 20 | prs=num/denom; 21 | 22 | 23 | % ALTERNATIVE ===== BETTER-DOCUMENTED ==================================== 24 | 25 | % Calculating the Pearson coefficient for a degree sequence 26 | % INPUTs: M - matrix, square 27 | % OUTPUTs: r - Pearson coefficient 28 | % source: "Assortative Mixing in Network", M.E.J. Newman, PhysRevLet 2002 29 | % GB, March 15, 2006 30 | 31 | % function r = pearson(M) 32 | % 33 | % [degs,~,~] = degrees(M); % get the total degree sequence 34 | % m = numedges(M); % number of edges in M 35 | % inc = adj2inc(M); % get incidence matrix for convience 36 | % 37 | % % j,k - remaining degrees of adjacent nodes for a given edge 38 | % % sumjk - sum of all products jk 39 | % % sumjplusk - sum of all sums j+k 40 | % % sumj2plusk2 - sum of all sums of squares j^2+k^2 41 | % 42 | % % compute sumjk, sumjplusk, sumj2plusk2 43 | % sumjk = 0; sumjplusk = 0; sumj2plusk2 = 0; 44 | % for i=1:m 45 | % [v] = find(inc(:,i)==1); 46 | % j = degs(v(1))-1; k = degs(v(2))-1; % remaining degrees of 2 end-nodes 47 | % sumjk = sumjk + j*k; 48 | % sumjplusk = sumjplusk + 0.5*(j+k); 49 | % sumj2plusk2 = sumj2plusk2 + 0.5*(j^2+k^2); 50 | % end 51 | % 52 | % % Pearson coefficient formula 53 | % r = (sumjk - sumjplusk^2/m)/(sumj2plusk2-sumjplusk^2/m); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/preferential_attachment.m: -------------------------------------------------------------------------------- 1 | % Routine implementing a simple preferential attachment (B-A) model for network growth 2 | % The probability that a new vertex attaches to a given old vertex is proportional to the (total) vertex degree 3 | % Vertices arrive one at a time 4 | % INPUTs: n - final (desired) number of vertices, m - # edges to attach at every step 5 | % OUTPUTs: edge list, [number of edges x 3] 6 | % NOTE: Assume undirected simple graph 7 | % Source: "The Structure and Function of Complex Networks", M.E.J. Newman; "Emergence of Scaling in Random Networks" B-A. 8 | % GB, March 18, 2006 9 | 10 | function el = preferential_attachment(n,m) 11 | 12 | vertices = 2; 13 | if not(vertices<=n); fprintf('the number of final nodes is smaller than the initial\n'); return; end 14 | el=[1 2 1; 2 1 1]; % start with an edge 15 | 16 | 17 | while vertices < n 18 | vertices=vertices+1; % add new vertex 19 | 20 | if m>=vertices 21 | for node=1:vertices-1 22 | el = [el; node vertices 1]; 23 | el = [el; vertices node 1]; 24 | end 25 | continue 26 | end 27 | 28 | deg=[]; % compute nodal degrees for this iteration 29 | for v=1:vertices; deg=[deg; v numel(find(el(:,1)==v))]; end 30 | deg=sortrows(deg); 31 | 32 | % add m edges 33 | r = randsample(deg(:,1),m,'true',deg(:,2)/max(deg(:,2))); 34 | while not(length(unique(r))==length(r)) 35 | r = randsample(deg(:,1),m,'true',deg(:,2)/max(deg(:,2))); 36 | end 37 | 38 | for node=1:length(r) 39 | el = [el; r(node) vertices 1]; 40 | el = [el; vertices r(node) 1]; 41 | end 42 | 43 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/purge.m: -------------------------------------------------------------------------------- 1 | % Removes a subset from a set, but preserves order of elements 2 | % Similar to setdiff - which sorts the elements 3 | % INPUTs: original set A, subset to remove B 4 | % OUTPUTs: set Anew = A-B 5 | % GB, Last updated: October 12, 2009 6 | 7 | function Anew = purge(A,B) 8 | 9 | Anew = []; 10 | for a=1:numel(A); 11 | if isempty(find(B==A(a))); Anew=[Anew, A(a)]; end 12 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/random_directed_graph.m: -------------------------------------------------------------------------------- 1 | % Random directed graph construction 2 | % INPUTS: N - number of nodes 3 | % p - probability, 0<=p<=1 4 | % Output: adjacency matrix 5 | % Note 1: if p is omitted, p=0.5 is default 6 | % Note 2: no self-loops, no double edges 7 | 8 | function adj = random_directed_graph(n,p) 9 | 10 | adj=zeros(n); % initialize adjacency matrix 11 | 12 | if nargin==1; p=0.5; end; 13 | 14 | % splitting j = 1:i-1,i+1,n avoids the if statement i==j 15 | 16 | for i=1:n 17 | 18 | for j=1:i-1 19 | if rand<=p; adj(i,j)=1; end; 20 | end 21 | 22 | 23 | for j=i+1:n 24 | if rand<=p; adj(i,j)=1; end; 25 | end 26 | 27 | end 28 | 29 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/random_modular_graph.m: -------------------------------------------------------------------------------- 1 | % Build a random modular graph, given number of modules, and link density 2 | % INPUTs: number of nodes, number of modules, total link density, 3 | % and proportion of links within modules compared to links across 4 | % OUTPUTs: adjacency matrix, modules to which the nodes are assigned 5 | % GB, Last updated: October 19, 2009 6 | 7 | function [A, modules] = random_modular_graph(n,c,p,r) 8 | 9 | % n - number of nodes 10 | % c - number of clusters/modules 11 | % p - overall probability of attachment 12 | % r - proportion of links within modules 13 | 14 | z=round(p*(n-1)); % z=p(n-1) - Erdos-Renyi average degree 15 | 16 | % assign nodes to modules: 1 -> n/c, n/c+1 -> 2n/c, ... , (c-1)n/c -> c(n/c); 17 | modules=cell(c,1); 18 | for k=1:c; modules{k}=round((k-1)*n/c+1):round(k*n/c); end 19 | 20 | A=zeros(n); % initialize adjacency matrix 21 | 22 | for i=1:n 23 | for j=i+1:n 24 | 25 | module_i=ceil(c*i/n); % the module to which i belongs to 26 | module_j=ceil(c*j/n); % the module to which j belongs to 27 | 28 | if module_i==module_j 29 | 30 | % prob of attachment within module 31 | if rand<=r*z/(n/c-1); A(i,j)=1; A(j,i)=1; end 32 | 33 | else 34 | 35 | % prob of attachment across modules 36 | if rand<=z*(1-r)/(n-n/c); A(i,j)=1; A(j,i)=1; end 37 | 38 | end 39 | end 40 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/rewire.m: -------------------------------------------------------------------------------- 1 | % Degree-preserving random rewiring 2 | % Note 1: Assume unweighted undirected graph 3 | % INPUTS: edgelist, el (mx3) and number of rewirings, k 4 | % OUTPUTS: rewired edgelist 5 | 6 | function el = rewire(el,k) 7 | 8 | rew=0; 9 | 10 | while rew0; continue; end % the two edges cannot overlap 17 | 18 | % else: rewire 19 | if not(ismember([edge1(1),edge2(2),1],el,'rows')) & not(ismember([edge1(2),edge2(1),1],el,'rows')) 20 | 21 | % first possibility: (e11,e22) & (e12,e21) 22 | el(ind(1),:)=[edge1(1),edge2(2),1]; 23 | el(ind(2),:)=[edge1(2),edge2(1),1]; 24 | 25 | % add the symmetric equivalents 26 | [~,inds1] = ismember([edge1(2),edge1(1),1],el,'rows'); 27 | el(inds1,:)=[edge2(2),edge1(1),1]; 28 | 29 | [~,inds2] = ismember([edge2(2),edge2(1),1],el,'rows'); 30 | el(inds2,:)=[edge2(1),edge1(2),1]; 31 | 32 | rew = rew + 1; 33 | 34 | elseif not(ismember([edge1(1),edge2(1),1],el,'rows')) & not(ismember([edge1(2),edge2(2),1],el,'rows')) 35 | 36 | % second possibility: (e11,e21) & (e12,e22) 37 | el(ind(1),:)=[edge1(1),edge2(1),1]; 38 | el(ind(2),:)=[edge1(2),edge2(2),1]; 39 | 40 | % add the symmetric equivalents 41 | [~,inds1] = ismember([edge1(2),edge1(1),1],el,'rows'); 42 | el(inds1,:)=[edge2(1),edge1(1),1]; 43 | 44 | [~,inds2] = ismember([edge2(2),edge2(1),1],el,'rows'); 45 | el(inds2,:)=[edge2(2),edge1(2),1]; 46 | 47 | rew = rew + 1; 48 | 49 | else 50 | 'creates a double edge'; 51 | continue 52 | end 53 | 54 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/rewire_assort.m: -------------------------------------------------------------------------------- 1 | % Degree-preserving random rewiring 2 | % Every rewiring increases the assortativity (pearson coefficient) 3 | % Note 1: There are rare cases of neutral rewiring (coeff stays the same within numerical error) 4 | % Note 2: Assume unweighted undirected graph 5 | % INPUTS: edgelist, el and number of rewirings, k 6 | % OUTPUTS: rewired edgelist 7 | % Other routines used: degrees.m 8 | 9 | function el = rewire_assort(el,k) 10 | 11 | [deg,~,~]=degrees(edgeL2adj(el)); 12 | 13 | rew=0; 14 | 15 | while rew0; continue; end % the two edges cannot overlap 22 | 23 | nodes=[edge1(1) edge1(2) edge2(1) edge2(2)]; 24 | [~,Y]=sort(deg(nodes)); 25 | 26 | % connect nodes(Y(1))-nodes(Y(2)) and nodes(Y(3))-nodes(Y(4)) 27 | if ismember([nodes(Y(1)),nodes(Y(2)),1],el,'rows') | ismember([nodes(Y(3)),nodes(Y(4)),1],el,'rows'); continue; end 28 | 29 | el(ind(1),:)=[nodes(Y(3)),nodes(Y(4)),1]; 30 | el(ind(2),:)=[nodes(Y(1)),nodes(Y(2)),1]; 31 | 32 | [~,inds1] = ismember([edge1(2),edge1(1),1],el,'rows'); 33 | el(inds1,:)=[nodes(Y(4)),nodes(Y(3)),1]; 34 | 35 | [~,inds2] = ismember([edge2(2),edge2(1),1],el,'rows'); 36 | el(inds2,:)=[nodes(Y(2)),nodes(Y(1)),1]; 37 | 38 | rew=rew+1; 39 | 40 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/rewire_disassort.m: -------------------------------------------------------------------------------- 1 | % Degree-preserving random rewiring 2 | % Every rewiring decreases the assortativity (pearson coefficient) 3 | % Note 1: There are rare cases of neutral rewiring (coeff stays the same within numerical error) 4 | % Note 2: Assume unweighted undirected graph 5 | % INPUTS: edgelist, el and number of rewirings, k 6 | % OUTPUTS: rewired edgelist 7 | 8 | function el = rewire_disassort(el,k) 9 | 10 | [deg,~,~]=degrees(edgeL2adj(el)); 11 | 12 | rew=0; 13 | 14 | while rew0; continue; end % the two edges cannot overlap 21 | 22 | nodes=[edge1(1) edge1(2) edge2(1) edge2(2)]; 23 | [~,Y]=sort(deg(nodes)); 24 | 25 | % connect nodes(Y(1))-nodes(Y(4)) and nodes(Y(2))-nodes(Y(3)) 26 | if ismember([nodes(Y(1)),nodes(Y(4)),1],el,'rows') | ismember([nodes(Y(2)),nodes(Y(3)),1],el,'rows'); continue; end 27 | 28 | el(ind(1),:)=[nodes(Y(1)),nodes(Y(4)),1]; 29 | el(ind(2),:)=[nodes(Y(2)),nodes(Y(3)),1]; 30 | 31 | [~,inds1] = ismember([edge1(2),edge1(1),1],el,'rows'); 32 | el(inds1,:)=[nodes(Y(4)),nodes(Y(1)),1]; 33 | 34 | [~,inds2] = ismember([edge2(2),edge2(1),1],el,'rows'); 35 | el(inds2,:)=[nodes(Y(3)),nodes(Y(2)),1]; 36 | 37 | rew=rew+1; 38 | 39 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/rich_club_metric.m: -------------------------------------------------------------------------------- 1 | % Compute the rich club metric for a graph 2 | % INPUTs: adjacency matrix, nxn, k - threshold number of links 3 | % OUTPUTs: rich club metric 4 | % Source: Colizza, Flammini, Serrano, Vespignani, "Detecting rich-club ordering in complex networks", Nature Physics, vol 2, Feb 2006 5 | % Other routines used: degrees.m, subgraph.m, numedges.m 6 | % GB, Last updated: October 16, 2009 7 | 8 | function phi=rich_club_metric(adj,k) 9 | 10 | [deg,~,~]=degrees(adj); 11 | 12 | Nk=find(deg>=k); % find the nodes with degree > k 13 | if isempty(Nk); phi = 0; return; end 14 | 15 | adjk=subgraph(adj,Nk); 16 | phi=2*numedges(adjk)/(length(Nk)*(length(Nk)-1)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/s_metric.m: -------------------------------------------------------------------------------- 1 | % The sum of products of degrees across all edges 2 | % Source: "Towards a Theory of Scale-Free Graphs: Definition, Properties, and Implications", by Li, Alderson, Doyle, Willinger 3 | % Note: The total degree is used regardless of whether the graph is directed or not. 4 | % INPUTs: adjacency matrix 5 | % OUTPUTs: s-metric 6 | % Other routines used: degrees.m 7 | 8 | function s=s_metric(adj) 9 | 10 | [deg,~,~]=degrees(adj); 11 | edges=find(adj>0); 12 | 13 | s=0; 14 | for e=1:length(edges) 15 | [i,j]=ind2sub([length(adj),length(adj)],edges(e)); 16 | s=s+deg(i)*deg(j); 17 | end 18 | 19 | 20 | % ALTERNATIVE ================ 21 | % $$$ [deg,~,~]=degrees(adj); 22 | % $$$ el=adj2edgeL(adj); 23 | % $$$ 24 | % $$$ s=0; 25 | % $$$ for e=1:size(el,1) 26 | % $$$ if el(e,1)==el(e,2) 27 | % $$$ s=s+deg(el(e,1))*deg(el(e,2))*el(e,3)*2; % count selfloops twice 28 | % $$$ else 29 | % $$$ s=s+deg(el(e,1))*deg(el(e,2))*el(e,3); % multiply by the weight for multiedges 30 | % $$$ end 31 | % $$$ end 32 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/selfloops.m: -------------------------------------------------------------------------------- 1 | % counts the number of self-loops in the graph 2 | % INPUT: adjacency matrix 3 | % OUTPUT: interger, number of self-loops 4 | % Last Updated: GB, October 1, 2009 5 | 6 | function sl=selfloops(adj) 7 | 8 | sl=sum(diag(adj)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/shortest_pathDP.m: -------------------------------------------------------------------------------- 1 | % Shortest path algorithm using Dynamic Programming 2 | % Valid for directed/undirected network 3 | % Disclaimer: if links have weights, they are treated as distances 4 | % INPUTs: L - (cost/path lengths matrix), s - (start/source node), t - (end/destination node) 5 | % OUTPUTS: 6 | % route - sequence of nodes on optimal path, at current stage 7 | % ex: route(i,j) - best route from j to destination in (i) steps 8 | % Jo - optimal cost function (path length) 9 | % Source: D. P. Bertsekas, Dynamic Programming and Optimal Control, Athena Scientific, 2005 (3rd edition) 10 | % GB, Last Updated: March 9, 2006 11 | 12 | function [J_st,route_st,J,route]=shortest_pathDP(L,s,t,steps) 13 | 14 | n = size(L,2); 15 | 16 | L(find(L==0))=Inf; % make all zero distances equal to infinity 17 | 18 | for i=1:n 19 | J(steps,i) = L(i,t); 20 | route(steps,i).path = [t]; 21 | end 22 | 23 | % find min for every i: Jk(i)=min_j(L(i,j)+Jk+1(j)) 24 | for p=1:steps-1 25 | k=steps-p; % recurse backwards 26 | 27 | for i=1:n 28 | %fprintf('stage %2i, node %2i \n',k,i) 29 | [J(k,i),ind_j] = min(L(i,:)+J(k+1,:)); 30 | route(k,i).path = [ind_j, route(k+1,ind_j).path]; 31 | end 32 | 33 | end 34 | 35 | [J_st,step_ind] = min(J(:,s)); 36 | route_st = [s, route(step_ind,s).path]; 37 | J=J(sort(1:n,'descend'),:); 38 | route=route(sort(1:n,'descend'),:); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/simple_dijkstra.m: -------------------------------------------------------------------------------- 1 | % Implements a simple version of the Dijkstra shortest path algorithm 2 | % Returns the distance from a single vertex to all others, doesn't save the path 3 | % INPUTS: adjacency matrix (adj), start node (s) 4 | % OUTPUTS: shortest path length from start node to all other nodes 5 | % Note: works with a weighted/directed matrix 6 | % GB, Last Updated: December 13, 2004 7 | 8 | function d = simple_dijkstra(adj,s) 9 | 10 | n=length(adj); 11 | d = inf*ones(1,n); % distance s-all nodes 12 | d(s) = 0; % s-s distance 13 | T = 1:n; % node set with shortest paths not found 14 | 15 | while not(isempty(T)) 16 | [dmin,ind] = min(d(T)); 17 | for j=1:length(T) 18 | if adj(T(ind),T(j))>0 & d(T(j))>d(T(ind))+adj(T(ind),T(j)) 19 | d(T(j))=d(T(ind))+adj(T(ind),T(j)); 20 | end 21 | end 22 | T = setdiff(T,T(ind)); 23 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/simple_spectral_partitioning.m: -------------------------------------------------------------------------------- 1 | % Uses the fiedler vector to assign nodes to groups 2 | % INPUTS: adj - adjancency matrix, k - desired number of nodes in groups [n1, n2, ..], [optional] 3 | % OUTPUTs: modules - [k] partitioned groups of nodes 4 | % Other functions used: fiedler_vector.m 5 | 6 | function modules = simple_spectral_partitioning(adj,k) 7 | 8 | % find the Fiedler vector: eigenvector corresponding to the second smallest eigenvalue of the Laplacian matrix 9 | fv = fiedler_vector(adj); 10 | [~,I]=sort(fv); 11 | 12 | % depending on k, partition the nodes 13 | if nargin==1 14 | 15 | modules{1}=[]; modules{2}=[]; 16 | % choose 2 groups based on signs of fv components 17 | for v=1:length(fv) 18 | if fv(v)>0; modules{2} = [modules{2}, v]; end 19 | if fv(v)<=0; modules{1} = [modules{1}, v]; end 20 | end 21 | end 22 | 23 | if nargin==2 24 | 25 | k = [0 k]; 26 | 27 | for kk=1:length(k) 28 | 29 | modules{kk}=[]; 30 | for x=1:k(kk); modules{kk} = [modules{kk} I(x+k(kk-1))]; end 31 | 32 | end 33 | 34 | modules = modules(2:length(modules)); 35 | end 36 | 37 | 38 | set(gcf,'Color',[1 1 1]) 39 | subplot(1,2,1) 40 | plot(fv(I),'k.'); 41 | xlabel('index i') 42 | ylabel('fv(i)') 43 | title('sorted fiedler vector') 44 | axis('tight') 45 | axis('square') 46 | 47 | subplot(1,2,2) 48 | spy(adj(I,I),'k') 49 | title('sorted adjacency matrix') -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/smooth_diameter.m: -------------------------------------------------------------------------------- 1 | % A relaxed/smoothed definition of diameter: the number "d" at which 2 | % a threshold fraction "p" of pairs of nodes are at distance at most 3 | % "d". Can be non-integer using interpolation. 4 | % Idea: Leskovec et al, "Graphs over Time: Densification Laws, Shrinking Diameters and Possible Explanations" 5 | % Input: adjacency matrix of graph and diameter threshold, p in [0,1] 6 | % Output: relaxed or "effective" diameter 7 | % Other routines used: simple_dijkstra.m 8 | 9 | function diam = smooth_diameter(adj,p) 10 | 11 | n=size(adj,1); 12 | 13 | dij=[]; 14 | for i=1:n; dij=[dij; simple_dijkstra(adj,i)]; end 15 | 16 | dij(find(dij==0))=inf; 17 | for i=1:n-1; ddist(i)=length(find(dij<=i)); end 18 | ddist=ddist/(n*(n-1)); 19 | 20 | lb = max(find(ddist<=p)); % lower bound 21 | ub = min(find(ddist>=p)); % upper bound 22 | 23 | if p==1; diam = ub; 24 | elseif ub==lb; diam = lb; 25 | elseif p1 16 | % Extract the neighbors of the first node only 17 | neigh=str(1:commas(1)-1); 18 | dots=find(neigh=='.'); 19 | for d=1:length(dots)-1; adj(1,str2num(neigh(dots(d)+1:dots(d+1)-1)))=1; end 20 | adj(1,str2num(neigh(dots(length(dots))+1:length(neigh))))=1; 21 | end 22 | 23 | % Extract the neighbors of the remaining 2:n nodes 24 | for i=2:n 25 | neigh=str(commas(i-1)+1:commas(i)-1); 26 | if isempty(neigh); continue; end 27 | 28 | dots=find(neigh=='.'); 29 | for d=1:length(dots)-1; adj(i,str2num(neigh(dots(d)+1:dots(d+1)-1)))=1; end 30 | 31 | adj(i,str2num(neigh(dots(length(dots))+1:length(neigh))))=1; 32 | 33 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/subgraph.m: -------------------------------------------------------------------------------- 1 | % This function outputs the adjacency matrix of a subgraph given the 2 | % supergraph and the node set of the subgraph 3 | % INPUTs: adj - supergraph adjacency matrix, S - vector of subgraph node indices 4 | % OUTPUTs: adj_sub - adjacency matrix of the subgraph 5 | % GB, January 5, 2006 6 | 7 | function adj_sub = subgraph(adj,S) 8 | 9 | adj_sub = adj(S,S); 10 | -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/symmetrize.m: -------------------------------------------------------------------------------- 1 | % Symmetrize a non-symmetric matrix 2 | % For matrices in which mat(i,j)~=mat(j,i), the larger (nonzero) value is chosen 3 | % INPUTS: a matrix - nxn 4 | % OUTPUT: corresponding symmetric matrix - nxn 5 | % Last Updated: October 1, 2009 6 | 7 | function adj_sym = symmetrize(adj) 8 | 9 | adj_sym = max(adj,transpose(adj)); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/symmetrize_edgeL.m: -------------------------------------------------------------------------------- 1 | % Making an edgelist (representation of a graph) symmetric 2 | % INPUTs: edge list, mx3 3 | % OUTPUTs: symmetrized edge list, mx3 4 | % GB, Last updated: October 8, 2009 5 | 6 | function el=symmetrize_edgeL(el) 7 | 8 | el2=[el(:,1), el(:,2)]; 9 | 10 | for e=1:size(el,1) 11 | ind=ismember(el2,[el2(e,2),el2(e,1)],'rows'); 12 | if sum(ind)==0; el=[el; el(e,2), el(e,1), el(e,3)]; end 13 | end 14 | 15 | % Alternative: Using the adjacency matrix 16 | % adj=edgeL2adj(el); 17 | % adj=symmetrize(adj); 18 | % el=adj2edgeL(adj); -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/tarjan.m: -------------------------------------------------------------------------------- 1 | % Find the giant stronly connected component in a directed graph 2 | % Source: Tarjan, R. E. (1972), "Depth-first search and linear graph algorithms", SIAM Journal on Computing 1 (2): 146-160 3 | % Input: graph, set of nodes and edges, in adjacency list format, ex: L{1}=[2], L{2]=[1] is the 1-2 edge 4 | % Outputs: set of strongly connected components, in cell array format 5 | % Other routines used: strongConnComp (embedded) 6 | % Last updated: July 6, 2011, GB 7 | 8 | function [GSCC,v] = tarjan(L) 9 | 10 | 11 | GSCC = {}; 12 | ind = 1; % node number counter 13 | S = []; % An empty stack of nodes 14 | for ll=1:length(L); v(ll).index = []; v(ll).lowlink = []; end % initialize indices 15 | 16 | for vi=1:length(L) 17 | if isempty(v(vi).index) 18 | [GSCC,S,ind,v]=strongConnComp(vi,S,ind,v,L,GSCC); % visit new nodes only 19 | end 20 | end 21 | 22 | 23 | function [GSCC,S,ind,v]=strongConnComp(vi,S,ind,v,L,GSCC) 24 | 25 | v(vi).index = ind; % Set the depth index for vi 26 | v(vi).lowlink = ind; 27 | ind = ind + 1; 28 | 29 | S = [vi S]; % Push vi on the stack 30 | 31 | for ll=1:length(L{vi}) 32 | vj = L{vi}(ll); % Consider successors of vi 33 | 34 | if isempty(v(vj).index) % Was successor vj visited? 35 | 36 | [GSCC,S,ind,v]=strongConnComp(vj,S,ind,v,L,GSCC); % Recursion 37 | v(vi).lowlink = min([v(vi).lowlink, v(vj).lowlink]); 38 | 39 | elseif not(isempty(find(S==vj))) % Is vj on the stack? 40 | v(vi).lowlink = min([v(vi).lowlink, v(vj).index]); 41 | 42 | end 43 | end 44 | 45 | 46 | if v(vi).lowlink == v(vi).index % Is v the root of an SCC? 47 | 48 | SCC = [vi]; 49 | while 1 50 | vj = S(1); S = S(2:length(S)); 51 | SCC = [SCC vj]; 52 | 53 | if vj==vi; SCC = unique(SCC); break; end 54 | end 55 | 56 | GSCC{length(GSCC)+1} = SCC; 57 | 58 | end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/vertex_eccentricity.m: -------------------------------------------------------------------------------- 1 | % Vertex eccentricity - the maximum distance to any other vertex 2 | % Input: adjacency matrix 3 | % Output: vector of eccentricities 4 | % Other routines used: simple_dijkstra.m 5 | 6 | function ec=vertex_eccentricity(adj) 7 | 8 | n=size(adj,1); 9 | ec=zeros(1,n); 10 | 11 | for s=1:n; ec(s)=max( simple_dijkstra(adj,s) ); end -------------------------------------------------------------------------------- /simu_config_tools/MIT_Network_Toolbox/original code/weighted_clust_coeff.m: -------------------------------------------------------------------------------- 1 | % Weighted clustering coefficient 2 | % Source: Barrat, The architecture of complex weighted networks 3 | % INPUTS: weighted adjacency matrix 4 | % OUTPUTs: vector of node weighted clustering coefficients 5 | % Other routines used: degrees.m, kneighbors.m 6 | 7 | function wC=weighted_clust_coeff(adj) 8 | 9 | [deg,~,~]=degrees(adj); 10 | n=size(adj,1); % number of nodes 11 | wC=zeros(n,1); % initialize weighted clust coeff 12 | 13 | for i=1:n % across all nodes 14 | neigh=kneighbors(adj,i,1); 15 | if length(neigh)<2; continue; end 16 | 17 | s=0; 18 | for ii=1:length(neigh) 19 | for jj=1:length(neigh) 20 | 21 | if adj(neigh(ii),neigh(jj))>0; s=s+(adj(i,neigh(ii))+adj(i,neigh(jj)))/2; end 22 | 23 | end 24 | end 25 | 26 | wC(i)=s/(deg(i)*(length(neigh)-1)); 27 | end 28 | 29 | 30 | % % ALTERNATIVE ========================================================= 31 | % wadj=adj; 32 | % adj=adj>0; 33 | % 34 | % [wdeg,~,~]=degrees(wadj); 35 | % [deg,~,~]=degrees(adj); 36 | % n=size(adj,1); % number of nodes 37 | % wC=zeros(n,1); 38 | % 39 | % for i=1:n 40 | % if deg(i)<2; continue; end 41 | % 42 | % s=0; 43 | % for ii=1:n 44 | % for jj=1:n 45 | % s=s+adj(i,ii)*adj(i,jj)*adj(ii,jj)*(wadj(i,ii)+wadj(i,jj))/2; 46 | % end 47 | % end 48 | % 49 | % wC(i)=s/(wdeg(i)*(deg(i)-1)); 50 | % end -------------------------------------------------------------------------------- /simu_config_tools/degree2stub.m: -------------------------------------------------------------------------------- 1 | function [ stub ] = degree2stub( degree ) 2 | % This function turn the in/out-degree vector into a stub vector 3 | % The stub vector will be randomly permuted. 4 | % Example: 5 | % if degree = [3 2 5 1]', for node i = 1, 2, 3, 4 6 | % the stub vector is 7 | % stub = [1 1 1 2 2 3 3 3 3 3 4]'; % before permutation 8 | % Note that degree must be column vector! 9 | % stub is also column vector. 10 | 11 | Ind = 1:length(degree); % index vector for the nodes 12 | stub = cell2mat(arrayfun(@(x, y) repmat(x, [1 y]), Ind, degree', 'UniformOutput', false)); 13 | stub = stub'; 14 | 15 | % random permutation 16 | edge_num = length(stub); 17 | ind_perm = randperm(edge_num); 18 | stub = stub(ind_perm); 19 | 20 | end -------------------------------------------------------------------------------- /simu_config_tools/lattice_nD.m: -------------------------------------------------------------------------------- 1 | function [Lattice, N] = lattice_nD(D, hw) 2 | 3 | 4 | % % parameters 5 | % D = 2; % dimension of embedding space (regular square lattice) 6 | % hw = 10; % half-width of the embedding space, width is 2*hw+1 7 | 8 | 9 | % put nodes on a regular square lattice 10 | if D == 2 11 | [X1,X2] = ndgrid(-hw:hw); % coordinates 12 | Lattice = [X1(:) X2(:)]; % every row is the coordinate of one node 13 | elseif D == 3 14 | [X1,X2,X3] = ndgrid(-hw:hw); % coordinates 15 | Lattice = [X1(:) X2(:) X3(:)]; % every row is the coordinate of one node 16 | end 17 | 18 | % show number of nodes 19 | N = length(Lattice(:,1)); 20 | 21 | end -------------------------------------------------------------------------------- /simu_config_tools/lattice_nD_find_dist.m: -------------------------------------------------------------------------------- 1 | function [dist] = lattice_nD_find_dist(Lattice, hw, varargin) 2 | % dist(j) is the Euclidean distance between node i and node j in the Lattice 3 | % Lattice 4 | % 5 | % hw is the half-width of the lattice 6 | % 7 | % the boundary condition is periodic 8 | % 9 | % p0 is the coordinates (x,y) of any point (not necessarily on the lattice) 10 | [N, D] = size(Lattice); 11 | if length(varargin) == 1 12 | i = varargin{1}; 13 | p0 = Lattice(i,:); 14 | elseif length(varargin) == 2 15 | p0 = [varargin{1}, varargin{2}]; 16 | end 17 | 18 | 19 | dist = zeros(N,1); 20 | for d = 1:D 21 | Xd = mod(Lattice(:,d)-p0(d)+hw, 2*hw+1) - hw; % periodic boundary condition 22 | dist = dist + Xd.^2; 23 | end 24 | dist = dist.^0.5; % Euclidean distance 25 | end -------------------------------------------------------------------------------- /simu_config_tools/poissrnd_2D.m: -------------------------------------------------------------------------------- 1 | 2 | function pois = poissrnd_2D(lambda, N, r) 3 | %Yahav, Inbal, and Galit Shmueli. 4 | % "On generating multivariate Poisson data 5 | % in management science applications." 6 | % Applied Stochastic Models in Business and Industry 28.1 (2012): 91-102. APA 7 | % 8 | % Yifan Gu, School of Physics, USYD, Aug 2016. 9 | % yigu8115@gmail.com 10 | 11 | D = 2; 12 | if min(lambda) <= 5 13 | r = CorrectInitialCorrel(lambda(1), lambda(2), r); 14 | end 15 | var = [1 r; r 1]; 16 | 17 | max_count = 100; 18 | count = 0; 19 | err = 1; 20 | err_max = 0.1; 21 | while err > err_max 22 | count = count + 1; 23 | if count > max_count 24 | break; 25 | end 26 | 27 | normal = mvnrnd(zeros(1, D), var, N); 28 | pois = normal; 29 | p = normcdf(normal); 30 | for s = 1:D 31 | pois(:,s) = poissinv( p(:,s), lambda(s) ); 32 | end 33 | 34 | r_a = corrcoef(pois(:,1), pois(:,2)); 35 | r_a = r_a(1,2); 36 | if r > 0.1 37 | err = abs(r_a-r)/r; 38 | else 39 | err = abs(r_a-r); 40 | end 41 | 42 | end 43 | 44 | if count > max_count 45 | pois = NaN; 46 | warning('Error cannot converge!') 47 | end 48 | 49 | end 50 | 51 | 52 | % only an approximation 53 | function corrected = CorrectInitialCorrel(lambda1, lambda2, r) 54 | samples = 500; 55 | u = rand(samples) ; 56 | 57 | maxcor = corrcoef(poissinv(u, lambda1), poissinv(u, lambda2)); 58 | maxcor = maxcor(1,2); 59 | mincor = corrcoef(poissinv(u, lambda1), poissinv(1-u, lambda2)); 60 | mincor = mincor(1,2); 61 | 62 | a = -maxcor*mincor/(maxcor+mincor); 63 | b = log( (maxcor+a)/a); 64 | 65 | corrected = log((r+a)/a)/b; 66 | 67 | if corrected > 1 || corrected < -1 68 | corrected = NaN; 69 | end 70 | 71 | end 72 | 73 | -------------------------------------------------------------------------------- /simu_config_tools/quasi_lattice_2D.m: -------------------------------------------------------------------------------- 1 | function Lattice = quasi_lattice_2D(N, hw) 2 | % N is the number of points 3 | % hw is the half-width, or 2*hw+1 is the full width 4 | % The quasi-lattice is centred at (0,0) 5 | % It is quasi because 6 | % (1) the coordinates of the points are uniformly distributed random numbers 7 | % (2) the indices of the points are re-arranged to resemble a regular square 8 | % lattice for convenience. 9 | 10 | w = 2*hw + 1; 11 | 12 | X = zeros(N,1); 13 | while X(1) == 0 || X(end) == w 14 | X = sort(rand(N,1) * w); 15 | end 16 | 17 | segs = linspace(0, w, round(sqrt(N))+1); 18 | Y = []; 19 | for i = 1:round(sqrt(N)) 20 | X_seg = X(X >= segs(i) & X < segs(i+1)); 21 | Y_tmp = rand(length(X_seg),1) * w; 22 | [Y_tmp, Y_tmp_ind] = sort(Y_tmp); 23 | X(X >= segs(i) & X < segs(i+1)) = X_seg(Y_tmp_ind); 24 | Y = [Y; Y_tmp]; %#ok 25 | end 26 | 27 | Lattice = [X Y] - (w/2); % centred at (0,0) 28 | 29 | 30 | % % visualization 31 | % figure(1); axis([-hw hw -hw hw]); 32 | % hold on 33 | % for i = 1:N 34 | % plot(Lattice(i,1), Lattice(i,2),'o');pause(0.01); 35 | % end 36 | 37 | 38 | end 39 | 40 | -------------------------------------------------------------------------------- /simu_config_tools/rand_unique_pairs.m: -------------------------------------------------------------------------------- 1 | function [pairs] = rand_unique_pairs(N, pair_num, ordered, self_pair) 2 | % This function randomly generates unique integer number pairs 3 | % either ordered or unordered. 4 | % 5 | % Input arguments: 6 | % N: defines the range of the numbers (from 1 to N) 7 | % pair_num: the number of pairs 8 | % ordered: 1 for ordered pairs and 0 for unordered. The default is 0. 9 | % self_pair: 1 for allowing self-pair (e.g, 3-3 is a self-pair). The 10 | % default is 0. 11 | % 12 | % Output argument: 13 | % pairs: a 2-by-pair_num matrix with each column containing a unique pair 14 | % 15 | % Yifan Gu, 6-Feb-2017 16 | % yigu8115@gmail.com 17 | 18 | 19 | % Input check 20 | if nargin == 2 21 | ordered = 0; 22 | end 23 | if nargin <= 3 24 | self_pair = 0; 25 | end 26 | 27 | 28 | % Generate pairs 29 | if ordered == 0 % (i,j) is the same as (j,i) 30 | max_pair_num = N*(N-1)/2; 31 | if pair_num > max_pair_num 32 | pair_num = max_pair_num; 33 | warning('pair_num is larger than allowed!'); 34 | end 35 | NN = ones(N); 36 | if self_pair == 0 37 | NN(logical(eye(N))) = 0; % set diagonal entries to zero, no self-pair 38 | end 39 | NN = triu(NN); % extract upper triangular part for non-ordered pair 40 | [I,J] = find(NN); 41 | ind = randperm(length(I),pair_num); 42 | pairs = [I(ind)'; J(ind)']; 43 | 44 | elseif ordered == 1 45 | max_pair_num = N*(N-1); 46 | if pair_num > max_pair_num 47 | pair_num = max_pair_num; 48 | warning('pair_num is larger than allowed!'); 49 | end 50 | NN = ones(N); 51 | if self_pair == 0 52 | NN(logical(eye(N))) = 0; % set diagonal entries to zero, no self-connection 53 | end 54 | [I,J] = find(NN); 55 | ind = randperm(length(I),pair_num); 56 | pairs = [I(ind)'; J(ind)']; 57 | end 58 | 59 | 60 | end 61 | -------------------------------------------------------------------------------- /simu_config_tools/uni_bi_connect_prob.m: -------------------------------------------------------------------------------- 1 | function [p, bi_p, uni_p, z_bi, z_uni] = uni_bi_connect_prob(A) 2 | 3 | A = double(A > 0); 4 | [n,~] = size(A); 5 | N = n*(n-1); % total number of pairs 6 | 7 | p = nnz(A(:))/(n*(n-1)); 8 | 9 | if sum(A(logical(eye(n)))) > 0 10 | warning('There is self connection!') 11 | end 12 | 13 | 14 | A = A + A'; 15 | 16 | 17 | bi_n = sum(A(:) == 2); 18 | bi_p = bi_n/(n*(n-1)); 19 | uni_n = sum(A(:) == 1); 20 | uni_p = uni_n/(n*(n-1)); 21 | 22 | % Given connection probability p and total number of pairs N, the expected 23 | % number of unconnected pairs should be N*(1-p)^2. The expected number of 24 | % unidirectionally connected pairs should be 2*N*p*(1-p), and the expected 25 | % number of bidirectionally connected pairsshould be N*p^2. 26 | 27 | z_bi = bi_n / (N*p^2); 28 | z_uni = uni_n / (2*N*p*(1-p)); 29 | 30 | % testing 31 | % [p, bi_p, uni_p, z_bi, z_uni] = uni_bi_connect_prob(MyRandomGraphGenerator('E_R')) 32 | end --------------------------------------------------------------------------------