-
Notifications
You must be signed in to change notification settings - Fork 0
/
GUI_RunModelForm.cpp
1535 lines (1283 loc) · 52.6 KB
/
GUI_RunModelForm.cpp
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
/* /////////////////////////////////////////////////////////////////////////////
NetSuite: NetClamp/NetSim/NetFit Neural Network Modeling and Dynamic Clamp Software
Copyright (C) 2011-2014 E. Brady Trexler, Ph.D.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Please direct correspondence to ebtrexler _at_ gothamsci _dot_ com
///////////////////////////////////////////////////////////////////////////// */
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <fstream>
#include <math.h>
#include <stdio.h>
#include <boost/shared_ptr.hpp>
#include "GUI_RunModelForm.h"
#include "MonotCubicInterpolator.h"
#include "abffiles.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "MultiPLOTPanel"
#pragma link "VCLTee.Chart"
#pragma link "VCLTee.TeEngine"
#pragma link "VCLTee.TeeProcs"
#pragma link "VCLTee.Series"
#pragma link "CGMComponent"
#pragma resource "*.dfm"
TRunDynamicClampForm *RunDynamicClampForm;
//---------------------------------------------------------------------------
__fastcall TRunDynamicClampForm::TRunDynamicClampForm(TComponent* Owner)
: TForm(Owner)
{
SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
SampleRate = 50000;
SecondsBefore = 0;
SecondsDuring = 0;
SecondsAfter = 0;
NumRepeats = 1;
InterpolationRate = 5000;
DoInterpolate = true;
for (int i=0; i < MAXPLOTS; i++) {
PlotValues[i] = NULL;
}
Terminated = true;
FileLocation = L"";
LogLocation = L"";
DataLoggingListBox->Clear();
ReadBins = NULL;
mVCells = NULL;
ADCVolts = NULL;
I_nA_DACVolts = NULL;
V_datalogs = NULL;
#ifndef SIM_ONLY_NO_NIDAQ
for (int i=0; i<GetNIDAQmxSetup().NumDevices; i++){
TNIDAQmxDevice *dev = GetNIDAQmxSetup().Devices[i];
DataLoggingListBox->Items->AddStrings(dev->AIChannels);
}
#else // no need to interpolate in NetSim
InterpolateCheckBox->Visible = false;
InterpolateRateEdit->Visible = false;
DoInterpolate = false;
#endif
}
//---------------------------------------------------------------------------
__fastcall TRunDynamicClampForm::~TRunDynamicClampForm()
{
FreeArrayMemory();
for (int i=0; i < MAXPLOTS; i++) {
if (PlotValues[i] != NULL) delete[] PlotValues[i];
}
}
//---------------------------------------------------------------------------
void __fastcall TRunDynamicClampForm::FreeArrayMemory()
{
if (ReadBins) delete[] ReadBins;
if (mVCells) delete[] mVCells;
if (ADCVolts) delete[] ADCVolts;
if (I_nA_DACVolts) delete[] I_nA_DACVolts;
if (NumDataLogChans > 0) {
if (V_datalogs) delete[] V_datalogs;
}
ReadBins = NULL;
mVCells = NULL;
ADCVolts = NULL;
I_nA_DACVolts = NULL;
V_datalogs = NULL;
}
//---------------------------------------------------------------------------
// called by LetErRip to populate PlotsDisplayedListBox
void __fastcall TRunDynamicClampForm::NewNetworkPlots(int numcells, int numelectrodes)
{
// add as many cells as possible
int count = std::min(numcells, MAXPANELS);
for (int i = 0; i < count; i++) {
PlotsDisplayedListBox->Items->Add(CellsPlotsListBox->Items->Strings[i]);
}
// add electrodes to limit set by MAXPANELS
if (count < MAXPANELS) {
int ecount = std::min(numelectrodes, MAXPANELS - count);
for (int i = 0; i < ecount; i++) {
PlotsDisplayedListBox->Items->Add(ElectrodesPlotsListBox->Items->Strings[i]);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TRunDynamicClampForm::LetErRip()
{
MaxRK4TimestepEdit->Text = FloatToStr(GetNet()->GetMaxRK4Timestep());
TimeBeforeEdit->Text = FloatToStr(SecondsBefore);
DurationEdit->Text = FloatToStr(SecondsDuring);
TimeAfterEdit->Text = FloatToStr(SecondsAfter);
SampleRateEdit->Text = FloatToStr(SampleRate);
InterpolateRateEdit->Text = FloatToStr(InterpolationRate);
InterpolateCheckBox->Checked = DoInterpolate;
CoercedSampleRateLabel->Caption = "We'll see...";
RepeatEdit->Text = NumRepeats;
int numcells = 0;
int numelectrodes = 0;
CellsPlotsListBox->Clear();
ElectrodesPlotsListBox->Clear();
// first add cells (voltages)
TCellsMapConstIterator citer = GetNet()->GetCells().begin();
while (citer != GetNet()->GetCells().end()) {
if (citer->second->IsActive()){
CellsPlotsListBox->Items->Add(citer->first.c_str());
numcells++;
}
citer++;
} ;
// second, add electrodes (currents)
TElectrodesMapConstIterator eiter = GetNet()->GetElectrodes().begin();
while (eiter != GetNet()->GetElectrodes().end()) {
if (eiter->second->IsActive()) {
ElectrodesPlotsListBox->Items->Add(eiter->first.c_str());
numelectrodes++;
}
eiter++;
} ;
// PlotsDisplayedListBox->Clear();
// NewNetworkPlots(numcells, numelectrodes);
// now worry about which plots were chosen before, if previous runs
if (PlotsDisplayedListBox->Items->Count == 0) { // this means no previous runs
// populate with network plots
NewNetworkPlots(numcells, numelectrodes);
}
else { // previous run, but perhaps cells or electrodes removed from network
int count = PlotsDisplayedListBox->Items->Count;
std::vector<int> plotstodelete;
for (int i=0; i < count; i++) {
if ((CellsPlotsListBox->Items->IndexOf(PlotsDisplayedListBox->Items->Strings[i]) == -1) &&
(ElectrodesPlotsListBox->Items->IndexOf(PlotsDisplayedListBox->Items->Strings[i]) == -1)) {
plotstodelete.push_back(i);
}
}
std::vector<int>::reverse_iterator to_del_Iter();
for (std::vector<int>::reverse_iterator to_del_Iter = plotstodelete.rbegin();
to_del_Iter != plotstodelete.rend(); to_del_Iter++) {
PlotsDisplayedListBox->Items->Delete(*to_del_Iter);
}
// now that old plots removed, repopulate with new network plots
// NewNetworkPlots(numcells, numelectrodes);
}
if (!GetNet()->Initialize(true)) return; // at start of run everything should be reset
Show();
}
void __fastcall TRunDynamicClampForm::RunTheModel(float64 requestedSampleRate)
{
SampleRate = requestedSampleRate;
CoercedSampleRateLabel->Caption = FloatToStr(SampleRate);
// Calculate Sample periods based on requested values
unsigned long NumSamplesDuring = ceil(SecondsDuring * SampleRate);
AvgSampsLabel->Caption = L"N/A ... Model network";
TotalSampsReqLabel->Caption = NumSamplesDuring;
TotalSampsReadLabel->Caption = NumSamplesDuring;
TotalReadsLabel->Caption = NumSamplesDuring;
AvgusDuringLabel->Caption = L"N/A ... Model network";
MaxusDuringLabel->Caption = L"N/A ... Model network";
FreeArrayMemory();
mVCells = new double[NumSamplesDuring*NetDescription.NumTimeCells];
double step = 1000.0 / SampleRate; // ms per step
// Run nested loops for network of entirely time dependent cells
int numReps = NumRepeats == 0 ? 1 : NumRepeats;
int decrement = NumRepeats == 0 ? -1 : 1;
do {
double * mVptr = mVCells;
Application->ProcessMessages();
for (unsigned long i=0; i<NumSamplesDuring; i++) {
GetNet()->Update(step, NULL, mVptr, NULL);
mVptr += NetDescription.NumTimeCells;
Application->ProcessMessages();
if (Terminated) {
break;
}
}
Application->ProcessMessages();
AvgSampleTime = 1.0 / SampleRate;
SamplesPerPlot = NumSamplesDuring;
NumCells = NetDescription.NumTimeCells;
NumDataLogChans = 0;
PackageTheData();
PlotTheData();
WriteTheData();
RunNumberLabel->Caption = IntToStr(numReps) + " of " + IntToStr(NumRepeats);
numReps -= decrement;
if (Terminated) {
break;
}
bool doReset = ResetAfterRunCheckBox->Checked;
GetNet()->Initialize(doReset); // for next rep
} while (numReps > 0);
}
int __fastcall TRunDynamicClampForm::RunDynamicClamp(float64 requestedSampleRate)
{
#ifndef SIM_ONLY_NO_NIDAQ
try {
// at start of run everything should be reset
// if (!TheNet->Initialize()) return -1;
/*********************************************/
// DAQmx Configure Code -- Analog Input
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxCreateTask ("FiniteSamplesInput", &AI_Task));
TNIDAQmxSetup::DAQmxErrChk (DAQmxCreateAIVoltageChan(AI_Task, AI_ChanString.c_str(),"",DAQmx_Val_RSE ,-10.0,10.0,DAQmx_Val_Volts,NULL));
TNIDAQmxSetup::DAQmxErrChk (DAQmxCfgSampClkTiming (AI_Task, "", requestedSampleRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, floor(SampleRate * 10)));
TNIDAQmxSetup::DAQmxErrChk (DAQmxSetReadReadAllAvailSamp(AI_Task, true));
//Get real (coerced) sample rate
TNIDAQmxSetup::DAQmxErrChk (DAQmxGetSampClkRate(AI_Task, &SampleRate));
CoercedSampleRateLabel->Caption = FloatToStr(SampleRate);
//Get the number of AI channels - from network and from dataloggers combined
TNIDAQmxSetup::DAQmxErrChk (DAQmxGetReadNumChans(AI_Task, &NumAIChans));
/*********************************************/
// DAQmx Configure Code -- Analog Output
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxCreateTask("SinglePointOutput",&AO_Task));
#ifdef USB6009
TNatInstSetup::DAQmxErrChk (DAQmxCreateAOVoltageChan (AO_Task, AO_ChanString, "", 0, 5.0, DAQmx_Val_Volts, ""));
#else
int AOerr = DAQmxCreateAOVoltageChan (AO_Task, AO_ChanString.c_str(), "", -10.0, 10.0, DAQmx_Val_Volts, "");
if (AOerr == -200219) { // ao channels in wrong order
Application->MessageBox(L"The Analog Out (ao) channels need to be in physical order. \
Try renaming the cell that uses ao0 with an underscore at the beginning. \
This will ensure proper order for devices with 2 ao channels.",
L"AO Channels in wrong order...");
}
else TNIDAQmxSetup::DAQmxErrChk (AOerr);
#endif
/* DONE -oebt : Do we need input/output synched with the same clock? I doubt it */
//#define USE_AI_CLOCK_FOR_AO
#ifdef USE_AI_CLOCK_FOR_AO
/* DONE : Warning -- only this routing is possible, for now,
for a single device. Must alter to accomodate multiple devices */
//get device name
UnicodeString temp = GetNIDAQmxSetup().Devices[0]->DeviceName;
temp = "/"+temp+"/ai/SampleClock";
TNIDAQmxSetup::DAQmxErrChk (DAQmxCfgSampClkTiming (AO_Task, temp.t_str(), SampleRate, DAQmx_Val_Rising, DAQmx_Val_HWTimedSinglePoint , 5000));
#else
double MaxDACRate;
TNIDAQmxSetup::DAQmxErrChk (DAQmxGetSampClkMaxRate(AO_Task, &MaxDACRate));
TNIDAQmxSetup::DAQmxErrChk (DAQmxCfgSampClkTiming (AO_Task, "", MaxDACRate, DAQmx_Val_Rising, DAQmx_Val_HWTimedSinglePoint , 5000));
#endif
// Call the signal acquisition and processing function
int numReps = NumRepeats == 0 ? 1 : NumRepeats;
int decrement = NumRepeats == 0 ? 0 : 1;
do {
SignalProcess();
RunNumberLabel->Caption = IntToStr(numReps) + " of " + IntToStr(NumRepeats);
numReps -= decrement;
bool doReset = ResetAfterRunCheckBox->Checked;
GetNet()->Initialize(doReset); // for next rep
} while (numReps > 0);
DAQmxStopTask(AI_Task);
DAQmxClearTask(AI_Task);
DAQmxStopTask(AO_Task);
DAQmxClearTask(AO_Task);
}
catch (const EDAQmxException &e)
{
Application->ShowException(&e);
//cleanup)
if( AI_Task!=0 ) {
/*********************************************/
// DAQmx Stop Code
/*********************************************/
DAQmxStopTask(AI_Task);
DAQmxClearTask(AI_Task);
}
if( AO_Task!=0 ) {
/*********************************************/
// DAQmx Stop Code
/*********************************************/
DAQmxStopTask(AO_Task);
DAQmxClearTask(AO_Task);
}
}
#endif //#ifndef SIM_ONLY_NO_NIDAQ
return 0;
}
void __fastcall TRunDynamicClampForm::TurnOffDACs ()
{
#ifndef SIM_ONLY_NO_NIDAQ
double *DACVolts = new double[NetDescription.NumVDepCells];
int32 written;
// turn "OFF" DAC outputs
memset(DACVolts, 0, sizeof(double)*NetDescription.NumVDepCells);
TNIDAQmxSetup::DAQmxErrChk (DAQmxWriteAnalogF64 (AO_Task, 1, false, 10.0, DAQmx_Val_GroupByScanNumber, DACVolts, &written, NULL));
delete[] DACVolts;
#endif //#ifndef SIM_ONLY_NO_NIDAQ
}
int32 __fastcall TRunDynamicClampForm::SignalProcess ()
{
#ifndef SIM_ONLY_NO_NIDAQ
ProgressBar1->Position = 0;
Application->ProcessMessages();
int32 totalRead=0;
int32 count = 0, readCount = 0;
int32 read=0, written = 0;
float64 avgpresamps, avgdursamps, avgaftsamps;
// need the total number of cells in network
NumCells = NetDescription.NumVDepCells + NetDescription.NumTimeCells;
// Calculate Sample periods based on requested values
NumSamplesBefore = ceil(SecondsBefore * SampleRate);
NumSamplesBeforeAndDuring = NumSamplesBefore + ceil(SecondsDuring * SampleRate);
NumSamplesBeforeAndDuringAndAfter = NumSamplesBeforeAndDuring + ceil(SecondsAfter *SampleRate);
TotalSeconds = SecondsBefore + SecondsDuring +SecondsAfter;
double mspersample = 1000.0 / SampleRate;
try {
FreeArrayMemory();
ReadBins = new int32[NumSamplesBeforeAndDuringAndAfter];
// give 10 ms buffer for read
int ReadBufferSize = ceil(0.01*SampleRate*NumAIChans);
ADCVolts = new double[ReadBufferSize];
mVCells = new double[NumSamplesBeforeAndDuringAndAfter*NumCells];
if (NumDataLogChans > 0) {
V_datalogs = new double[NumSamplesBeforeAndDuringAndAfter*NumDataLogChans];
}
I_nA_DACVolts = new double[NetDescription.NumVDepCells];
memset(I_nA_DACVolts, 0, sizeof(double)*NetDescription.NumVDepCells);
memset(ADCVolts, 0, sizeof(double)*ReadBufferSize);
double * mVptr = mVCells;
double * Vdataptr = V_datalogs;
/*********************************************/
// DAQmx Start Code
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxStartTask(AO_Task));
TNIDAQmxSetup::DAQmxErrChk (DAQmxWriteAnalogF64 (AO_Task, 1, false, 10.0, DAQmx_Val_GroupByScanNumber, I_nA_DACVolts, &written, NULL));
TNIDAQmxSetup::DAQmxErrChk (DAQmxStartTask(AI_Task));
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
//make a loop for the samples preceding the dynamic clamp period
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
count = 0;
do {
/*********************************************/
// DAQmx Read Code
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxReadAnalogF64 (AI_Task, -1, 10.0, DAQmx_Val_GroupByScanNumber, ADCVolts, ReadBufferSize, &read, NULL));
count++;
if( read>0 ) {
// for tracking read efficiency and interrupts
ReadBins[readCount++] = read;
totalRead += read;
Application->ProcessMessages();
if (Terminated) {
TurnOffDACs();
return -1;
}
/*********************************************/
// Update the network
/*********************************************/
// step is in ms
double step = read * mspersample;
// send the last sample from the ADCs, disregard previous samples
double * VoltsIn = &ADCVolts[(read-1)*NumAIChans];//NetDescription.NumVDepCells];
// Call TheNet->Update to SetVm() and CalcVm() appropriately
// I_nA_DACVolts is ignored, and will not be written in this period
GetNet()->Update(step, VoltsIn, mVptr, I_nA_DACVolts);
// move to next segment of mVptr (or mVCells).
mVptr += NumCells;
// Copy data log samples to storage
if (NumDataLogChans > 0) {
// need pointer to correct sample
memcpy(Vdataptr, &VoltsIn[NetDescription.NumVDepCells], sizeof(double) * NumDataLogChans);
Vdataptr += NumDataLogChans;
}
}
} while (totalRead < NumSamplesBefore);
avgpresamps = NumSamplesBefore;
avgpresamps /= count;
ProgressBar1->Position = 30;
Application->ProcessMessages();
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
//make a loop for the samples during the dynamic clamp period
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// readCount = 0;
count = 0;
double mspersample = 1000.0 / SampleRate;
do {
/*********************************************/
// DAQmx Read Code
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxReadAnalogF64 (AI_Task, -1, 10.0, DAQmx_Val_GroupByScanNumber, ADCVolts, ReadBufferSize, &read, NULL));
count++;
if( read>0 ) {
// for tracking read efficiency and interrupts
ReadBins[readCount++] = read;
totalRead += read;
Application->ProcessMessages();
/*********************************************/
// Update the network
/*********************************************/
// step is in ms
double step = read * mspersample;
// send the last sample from the ADCs, disregard previous samples
double * VoltsIn = &ADCVolts[(read-1)*NumAIChans];//NetDescription.NumVDepCells];
// Get the Currents to apply (in volts) from Update
GetNet()->Update(step, VoltsIn, mVptr, I_nA_DACVolts);
// move to next segment of mVptr (or mVCells).
mVptr += NumCells;
// Copy data log samples to storage
if (NumDataLogChans > 0) {
// need pointer to correct sample
memcpy(Vdataptr, &VoltsIn[NetDescription.NumVDepCells], sizeof(double) * NumDataLogChans);
Vdataptr += NumDataLogChans;
}
/*********************************************/
// DAQmx Write Code
/*********************************************/
// check for exceeding DAC limits
double *Iptr = I_nA_DACVolts;
for (int i=0; i<NetDescription.NumVDepCells; i++){
if (*Iptr > 10.0000) {
*Iptr = 10.0000;
}
if (*Iptr < -10.0000) {
*Iptr = -10.0000;
}
Iptr++;
}
TNIDAQmxSetup::DAQmxErrChk (DAQmxWriteAnalogF64 (AO_Task, 1, false, 10.0, DAQmx_Val_GroupByScanNumber, I_nA_DACVolts, &written, NULL));
if (Terminated) {
TurnOffDACs();
return -1;
}
}
} while (totalRead < NumSamplesBeforeAndDuring);
avgdursamps = NumSamplesBeforeAndDuring - NumSamplesBefore;
avgdursamps /= count;
ProgressBar1->Position = 70;
Application->ProcessMessages();
TurnOffDACs();
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
//make a loop for the samples after the dynamic clamp period
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
count = 0;
do {
/*********************************************/
// DAQmx Read Code
/*********************************************/
TNIDAQmxSetup::DAQmxErrChk (DAQmxReadAnalogF64 (AI_Task, -1, 10.0, DAQmx_Val_GroupByScanNumber, ADCVolts, ReadBufferSize, &read, NULL));
count++;
if( read>0 ) {
// for tracking read efficiency and interrupts
ReadBins[readCount++] = read;
totalRead += read;
Application->ProcessMessages();
if (Terminated) {
TurnOffDACs();
return -1;
}
/*********************************************/
// Update the network
/*********************************************/
// step is in ms
double step = read * mspersample;
// send the last sample from the ADCs, disregard previous samples
double * VoltsIn = &ADCVolts[(read-1)*NumAIChans];//NetDescription.NumVDepCells];
// Call TheNet->Update to SetVm() and CalcVm() appropriately
// I_nA_DACVolts is ignored, and will not be written in this period
GetNet()->Update(step, VoltsIn, mVptr, I_nA_DACVolts);
// move to next segment of mVptr (or mVCells).
mVptr += NumCells;
// Copy data log samples to storage
if (NumDataLogChans > 0) {
// need pointer to correct sample
memcpy(Vdataptr, &VoltsIn[NetDescription.NumVDepCells], sizeof(double) * NumDataLogChans);
Vdataptr += NumDataLogChans;
}
}
} while (totalRead < NumSamplesBeforeAndDuringAndAfter);
avgaftsamps = NumSamplesBeforeAndDuringAndAfter - NumSamplesBeforeAndDuring;
avgaftsamps /= count;
ProgressBar1->Position = 100;
Application->ProcessMessages();
TNIDAQmxSetup::DAQmxErrChk (DAQmxStopTask(AI_Task));
TNIDAQmxSetup::DAQmxErrChk (DAQmxStopTask(AO_Task));
}
catch (const Exception &e)
{
FreeArrayMemory();
throw(e);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Fill in run performance parameters
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
UnicodeString avgsamps = "Pre: " + FloatToStrF(avgpresamps,ffFixed,4,4) +
", During: " + FloatToStrF(avgdursamps,ffFixed,4,4) +
", After: " + FloatToStrF(avgaftsamps,ffFixed,4,4);
AvgSampsLabel->Caption = avgsamps;
TotalSampsReqLabel->Caption = FloatToStr(TotalSeconds*SampleRate);
TotalSampsReadLabel->Caption = FloatToStr(totalRead);
TotalReadsLabel->Caption = FloatToStr(readCount);
double temp = 0.0;
double testbin ;
double max = 0;
double uspersample = (1.0e6/SampleRate);
//Assign bin edges for histogram
double bin_edges[14] = {0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0,
500.0, 1000.0, 2000.0, 5000.0, 10000.0};
// double bin_centers[13];
unsigned long bins[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int line = 0; line < readCount; line++) {
testbin = ReadBins[line] * uspersample;
temp += testbin; // store for average samp time later
if (max < testbin) {
max = testbin; // store for max samp time
}
// make histogram
for (int j=0; j < 13; j++) {
if (testbin > bin_edges[j] && testbin <= bin_edges[j+1]) {
bins[j]++;
}
}
}
Series1->Clear();
for (int i=0; i<13; i++) {
// bin_centers[i] = (bin_edges[i] + bin_edges[i+1]) / 2.0;
// Series1->AddXY(bin_centers[i], bins[i], FloatToStr(bin_centers[i]));
Series1->AddXY(bin_edges[i+1], bins[i], FloatToStr(bin_edges[i+1]));
}
temp /= readCount;
AvgusDuringLabel->Caption = FloatToStrF(temp,ffFixed,4,4);
AvgSampleTime = temp * 1e-6; // convert to seconds for plotting
temp = max;
temp *= uspersample;
MaxusDuringLabel->Caption = FloatToStrF(temp,ffFixed,6,6);
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Plot the data
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
SamplesPerPlot = readCount;
PackageTheData();
PlotTheData();
WriteTheData();
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Cleanup
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// delete[] ReadBins;
// delete[] mVCells;
// delete[] ADCVolts;
// delete[] I_nA_DACVolts;
#endif //#ifndef SIM_ONLY_NO_NIDAQ
return 0;
}
//---------------------------------------------------------------------------
void __fastcall TRunDynamicClampForm::PackageTheData()
{
// this method places all available traces --
// mV from all cells, Volts from all data loggers, nA from all electrodes
// into PlotsMap that can be reused if user changes plotted channels or wishes
// to write to disk after an acquisition has already occurred.
TCellsMapConstIterator celliter = GetNet()->GetCells().begin();
TCellsMapConstIterator cells_end = GetNet()->GetCells().end();
TElectrodesMapConstIterator trodeiter = GetNet()->GetElectrodes().begin();
PlotsMap.clear();
NumAvailablePlots = 0;
MonotCubicInterpolator *terp = NULL;
double *demux = NULL;
double *time = NULL;
unsigned long InterpSamps = 0;
double interptime = 1000.0 / InterpolationRate;
NumPlotVals = SamplesPerPlot;
if (DoInterpolate) {
InterpSamps = ceil((SecondsBefore + SecondsDuring + SecondsAfter) * InterpolationRate);
NumPlotVals = InterpSamps;
demux = new double[SamplesPerPlot];
time = new double[SamplesPerPlot];
double mspersamp = 1000.0 / SampleRate;
time[0] = 0.0;
for (unsigned long i = 1; i < SamplesPerPlot; i++) {
time[i] = (ReadBins[i] * mspersamp) + time[i - 1];
}
// SampleTime is the interpolation rate
SampleTime = 1.0 / InterpolationRate;
}
else SampleTime = AvgSampleTime;
// de-multiplex voltage data from cells
// voltage dependent cells first, then rest of cells
while (celliter != cells_end) {
if (celliter->second->IsActive()) {
if (celliter->second->IsVoltageDependent()) {
// handle memory for PlotValues
if (PlotValues[NumAvailablePlots] != NULL) {
delete[] PlotValues[NumAvailablePlots];
}
PlotValues[NumAvailablePlots] = new double[NumPlotVals];
// Demux mVCells into PlotValues
double * plotPtr = &mVCells[NumAvailablePlots];
if (!DoInterpolate) {
demux = PlotValues[NumAvailablePlots];
}
for (unsigned long j = 0; j < SamplesPerPlot; j++) {
demux[j] = *plotPtr;
plotPtr += NumCells;
}
if (DoInterpolate) {
terp = new MonotCubicInterpolator(time, demux, SamplesPerPlot);
for (unsigned long j = 0; j < InterpSamps; j++) {
PlotValues[NumAvailablePlots][j] = terp->evaluate(j*interptime);
}
delete terp;
}
UnitsDataPair udpair(L"mV",PlotValues[NumAvailablePlots]);
PlotsMap[celliter->first] = udpair; // assign each channel's data to map
NumAvailablePlots++;
}
}
celliter++;
}
// demux rest of cells
celliter = GetNet()->GetCells().begin(); //start over from beginning
while (celliter != cells_end) {
if (celliter->second->IsActive()) {
if (!celliter->second->IsVoltageDependent()) { //not voltage dependent
// handle memory for PlotValues
if (PlotValues[NumAvailablePlots] != NULL) {
delete[] PlotValues[NumAvailablePlots];
}
PlotValues[NumAvailablePlots] = new double[NumPlotVals];
// Demux mVCells into PlotValues
double * plotPtr = &mVCells[NumAvailablePlots];
if (!DoInterpolate) {
demux = PlotValues[NumAvailablePlots];
}
for (unsigned long j = 0; j < SamplesPerPlot; j++) {
demux[j] = *plotPtr;
plotPtr += NumCells;
}
if (DoInterpolate) {
terp = new MonotCubicInterpolator(time, demux, SamplesPerPlot);
for (unsigned long j = 0; j < InterpSamps; j++) {
PlotValues[NumAvailablePlots][j] = terp->evaluate(j*interptime);
}
delete terp;
}
UnitsDataPair udpair(L"mV",PlotValues[NumAvailablePlots]);
PlotsMap[celliter->first] = udpair; // assign each channel's data to map
NumAvailablePlots++;
}
}
celliter++;
}
// de-multiplex voltage data from data loggers
for (uInt32 i=0; i < NumDataLogChans; i++) {
if (PlotValues[NumAvailablePlots] != NULL) {
delete[] PlotValues[NumAvailablePlots];
}
PlotValues[NumAvailablePlots] = new double[NumPlotVals];
double * plotPtr = &V_datalogs[i];
if (!DoInterpolate) {
demux = PlotValues[NumAvailablePlots];
}
for (unsigned long j = 0; j < SamplesPerPlot; j++) {
demux[j] = *plotPtr;
plotPtr += NumDataLogChans;
}
if (DoInterpolate) {
terp = new MonotCubicInterpolator(time, demux, SamplesPerPlot);
for (unsigned long j = 0; j < InterpSamps; j++) {
PlotValues[NumAvailablePlots][j] = terp->evaluate(j*interptime);
}
delete terp;
}
UnitsDataPair udpair(L"V",PlotValues[NumAvailablePlots]);
std::wstring name(DataLogsPlotsListBox->Items->Strings[i].c_str());
PlotsMap[name] = udpair; // assign each channel's data to map
NumAvailablePlots++;
}
// Now add electrodes to PlotsMap
int numElectrodes = GetNet()->GetElectrodes().size();
NumElectrodes = 0;
for (int i=0; i < numElectrodes; i++) {
if (trodeiter->second->IsActive()) {
if (PlotValues[NumAvailablePlots] != NULL) {
delete[] PlotValues[NumAvailablePlots];
}
PlotValues[NumAvailablePlots] = new double[NumPlotVals];
trodeiter->second->Initialize(true);
double trode_time = SampleTime*1000.0;
for (unsigned long j = 0; j < NumPlotVals; j++) {
PlotValues[NumAvailablePlots][j] = trodeiter->second->Update(trode_time);
}
UnitsDataPair udpair(L"nA",PlotValues[NumAvailablePlots]);
PlotsMap[trodeiter->first] = udpair; // assign each electrode's data to map
NumElectrodes++;
NumAvailablePlots++;
}
trodeiter++;
}
if (DoInterpolate) {
delete[] demux;
delete[] time;
}
}
//---------------------------------------------------------------------------
void __fastcall TRunDynamicClampForm::PlotTheData()
{
TColor colors[12] = {clRed, TColor(0x000080FF) , clYellow, clGreen, clBlue, clPurple,
clMaroon, clBlack, clNavy, clTeal, clFuchsia, clDkGray};
// only draw chosen plots
int count = PlotsDisplayedListBox->Items->Count;
MultiPLOTPanel1->NumVisiblePlots = count;
MultiPLOTPanel1->IsRealTimePlot = false;
TStrings *plots = PlotsDisplayedListBox->Items;
for (int i = 0; i < count; i++) {
MultiPLOTPanel1->PLOTPanel[i]->ClearPlots();
MultiPLOTPanel1->PLOTPanel[i]->XUnits = "seconds";
std::wstring label = (PlotsMap[plots->Strings[i].c_str()].first + L" (");
label += plots->Strings[i].c_str();
label += L")";
MultiPLOTPanel1->PLOTPanel[i]->YUnits = label.c_str();
MultiPLOTPanel1->PLOTPanel[i]->AddPlot(
new TStaticFunctionPlot(MultiPLOTPanel1->PLOTPanel[i], 0, "",
colors[8], 0.0, SampleTime,
NumPlotVals,
PlotsMap[plots->Strings[i].c_str()].second),
false);
MultiPLOTPanel1->PLOTPanel[i]->ScalePlots(true);
}
}
//---------------------------------------------------------------------------
void __fastcall TRunDynamicClampForm::WriteTheData()
{
if (NumAvailablePlots == 0 || NumPlotVals == 0) {
return;
}
// if requested, write all channels to disk
if (SaveDataCheckBox->Checked) {
if (FileLocation.Length() != 0) {
FormatSettings.DateSeparator = L'-';
FormatSettings.ShortDateFormat = L"yyyy/mm/dd";
FormatSettings.TimeSeparator = L'_';
double *plotdata = NULL;
double factor = 327.7;
switch (SaveDialog1->FilterIndex) {
case 1: { ////// text format
UnicodeString filename = ChangeFileExt(FileLocation, L"") + L"__" +
DateToStr(Date()) + L"__" +
TimeToStr(Time()) + L".txt";
std::wofstream datafile_fs(filename.c_str());
if (datafile_fs) {
datafile_fs.precision(6);
PlotsMapType::iterator pmIter = PlotsMap.begin();
// write header row -- # hashtag for gnuplot
datafile_fs << L"#Time (s)" << L"\t";
for (unsigned long n=0; n < NumAvailablePlots; n++) {
datafile_fs << pmIter->first << L"\t";
pmIter++;
}
datafile_fs << L"\n";
for (unsigned long j = 0; j < NumPlotVals ; j++) {
// reset PlotsMap iterator
pmIter = PlotsMap.begin();
datafile_fs << j * SampleTime << L"\t" ;
for (unsigned long i=0; i < NumAvailablePlots; i++) {
plotdata = pmIter->second.second;
datafile_fs << plotdata[j] << L"\t";
pmIter++;
}
datafile_fs << L"\n";
}
}
}; break;
case 2: { //////// abf format
AnsiString filename = ChangeFileExt(FileLocation, L"") + L"__" +
DateToStr(Date()) + L"__" +
TimeToStr(Time()) + L".abf";
int hFile;
HANDLE hHandle;
int nError = 0;
DWORD dwEpisodes, dwSamples;
uInt32 numElectrodes = GetNet()->GetElectrodes().size();
short *abfdata = new short[NumAvailablePlots*NumPlotVals];
short *pabfdata = abfdata;
ABFFileHeader *pFH = new ABFFileHeader;
ABFH_Initialize( pFH );
pFH->nADCNumChannels = NumAvailablePlots > ABF_ADCCOUNT ?
ABF_ADCCOUNT : NumAvailablePlots;
pFH->fADCSequenceInterval = SampleTime * 1000000.0;
pFH->lNumSamplesPerEpisode = NumPlotVals;
pFH->fADCRange = 20.0;