forked from jonescompneurolab/hnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhnn_qt5.py
2466 lines (2114 loc) · 94.9 KB
/
hnn_qt5.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys, os
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication, QToolTip, QPushButton, QFormLayout
from PyQt5.QtWidgets import QMenu, QSizePolicy, QMessageBox, QWidget, QFileDialog, QComboBox, QTabWidget
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QGroupBox, QDialog, QGridLayout, QLineEdit, QLabel
from PyQt5.QtWidgets import QCheckBox, QTextEdit, QInputDialog
from PyQt5.QtGui import QIcon, QFont, QPixmap
from PyQt5.QtCore import QCoreApplication, QThread, pyqtSignal, QObject, pyqtSlot, Qt
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import multiprocessing
from subprocess import Popen, PIPE, call
import shlex, shutil
from collections import OrderedDict
from time import time, clock, sleep
import pickle, tempfile
from conf import dconf
import conf
import numpy as np
import random
from math import ceil
import spikefn
import params_default
from paramrw import quickreadprm, usingOngoingInputs, countEvokedInputs, usingEvokedInputs
from simdat import SIMCanvas, getinputfiles, readdpltrials
from gutils import scalegeom, scalefont, setscalegeom, lowresdisplay, setscalegeomcenter, getmplDPI, getscreengeom
from ctune import expval, expvals, logval, logvals
prtime = False
def isWindows ():
# are we on windows? or linux/mac ?
return sys.platform.startswith('win')
def getPyComm ():
# get the python command - Windows only has python linux/mac have python3
if sys.executable is not None: # check python command interpreter path - if available
pyc = sys.executable
if pyc.count('python') > 0 and len(pyc) > 0:
return pyc # full path to python
if isWindows():
return 'python'
return 'python3'
def parseargs ():
for i in range(len(sys.argv)):
if sys.argv[i] == '-dataf' and i + 1 < len(sys.argv):
print('-dataf is ', sys.argv[i+1])
conf.dconf['dataf'] = dconf['dataf'] = sys.argv[i+1]
i += 1
elif sys.argv[i] == '-paramf' and i + 1 < len(sys.argv):
print('-paramf is ', sys.argv[i+1])
conf.dconf['paramf'] = dconf['paramf'] = sys.argv[i+1]
i += 1
parseargs()
simf = dconf['simf']
paramf = dconf['paramf']
debug = dconf['debug']
testLFP = dconf['testlfp'] or dconf['testlaminarlfp']
defncore = multiprocessing.cpu_count() # default number of cores
if dconf['fontsize'] > 0: plt.rcParams['font.size'] = dconf['fontsize']
else: plt.rcParams['font.size'] = dconf['fontsize'] = 10
if debug: print('getPyComm:',getPyComm())
# for signaling
class Communicate (QObject):
finishSim = pyqtSignal()
# for signaling - passing text
class TextSignal (QObject):
tsig = pyqtSignal(str)
# for signaling - updating GUI & param file during optimization
class ParamSignal (QObject):
psig = pyqtSignal(OrderedDict)
class CanvSignal (QObject):
csig = pyqtSignal(bool)
def bringwintobot (win):
#win.show()
#win.lower()
win.hide()
def bringwintotop (win):
# bring a pyqt5 window to the top (parents still stay behind children)
# based on examples from https://www.programcreek.com/python/example/101663/PyQt5.QtCore.Qt.WindowActive
#win.show()
#win.setWindowState(win.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
#win.raise_()
win.showNormal()
win.activateWindow()
#win.setWindowState((win.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive)
#win.activateWindow()
#win.raise_()
#win.show()
# based on https://nikolak.com/pyqt-threading-tutorial/
class RunSimThread (QThread):
def __init__ (self,c,ntrial,ncore,waitsimwin,opt=False,baseparamwin=None,mainwin=None,onNSG=False):
QThread.__init__(self)
self.c = c
self.killed = False
self.proc = None
self.ntrial = ntrial
self.ncore = ncore
self.waitsimwin = waitsimwin
self.opt = opt
self.baseparamwin = baseparamwin
self.mainwin = mainwin
self.onNSG = onNSG
self.txtComm = TextSignal()
self.txtComm.tsig.connect(self.waitsimwin.updatetxt)
self.prmComm = ParamSignal()
if self.baseparamwin is not None:
self.prmComm.psig.connect(self.baseparamwin.updatesaveparams)
self.canvComm = CanvSignal()
if self.mainwin is not None:
self.canvComm.csig.connect(self.mainwin.initSimCanvas)
def updatewaitsimwin (self, txt):
# print('RunSimThread updatewaitsimwin, txt=',txt)
self.txtComm.tsig.emit(txt)
def updatebaseparamwin (self, d):
self.prmComm.psig.emit(d)
def updatedrawerr (self):
self.canvComm.csig.emit(False) # False means do not recalculate error
def stop (self): self.killed = True
def __del__ (self):
self.quit()
self.wait()
def run (self):
if self.opt and self.baseparamwin is not None:
self.optmodel() # run optimization
else:
self.runsim() # run simulation
self.c.finishSim.emit() # send the finish signal
def killproc (self):
if self.proc is None: return
if debug: print('Thread killing sim. . .')
try:
self.proc.kill() # has to be called before proc ends
self.proc = None
except:
print('ERR: could not stop simulation process.')
# run sim command via mpi, then delete the temp file.
def runsim (self):
import simdat
self.killed = False
if debug: print("Running simulation using",self.ncore,"cores.")
if debug: print('self.onNSG:',self.onNSG)
if self.onNSG:
cmd = 'python nsgr.py ' + paramf + ' ' + str(self.ntrial) + ' 710.0'
else:
cmd = 'mpiexec -np ' + str(self.ncore) + ' nrniv -python -mpi ' + simf + ' ' + paramf + ' ntrial ' + str(self.ntrial)
maxruntime = 1200 # 20 minutes - will allow terminating sim later
simdat.dfile = getinputfiles(paramf)
cmdargs = shlex.split(cmd,posix="win" not in sys.platform) # https://github.com/maebert/jrnl/issues/348
if debug: print("cmd:",cmd,"cmdargs:",cmdargs)
if prtime:
self.proc = Popen(cmdargs,cwd=os.getcwd())
else:
#self.proc = Popen(cmdargs,stdout=PIPE,stderr=PIPE,cwd=os.getcwd()) # may want to read/display stderr too
self.proc = Popen(cmdargs,stdout=PIPE,cwd=os.getcwd(),universal_newlines=True)
#cstart = time();
while not self.killed and self.proc.poll() is None: # job is not done
for stdout_line in iter(self.proc.stdout.readline, ""):
try: # see https://stackoverflow.com/questions/2104779/qobject-qplaintextedit-multithreading-issues
self.updatewaitsimwin(stdout_line.strip()) # sends a pyqtsignal to waitsimwin, which updates its textedit
except:
if debug: print('RunSimThread updatewaitsimwin exception...')
pass # catch exception in case anything else goes wrong
if self.killed:
self.killproc()
return
self.proc.stdout.close()
sleep(1)
# cend = time(); rtime = cend - cstart
if debug: print('sim finished')
if not self.killed:
if debug: print('not self.killed')
try: # lack of output file may occur if invalid param values lead to an nrniv crash
simdat.ddat['dpl'] = np.loadtxt(simdat.dfile['dpl'])
if debug: print('loaded new dpl file:', simdat.dfile['dpl'])#,'time=',time())
if os.path.isfile(simdat.dfile['spec']):
simdat.ddat['spec'] = np.load(simdat.dfile['spec'])
else:
simdat.ddat['spec'] = None
simdat.ddat['spk'] = np.loadtxt(simdat.dfile['spk'])
simdat.ddat['dpltrials'] = readdpltrials(os.path.join(dconf['datdir'],paramf.split(os.path.sep)[-1].split('.param')[0]),self.ntrial)
if debug: print("Read simulation outputs:",simdat.dfile.values())
simdat.updatelsimdat(paramf,simdat.ddat['dpl']) # update lsimdat and its current sim index
except: # no output to read yet
print('WARN: could not read simulation outputs:',simdat.dfile.values())
else:
if debug: print('self.killproc')
self.killproc()
print(''); self.updatewaitsimwin('')
def optmodel (self):
self.updatewaitsimwin('Optimizing model. . .')
from neuron import h # for praxis
self.optiter = 0 # optimization iteration
fpopt = open(os.path.join(dconf['datdir'],paramf.split(os.path.sep)[-1].split('.param')[0],'optinf.txt'),'w')
fpopt.close()
self.minopterr = 1e9
def optrun (vparam):
# create parameter dictionary of current values to test
lparam = list(dconf['params'].values())
dtest = OrderedDict() # parameter values to test
for prm,val in zip(lparam,expvals(vparam,lparam)): # set parameters
if val >= prm.minval and val <= prm.maxval:
if debug: print('optrun prm:',prm.var,prm.minval,prm.maxval,val)
dtest[prm.var] = val
else:
if debug: print('optrun:', val, 'out of bounds for ' , prm.var, prm.minval, prm.maxval)
return 1e9 # invalid param value -> large error
if debug:
if type(vparam)==list: print('set params:', vparam)
else: print('set params:', vparam.as_numpy())
self.updatebaseparamwin(dtest) # put new param values into GUI
sleep(1)
self.runsim() # run the simulation as usual and read its output
import simdat
simdat.calcerr(simdat.ddat) # make sure error re-calculated (synchronously)
self.updatedrawerr() # send event to draw updated error (asynchronously)
self.updatewaitsimwin(os.linesep+'Simulation finished: error='+str(simdat.ddat['errtot'])+os.linesep) # print error
print(os.linesep+'Simulation finished: error='+str(simdat.ddat['errtot'])+os.linesep)#,'time=',time())
with open(os.path.join(dconf['datdir'],paramf.split(os.path.sep)[-1].split('.param')[0],'optinf.txt'),'a') as fpopt:
fpopt.write(str(simdat.ddat['errtot'])+os.linesep) # write error
# backup the current param file
outdir = os.path.join(dconf['datdir'],paramf.split(os.path.sep)[-1].split('.param')[0])
prmloc0 = os.path.join(outdir,paramf.split(os.path.sep)[-1])
prmloc1 = os.path.join(outdir,str(self.optiter)+'.param')
shutil.copyfile(prmloc0,prmloc1)
if simdat.ddat['errtot'] < self.minopterr:
self.minopterr = simdat.ddat['errtot']
shutil.copyfile(prmloc0,os.path.join(outdir,'best.param')) # convenience, save best here
self.optiter += 1
return simdat.ddat['errtot'] # return error to praxis
tol = 1e-5; nstep = 100; stepsz = 0.5 # 1.0 #stepsz = 0.5
h.attr_praxis(tol, stepsz, 3)
h.stop_praxis(nstep) #
lparam = list(dconf['params'].values())
lvar = [p.var for p in lparam]
if debug: print('lparam=',lparam)
vparam = h.Vector()
# read current parameters from GUI
s = str(self.baseparamwin)
for l in s.split(os.linesep):
if l.count(': ') < 1: continue
k,v = l.split(': ')
if debug: print('k=',k,'v=',v)
if k in lvar:
prm = lparam[lvar.index(k)]
vparam.append(logval(prm,float(v)))
if debug: print('optmodel: k',k,'in lparam')
x = h.fit_praxis(optrun, vparam) #x = optrun(vparam)
# look up resource adjusted for screen resolution
def lookupresource (fn):
lowres = lowresdisplay() # low resolution display
if lowres:
return os.path.join('res',fn+'2.png')
else:
return os.path.join('res',fn+'.png')
# DictDialog - dictionary-based dialog with tabs - should make all dialogs
# specifiable via cfg file format - then can customize gui without changing py code
# and can reduce code explosion / overlap between dialogs
class DictDialog (QDialog):
def __init__ (self, parent, din):
super(DictDialog, self).__init__(parent)
self.ldict = [] # subclasses should override
self.ltitle = []
self.dtransvar = {} # for translating model variable name to more human-readable form
self.stitle = ''
self.initd()
self.initUI()
self.initExtra()
self.setfromdin(din) # set values from input dictionary
self.addtips()
def addtips (self):
for ktip in dconf.keys():
if ktip in self.dqline:
self.dqline[ktip].setToolTip(dconf[ktip])
elif ktip in self.dqextra:
self.dqextra[ktip].setToolTip(dconf[ktip])
def __str__ (self):
s = ''
for k,v in self.dqline.items(): s += k + ': ' + v.text().strip() + os.linesep
return s
def saveparams (self): self.hide()
def initd (self): pass # implemented in subclass
def getval (self,k):
if k in self.dqline.keys():
return self.dqline[k].text().strip()
def lines2val (self,ksearch,val):
for k in self.dqline.keys():
if k.count(ksearch) > 0:
self.dqline[k].setText(str(val))
def setfromdin (self,din):
if not din: return
for k,v in din.items():
if k in self.dqline:
self.dqline[k].setText(str(v).strip())
def transvar (self,k):
if k in self.dtransvar: return self.dtransvar[k]
return k
def addtransvar (self,k,strans):
self.dtransvar[k] = strans
self.dtransvar[strans] = k
def initExtra (self): self.dqextra = OrderedDict() # extra items not written to param file
def initUI (self):
self.layout = QVBoxLayout(self)
# Add stretch to separate the form layout from the button
self.layout.addStretch(1)
# Initialize tab screen
self.ltabs = []
self.tabs = QTabWidget(); self.layout.addWidget(self.tabs)
for i in range(len(self.ldict)): self.ltabs.append(QWidget())
self.tabs.resize(575,200)
# create tabs and their layouts
for tab,s in zip(self.ltabs,self.ltitle):
self.tabs.addTab(tab,s)
tab.layout = QFormLayout()
tab.setLayout(tab.layout)
self.dqline = OrderedDict() # QLineEdits dict; key is model variable
for d,tab in zip(self.ldict, self.ltabs):
for k,v in d.items():
self.dqline[k] = QLineEdit(self)
self.dqline[k].setText(str(v))
tab.layout.addRow(self.transvar(k),self.dqline[k]) # adds label,QLineEdit to the tab
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
self.setWindowTitle(self.stitle)
nw, nh = setscalegeom(self, 150, 150, 625, 300)
#nx = parent.rect().x()+parent.rect().width()/2-nw/2
#ny = parent.rect().y()+parent.rect().height()/2-nh/2
#print(parent.rect(),nx,ny)
#self.move(nx, ny)
#self.move(self.parent.
#self.move(self.parent.widget.rect().x+self.parent.widget.rect().width()/2-nw,
# self.parent.widget.rect().y+self.parent.widget.rect().height()/2-nh)
def TurnOff (self): pass
def addOffButton (self):
# Create a horizontal box layout to hold the button
self.button_box = QHBoxLayout()
self.btnoff = QPushButton('Turn Off Inputs',self)
self.btnoff.resize(self.btnoff.sizeHint())
self.btnoff.clicked.connect(self.TurnOff)
self.btnoff.setToolTip('Turn Off Inputs')
self.button_box.addWidget(self.btnoff)
self.layout.addLayout(self.button_box)
def addHideButton (self):
self.bbhidebox = QHBoxLayout()
self.btnhide = QPushButton('Hide Window',self)
self.btnhide.resize(self.btnhide.sizeHint())
self.btnhide.clicked.connect(self.hide)
self.btnhide.setToolTip('Hide Window')
self.bbhidebox.addWidget(self.btnhide)
self.layout.addLayout(self.bbhidebox)
# widget to specify ongoing input params (proximal, distal)
class OngoingInputParamDialog (DictDialog):
def __init__ (self, parent, inty, din=None):
self.inty = inty
if self.inty.startswith('Proximal'):
self.prefix = 'input_prox_A_'
self.postfix = '_prox'
self.isprox = True
else:
self.prefix = 'input_dist_A_'
self.postfix = '_dist'
self.isprox = False
super(OngoingInputParamDialog, self).__init__(parent,din)
self.addOffButton()
self.addImages()
self.addHideButton()
# add png cartoons to tabs
def addImages (self):
if self.isprox: self.pix = QPixmap(lookupresource('proxfig'))
else: self.pix = QPixmap(lookupresource('distfig'))
for tab in self.ltabs:
pixlbl = ClickLabel(self)
pixlbl.setPixmap(self.pix)
tab.layout.addRow(pixlbl)
# turn off by setting all weights to 0.0
def TurnOff (self): self.lines2val('weight',0.0)
def initd (self):
self.dtiming = OrderedDict([#('distribution' + self.postfix, 'normal'),
('t0_input' + self.postfix, 1000.),
('t0_input_stdev' + self.postfix, 0.),
('tstop_input' + self.postfix, 250.),
('f_input' + self.postfix, 10.),
('f_stdev' + self.postfix, 20.),
('events_per_cycle' + self.postfix, 2),
('repeats' + self.postfix, 10)])
self.dL2 = OrderedDict([(self.prefix + 'weight_L2Pyr_ampa', 0.),
(self.prefix + 'weight_L2Pyr_nmda', 0.),
(self.prefix + 'weight_L2Basket_ampa', 0.),
(self.prefix + 'weight_L2Basket_nmda',0.),
(self.prefix + 'delay_L2', 0.1),])
self.dL5 = OrderedDict([(self.prefix + 'weight_L5Pyr_ampa', 0.),
(self.prefix + 'weight_L5Pyr_nmda', 0.)])
if self.isprox:
self.dL5[self.prefix + 'weight_L5Basket_ampa'] = 0.0
self.dL5[self.prefix + 'weight_L5Basket_nmda'] = 0.0
self.dL5[self.prefix + 'delay_L5'] = 0.1
self.ldict = [self.dtiming, self.dL2, self.dL5]
self.ltitle = ['Timing', 'Layer 2/3', 'Layer 5']
self.stitle = 'Set Rhythmic '+self.inty+' Inputs'
dtmp = {'L2':'L2/3 ','L5':'L5 '}
for d in [self.dL2, self.dL5]:
for k in d.keys():
lk = k.split('_')
if k.count('weight') > 0:
self.addtransvar(k, dtmp[lk[-2][0:2]] + lk[-2][2:]+' '+lk[-1].upper()+u' weight (µS)')
else:
self.addtransvar(k, 'Delay (ms)')
#self.addtransvar('distribution'+self.postfix,'Distribution')
self.addtransvar('t0_input'+self.postfix,'Start time mean (ms)')
self.addtransvar('t0_input_stdev'+self.postfix,'Start time stdev (ms)')
self.addtransvar('tstop_input'+self.postfix,'Stop time (ms)')
self.addtransvar('f_input'+self.postfix,'Burst frequency (Hz)')
self.addtransvar('f_stdev'+self.postfix,'Burst stdev (ms)')
self.addtransvar('events_per_cycle'+self.postfix,'Spikes/burst')
self.addtransvar('repeats'+self.postfix,'Number bursts')
class EvokedOrRhythmicDialog (QDialog):
def __init__ (self, parent, distal, evwin, rhythwin):
super(EvokedOrRhythmicDialog, self).__init__(parent)
if distal: self.prefix = 'Distal'
else: self.prefix = 'Proximal'
self.evwin = evwin
self.rhythwin = rhythwin
self.initUI()
def initUI (self):
self.layout = QVBoxLayout(self)
# Add stretch to separate the form layout from the button
self.layout.addStretch(1)
self.btnrhythmic = QPushButton('Rhythmic ' + self.prefix + ' Inputs',self)
self.btnrhythmic.resize(self.btnrhythmic.sizeHint())
self.btnrhythmic.clicked.connect(self.showrhythmicwin)
self.layout.addWidget(self.btnrhythmic)
self.btnevoked = QPushButton('Evoked Inputs',self)
self.btnevoked.resize(self.btnevoked.sizeHint())
self.btnevoked.clicked.connect(self.showevokedwin)
self.layout.addWidget(self.btnevoked)
self.addHideButton()
setscalegeom(self, 150, 150, 270, 120)
self.setWindowTitle("Pick Input Type")
def showevokedwin (self):
bringwintotop(self.evwin)
self.hide()
def showrhythmicwin (self):
bringwintotop(self.rhythwin)
self.hide()
def addHideButton (self):
self.bbhidebox = QHBoxLayout()
self.btnhide = QPushButton('Hide Window',self)
self.btnhide.resize(self.btnhide.sizeHint())
self.btnhide.clicked.connect(self.hide)
self.btnhide.setToolTip('Hide Window')
self.bbhidebox.addWidget(self.btnhide)
self.layout.addLayout(self.bbhidebox)
class SynGainParamDialog (QDialog):
def __init__ (self, parent, netparamwin):
super(SynGainParamDialog, self).__init__(parent)
self.netparamwin = netparamwin
self.initUI()
def scalegain (self, k, fctr):
oldval = float(self.netparamwin.dqline[k].text().strip())
newval = oldval * fctr
self.netparamwin.dqline[k].setText(str(newval))
if debug: print('scaling ',k,' by', fctr, 'from ',oldval,'to ',newval,'=',oldval*fctr)
return newval
def isE (self,ty): return ty.count('Pyr') > 0
def isI (self,ty): return ty.count('Basket') > 0
def tounity (self):
for k in self.dqle.keys(): self.dqle[k].setText('1.0')
def scalegains (self):
if debug: print('scaling synaptic gains')
for i,k in enumerate(self.dqle.keys()):
fctr = float(self.dqle[k].text().strip())
if fctr < 0.:
fctr = 0.
self.dqle[k].setText(str(fctr))
elif fctr == 1.0:
continue
if debug: print(k,fctr)
for k2 in self.netparamwin.dqline.keys():
l = k2.split('_')
ty1,ty2 = l[1],l[2]
if self.isE(ty1) and self.isE(ty2) and k == 'E -> E':
self.scalegain(k2,fctr)
elif self.isE(ty1) and self.isI(ty2) and k == 'E -> I':
self.scalegain(k2,fctr)
elif self.isI(ty1) and self.isE(ty2) and k == 'I -> E':
self.scalegain(k2,fctr)
elif self.isI(ty1) and self.isI(ty2) and k == 'I -> I':
self.scalegain(k2,fctr)
self.tounity() # go back to unity since pressed OK - next call to this dialog will reset new values
self.hide()
def initUI (self):
grid = QGridLayout()
grid.setSpacing(10)
self.dqle = OrderedDict()
for row,k in enumerate(['E -> E', 'E -> I', 'I -> E', 'I -> I']):
lbl = QLabel(self)
lbl.setText(k)
lbl.adjustSize()
grid.addWidget(lbl,row, 0)
qle = QLineEdit(self)
qle.setText('1.0')
grid.addWidget(qle,row, 1)
self.dqle[k] = qle
row += 1
self.btnok = QPushButton('OK',self)
self.btnok.resize(self.btnok.sizeHint())
self.btnok.clicked.connect(self.scalegains)
grid.addWidget(self.btnok, row, 0, 1, 1)
self.btncancel = QPushButton('Cancel',self)
self.btncancel.resize(self.btncancel.sizeHint())
self.btncancel.clicked.connect(self.hide)
grid.addWidget(self.btncancel, row, 1, 1, 1);
self.setLayout(grid)
setscalegeom(self, 150, 150, 270, 180)
self.setWindowTitle("Synaptic Gains")
# widget to specify tonic inputs
class TonicInputParamDialog (DictDialog):
def __init__ (self, parent, din):
super(TonicInputParamDialog, self).__init__(parent,din)
self.addOffButton()
self.addHideButton()
# turn off by setting all weights to 0.0
def TurnOff (self): self.lines2val('A',0.0)
def initd (self):
self.dL2 = OrderedDict([
# IClamp params for L2Pyr
('Itonic_A_L2Pyr_soma', 0.),
('Itonic_t0_L2Pyr_soma', 0.),
('Itonic_T_L2Pyr_soma', -1.),
# IClamp param for L2Basket
('Itonic_A_L2Basket', 0.),
('Itonic_t0_L2Basket', 0.),
('Itonic_T_L2Basket', -1.)])
self.dL5 = OrderedDict([
# IClamp params for L5Pyr
('Itonic_A_L5Pyr_soma', 0.),
('Itonic_t0_L5Pyr_soma', 0.),
('Itonic_T_L5Pyr_soma', -1.),
# IClamp param for L5Basket
('Itonic_A_L5Basket', 0.),
('Itonic_t0_L5Basket', 0.),
('Itonic_T_L5Basket', -1.)])
dtmp = {'L2':'L2/3 ','L5':'L5 '} # temporary dictionary for string translation
for d in [self.dL2, self.dL5]:
for k in d.keys():
cty = k.split('_')[2] # cell type
tcty = dtmp[cty[0:2]] + cty[2:] # translated cell type
if k.count('A') > 0:
self.addtransvar(k, tcty + ' amplitude (nA)')
elif k.count('t0') > 0:
self.addtransvar(k, tcty + ' start time (ms)')
elif k.count('T') > 0:
self.addtransvar(k, tcty + ' stop time (ms)')
self.ldict = [self.dL2, self.dL5]
self.ltitle = ['Layer 2/3', 'Layer 5']
self.stitle = 'Set Tonic Inputs'
# widget to specify ongoing poisson inputs
class PoissonInputParamDialog (DictDialog):
def __init__ (self, parent, din):
super(PoissonInputParamDialog, self).__init__(parent,din)
self.addOffButton()
self.addHideButton()
# turn off by setting all weights to 0.0
def TurnOff (self): self.lines2val('weight',0.0)
def initd (self):
self.dL2,self.dL5 = OrderedDict(),OrderedDict()
ld = [self.dL2,self.dL5]
for i,lyr in enumerate(['L2','L5']):
d = ld[i]
for ty in ['Pyr', 'Basket']:
for sy in ['ampa','nmda']: d[lyr+ty+'_Pois_A_weight'+'_'+sy]=0.
d[lyr+ty+'_Pois_lamtha']=0.
self.dtiming = OrderedDict([('t0_pois', 0.),
('T_pois', -1)])
self.addtransvar('t0_pois','Start time (ms)')
self.addtransvar('T_pois','Stop time (ms)')
dtmp = {'L2':'L2/3 ','L5':'L5 '} # temporary dictionary for string translation
for d in [self.dL2, self.dL5]:
for k in d.keys():
ks = k.split('_')
cty = ks[0] # cell type
tcty = dtmp[cty[0:2]] + cty[2:] # translated cell type
if k.count('weight'):
self.addtransvar(k, tcty+ ' ' + ks[-1].upper() + u' weight (µS)')
elif k.endswith('lamtha'):
self.addtransvar(k, tcty+ ' freq (Hz)')
self.ldict = [self.dL2, self.dL5, self.dtiming]
self.ltitle = ['Layer 2/3', 'Layer 5', 'Timing']
self.stitle = 'Set Poisson Inputs'
# evoked input param dialog (allows adding/removing arbitrary number of evoked inputs)
class EvokedInputParamDialog (QDialog):
def __init__ (self, parent, din):
super(EvokedInputParamDialog, self).__init__(parent)
self.nprox = self.ndist = 0 # number of proximal,distal inputs
self.ld = [] # list of dictionaries for proximal/distal inputs
self.dqline = OrderedDict()
self.dtransvar = {} # for translating model variable name to more human-readable form
self.initUI()
self.setfromdin(din)
def addtips (self):
for ktip in dconf.keys():
if ktip in self.dqline:
self.dqline[ktip].setToolTip(dconf[ktip])
def transvar (self,k):
if k in self.dtransvar: return self.dtransvar[k]
return k
def addtransvar (self,k,strans):
self.dtransvar[k] = strans
self.dtransvar[strans] = k
def setfromdin (self,din):
if not din: return
self.removeAllInputs() # turn off any previously set inputs
nprox, ndist = countEvokedInputs(din)
for i in range(nprox+ndist):
if i % 2 == 0:
if self.nprox < nprox:
self.addProx()
elif self.ndist < ndist:
self.addDist()
else:
if self.ndist < ndist:
self.addDist()
elif self.nprox < nprox:
self.addProx()
for k,v in din.items():
if k == 'sync_evinput':
if float(v)==0.0:
self.chksync.setChecked(False)
elif float(v)==1.0:
self.chksync.setChecked(True)
elif k == 'inc_evinput':
self.incedit.setText(str(v).strip())
elif k in self.dqline:
self.dqline[k].setText(str(v).strip())
elif k.count('gbar') > 0 and (k.count('evprox')>0 or k.count('evdist')>0):
# for back-compat with old-style specification which didn't have ampa,nmda in evoked gbar
lks = k.split('_')
eloc = lks[1]
enum = lks[2]
if eloc == 'evprox':
for ct in ['L2Pyr','L2Basket','L5Pyr','L5Basket']:
# ORIGINAL MODEL/PARAM: only ampa for prox evoked inputs
self.dqline['gbar_'+eloc+'_'+enum+'_'+ct+'_ampa'].setText(str(v).strip())
elif eloc == 'evdist':
for ct in ['L2Pyr','L2Basket','L5Pyr']:
# ORIGINAL MODEL/PARAM: both ampa and nmda for distal evoked inputs
self.dqline['gbar_'+eloc+'_'+enum+'_'+ct+'_ampa'].setText(str(v).strip())
self.dqline['gbar_'+eloc+'_'+enum+'_'+ct+'_nmda'].setText(str(v).strip())
def initUI (self):
self.layout = QVBoxLayout(self)
# Add stretch to separate the form layout from the button
self.layout.addStretch(1)
self.ltabs = []
self.tabs = QTabWidget();
self.layout.addWidget(self.tabs)
self.button_box = QVBoxLayout()
self.btnprox = QPushButton('Add Proximal Input',self)
self.btnprox.resize(self.btnprox.sizeHint())
self.btnprox.clicked.connect(self.addProx)
self.btnprox.setToolTip('Add Proximal Input')
self.button_box.addWidget(self.btnprox)
self.btndist = QPushButton('Add Distal Input',self)
self.btndist.resize(self.btndist.sizeHint())
self.btndist.clicked.connect(self.addDist)
self.btndist.setToolTip('Add Distal Input')
self.button_box.addWidget(self.btndist)
self.chksync = QCheckBox('Synchronous Inputs',self)
self.chksync.resize(self.chksync.sizeHint())
self.chksync.setChecked(True)
self.button_box.addWidget(self.chksync)
self.incbox = QHBoxLayout()
self.inclabel = QLabel(self)
self.inclabel.setText('Increment start time (ms)')
self.inclabel.adjustSize()
self.inclabel.setToolTip('Increment mean evoked input start time(s) by this amount on each trial.')
self.incedit = QLineEdit(self)
self.incedit.setText('0.0')
self.incbox.addWidget(self.inclabel)
self.incbox.addWidget(self.incedit)
self.layout.addLayout(self.button_box)
self.layout.addLayout(self.incbox)
self.tabs.resize(425,200)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
setscalegeom(self, 150, 150, 475, 300)
self.setWindowTitle('Evoked Inputs')
self.addRemoveInputButton()
self.addHideButton()
self.addtips()
def lines2val (self,ksearch,val):
for k in self.dqline.keys():
if k.count(ksearch) > 0:
self.dqline[k].setText(str(val))
def allOff (self): self.lines2val('gbar',0.0)
def removeAllInputs (self):
for i in range(len(self.ltabs)): self.removeCurrentInput()
self.nprox = self.ndist = 0
def IsProx (self,idx):
# is this evoked input proximal (True) or distal (False) ?
try:
d = self.ld[idx]
for k in d.keys():
if k.count('evprox'):
return True
except:
pass
return False
def getInputID (self,idx):
# get evoked input number of the evoked input associated with idx
try:
d = self.ld[idx]
for k in d.keys():
lk = k.split('_')
if len(lk) >= 3:
return int(lk[2])
except:
pass
return -1
def downShift (self,idx):
# downshift the evoked input ID, keys, values
d = self.ld[idx]
dnew = {} # new dictionary
newidx = 0 # new evoked input ID
for k,v in d.items():
lk = k.split('_')
if len(lk) >= 3:
if lk[0]=='sigma':
newidx = int(lk[3])-1
lk[3] = str(newidx)
else:
newidx = int(lk[2])-1
lk[2] = str(newidx)
newkey = '_'.join(lk)
dnew[newkey] = v
if k in self.dqline:
self.dqline[newkey] = self.dqline[k]
del self.dqline[k]
self.ld[idx] = dnew
currtxt = self.tabs.tabText(idx)
newtxt = currtxt.split(' ')[0] + ' ' + str(newidx)
self.tabs.setTabText(idx,newtxt)
# print('d original:',d, 'd new:',dnew)
def removeInput (self,idx):
# remove the evoked input specified by idx
if idx < 0 or idx > len(self.ltabs): return
# print('removing input at index', idx)
self.tabs.removeTab(idx)
tab = self.ltabs[idx]
self.ltabs.remove(tab)
d = self.ld[idx]
isprox = self.IsProx(idx) # is it a proximal input?
isdist = not isprox # is it a distal input?
inputID = self.getInputID(idx) # wht's the proximal/distal input number?
# print('isprox,isdist,inputid',isprox,isdist,inputID)
for k in d.keys():
if k in self.dqline:
del self.dqline[k]
self.ld.remove(d)
tab.setParent(None)
# now downshift the evoked inputs (only proximal or only distal) that came after this one
# first get the IDs of the evoked inputs to downshift
lds = [] # list of inputs to downshift
for jdx in range(len(self.ltabs)):
if isprox and self.IsProx(jdx) and self.getInputID(jdx) > inputID:
#print('downshift prox',self.getInputID(jdx))
lds.append(jdx)
elif isdist and not self.IsProx(jdx) and self.getInputID(jdx) > inputID:
#print('downshift dist',self.getInputID(jdx))
lds.append(jdx)
for jdx in lds: self.downShift(jdx) # then do the downshifting
# print(self) # for testing
def removeCurrentInput (self): # removes currently selected input
idx = self.tabs.currentIndex()
if idx < 0: return
self.removeInput(idx)
def __str__ (self):
s = ''
for k,v in self.dqline.items(): s += k + ': ' + v.text().strip() + os.linesep
if self.chksync.isChecked(): s += 'sync_evinput: 1'+os.linesep
else: s += 'sync_evinput: 0'+os.linesep
s += 'inc_evinput: ' + self.incedit.text().strip() + os.linesep
return s
def addRemoveInputButton (self):
self.bbremovebox = QHBoxLayout()
self.btnremove = QPushButton('Remove Input',self)
self.btnremove.resize(self.btnremove.sizeHint())
self.btnremove.clicked.connect(self.removeCurrentInput)
self.btnremove.setToolTip('Remove This Input')
self.bbremovebox.addWidget(self.btnremove)
self.layout.addLayout(self.bbremovebox)
def addHideButton (self):
self.bbhidebox = QHBoxLayout()
self.btnhide = QPushButton('Hide Window',self)
self.btnhide.resize(self.btnhide.sizeHint())
self.btnhide.clicked.connect(self.hide)
self.btnhide.setToolTip('Hide Window')
self.bbhidebox.addWidget(self.btnhide)
self.layout.addLayout(self.bbhidebox)
def addTab (self,prox,s):
tab = QWidget()
self.ltabs.append(tab)
self.tabs.addTab(tab,s)
tab.layout = QFormLayout()
tab.setLayout(tab.layout)
return tab
def addFormToTab (self,d,tab):
for k,v in d.items():
self.dqline[k] = QLineEdit(self)
self.dqline[k].setText(str(v))
tab.layout.addRow(self.transvar(k),self.dqline[k]) # adds label,QLineEdit to the tab
def makePixLabel (self,fn):
pix = QPixmap(fn)
pixlbl = ClickLabel(self)
pixlbl.setPixmap(pix)
return pixlbl
def addtransvarfromdict (self,d):
dtmp = {'L2':'L2/3 ','L5':'L5 '}
for k in d.keys():
if k.startswith('gbar'):
ks = k.split('_')
stmp = ks[-2]
self.addtransvar(k,dtmp[stmp[0:2]] + stmp[2:] + ' ' + ks[-1].upper() + u' weight (µS)')
elif k.startswith('t'):
self.addtransvar(k,'Start time mean (ms)')
elif k.startswith('sigma'):
self.addtransvar(k,'Start time stdev (ms)')
elif k.startswith('numspikes'):
self.addtransvar(k,'Number spikes')
def addProx (self):
self.nprox += 1 # starts at 1
# evprox feed strength
dprox = OrderedDict([('t_evprox_' + str(self.nprox), 0.), # times and stdevs for evoked responses
('sigma_t_evprox_' + str(self.nprox), 2.5),
('numspikes_evprox_' + str(self.nprox), 1),
('gbar_evprox_' + str(self.nprox) + '_L2Pyr_ampa', 0.),
('gbar_evprox_' + str(self.nprox) + '_L2Pyr_nmda', 0.),
('gbar_evprox_' + str(self.nprox) + '_L2Basket_ampa', 0.),
('gbar_evprox_' + str(self.nprox) + '_L2Basket_nmda', 0.),
('gbar_evprox_' + str(self.nprox) + '_L5Pyr_ampa', 0.),
('gbar_evprox_' + str(self.nprox) + '_L5Pyr_nmda', 0.),
('gbar_evprox_' + str(self.nprox) + '_L5Basket_ampa', 0.),
('gbar_evprox_' + str(self.nprox) + '_L5Basket_nmda', 0.)])
self.ld.append(dprox)
self.addtransvarfromdict(dprox)
self.addFormToTab(dprox, self.addTab(True,'Proximal ' + str(self.nprox)))
self.ltabs[-1].layout.addRow(self.makePixLabel(lookupresource('proxfig')))
#print('index to', len(self.ltabs)-1)
self.tabs.setCurrentIndex(len(self.ltabs)-1)
#print('index now', self.tabs.currentIndex(), ' of ', self.tabs.count())
self.addtips()
def addDist (self):
self.ndist += 1