-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKTzV2_Sims_Network.cs
2397 lines (2191 loc) · 99.1 KB
/
KTzV2_Sims_Network.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
//using System.Threading.Tasks;
using KTzV2.Stimuli;
using KTzV2.Neurons;
using KTzV2.Synapses;
using KTzV2.Data;
using KTzV2.Data.Header;
using KTzV2.Maths.Random;
using KTzV2.Maths.Matrices;
using KTzV2.Maths.Matrices.AdjacencyMatrix;
using MatFileHandler;
namespace KTzV2.Sims.Network
{
public enum StimulusIndexChoice
{
Fixed,
SquareCenter,
Random,
MultipleRandom,
MostConnected
}
public enum SimulationTimeScheme
{
// total simulation time (nSteps - nStartStep; discounting transient)
// is proportional to 10/(r*N)
// r->Poisson rate, N->number of neurons in the network
ProportionalToPoissonRate,
// total simulation time is whatever is set by the user
Free
}
public enum CouplingParam
{
Homogeneous, // same J for every synapse
AdjMatrix // uses adj matrix weight as each J
}
public class KTzNetworkSimulator
{
private SparseMatrix<Double> AMatrix { get; set; }
private Int32 Lx, Ly, Lz, nSteps, nStartStep;
private InitialConditionType icType;
private AdjacencyMatrixType networkType;
private SynapseType synapseType;
private StimulusType stimulusType;
private NeuronType neuronType;
private NoiseType noiseType;
private CouplingParam couplingParamType;
private Boolean doWriteDif = false;
private Int32 nNeighbours;
public Int32 nNeurons { get; private set; }
private Int32 netDim;
private Int32 tForStimulus;
private Double x0i, y0i, z0i;
private Double[] x0p, y0p, z0p;
private Double K, T, d, l, xR, H, J, tauf, taug, Theta, Q;
private Double noiseAmp, noiseRatio;
//private Double[] Ji;
private GetICInstance icGetter;
//private Int32[] tData;
private Double[][] xData;
private List<Int32> spikeNeuronData;
private List<Int32> spikeTimeData;
// number of spikes M in a give time step t
private Int32 M_t;
private Boolean hasRunned;
//private KTNeuron[] neuron;
private INeuron[] neuron;
private List<ISynapse> synapseList;
private Int32 nSynapse;
//private Int32[] indForStimulus;
private Double stimulusAmp;
private Double stimulusStdDev;
private Int32 neuronIndStim;
private Double poissonRate;
private ExternalStimulusBase stimulus;
private Int32 timestep;
private HomogeneousRand rand;
private List<Int32> spikeDistribution;
private List<Int32> timeDistribution;
private Int32 numOfConnBAGraph;
private Double rewireProbWSGraph;
private Boolean hasToAverageInput;
private Int32 deltaTrainDt;
private Double dyn_alpha;
private Double dyn_u;
private Double dyn_tauJ;
private Double dyn_dt;
private KTzV2.Data.NetworkSamplingType samplingType;
private Double samplingFraction;
private Int32[] samplingIndices;
private Int32[] unsampledIndices;
private Boolean[] countedNeuron;
private Int32 samplingN;
private Int32 restIntervals;
private Int32 timeBin;
private Int32 NAvalSim;
private KTzV2.Data.CountVariable countVar;
private StimulusIndexChoice indChoice;
public Action<Int32?> RunForAvalanches { get; private set; }
private Func<Int32> GetNeuronIndexForStim { get; set; }
private Func<Int32> RunSingleAvalanche { get; set; }
private Action<Int32> SetNextStimTimeIfNeeded { get; set;}
private Action<Int32> Update { get; set; }
private Action<Int32> UpdateDuringTransient { get; set; }
private Action<Double[]> WriteRhoTimeSeriesFile { get; set; }
public Action<String> WriteDataToFile { get; private set; }
public Action<String, String> WriteSpikeDistributionToFile { get; private set; }
private Double[] elAdjMatVal;
private Func<Int32, Double> GetJValue;
private Boolean writeRhoTimeSeries; //simulation parameter - writes rho(t) for each J in JRange (only if outAvgMode=OverTime); rho(t) = sum x(t)>0
private Boolean writeXDataFile;
private Boolean writeXDataCSVFile;
private Boolean saveSpikeTimes;
private KTzV2.Data.Header.OutputFileFormat outputFileFormat;
#if DEBUG
//private List<Double>[] DEBUG_XData;
//private List<Int32> DEBUG_TData;
#endif
public KTzNetworkSimulator(Boolean silent)
{
this.rand = new HomogeneousRand();
Console.WriteLine("Getting parameters...");
this.getSetOfParameters();
Console.WriteLine("Setting adjacency matrix...");
this.createAdjacencyMatrix();
this.hasRunned = false;
if (!silent)
{
Console.WriteLine("" + "___________");
Console.WriteLine("");
Console.WriteLine("" + " KTz network simulator instanciated");
Console.WriteLine("");
Console.WriteLine("" + "-");
}
}
private void createAdjacencyMatrix()
{
//Int32 linearSize;
//if ((networkType == AdjacencyMatrixType.SquareLatticeFreeBC) || (networkType == AdjacencyMatrixType.SquareLatticePeriodicBC))
//{
// linearSize = nNeuronsOnARow;
//}
//else
//{
// linearSize = nNeurons;
//}
IAdjacencyMatrix<Double> boolMatrixGetter = FGetAdjacencyMatrix.GetMatrixFor(this.networkType,
this.nNeurons,
new Int32[] { this.Lx, this.Ly, this.Lz },
this.nNeighbours,
this.numOfConnBAGraph,
this.rewireProbWSGraph,
Convert.ToBoolean(KTzHeader.GetPar_Int32(KTzParameters.netDir)),
KTzHeader.GetPar_String(KTzParameters.netFile)
);
AMatrix = boolMatrixGetter.BuildAndGetMatrix();
if (this.networkType == AdjacencyMatrixType.FromFile)
{
if (this.AMatrix == null)
throw new ArgumentNullException("Could not load and/or create adjacency matrix FromFile");
else
{
this.nNeurons = this.AMatrix.nRow;
this.Lx = this.nNeurons;
this.Ly = 1;
this.Lz = 1;
KTzHeader.SetPar(KTzParameters.Lx, this.Lx);
KTzHeader.SetPar(KTzParameters.Ly, this.Ly);
KTzHeader.SetPar(KTzParameters.Lz, this.Lz);
}
}
this.GetSampParAndSetSamplingIndices();
}
private void getSetOfParameters()
{
this.networkType = (AdjacencyMatrixType)KTzHeader.GetPar_Int32(KTzParameters.netType);
this.synapseType = (SynapseType)KTzHeader.GetPar_Int32(KTzParameters.sType);
this.neuronType = (NeuronType)KTzHeader.GetPar_Int32(KTzParameters.neuron);
this.icType = (InitialConditionType)KTzHeader.GetPar_Int32(KTzParameters.iCond);
this.countVar = (KTzV2.Data.CountVariable)KTzHeader.GetPar_Int32(KTzParameters.cVar);
this.stimulusType = (StimulusType)KTzHeader.GetPar_Int32(KTzParameters.stimType);
this.noiseType = (KTzV2.Synapses.NoiseType)KTzHeader.GetPar_Int32(KTzParameters.noiseType);
this.couplingParamType = (CouplingParam)KTzHeader.GetPar_Int32(KTzParameters.coupParam);
this.indChoice = (StimulusIndexChoice)KTzHeader.GetPar_Int32(KTzParameters.indChoice);
this.saveSpikeTimes = KTzHeader.GetPar_Int32(KTzParameters.saveSpikeTimes) == 1;
/***
**
**
** Network parameters
**
**
***/
this.Lx = KTzHeader.GetPar_Int32(KTzParameters.Lx);
this.Ly = KTzHeader.GetPar_Int32(KTzParameters.Ly);
this.Lz = KTzHeader.GetPar_Int32(KTzParameters.Lz);
this.nNeurons = this.Lx * this.Ly * this.Lz;//Convert.ToInt32(Math.Pow(Lx, netDim));
this.netDim = KTzHeader.GetPar_Int32(KTzParameters.dim);
this.nNeighbours = KTzHeader.GetPar_Int32(KTzParameters.nNeigh);
this.numOfConnBAGraph = KTzHeader.GetPar_Int32(KTzParameters.nConn);
this.rewireProbWSGraph = KTzHeader.GetPar_Double(KTzParameters.rewP);
/***
**
**
** Simulation parameters
**
**
***/
// adjusting RunForAvalanche
this.ChooseRunForAvalancheMethods();
// adjusting output writers
this.ChooseOutputMethods();
// adjusting time step update function
this.ChooseTimestepUpdateMethod();
// adjusting constant parameters
var simTimeScheme = (SimulationTimeScheme)KTzHeader.GetPar_Int32(KTzParameters.simTimeScheme);
this.nSteps = KTzHeader.GetPar_Int32(KTzParameters.nSteps);
this.nStartStep = KTzHeader.GetPar_Int32(KTzParameters.nStart);
this.poissonRate = KTzHeader.GetPar_Double(KTzParameters.r);
this.tForStimulus = KTzHeader.GetPar_Int32(KTzParameters.sStim);
this.stimulusAmp = KTzHeader.GetPar_Double(KTzParameters.I);
this.stimulusStdDev = KTzHeader.GetPar_Double(KTzParameters.IStdDev);
this.deltaTrainDt = KTzHeader.GetPar_Int32(KTzParameters.deltaT);
this.restIntervals = KTzHeader.GetPar_Int32(KTzParameters.rest);
this.timeBin = KTzHeader.GetPar_Int32(KTzParameters.tBin);
this.NAvalSim = KTzHeader.GetPar_Int32(KTzParameters.nSim);
this.neuronIndStim = KTzHeader.GetPar_Int32(KTzParameters.iStim);
// adjusting total simulation time if needed
if ((simTimeScheme == SimulationTimeScheme.ProportionalToPoissonRate) && (this.stimulusType == StimulusType.PoissonProcess))
{
var T = this.nStartStep + (int)(10.0D / (double)(this.poissonRate * this.nNeurons));
if (T > this.nSteps)
{
this.nSteps = T;
KTzHeader.SetPar(KTzParameters.nSteps, this.nSteps);
Console.WriteLine("WARNING ::: Auto-adjusting total simulation time to nSteps = nStartStep + {0:D}",T);
}
}
/***
**
**
** Synapse parameters
**
**
***/
if (this.couplingParamType == CouplingParam.Homogeneous)
this.GetJValue = this.GetJValueHomogeneous;
else
this.GetJValue = this.GetJValueAdjMatrix;
this.J = KTzHeader.GetPar_Double(KTzParameters.J);
this.tauf = KTzHeader.GetPar_Double(KTzParameters.tauf);
this.taug = KTzHeader.GetPar_Double(KTzParameters.taug);
this.noiseAmp = KTzHeader.GetPar_Double(KTzParameters.R);
this.noiseRatio = KTzHeader.GetPar_Double(KTzParameters.noiseRatio);
this.dyn_alpha = KTzHeader.GetPar_Double(KTzParameters.alpha);
this.dyn_u = KTzHeader.GetPar_Double(KTzParameters.u);
this.dyn_tauJ = KTzHeader.GetPar_Double(KTzParameters.tauJ);
this.dyn_dt = KTzHeader.GetPar_Double(KTzParameters.dt);
this.hasToAverageInput = KTzHeader.GetPar_Int32(KTzParameters.avgInp) == 1;
if ((neuronType == NeuronType.KTzLogMF) || (neuronType == NeuronType.KTzMF))
{
this.hasToAverageInput = true;
}
/***
**
**
** Neuron parameters
**
**
***/
this.K = KTzHeader.GetPar_Double(KTzParameters.K);
this.T = KTzHeader.GetPar_Double(KTzParameters.T);
this.d = KTzHeader.GetPar_Double(KTzParameters.d);
this.l = KTzHeader.GetPar_Double(KTzParameters.l);
this.xR = KTzHeader.GetPar_Double(KTzParameters.xR);
this.H = KTzHeader.GetPar_Double(KTzParameters.H);
this.Q = KTzHeader.GetPar_Double(KTzParameters.Q);
this.x0i = KTzHeader.GetPar_Double(KTzParameters.x0);
this.y0i = KTzHeader.GetPar_Double(KTzParameters.y0);
this.z0i = KTzHeader.GetPar_Double(KTzParameters.z0);
this.Theta = KTzHeader.GetPar_Double(KTzParameters.Theta);
this.doWriteDif = false;
if (KTzHeader.GetPar_Int32(KTzParameters.wDif) == 1)
Console.WriteLine("WARNING: parameter wDif has no effect anymore");
}
private void ChooseRunForAvalancheMethods()
{
var dynType = (KTzV2.DynamicsSimType)KTzHeader.GetPar_Int32(KTzParameters.dynType);
var simType = (KTzV2.SimulationType)KTzHeader.GetPar_Int32(KTzParameters.simType);
// if we want to run the dynamics (instead of bifurcation)
// and the stimulus IS NOT DeltaWhenInactive
// we force the simulation to be "ContinuousTime"
if ((this.stimulusType != StimulusType.DeltaWhenInactive) && (simType == KTzV2.SimulationType.Dynamics))
{
dynType = KTzV2.DynamicsSimType.ContinuousTime;
KTzHeader.SetPar(KTzParameters.dynType, (Int32)KTzV2.DynamicsSimType.ContinuousTime);
Console.WriteLine("WARNING: Forcing dynType == ContinuousTime because stimType != DeltaWhenInactive");
}
if (dynType == KTzV2.DynamicsSimType.NetworkReset)
{
this.stimulusType = StimulusType.DeltaWhenInactive;
KTzHeader.SetPar(KTzParameters.stimType, (Int32)StimulusType.DeltaWhenInactive);
Console.WriteLine("WARNING: Forcing stimType == DeltaWhenInactive because dynType == NetworkReset");
}
if (dynType == KTzV2.DynamicsSimType.ContinuousTime)
{
this.RunForAvalanches = RunForSpikeDistribution;
}
else if (dynType == KTzV2.DynamicsSimType.NetworkReset)
{
this.RunForAvalanches = RunForSpikeDistReset;
this.stimulusType = StimulusType.Delta;
KTzHeader.SetPar(KTzParameters.stimType, (int)this.stimulusType);
}
// adjusting RunSingleAvalanche
if (this.countVar == CountVariable.NumberOfNeurons)
this.RunSingleAvalanche = this.RunSingleAvalancheForNeurons;
else if (this.countVar == CountVariable.NumberOfSpikes)
this.RunSingleAvalanche = this.RunSingleAvalancheForSpike;
}
private void ChooseOutputMethods()
{
this.outputFileFormat = (KTzV2.Data.Header.OutputFileFormat)KTzHeader.GetPar_Int32(KTzParameters.oFileFormat);
if (this.outputFileFormat == OutputFileFormat.txt)
{
this.WriteRhoTimeSeriesFile = this.WriteRhoTimeSeriesFileTxt;
this.WriteDataToFile = this.WriteDataToFileTxt;
this.WriteSpikeDistributionToFile = this.WriteSpikeDistributionToFileTxt;
}
else
{
this.WriteRhoTimeSeriesFile = this.WriteRhoTimeSeriesFileMat;
this.WriteDataToFile = this.WriteDataToFileMat;
this.WriteSpikeDistributionToFile = this.WriteSpikeDistributionToFileMat;
}
this.writeRhoTimeSeries = KTzHeader.GetPar_Int32(KTzParameters.writeRhoTS) == 1;
this.writeXDataFile = KTzHeader.GetPar_Int32(KTzParameters.wData) == 1;
this.writeXDataCSVFile = KTzHeader.GetPar_Int32(KTzParameters.wCSV) == 1;
}
private void ChooseTimestepUpdateMethod()
{
if (this.saveSpikeTimes)
{
if (this.indChoice == StimulusIndexChoice.MultipleRandom)
{
this.Update = this.UpdateForMultipleStimSaveSpike;
this.UpdateDuringTransient = this.UpdateForMultipleStim;
}
else
{
this.Update = this.UpdateSingleStimSaveSpike;
this.UpdateDuringTransient = this.UpdateSingleStim;
}
}
else
{
if (this.indChoice == StimulusIndexChoice.MultipleRandom)
{
this.Update = this.UpdateForMultipleStim;
this.UpdateDuringTransient = this.UpdateForMultipleStim;
}
else
{
this.Update = this.UpdateSingleStim;
this.UpdateDuringTransient = this.UpdateSingleStim;
}
}
}
private Int32 GetNeuronIndForStimAll()
{
return -1;
}
private Int32 GetNeuronIndForStimRandom()
{
return (Int32)(this.rand.GetRandomLT1() * this.nNeurons);
}
private Int32 GetNeuronIndForStimSimple()
{
return this.neuronIndStim;
}
private void GetSampParAndSetSamplingIndices()
{
this.samplingFraction = KTzHeader.GetPar_Double(KTzParameters.sampFrac);
this.samplingType = (KTzV2.Data.NetworkSamplingType)KTzHeader.GetPar_Int32(KTzParameters.samp);
this.samplingN = (Int32)(this.samplingFraction * this.nNeurons);
if (this.samplingN == this.nNeurons)
this.samplingType = NetworkSamplingType.Full;
Int32 i;
if (this.samplingType == KTzV2.Data.NetworkSamplingType.Full)
{
this.unsampledIndices = new Int32[] {};
this.samplingN = this.nNeurons;
this.samplingIndices = new Int32[this.samplingN];
i = 0;
while (i < this.samplingN)
{
this.samplingIndices[i] = i;
i++;
}
}
else if (this.samplingType == KTzV2.Data.NetworkSamplingType.Partial)
{
this.samplingN = (Int32)(this.samplingFraction * this.nNeurons);
this.samplingIndices = new Int32[this.samplingN];
List<Int32> selected = new List<Int32>();
Int32 n;
i = 0;
while (i < this.samplingN)
{
do
{
n = (Int32)(this.rand.GetRandomLT1() * this.nNeurons); // choose a random index different of the already taken
}
while (selected.Contains(n));
this.samplingIndices[i] = n;
selected.Add(n);
i++;
}
selected = null;
this.unsampledIndices = new Int32[this.nNeurons - this.samplingN];
var diff = Enumerable.Range(0, this.nNeurons).Except(this.samplingIndices);
int k = 0;
foreach (int d in diff)
{
this.unsampledIndices[k] = d;
k++;
}
}
else
{
throw new ArgumentOutOfRangeException("Unrecognized sampling type! " + this.samplingType.ToString());
}
}
private void prepareNeurons()
{
Int32 i, j, k;
//Console.WriteLine(lb + " * Generating initial conditions...");
this.x0p = new Double[nNeurons];
this.y0p = new Double[nNeurons];
this.z0p = new Double[nNeurons];
this.icGetter = new GetICInstance();
i = 0;
try
{
this.icGetter = FGetInitCond.use(this.icType, 1, nNeurons);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Using type 3 as default initial condition!");
this.icType = (InitialConditionType)3;
this.icGetter = FGetInitCond.use(this.icType, 1, nNeurons);
}
while (i < this.nNeurons)
{
if (this.icType == InitialConditionType.FromXMLFile)
{
this.x0p[i] = icGetter.getX(0, i);
this.y0p[i] = icGetter.getY(0, i);
this.z0p[i] = icGetter.getZ(0, i);
}
else
{
this.x0p[i] = icGetter.getX(x0i);
this.y0p[i] = icGetter.getY(y0i);
this.z0p[i] = icGetter.getZ(z0i);
}
i++;
}
this.countedNeuron = new Boolean[this.nNeurons];
this.neuron = new INeuron[nNeurons]; // array of neurons
i = 0;
while (i < this.nNeurons)
{
//neuron[i] = new KTzNeuron(i, K, T, d, l, xR, x0[i], y0[i], z0[i]);
// I have to get the parameters here again because these parameters may have quenched disorder
this.K = KTzHeader.GetPar_Double(KTzParameters.K);
this.T = KTzHeader.GetPar_Double(KTzParameters.T);
this.d = KTzHeader.GetPar_Double(KTzParameters.d);
this.l = KTzHeader.GetPar_Double(KTzParameters.l);
this.xR = KTzHeader.GetPar_Double(KTzParameters.xR);
this.H = KTzHeader.GetPar_Double(KTzParameters.H);
this.Q = KTzHeader.GetPar_Double(KTzParameters.Q);
this.Theta = KTzHeader.GetPar_Double(KTzParameters.Theta);
var normInput = (KTzV2.Data.YesOrNoAnswer)KTzHeader.GetPar_Int32(KTzParameters.avgInp) == KTzV2.Data.YesOrNoAnswer.Yes;
this.neuron[i] = NeuronFactory.GetKTNeuron(this.neuronType,
new NeuronParam(i, this.K, this.T, this.d, this.l, this.xR, this.H, this.x0p[i], this.y0p[i], this.z0p[i], this.Theta, normalizeInput: normInput, Q: this.Q)
);
this.countedNeuron[i] = false;
i++;
}
this.synapseList = new List<ISynapse>();
Int32[] preNeuronsInd;
// adding the connections to the neurons
UInt64 seed = 0;
i = 0;
while (i < this.nNeurons)
{
// getting the indeces of the pre-synaptic neurons of the i-th neuron
preNeuronsInd = this.AMatrix.GetNonEmptyRowsInd(i, out this.elAdjMatVal);
j = 0;
k = preNeuronsInd.Length; // amount of neurons connected to this one
while (j < k)
{
// I have to retrieve these parameters because they may be subject to quenched disorder
this.J = this.GetJValue(j);
this.tauf = KTzHeader.GetPar_Double(KTzParameters.tauf);
this.taug = KTzHeader.GetPar_Double(KTzParameters.taug);
this.noiseAmp = KTzHeader.GetPar_Double(KTzParameters.R);
this.noiseRatio = KTzHeader.GetPar_Double(KTzParameters.noiseRatio);
this.dyn_alpha = KTzHeader.GetPar_Double(KTzParameters.alpha);
this.dyn_u = KTzHeader.GetPar_Double(KTzParameters.u);
this.dyn_tauJ = KTzHeader.GetPar_Double(KTzParameters.tauJ);
this.synapseList.Add(
SynapseFactory.GetSynapse(
this.synapseType, new SynapseParam(this.neuron[preNeuronsInd[j]], this.neuron[i],
this.tauf, this.taug, this.J, this.noiseAmp, this.noiseRatio,
seed + (UInt64)DateTime.Now.Ticks,
this.noiseType,
(this.dyn_alpha / this.dyn_u), this.dyn_tauJ, this.dyn_alpha, this.dyn_u, this.dyn_dt)
)
);
this.neuron[i].AddInput(this.synapseList.Last());
seed++;
j++;
}
i++;
}
this.nSynapse = this.synapseList.Count;
}
private Double GetJValueHomogeneous(Int32 i)
{
return KTzHeader.GetPar_Double(KTzParameters.J);
}
private Double GetJValueAdjMatrix(Int32 i)
{
return this.elAdjMatVal[i];
}
private void NoNextStimulus(Int32 dt)
{
return;
}
private void prepareStimulus()
{
// neurons are already prepared at this point
if (this.neuronIndStim == -1)
{
if (this.indChoice == StimulusIndexChoice.SquareCenter)
{
this.neuronIndStim = this.GetSquareCenterIndex();
this.GetNeuronIndexForStim = this.GetNeuronIndForStimSimple;
}
else if (this.indChoice == StimulusIndexChoice.Fixed)
{
this.neuronIndStim = this.GetSquareCenterIndex();
this.GetNeuronIndexForStim = this.GetNeuronIndForStimSimple;
}
else if (this.indChoice == StimulusIndexChoice.MostConnected)
{
this.neuronIndStim = this.GetMostConnectedNeuronIndex();
this.GetNeuronIndexForStim = this.GetNeuronIndForStimSimple;
}
else if (this.indChoice == StimulusIndexChoice.Random)
{
this.GetNeuronIndexForStim = this.GetNeuronIndForStimRandom;
}
else if (this.indChoice == StimulusIndexChoice.MultipleRandom)
{
this.GetNeuronIndexForStim = this.GetNeuronIndForStimAll;
}
else
{
throw new ArgumentOutOfRangeException("Unknown StimulusIndexChoice");
}
}
else
{
KTzHeader.SetPar(KTzParameters.indChoice, (Int32)StimulusIndexChoice.Fixed);
this.GetNeuronIndexForStim = GetNeuronIndForStimSimple;
}
// each time we simulate, we create a new stimulus vector
this.stimulus = FExternalStimulus.Get(this.stimulusType, this.tForStimulus, this.stimulusAmp, this.deltaTrainDt, this.nSteps / this.deltaTrainDt, 1.0 / this.poissonRate, this.stimulusStdDev);
if (this.saveSpikeTimes && (this.stimulusType == StimulusType.DeltaWhenInactive))
{
this.SetNextStimTimeIfNeeded = this.stimulus.SetNextStimulusTime;
}
else
this.SetNextStimTimeIfNeeded = this.NoNextStimulus;
//if (this.stimulus.timeForStimulus < (this.nStartStep+1))
}
private Int32 GetSquareCenterIndex()
{
return (this.networkType == AdjacencyMatrixType.SquareLatticeFreeBC || this.networkType == AdjacencyMatrixType.SquareLatticePeriodicBC) ? ((Int32)Math.Floor(this.Lx / 2.0D) * this.Ly + (Int32)Math.Floor(this.Lx / 2.0D)) : (this.nNeurons / 2);
}
private Int32 GetMostConnectedNeuronIndex()
{
return this.neuron.Aggregate(this.neuron[0], (curMax, next) => next.Input.Count > curMax.Input.Count ? next : curMax).Index;
}
public void SetParam(KTzParameters param, Double value)
{
if (!KTzHeader.HasParam(param))
{
throw new Exception("Specified parameter does not exist!");
}
KTzHeader.SetPar(param, value);
hasRunned = false;
getSetOfParameters();
if (param == KTzParameters.rewP)
{
Console.WriteLine("Resetting adjacency matrix...");
createAdjacencyMatrix();
}
}
public void SetParam(KTzParameters param, Int32 value)
{
if (!KTzHeader.HasParam(param))
{
throw new Exception("Specified parameter does not exist!");
}
KTzHeader.SetPar(param, value);
hasRunned = false;
getSetOfParameters();
if ((param == KTzParameters.Lx) ||
(param == KTzParameters.Ly) ||
(param == KTzParameters.Lz) ||
(param == KTzParameters.netType) ||
(param == KTzParameters.nNeigh) ||
(param == KTzParameters.nConn) ||
(param == KTzParameters.dim))
{
Console.WriteLine("Resetting adjacency matrix...");
createAdjacencyMatrix();
}
}
public void ClearSimulation()
{
this.xData = null;
//this.tData = null;
this.hasRunned = false;
if (icType != InitialConditionType.FromLastSimulation)
{
this.ResetNeuronsAndSynapses();
}
}
private void ResetNeuronsAndSynapses()
{
this.timestep = -1;
int i = 0;
while (i < this.nNeurons)
{
this.neuron[i].ResetIC(new Double[3] { this.x0p[i], this.y0p[i], this.z0p[i] });
i++;
}
this.synapseList.ForEach(ss => ss.ResetSignal());
}
private void SaveSpikeTime(int neuronInd, int time)
{
this.spikeNeuronData.Add(neuronInd);
this.spikeTimeData.Add(time);
}
private void UpdateSingleStimSaveSpike(Int32 i = 0)
{
// evaluating the output synapses of each neuron
Int32 k = 0, j;
while (k < this.nSynapse)
{
synapseList[k].Evolve();
k++;
}
// evaluating the membrane potential of each neuron
k = 0;
this.M_t = 0;
while (k < this.samplingIndices.Length)
{
j = this.samplingIndices[k];
if (j == i)
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
else
neuron[j].Evolve();
if (neuron[j].SpikeDetector())
{
this.M_t += 1;
this.SaveSpikeTime(j, this.timestep);
}
k++;
}
k = 0;
while (k < this.unsampledIndices.Length)
{
j = this.unsampledIndices[k];
if (j == i)
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
else
neuron[j].Evolve();
if (neuron[j].SpikeDetector())
this.M_t += 1;
k++;
}
}
/// <summary>
/// updates this network 1 timestep and the given neuron to stimulate
/// if synapses have no dynamics at all (Pulse coupling or GapJunction)
/// </summary>
/// <param name="i">index of the neuron to stimulate</param>
private void UpdateSingleStim(Int32 i = 0)
{
// evaluating the output synapses of each neuron
Int32 j = 0;
while (j < this.nSynapse)
{
synapseList[j].Evolve();
j++;
}
// evaluating the membrane potential of each neuron
j = 0;
while (j < i)
{
neuron[j].Evolve();
j++;
}
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
j++;
while (j < this.nNeurons)
{
neuron[j].Evolve();
j++;
}
}
private void UpdateForMultipleStimSaveSpike(Int32 i = 0)
{
// evaluating the output synapses of each neuron
Int32 k = 0, j;
while (k < this.nSynapse)
{
synapseList[k].Evolve();
k++;
}
// evaluating the membrane potential of each neuron
k = 0;
this.M_t = 0; // counts number of spikes in this iteration
while (k < this.samplingIndices.Length)
{
j = this.samplingIndices[k];
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
if (neuron[j].SpikeDetector())
{
this.M_t += 1;
this.SaveSpikeTime(j, this.timestep);
}
k++;
}
k = 0;
while (k < this.unsampledIndices.Length)
{
j = this.unsampledIndices[k];
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
if (neuron[j].SpikeDetector())
this.M_t += 1;
k++;
}
}
private void UpdateForMultipleStim(Int32 i = 0)
{
// evaluating the output synapses of each neuron
Int32 j = 0;
while (j < this.nSynapse)
{
synapseList[j].Evolve();
j++;
}
// evaluating the membrane potential of each neuron
j = 0;
while (j < this.nNeurons)
{
neuron[j].Evolve(stimulus.GetSignal(this.timestep));
j++;
}
}
/// <summary>
/// prepares this simulation... prepares the data vars, the neurons, the connections and the stimulus
/// </summary>
private void prepareToRunWithData(bool recordXData = true)
{
this.prepareToRunWithData(this.nSteps - this.nStartStep + 1, recordXData);
}
/// <summary>
/// prepares the simulation to store an defined amount of data
/// </summary>
/// <param name="amountOfData">the amount of data to be stored (amount of timesteps that simulation will run)</param>
private void prepareToRunWithData(Int32 amountOfData, bool recordXData = true)
{
this.prepareToRun();
if (recordXData)
{
this.xData = new Double[this.nNeurons][];
//this.tData = new Int32[amountOfData];
Int32 i = 0;
while (i < this.nNeurons)
{
this.xData[i] = new Double[amountOfData];
i++;
}
}
this.M_t = 0;
this.spikeNeuronData = new List<int>();
this.spikeTimeData = new List<int>();
this.spikeDistribution = new List<int>();
this.timeDistribution = new List<int>();
}
private void prepareToRun()
{
prepareNeurons();
prepareStimulus();
}
/// <summary>
/// runs the simulation for a random neuron index for stimulus
/// </summary>
public void Run(Int32? indToStimulate = null, bool recordXData = true)
{
if (hasRunned)
{
throw new Exception("Simulation already runned!");
}
this.prepareToRunWithData(recordXData);
if (indToStimulate.HasValue)
{
KTzHeader.SetPar(KTzParameters.indChoice, (Int32)StimulusIndexChoice.Fixed);
this.neuronIndStim = indToStimulate.Value;
}
this.timestep = -1;
while (this.timestep < this.nStartStep)
{
this.timestep++;
this.UpdateDuringTransient(GetNeuronIndexForStim());
}
if (recordXData)
{
if (this.stimulusType == StimulusType.DeltaWhenInactive)
this.RunDeltaInactive(this.nSteps - this.nStartStep + 1);
else
this.RunAndRecordTimeLength(this.nSteps - this.nStartStep + 1);
}
else
{
this.RunTimeLength(this.nSteps - this.nStartStep + 1);
}
hasRunned = true;
}
private void RunDeltaInactive(Int32 timeLength)
{
Double[][] xDataTemp = new Double[this.nNeurons][];
this.prepareToRunWithData(this.timeBin);
Int32 t = 0, countTemp = 0;
Int32 tMax = this.timeBin * (timeLength / this.timeBin); // total time
for (int i = 0; i < this.nNeurons; i++)
{
xDataTemp[i] = new Double[tMax];
}
this.timestep = -1;
while (t < tMax)
{
// running the simulation on this bin
this.RunAndRecordTimeLength(this.timeBin, ref xDataTemp);
countTemp = this.CountNonConsecutiveDataPeaks(0, this.timeBin); // counts spikes only in the sampled data
// checks the full data for spikes - needed for deciding whether to stimulate the network
if ((countTemp == 0) && this.IsThereNoActivityInUnsampledData()) // if there's no activity in complete sampled data
{
if (this.stimulus.timeForStimulus < t)
this.stimulus.SetNextStimulusTime(1+this.timestep + this.restIntervals * this.timeBin); // set the next stimulus timestep
}
// setting the start of the next bin
t += this.timeBin;
}
this.xData = xDataTemp;
}
/// <summary>
/// runs this simulation in order to get the spike count and returns it, storing it
/// </summary>
/// <param name="tWindow">the time bin length to count spikes</param>
public ThermoStatistics RunForSpikeCountTemporalDynamics(Int32 indexForStimulus = -1, Int32 tWindow = 1000)
{
Int32? indSt;
if (indexForStimulus > -1)
indSt = indexForStimulus;
else
indSt = null;
//
//
// simulation has to run many times
//
//
if (this.saveSpikeTimes)
this.Run(indSt, recordXData: false);
else
this.Run(indSt);
Double[] rho_t;
Double rho, rho2, rho4, rhoMax;
Int32 t_total;
if (this.saveSpikeTimes)
this.GenerateRhoTimeSeriesFromSpikeData(out rho_t, out rho, out rho2, out rho4, out rhoMax, out t_total);
else
this.GenerateRhoTimeSeriesFromXData(out rho_t, out rho, out rho2, out rho4, out rhoMax, out t_total);
if (this.writeRhoTimeSeries)
this.WriteRhoTimeSeriesFile(rho_t);
if (this.writeXDataFile)
this.WriteDataToFile("");
//
//
// mean has to be taken over many realizations
//
//
return new ThermoStatistics(rho, rho2, rho4, rho_t, rhoMax, t_total);
}
private void GenerateRhoTimeSeriesFromSpikeData(out Double[] rho_t, out Double rho, out Double rho2, out Double rho4, out Double rhoMax, out Int32 t_total)
{
Double n_sample = (Double)this.samplingIndices.Length;
t_total = -1;
Double rho_tmp = 0.0D;
rho = 0.0D;
rho2 = 0.0D;
rho4 = 0.0D;