-
Notifications
You must be signed in to change notification settings - Fork 8
/
findSim.py
1649 lines (1505 loc) · 74.2 KB
/
findSim.py
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
#
# 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, 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; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA.
#
'''
*******************************************************************
* File: findSim.py
* Description:
* Author: Upinder S. Bhalla, NishaAnnViswan, HarshaRani
* E-mail: bhalla@ncbs.res.in
nishaav@ncbs.res.in
hrani@ncbs.res.in
********************************************************************/
/**********************************************************************
** This program is part of 'MOOSE', the
** Messaging Object Oriented Simulation Environment,
** also known as GENESIS 3 base code.
** copyright (C) 2003-2021 Upinder S. Bhalla. and NCBS
**********************************************************************/
'''
from __future__ import print_function
import heapq
import matplotlib.pyplot as plt
import numpy as np
import sys
import json
import jsonschema
import traceback
import argparse
import copy
import os
import re
import time
if sys.version_info < (3, 4):
import imp # This is apparently deprecated in Python 3.4 and up
else:
import importlib
'''
from simError import SimError
import simWrap
import simWrapMoose
import simWrapHillTau
'''
foundLib_HillTau_ = False
try:
import hillTau
foundLib_HillTau_ = True
except Exception as e:
pass
if __package__ is None or __package__ == '':
from simError import SimError
from simWrap import SimWrap
from simWrapMoose import SimWrapMoose
if foundLib_HillTau_:
from simWrapHillTau import SimWrapHillTau
else:
from FindSim.simError import SimError
from FindSim.simWrap import SimWrap
from FindSim.simWrapMoose import SimWrapMoose
if foundLib_HillTau_:
from FindSim.simWrapHillTau import SimWrapHillTau
convertTimeUnits = {'sec': 1.0,'s': 1.0,
'ms': 1e-3, 'millisec': 1e-3, 'msec' : 1e-3,
'us': 1e-6, 'usec': 1e-6, 'microsec' : 1e-6,
'ns': 1e-6, 'nanosec' : 1e-9,
'min': 60.0 ,'m' : 60.0,
'hours': 3600.0, 'hrs' : 3600.0,
"days": 86400.0}
convertQuantityUnits = { 'M': 1e3, 'mM': 1.0, 'uM': 1.0e-3,
'nM':1.0e-6, 'pM': 1.0e-9, 'number':1.0, '#': 1.0, 'ratio':1.0,
'V': 1.0, 'mV': 0.001, 'uV': 1.0e-6, 'nV':1.0e-9,
'A': 1.0, 'mA': 0.001, 'uA': 1.0e-6, 'nA':1.0e-9, 'pA':1.0e-12,
'Hz': 1.0, '1/sec':1.0, 'sec':1.0, '1/s': 1.0, 's':1.0, 'min':60.0,
'mV/ms':1.0, '%':100.0, 'Fold change':1.0, 'none': 1 }
# The below version is kept for backward compatibility with some examples.
# It is deprecated and the default will become NRMS.
#defaultScoreFunc = "(expt-sim)*(expt-sim)/(datarange*datarange + 1e-9)"
defaultScoreFunc = "NRMS"
sw = "" #default dummy value for SimWrap
fschema = "FindSim-Schema.json" # Name of JSON schema file
def keywordMatches( k, m ):
return k.lower() == m.lower()
'''
class SimError( Exception ):
def __init__( self, value ):
self.value = value
def __str__( self ):
return repr( self.value )
'''
##########################################################################
class Experiment:
"""The Experiment class defines the experimental context and source
information. It isn't really useful in running the model but is needed
in the experiement specification file so that we know where the
data came from, and to look up details."""
def __init__( self, metadata, expt ):
self.exptType = expt["design"].lower()
source = metadata["source"]
self.exptSource = source.get( "type" )
self.authors = source.get("authors")
self.year = source.get( "year" )
self.citationId = source.get( "PMID" )
if not self.citationId:
self.citationId = source.get( "doi" )
self.journal = source.get( "journal" )
self.temperature = expt.get( "temperature" )
self.species = expt.get( "species" )
self.cellType = expt.get( "cellType" )
self.testModel = metadata.get( "testModel" )
self.testMap = metadata.get( "testMap" )
##########################################################################
class Stimulus:
"""Specifies manipulations to be done on a specific component of
the model in the course of the simulated experiment. Typically this
would include adding or removing molecules. Less common might be a
change in rates (e.g., temperature, or a pharmacological agent that
is being modeled as a rate change).
There can be multiple stimuli during an experiment.
Dose response is a little special, as here the stimulus only specifies
the molecule involved. The actual concentrations used are specified in
the Readout, which contains the dose-response table.
"""
def __init__( self, s ):
#self.quantityUnits = s["quantityUnits"].encode( "ascii" ) # Schema ensures it is OK
self.quantityUnits = s["quantityUnits"] # Schema ensures it is OK
self.quantityScale = convertQuantityUnits[ self.quantityUnits ]
self.entities = [s["entity"],]
self.field = str( s["field"] )
self.isBuffered = s.get( "isBuffered" )
if self.isBuffered == None:
self.isBuffered = 1
#self.timeUnits = s.get( "timeUnits" ).encode( "ascii" )
self.timeUnits = s.get( "timeUnits" )
if not self.timeUnits:
self.timeUnits = "s"
self.timeScale = convertTimeUnits[ self.timeUnits ]
self.data = s.get( "data" )
if "label" in s:
self.label = s["label"]
else:
self.label = self.entities[0]
if not self.data:
if "value" in s:
self.data = [[0, s["value"]],]
else:
self.data = []
def load( findsim ):
ret = []
fstims = findsim.get( "Stimuli" )
if fstims:
for i in fstims:
ret.append( Stimulus( i ) )
return ret
load = staticmethod( load )
def minInterval( self ):
ret = 1000.0
lastt = 0.0
lastval = 0.0
newdata = []
isElec = self.field in ['Im', 'current', 'Vclamp'] or (self.field=='rate' and 'syn' in self.entities[0])
for d in self.data:
if float( d[0] ) == 0.0: # Stim at starting time. Legit.
newdata.append( [d[0], d[1]] )
lastval = float(d[1])*self.quantityScale
continue
t = float(d[0])*self.timeScale
val = float(d[1])*self.quantityScale
if t > lastt: # Avoid zeros, could set many things at once.
ret = min( ret, t - lastt )
if (not isElec) and (t - lastt) >= 100.0 and lastval < 1e-7 and val > 0.5e-4:
# Have to insert intermediate step in data.
newdata.append( [float(d[0]), 1e-6 / self.quantityScale] )
newt = t + (t - lastt)/( 100.0 * self.timeScale )
#print( "inserting: ", [d[0], 1e-6], [newt, d[1]] )
newdata.append( [newt, d[1]] )
ret = min( ret, (t - lastt)/100.0 )
else:
newdata.append( [d[0], d[1]] )
lastt = t
lastval = val
self.data = newdata
self.shortestStimInterval = ret
return ret
def configure( self, modelLookup ):
"""Sanity check on all fields. First, check that all the entities
named in experiment have counterparts in the model definition"""
#self.minInterval()
for i in self.entities:
#if not i.encode( 'ascii' ) in modelLookup:
if not i in modelLookup:
raise SimError( "Stim::configure: Error: object {} not defined in model lookup.".format( i ) )
##########################################################################
# Shifted to Readout class as static fields.
#elecFields = ['Vm', 'Im', 'current'] + epspFields + epscFields
class Readout:
"""Specifies readouts to be obtained from a specific component of
the model in the course of the simulated experiment. Almost always
molecule quantity, but later might be electrical things like membrane
potential.
Currently only a single readout is supported.
"""
epspFields = [ 'EPSP_peak', 'EPSP_slope', 'IPSP_peak', 'IPSP_slope' ]
epscFields = [ 'EPSC_peak', 'EPSC_slope', 'IPSC_peak', 'IPSC_slope' ]
fepspFields = [ 'fEPSP_peak','fEPSP_slope','fIPSP_peak','fIPSP_slope' ]
postSynFields = fepspFields + epspFields + epscFields
elecFields = ['Vm', 'Im', 'current'] + epspFields + epscFields
def __init__( self, findsim, isPlotOnly = False ):
self.findsim = findsim
ro = findsim["Readouts"]
self.directParamData = ro.get( "paramdata" )
self.isPlotOnly = isPlotOnly
self.simData = []
self.window = None # If present, use [startt, endt, dt, operation]
self.data = []
if not self.directParamData:
self.timeUnits = ro["timeUnits"]
self.timeScale = convertTimeUnits[self.timeUnits]
self.quantityUnits = ro["quantityUnits"]
self.quantityScale = convertQuantityUnits[self.quantityUnits]
self.entities = ro["entities"]
self.field = ro["field"]
self.settleTime = ro.get("settleTime")
if not self.settleTime:
self.settleTime = 300.0
self.data = ro.get("data") # For most kinds of data
if self.data:
for i in self.data: # force it to have [t, v, sem] in each row
if len( i ) == 2:
i.append( 0 )
assert( len( i ) == 3 )
self.bardata = ro.get( "bardata" ) # only for barcharts
self.tabulateOutput = False
self.generate = None
self.generateFile = None
if "window" in ro:
win = ro["window"]
self.window = [win["startt"], win["endt"], win["dt"],
win["operation"] ]
self.normMode = "none"
norm = ro.get( "normalization" )
self.useNormalization = False
self.ratioReferenceEntities = []
self.ratioReferenceTime = 0
self.ratioReferenceDose = 0
self.ratioReferenceValue = 1.0
if norm:
self.useNormalization = True
self.ratioReferenceEntities = norm["entities"]
#if len( self.ratioReferenceEntities ) > 0 and not self.entities[0] in self.ratioReferenceEntities:
self.normMode = norm["sampling"]
if self.normMode == "none":
self.useNormalization = False
elif self.normMode == "start":
self.ratioReferenceTime = 0
elif self.normMode == "presetTime":
self.ratioReferenceTime = norm["time"]
elif self.normMode == "each":
self.ratioReferenceTime = -1
elif self.normMode == "dose":
self.ratioReferenceDose = norm["dose"]
self.settleTime = ro.get("settleTime")
self.ratioReferenceTime = norm.get("time")
if not self.ratioReferenceTime:
self.ratioReferenceTime = self.settleTime
# Set up lists to use in the analysis
self.ratioData = []
self.plots = []
# Set up Display parameters
self.useXlog = False
self.useYlog = False
self.plotDt = [0.1]
self.numMainPlots = 0
disp = ro.get( "display" )
if disp:
if "useXlog" in disp:
self.useXlog = disp["useXlog"]
if "useYlog" in disp:
self.useYlog = disp["useYlog"]
if "plotDt" in disp:
self.plotDt = disp["plotDt"]
# Set up EPSP parameters.
self.epspFreq = 100.0 # Used to generate single synaptic event
self.epspWindow = 0.02 # Time of epspPlot to scan for pk/slope
self.ex = 0.0005 # Electrode position for field recordings.
self.ey = 0.0
self.ez = 0.0
self.fepspMin = -0.002 # 2 mm to the left of trode
self.fepspMax = 0.001 # 1 mm to the right of trode
epsp = ro.get( "epsp" )
if epsp:
if "epspFreq" in epsp:
self.epspFreq = epsp["epspFreq"]
if "epspWindow" in epsp:
self.epspWindow = epsp["epspWindow"]
if "electrodePosition" in epsp:
self.ex, self.ey, self.ez = epsp["electrodePosition"]
if "epspDepthIntegMin" in epsp:
self.fepspMin = epsp["DepthIntegMin"]
if "epspDepthIntegMax" in epsp:
self.fepspMax = epsp["DepthIntegMax"]
def plotCopy( self, entity, field):
ret = copy.copy( self )
ret.entities = [ entity ]
ret.field = field
if field == 'conc' or field == 'concInit':
if self.field in ['conc', 'concInit'] and not self.quantityUnits == 'ratio':
ret.quantityUnits = self.quantityUnits
else:
ret.quantityUnits = "uM"
ret.useNormalization = False
if field == 'n' or field == 'nInit':
ret.quantityUnits = "#"
if field == 'Vm' or field == 'Em':
ret.quantityUnits = "mV"
if field == 'current' or field == 'Im' or field == 'Ik':
ret.quantityUnits = "pA"
ret.quantityScale = convertQuantityUnits[ret.quantityUnits]
ret.isPlotOnly = True
return ret
def configure( self, modelLookup ):
"""Sanity check on all fields. First, check that all the entities
named in experiment have counterparts in the model definition"""
for i in self.entities:
#if not i.encode("ascii") in modelLookup:
if not i in modelLookup:
raise SimError( "Readout::configure: Error: object {} not defined in model lookup.".format( i ) )
for i in self.ratioReferenceEntities:
#if not i.encode("ascii") in modelLookup:
if not i in modelLookup:
raise SimError( "Readout::configure: Error: ratioReferenceEntity '{}' not defined in model lookup.".format( i ) )
def digestSteadyStateRun( self, ref, ret ):
if self.useNormalization:
if self.normMode == "dose":
# Here we have specified a distinct dose against which to
# normalize. This is run as an extra data point, and has
#to be popped.
assert( len( ret ) > 1 and len( ref ) == len( ret ) )
referenceAtExtraDose = ref.pop()
ref = [referenceAtExtraDose] * len( ref )
tempret = ret.pop() # Pop the readout mol here too.
elif self.normMode == "start":
ref = [ref[0]] * len( ret )
elif self.normMode == "end":
ref = [ref[-1]] * len( ret )
elif self.normMode == "min":
ref = [min(ref)] * len( ret )
elif self.normMode == "max":
ref = [max(ref)] * len( ret )
elif self.normMode == "presetTime":
print( "Probably you want sampling mode to be one of: start, end, min, max, dose. Defaulting to 'start'")
ref = [ref[0]] * len( ret )
else:
ref = [self.quantityScale * 1.0] * len( ret )
# The remaining case is that normMode == 'each', in which case we
# compute the ref for each stimulus value. Ref goes through
# unchanged in this case.
# Check for zeroes in the denominator
eps = 1e-16
if len( [ x for x in ref if abs(x) < eps ] ) > 0:
# Treat the output as all zeroes in this case.
self.simData = [0.0] * len( ref )
#raise SimError( "runDoser: Normalization3 failed due to zero denominator" )
print( "Warning: runDoser: Normalization3 failed due to zero denominator: ", str( min( ref ) ) )
return
# Finally assign the simData.
self.simData = [ x/y for x, y in zip( ret, ref ) ]
def displayPlots( self, fname, modelLookup, stims, hideSubplots, exptType, bigFont = False, labelPos = None, deferPlot = False ):
if self.isPlotOnly:
separator = ":"
else:
separator = "."
if not deferPlot:
plt.figure( self.entities[0] + "." + self.field )
if "doseresponse" in exptType:
for i in stims[0].entities:
#elms = modelLookup[i.encode("ascii")]
#elms = modelLookup.get( i.encode("ascii") )
elms = modelLookup.get( i )
if not elms:
raise SimError( "displayPlots 1: could not find entity '{}'".format( i ) )
for j in elms:
pp = PlotPanel( self, exptType, xlabel = str(j) +' ('+stims[0].quantityUnits+')', useBigFont = bigFont )
pp.plotme( fname, pp.ylabel, joinSimPoints = True,
labelPos = labelPos )
elif "barchart" in exptType:
for i in self.entities:
#elms = modelLookup[i.encode("ascii")]
#elms = modelLookup.get( i.encode("ascii") )
elms = modelLookup.get( i )
if not elms:
raise SimError( "displayPlots 2: could not find entity '{}'".format(i) )
for j in elms:
pp = PlotPanel( self, exptType, xlabel = str(j) +' ('+stims[0].quantityUnits+')', useBigFont = bigFont )
pp.plotbar( self, stims, fname, labelPos = labelPos )
elif "timeseries" in exptType:
tsUnits = self.quantityUnits
'''
if self.field in Readout.epspFields:
tsUnits = 'mV'
elif self.field in Readout.epscFields:
tsUnits = 'pA'
elif self.field in Readout.fepspFields:
if not hideSubplots:
self.plotFepsps( fname, useBigFont = bigFont )
return
elif self.useNormalization:
tsUnits = 'Fold change'
'''
tsScale = convertQuantityUnits[tsUnits]
if self.field in Readout.fepspFields:
if not hideSubplots:
self.plotFepsps( fname, useBigFont = bigFont )
return
######################################
pp = PlotPanel( self, exptType, useBigFont = bigFont )
assert( len( self.plots ) > 0)
numPts = len( self.plots[0] )
assert( numPts > 0 )
sumvec = np.zeros( numPts )
scale = self.quantityScale
if self.useNormalization:
if self.normMode == "presetTime":
scale = tsScale * self.ratioReferenceValue
elif len( self.ratioData ) > 0:
if self.normMode == "start" and self.ratioData[0] > 0.0:
scale = tsScale * self.ratioData[0]
elif self.normMode == "end" and self.ratioData[-1] > 0.0:
scale = tsScale * self.ratioData[-1]
elif self.normMode == "min" and min(self.ratioData) > 0.0:
scale = tsScale * min( self.ratioData )
elif self.normMode == "max" and max(self.ratioData) > 0.0:
scale = tsScale * max( self.ratioData )
elif self.normMode == "each" and max(self.ratioData) > 0.0:
scale = tsScale * max( self.ratioData )
# For 'each' we don't realy have a good way to do
# timeseries. So just use the biggest.
'''
if len( self.ratioData ) > 0:
scale = tsScale * self.ratioData[0]
print( "Scale 1: {} {} {}".format( scale, tsScale, self.ratioData ) )
else:
scale = tsScale * self.ratioReferenceValue
print( "Scale 2: {} {} {}".format( scale, tsScale, self.ratioReferenceValue ) )
print( "Scale 0: {} {} {}".format( scale, tsScale, self.normMode ) )
'''
for idx, ypts in enumerate( self.plots ):
tconv = convertTimeUnits[ self.timeUnits ]
xpts = np.array( range( len( ypts ) ) ) * self.plotDt[idx] / tconv
ypts /= scale
if not self.isPlotOnly :
sumvec += ypts
if not hideSubplots:
# Plot summed components. Need to access name.
#plt.plot( xpts, ypts, 'r:', label = j.name )
plt.plot( xpts, ypts, 'r:' )
else:
plt.plot( xpts, ypts )
#plt.figure( "Main FindSim Plots" ) # Go back to original plot.
if not self.isPlotOnly :
plt.plot( xpts, sumvec, 'r' )
ylabel = pp.ylabel
if self.field in ( Readout.epspFields + Readout.epscFields ):
if self.field in Readout.epspFields:
plt.ylabel( '{} Vm ({})'.format( self.entities[0], tsUnits ) )
else:
plt.ylabel( '{} holding current ({})'.format( self.entities[0], tsUnits ) )
plt.figure( self.field ) # Do the EPSP in a new figure
if self.useNormalization:
ylabel = '{} Fold change'.format( self.field )
pp.plotme( fname, ylabel, isPlotOnly = self.isPlotOnly,
labelPos = labelPos, joinSimPoints = False )
######################################
def plotFepsps( self, fname, useBigFont = False ):
#tconv = next( v for k, v in convertTimeUnits.items() if self.timeUnits in k )
tconv = convertTimeUnits[ self.timeUnits ]
assert( len( self.plots ) > 0 )
numPts = len( self.plots[0] )
xpts = np.array( range( numPts) ) * self.plotDt / tconv
sumvec = np.zeros( numPts )
for i, wt in zip( self.plots, self.wts ):
# I'm going to plot the original currents rather than the
# variously scaled contributions leading up to the fEPSP
ypts = i * 1e12 # Hack, hard code currents in pA
plt.plot( xpts, ypts, 'r:' )
sumvec += ypts
plt.plot( xpts, sumvec, 'r--' )
plt.xlabel( "time ({})".format( self.timeUnits) )
plt.ylabel( "Compartment currents Im (pA)" )
plt.figure( self.entities[0] + "." + self.field + "_fEPSP")
pp = PlotPanel( self, "timeseries", useBigFont = useBigFont )
pp.plotme( fname, "fEPSP (mV)" )
def doScore( self, scoringFormula ):
#assert( len(self.data) == len( self.simData ) )
score = 0.0
numScore = 0.0
dat = []
datarange = max( self.simData )
if self.data:
dvals = [i[1] for i in self.data]
dat = self.data
elif self.bardata:
dvals = [i["value"] for i in self.bardata]
dat = [ [0, i["value"], i["stderr"] ] for i in self.bardata ]
if self.tabulateOutput:
print( "{:>12s} {:>12s} {:>12s} {:>12s}".format( "t", "expt", "sim", "sem" ) )
if self.generate:
self.dumpFindSimFileOpen()
for dd in dat:
datarange = max( datarange, dd[1] ) # dd[1] is expt data
comma = ""
if scoringFormula in ['nrms', 'NRMS']:
for i, sim in zip( dat, self.simData ):
t = i[0]
expt = i[1]
sem = i[2]
if self.tabulateOutput:
print( "{:12.3f} {:12.3f} {:12.5g} {:12.3f}".format( t, expt, sim, sem ) )
if self.generateFile:
self.generateFile.write( "{} [{:.3f}, {:.3f}, {:.3f}]".format( comma, t, sim, sem ) )
comma = ",\n"
score += (expt - sim) * (expt - sim)
if datarange > 1e-6:
nrmsScore = np.sqrt(score / len(dat))/datarange
else:
nrmsScore = np.sqrt(score / len(dat))
else:
for i, sim in zip( dat, self.simData ):
#sim /= self.quantityScale
t = i[0]
expt = i[1]
sem = i[2]
if self.tabulateOutput:
print( "{:12.3f} {:12.3f} {:12.5g} {:12.3f}".format( t, expt, sim, sem ) )
if self.generateFile:
self.generateFile.write( "{} [{:.3f}, {:.3f}, {:.3f}]".format( comma, t, sim, sem ) )
comma = ",\n"
#print "Formula = ", scoringFormula, eval( scoringFormula )
score += eval( scoringFormula )
numScore += 1.0
if self.generateFile:
self.dumpFindSimFileClose()
if scoringFormula in ['nrms', 'NRMS']:
return nrmsScore
elif numScore == 0:
return -1
return score/numScore
def getMinInterval( self ):
ret = self.data[-1][0]
lastt = 0.0
for sample in self.data:
dt = sample[0] - lastt
if dt > 0.0:
ret = min( ret, dt )
lastt = sample[0]
return ret
def directParamScore( readouts, scoringFormula ):
score = 0.0
numScore = 0.0
for d in readouts.directParamData:
entity = d["entity"]
qs = convertQuantityUnits[ d["units"] ]
expt = d["value"] * qs
sem = d["stderr"] * qs
sim = sw.getObjParam( entity, str( d["field"] ), isSilent = True )
if ( sim == -2 ):
continue
datarange = max( expt, sim, 1e-9 )
if scoringFormula in ["NRMS", "nrms"]:
#print( "Expt={:.4g}, Sim = {:.4g}, datarange = {:.4g}".format( expt, sim, datarange ) )
score += (expt - sim) * (expt-sim) / (datarange*datarange)
else:
score += eval( scoringFormula )
numScore += 1.0
'''
for rd in readouts:
dvals = [i[1]*rd.quantityScale for i in rd.data]
for d in rd.data:
entity = d[0]
expt = d[1]*rd.quantityScale
sem = d[2]*rd.quantityScale
sim = sw.getObjParam( entity, rd.field )
datarange = max( expt, sim, 1e-9 )
score += eval( scoringFormula )
numScore += 1.0
'''
#print( "direct score of {}".format( score / numScore ) )
if numScore == 0:
return -1
if scoringFormula in ["NRMS", "nrms"]:
return np.sqrt( score / numScore )
return score/numScore
directParamScore = staticmethod( directParamScore )
# This function handles cases where the readout is a function of a
# small window of samples, such as a min, max, or mean. It converts
# each small window into individual simData and ratioData values.
def consolidateWindows( self ):
# Consolidate windows. If readouts.windows != None, then we have to
# condense the ratio and the simData terms as per specified op
if self.window:
w = self.window
assert( len( w ) == 4 )
assert( w[3] in ["min", "max", "mean", "sdev", "oscPk", "oscVal" ] )
numSamples = int( round( (w[1] - w[0]) / w[2] ) +1 )
sd = []
#print( "numSamples = {}, len = {}, ".format( numSamples, len( self.simData ) ) )
for ii in range( len( self.simData ) // numSamples ):
sb = self.simData[ii*numSamples:(ii+1)*numSamples]
if w[3] == "min":
sd.append( min( sb ) )
elif w[3] == "oscVal" and (ii % 2) == 0: # start osc on val
sd.append( min( sb ) )
elif w[3] == "oscPk" and (ii % 2) == 1:
sd.append( min( sb ) )
elif w[3] == "max":
sd.append( max( sb ) )
elif w[3] == "oscPk" and (ii % 2) == 0: # start osc on pk
sd.append( max( sb ) )
elif w[3] == "oscVal" and (ii % 2) == 1:
sd.append( max( sb ) )
elif w[3] == "mean":
sd.append( np.mean( sb ) )
elif w[3] == "sdev":
sd.append( np.sdev( sb ) )
if len( self.ratioData ) == len( self.simData ):
rd = []
for ii in range( len( self.ratioData ) // numSamples ):
rb = self.ratioData[ii*numSamples:(ii+1)*numSamples]
if w[3] == "min":
rd.append( min( rb ) )
elif w[3] == "oscVal" and (ii % 2) == 0: # start on val
rd.append( min( rb ) )
elif w[3] == "oscPk" and (ii % 2) == 1:
rd.append( min( rb ) )
elif w[3] == "max":
rd.append( max( rb ) )
elif w[3] == "oscPk" and (ii % 2) == 0: # start on pk
rd.append( max( rb ) )
elif w[3] == "oscVal" and (ii % 2) == 1:
rd.append( max( rb ) )
elif w[3] == "mean":
rd.append( np.mean( rb ) )
elif w[3] == "sdev":
rd.append( np.sdev( rb ) )
self.ratioData = rd
self.simData = sd
def writeStims( self ):
if not "Stimuli" in self.findsim:
return
gf = self.generateFile
gf.write( ' "Stimuli": [\n' )
stims = self.findsim["Stimuli"]
stimComma = ""
for ss in stims:
gf.write( stimComma + ' {\n' )
if "timeUnits" in ss:
gf.write( ' "timeUnits": "{}",\n'.format(ss["timeUnits"]) )
gf.write( ' "quantityUnits": "{}",\n'.format( ss["quantityUnits"] ) )
gf.write( ' "entity": "{}",\n'.format( ss["entity"]) )
gf.write( ' "field": "{}"'.format( ss["field"]) )
if "data" in ss:
gf.write( ',\n "data": ['.format(self.field) )
comma = "\n"
for dd in ss["data"]:
gf.write( '{} {}'.format( comma, dd ) )
comma = ",\n"
gf.write( '\n ]'.format( self.field ) )
gf.write( '\n }' )
stimComma = ",\n"
gf.write( '\n ],\n' )
def dumpFindSimFileOpen(self ):
if not self.generate or self.generate.split(".")[-1] != "json":
return
if self.generate.split(".")[-1] != "json":
print( "Warning: generate file name '{}' does not have .json suffix. Skipping.\n".format( self.generate ) )
return
self.generateFile = open( self.generate, "w" )
gf = self.generateFile
gf.write( '{\n "FileType":"FindSim",\n' )
gf.write( ' "Version":"1.0",\n' )
gf.write( ' "Metadata":{\n' )
transcriber = self.findsim["Metadata"]["transcriber"]
if "findSim Generate" in transcriber:
gf.write( ' "transcriber":"{}",\n'.format(transcriber) )
else:
gf.write( ' "transcriber":"{} and findSim Generate",\n'.format( transcriber ) )
gf.write( ' "organization":"{}",\n'.format( self.findsim["Metadata"]["organization"] ) )
gf.write( ' "source": {\n' )
gf.write( ' "sourceType": "simulation",\n' )
gf.write( ' "PMID": 0,\n' )
gf.write( ' "authors": "",\n' )
gf.write( ' "journal": "",\n' )
gf.write( ' "year": 2022,\n' )
gf.write( ' "figure": "0"\n' )
gf.write( ' }\n' )
gf.write( ' },\n' )
#############################
gf.write( ' "Experiment": {\n' )
gf.write( ' "design": "{}",\n'.format(self.findsim["Experiment"]["design"]) )
gf.write( ' "species": "Silico",\n' )
gf.write( ' "cellType": "Simulation",\n' )
gf.write( ' "temperature": 37,\n' )
if "notes" in self.findsim["Experiment"]:
notes = self.findsim["Experiment"]["notes"]
gf.write( ' "notes": "{}"\n'.format( notes ) )
else:
gf.write( ' "notes": "Readouts generated by FindSim simulation."\n' )
gf.write( ' },\n' )
#############################
self.writeStims()
#############################
gf.write( ' "Readouts": {\n' )
gf.write( ' "timeUnits": "{}",\n'.format(self.timeUnits) )
gf.write( ' "quantityUnits": "{}",\n'.format( self.quantityUnits ) )
gf.write( ' "entities": [{}],\n'.format( array2str(self.entities) ) )
gf.write( ' "field": "{}",\n'.format( self.field ) )
if "settleTime" in self.findsim["Readouts"]:
gf.write( ' "settleTime": {:.3f},\n'.format( self.settleTime ) )
rr = self.findsim["Readouts"]
if "display" in rr:
gf.write( ' "display": {\n' )
gf.write( ' "useXlog": {},\n'.format( convBool( self.useXlog ) ) )
gf.write( ' "useYlog": {}\n'.format( convBool( self.useYlog ) ) )
gf.write( ' },\n' )
gf.write( ' "data": [\n'.format( self.field ) )
def dumpFindSimFileClose( self ):
gf = self.generateFile
if not gf:
return
gf.write( '\n ]\n'.format( self.field ) )
gf.write( ' }' )
if "Modifications" in self.findsim:
gf.write( ',\n "Modifications": {\n' )
for key, val in self.findsim["Modifications"].items():
if key in ["subset", "itemsToDelete"]:
gf.write( ' "{}":[{}]\n'.format( key, array2str(val) ) )
elif key == "notes":
gf.write( ' "notes":{}\n'.format( val ) )
elif key == "parameterChange":
gf.write( ' "parameterChange": [' )
comma = "\n"
for pp in val:
gf.write( '{} {\n'.format( comma ) )
gf.write( ' "entity": "{},"\n'.format( pp["entity"] ) )
gf.write( ' "field": "{},"\n'.format( pp["field"] ) )
gf.write( ' "value": {},\n'.format( pp["value"] ) )
gf.write( ' "units": "{}"\n'.format( pp["units"] ) )
gf.write( ' }' )
comma = ",\n"
gf.write( ' ]\n' )
gf.write( ' }\n' )
gf.write( '}' )
gf.close()
self.generateFile = None
def array2str( arr ):
ret = '"' + arr[0] + '"'
for aa in arr[1:]:
ret += ', "' + aa + '"'
return ret
def convBool( arg ):
if arg:
return "true"
else:
return "false"
##########################################################################
class Model:
"""The Model class specifies the baseline model against which the
experiment protocol has been developed. It is expected that the
protocol should run and generate a valid score against this baseline
model. Typically actual models will be derived from this original
one.
The key additional field here is the 'subset'. This defines the
subset of the entire model that should be used for running the protocol.
This subset may be defined as a 'group', which is is like a directory
and is a standarad model organizational structure in MOOSE. It may,
less cleanly, be defined as a list of relevant molecules and reactions.
In keeping with the SED-ML convention, changes to the model are also
handled by the Model class. Two kinds of changes are supported: \n
- parameter changes, in which fields get set. \n
- structural changes, in which the model itself is altered. \n
"""
def __init__( self, findsim, mapFile ):
self.modelSubset = []
self.parameterChange = []
self.itemsToDelete = []
mod = findsim.get( "Modifications" )
if mod:
if "subset" in mod:
self.modelSubset = mod[ "subset" ]
if "itemsToDelete" in mod:
self.itemsToDelete = mod[ "itemsToDelete" ]
if "parameterChange" in mod:
self.parameterChange = mod[ "parameterChange" ]
if mapFile == "":
mapFile = findsim["Metadata"].get( "testMap" )
if not mapFile:
raise SimError( "Map file not specified" )
if mapFile.split('.')[-1] != 'json':
raise SimError( "Map file '{}' not in JSON format".format( mapFile ) )
self._tempModelLookup = {}
try:
with open( mapFile ) as json_file:
m1 = json.load( json_file )
m2 = {}
for key, val in m1.items():
#m2[ key.encode( "ascii" ) ] = [ i.encode( "ascii" ) for i in val ]
m2[ str(key) ] = [ str(i) for i in val ]
self._tempModelLookup = m2
except:
raise SimError( "Map file name {} not found".format(mapFile) )
#print( "LOADED MAPFILE {}".format( mapFile ) )
def modify( self, erSPlist, modelWarning):
'''
Semantics: There are two specifiers: what to save (modelSubset)
and what to delete (itemstodelete).
modelSubset: A list of object identifier strings.
- If the object is a group or compartment:
- it is saved
- everything under it is saved
- Parent group and compartment is saved, recursively
- Siblings are NOT saved.
- If the object is a pool, reaction, etc:
- it is saved
- Parent group and compartment is saved, recursively
- Siblings are NOT saved.
itemstodelete: A list of object identifier strings.
- If the object is a group or compartment:
- It is deleted
- Everthing under it is deleted
- If the object is a regular pool, reaction etc:
- It is deleted
- Everthing under it is deleted. Note that a pool might have
multiple enzyme sites. All of them will be deleted.
After all this is done, there is a cleanup:
- If a reaction or enzyme has had a substrate or product
deleted, it is deleted. Otherwise we would end up with
dangling reactions.
'''
sw.deleteItems( [ ( i, "delete") for i in self.itemsToDelete] )
if len( self.modelSubset ) > 0 and not "all" in self.modelSubset:
sw.subsetItems( self.modelSubset )
#Function call for checking dangling Reaction/Enzyme/Function's
sw.pruneDanglingObj( erSPlist)
#print( "{}".format( self.parameterChange ) )
sw.changeParams( [ [i["entity"], i["field"], i["value"] * convertQuantityUnits[ i["units"] ] ] for i in self.parameterChange] )
##########################################################################
# Utility functions needed by Model class.
class PauseHsolve:
def __init__(self, optimizeElec = False):
self.optimizeElec = optimizeElec
self.epspSettle = 0.5
self.stimSettle = 2.0
def setHsolveState(self, state):
if not self.optimizeElec:
return
sw.setHsolveState( state, self )
#######################################################################
class Qentry():
def __init__( self, t, entry, val ):
self.t = t
self.entry = entry
self.val = val
def __lt__( self, other ):
return self.t < other.t
def putStimsInQ( q, stims, pauseHsolve ):
for i in stims:
isElec = i.field in ['Im', 'current', 'Vclamp'] or (i.field=='rate' and 'syn' in i.entities[0])
for j in i.data:
if len(j) == 0:
continue
elif len(j) == 1:
val = 0.0
else:
val = float(j[1]) * i.quantityScale
t = float(j[0])*i.timeScale
heapq.heappush( q, Qentry( t, i, val ) )
if isElec:
# Below we tell the Hsolver to turn off or on for elec calcn.
if val == 0.0:
heapq.heappush( q, Qentry(t+pauseHsolve.stimSettle, pauseHsolve, 0) )
else:
heapq.heappush( q, Qentry(t, pauseHsolve, 1) ) # Turn on hsolve
def putReadoutsInQ( q, readouts, pauseHsolve ):
stdError = []
plotLookup = {}
if readouts.field in Readout.postSynFields:
for j in range( len( readouts.data ) ):
t = float( readouts.data[j][0] ) * readouts.timeScale
heapq.heappush( q, Qentry(t, pauseHsolve, 1) ) # Turn on hsolve
heapq.heappush( q, Qentry(t, readouts.stim, readouts.epspFreq) )
heapq.heappush( q, Qentry(t+1.0/readouts.epspFreq, readouts.stim, 0) )
heapq.heappush( q, Qentry(t+readouts.epspWindow, readouts, j) )# Measure after EPSP
heapq.heappush( q, Qentry(t+readouts.epspWindow+pauseHsolve.epspSettle, pauseHsolve, 0) )
else:
# We push in the index of the data entry so the readout can
# process it when it is run. It will grab both the readout and
# ratio reference if needed.
for j in range( len( readouts.data ) ):
t = float( readouts.data[j][0] ) * readouts.timeScale
if readouts.window:
startt = t + readouts.window[0] * readouts.timeScale
endt = t + readouts.window[1] * readouts.timeScale
dt = readouts.window[2] * readouts.timeScale
for t in np.arange( startt, endt + 1e-8, dt ):
t *= readouts.timeScale
heapq.heappush( q, Qentry(t, readouts, j) )
else:
heapq.heappush( q, Qentry(t, readouts, j) )
if readouts.useNormalization and readouts.normMode == "presetTime":
# We push in -1 to signify that this is to get ratio reference
heapq.heappush( q, Qentry(float(readouts.ratioReferenceTime)*readouts.timeScale, readouts, -1) )
def doReadout( qe, model ):
'''
This function obtains readout values from the simulation.