forked from ICEACE/PopGUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopgui.py
More file actions
1481 lines (1416 loc) · 60.3 KB
/
popgui.py
File metadata and controls
1481 lines (1416 loc) · 60.3 KB
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/python
"""
Experiment manager Library for EURACE
Author: Mehmet Gencer, mgencer@cs.bilgi.edu.tr
Bulent Ozel, bulent.ozel@gmail.com, Reykjavik University
"""
import sys, os, os.path, pickle, textwrap, traceback, copy, getopt, thread
from poplib import *
#from pygtk import *
import pygtk,gobject
pygtk.require('2.0')
import gtk
try:
import signal
HASSIGNAL=1
except:
debug("No 'signal' module")
HASSIGNAL=0
VERSION="0.7.14"
global VERSIONCHECKING
VERSIONCHECKING=1
EVALUATOR=0
USERHOME=os.path.expanduser("~")
CONFIGPATH="%s/euracepopgui.config"%USERHOME
CONFIG={
"GUIHOME":os.path.expanduser("~"),
"LASTMODELDIR":os.path.expanduser("~"),
"LASTPOPDIR":os.path.expanduser("~"),
"LASTXMLDIR":os.path.expanduser("~"),
"CONSOLEBUFFERLEN":1500
#"MVEDITLABELSIZE":30
}
INITFORMHELP=MemVar.help
ABOUT="EURACE Population GUI Version %s\nCreated by TUBITAK-UEKAE Team, 2008:\nContact: Mehmet Gencer, mgencer@cs.bilgi.edu.tr"%VERSION
if os.path.exists(CONFIGPATH):
newc=pickle.load(open(CONFIGPATH,"rb"))
for k in CONFIG.keys():
if not newc.has_key(k):
newc[k]=CONFIG[k]
CONFIG=newc
def saveConfig():
pickle.dump(CONFIG,open(CONFIGPATH,"wb"))
class PopGUI:
def __init__(self):
self.state="init"
self.window=gtk.Window()
self.window.set_title("PopGUI v%s"%VERSION)
self.window.set_default_size(300,200)
self.window.connect("destroy", self.quit)
self.window.connect("delete-event",self.preQuit)
self.window.set_position(gtk.WIN_POS_CENTER)
self.window.set_default_size(400,300)
self.window.set_icon_from_file("euracelogo.ico")
self.modified=0
self.widgets={}
self.toolbuttoncount=0
def addToolButton(self,id,label,method):
self.widgets[id]=gtk.Button(label)
self.widgets[id].connect("clicked",method)
self.widgets[id].show()
self.toolbar.pack_start(self.widgets[id],expand=False,fill=False)
def start(self,fname=""):
self.table=gtk.Table(rows=3, columns=1, homogeneous=False)
self.toolbar=gtk.HBox()
self.table.attach(self.toolbar, 0, 1, 1, 2,yoptions=0)
self.menuitems=(
("/_File", None, None, 0, "<Branch>" ),
("/File/_New Population", "<control>N", self.newPop, 0, None ),
("/File/_Open Population", "<control>O", self.openPop, 0, None ),
("/File/_Save Population", "<control>S", self.savePop, 0, None ),
("/File/_Save Population As", "<control>A", self.savePopAs, 0, None ),
( "/File/sep1", None, None, 0, "<Separator>" ),
("/File/_Quit", "<control>Q", self.quitManual, 0, None ),
("/Tools", None, None, 0, "<Branch>"),
("/Tools/_Export to LaTeX", None, self.exportToLatex,0,None),
("/Help", None, None, 0, "<Branch>"),
("/Help/_Contents", None, self.help,0,None),
("/Help/_About", None, self.about,0,None),
)
accel_group = gtk.AccelGroup()
item_factory = gtk.ItemFactory(gtk.MenuBar, "<main>", accel_group)
item_factory.create_items(self.menuitems)
self.window.add_accel_group(accel_group)
#self.menubarhbox=gtk.HBox()
#self.menubarhbox.pack_start(item_factory.get_widget("<main>"),expand=False,fill=False)
self.table.attach(item_factory.get_widget("<main>"),0,1,0,1,yoptions=0)
#self.table.attach(self.menubarhbox,0,1,0,1,xoptions=0,yoptions=0)
self.addToolButton("modelsummary","Model Summary",self.showSummary)
self.addToolButton("genpropbut","1 - Properties",self.setPopProp)
self.addToolButton("regbut","2 - Edit Regions",self.editRegions)
self.addToolButton("constbut","3 - Edit Constants",self.editConstants)
self.addToolButton("mvbut","4 - Edit Memory Variables",self.editMemVars)
self.addToolButton("insbut","5 - Instantiate population (0.xml)",self.instantiate)
self.textscroll=gtk.ScrolledWindow()
self.textscroll.show()
self.textview = gtk.TextView()
self.textview.set_size_request(350,250)
#textscrollbar = gtk.VScrollbar(self.textview.get_vadjustment())
self.textview.set_editable(0)
self.textview.set_cursor_visible(0)
self.textview.set_wrap_mode(gtk.WRAP_CHAR)
self.textview.show()
self.textscroll.add(self.textview)
self.table.attach(self.textscroll,0,1,2,3)
self.progbar=gtk.ProgressBar()
self.progbar.hide()
self.progbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
self.cancelpop=gtk.Button("CANCEL")
self.cancelpop.connect("clicked",self.cancelPopulationCreation)
self.cancelpop.hide()
self.window.add(self.table)
self.window.show_all()
self.message("PopGUI version %s started."%VERSION)
if fname:
if fname[-5:]==".xmml" or fname[-4:]==".xml":
self.newPopFromFile(fname)
else:
self.openPop(fname=fname)
gtk.main()
def exportToLatex(self,*args,**kwargs):
try:
print self.population.name
except:
self.dialogMessage("No population is created or opened yet!")
return
def escape(x):
y=x.replace("_","\\_")
y=y.replace("%","\\%")
return y
def dump(*args):
lastarg=0
for a in args:
outputfile.write(str(a))
lastarg=a
if not lastarg==None:outputfile.write("\n")
outputfile.flush()
def memory(pop):
numreg=pop.getNumRegions()
for rno in range(1,numreg+1):
dump( "************************ MEMORY VARIABLES FOR REGION ",rno)
regionMemory(pop,rno)
def regionMemory(pop,rno):
dump()
def printVar(aname,mv,prefix=""):
for k in mv.getKeys():
vname,vtype=k
initform=mv.getForm(vname)
if isinstance(initform,MemVar):#Will need to recurse into this var!
printVar(aname,initform,prefix=prefix+"."+vname)
else:
pref=""
if prefix:
pref=escape(prefix)
dump( "%s%s.%s & %s \\\\"%(escape(aname),pref,escape(vname),escape(initform.getFormStr())))
dump( "\\begin{longtable}{ll}")
agents=pop.model.getAgentNames()
r=pop.getNumberedRegion(rno-1)
for aname in agents:
a=r.model.getAgentByName(aname)
for mv in a.memvars:
printVar(aname,mv)
dump( "\\end{longtable}")
filec=gtk.FileChooserDialog(title="Choose file to save memory variable list",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
#filec.set_current_folder(CONFIG["LASTXMLDIR"])
filter = gtk.FileFilter()
#filter.add_pattern("*.tex")
#filter.set_name(".xml")
#filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
texfile= filec.get_filename()
else:
texfile=""
filec.destroy()
if texfile:
outputfile=open(texfile,"w")
memory(self.population)
self.dialogMessage("Export finished!")
def cancelPopulationCreation(self,*args,**kwargs):
#print "CANCEL BUTTON PRESSED"
self.population.setCancelFlag()
#raise PoplibException("Population instantiation is cancelled")
def preQuit(self,*args,**kwargs):
"Returns true to avoid destroying, if necessary"
if self.modified:
if not self.askYesNo("Modifications to current population are not saved. Quit anyway?"):
return True
return False
def quit(self,*args,**kwargs):
#if self.modified:
# if not self.askYesNo("Modifications to current population is not saved. Proceed?"):
# return
#self.quitManual()
sys.exit(0)
def quitManual(self,*args,**kwargs):
debug("Making checks before quit")
if self.modified:
if not self.askYesNo("Modifications to current population are not saved. Quit anyway?"):
return
sys.exit(0)
def about(self,*args,**kwargs):
self.dialogMessage(ABOUT)
def help(self,*args,**kwargs):
if os.path.exists("UserGuide.txt"):
HELP=open("UserGuide.txt","r").read()
else:
HELP="Please see the User Guide distributed with PopGUI."
self.longDisplay("Using PopGUI",HELP)
def message(self,*args,**kwargs):
b=self.textview.get_buffer()
msg=""
for a in args:
msg+=str(a)+"\n"
for k in kwargs.keys():
mag+=str(k)+":"+str(kwargs[k])
rmsg=b.get_text(b.get_start_iter(),b.get_end_iter())+"\n"+msg
rmsg=rmsg[-CONFIG["CONSOLEBUFFERLEN"]:]
b.set_text(rmsg)
def dialogMessage(self,msg):
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,msg)
self.message(msg)
dialog.run()
dialog.destroy()
def longDisplay(self,title,text,wtype="modal"):
if wtype=="modal":
popwindow = gtk.Dialog(title,self.window,gtk.DIALOG_MODAL)
elif wtype=="dwp":
popwindow = gtk.Dialog(title,self.window,gtk.DIALOG_DESTROY_WITH_PARENT)
else:
raise Exception("Unknown window type")
popwindow.set_default_size(400,500)
popwindow.set_title(title)
scrolled_window = gtk.ScrolledWindow()
scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
popwindow.vbox.pack_start(scrolled_window, True, True, 0)
scrolled_window.show()
textview = gtk.TextView()
textview.set_editable(0)
textview.set_cursor_visible(0)
textview.set_wrap_mode(gtk.WRAP_CHAR)
textview.show()
textview.get_buffer().set_text(text)
scrolled_window.add_with_viewport(textview)
popwindow.run()
popwindow.destroy()
def askYesNo(self,msg):
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK_CANCEL,msg)
response=dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_OK:
return 1
return 0
def invalidStateWarning(self,msg=""):
if msg:
self.dialogMessage(msg)
else:
self.dialogMessage("Invalid state for operation (e.g. no population is created or loaded yet)")
def newPopFromFile(self,modelfile):
popfile=modelfile
try:
self.population=Population("",popfile)
CONFIG["LASTMODELDIR"]=os.path.dirname(popfile)
#self.message(reprMultiDictAsTXT(self.population.model.info["domdic"]))
self.message("Model file '%s' is read successfully"%popfile)
self.state="newpop"
self.modified=1
self.savefile=""
self.setPopProp()
except:
self.dialogMessage("Cannot create population"+str(sys.exc_info()))
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
saveConfig()
def newPop(self,*args,**kwargs):
if self.modified:
if not self.askYesNo("Modifications to current population are not saved. Proceed?"):
return
filec=gtk.FileChooserDialog(title="Choose Model XMML file",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
filec.set_current_folder(CONFIG["LASTMODELDIR"])
filter = gtk.FileFilter()
filter.add_pattern("*.xml")
filter.set_name(".xml")
filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
popfile= filec.get_filename()
else:
popfile=""
filec.destroy()
if not popfile:return
try:
self.population=Population("",popfile)
CONFIG["LASTMODELDIR"]=os.path.dirname(popfile)
#self.message(reprMultiDictAsTXT(self.population.model.info["domdic"]))
self.message("Model file '%s' is read successfully"%popfile)
self.state="newpop"
self.modified=1
self.savefile=""
self.setPopProp()
except:
self.dialogMessage("Cannot create population due to following error:\n(%s)\n%s"%(str(sys.exc_info()[0]),str(sys.exc_info()[1])))
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
saveConfig()
def openPop(self,*args,**kwargs):
if self.modified:
if not self.askYesNo("Modifications to current population is not saved. Proceed?"):
return
if kwargs.has_key("fname"):
popfile=kwargs["fname"]
else:
filec=gtk.FileChooserDialog(title="Choose population to load",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
filec.set_current_folder(CONFIG["LASTPOPDIR"])
filter = gtk.FileFilter()
filter.add_pattern("*.pop")
filter.set_name(".pop")
filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
popfile= filec.get_filename()
else:
popfile=""
filec.destroy()
if not popfile:return
tmppop=pickle.load(open(popfile,"rb"))
try:
tmppopver=tmppop.version
except:
tmppopver="None"
if VERSIONCHECKING:
if tmppopver!=Population.CURRENTVERSION:
self.dialogMessage("Version of the population (%s) is different from what the program currently supports(%s)"%(tmppopver,Population.CURRENTVERSION))
return
self.population=tmppop
self.state=self.population.state
self.savefile=popfile
CONFIG["LASTPOPDIR"]=os.path.dirname(popfile)
self.modified=0
globalSetNumRegions(self.population.numregions)
self.message("Population '%s' is read successfully"%popfile)
def savePopAs(self,*args,**kwargs):
self.savePop(saveas=1)
def savePop(self,*args,**kwargs):
if kwargs.has_key("saveas"):
saveas=kwargs["saveas"]
else:
saveas=0
if self.state=="init":
self.invalidStateWarning()
return
if self.savefile and (not saveas):
popfile=self.savefile
else:
filec=gtk.FileChooserDialog(title="Choose file to save population",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
filec.set_current_folder(CONFIG["LASTPOPDIR"])
filter = gtk.FileFilter()
filter.add_pattern("*.pop")
filter.set_name(".pop")
filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
popfile= filec.get_filename()
if os.path.exists(popfile):
if not self.askYesNo("The file '%s' already exists. Overwrite?"%popfile):return
else:
popfile=""
filec.destroy()
if not popfile:return
if popfile.lower()[-4:]!=".pop":
popfile+=".pop"
#if saveas and os.path.exists(popfile):
# if not self.askYesNo("The file '%s' already exists. Overwrite?"%popfile):return
CONFIG["LASTPOPDIR"]=os.path.dirname(popfile)
saveConfig()
try:
self.population.cleanUp()
pickle.dump(self.population,open(popfile,"wb"))
self.savefile=popfile
self.message("Population is saved successfully into '%s'"%popfile)
self.modified=0
except:
dialogMessage("Cannot save population"+str(sys.exc_info()))
def showSummary(self,*args,**kwarg):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
self.longDisplay("Model Summary",(str(self.population.model)))
def setPopProp(self,*args,**kwargs):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
PopPropDialog(self)
def editRegions(self,*args,**kwargs):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
if self.population.numregions==0:
self.invalidStateWarning("No Regions defined!")
return
EditRegionsDialog(self)
def editConstants(self,*args,**kwargs):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
EditConstantsDialog(self)
def editMemVars(self,*args,**kwargs):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
if self.population.numregions==0:
self.invalidStateWarning("No Regions defined!")
return
EditMemVarsDialog(self)
def instantiate(self,*args,**kwargs):
if self.state=="init":
self.invalidStateWarning("No population is created or loaded yet!")
return
if self.population.numregions==0:
self.invalidStateWarning("No Regions defined!")
return
filec=gtk.FileChooserDialog(title="Choose file to save population instance (0.xml)",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
filec.set_current_folder(CONFIG["LASTXMLDIR"])
filter = gtk.FileFilter()
filter.add_pattern("*.xml")
filter.set_name(".xml")
filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
popfile= filec.get_filename()
else:
popfile=""
filec.destroy()
if not popfile:return
if popfile.lower()[-4:]!=".xml":
popfile+=".xml"
if os.path.exists(popfile):
if not self.askYesNo("The file '%s' already exists. Overwrite?"%popfile):return
CONFIG["LASTXMLDIR"]=os.path.dirname(popfile)
saveConfig()
self.message("Creating 0.xml ...")
self.progbar.show()
self.progbar.set_text("Instantiating ...")
self.progbar.pulse()
self.progbar.set_fraction(0)
self.cancelpop.show()
self.table.resize(5,1)
try:
self.table.attach(self.progbar,0,1,3,4)
except:pass #perhaps second attempt!
try:
self.table.attach(self.cancelpop,0,1,4,5)
except:pass #perhaps second attempt!
#thread.start_new_thread(progwin.run,())
#progwin.run()
while gtk.events_pending():
gtk.main_iteration_do(False)
resetGlobalMsg()
outfile=open(popfile,"w")
try:
numagents,totaltime=self.population.instantiate(outfile,progbar=self.progbar)
except PoplibException:
msg="There was a problem while instantiating population:\n"+str(sys.exc_info()[1])
try:
msg+="\n"
msg+=getGlobalMsg()
except:
pass
self.dialogMessage(msg)
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
self.progbar.hide()
self.cancelpop.hide()
self.table.resize(3,1)
gtk.main_iteration_do(False)
return
except:
msg="There was an unexpected problem while instantiating population:\n"+str(sys.exc_info()[1])
try:
msg+="\n"
msg+=getGlobalMsg()
except:
pass
self.dialogMessage(msg)
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
self.progbar.hide()
self.cancelpop.hide()
self.table.resize(3,1)
gtk.main_iteration_do(False)
return
finally:
self.population.cleanUp()
outfile.close()
self.message("Successful. Number of agents created %d." % numagents)
#open(popfile,"w").write(zeroxml)
self.message("Population instance saved in %s." % popfile)
self.cancelpop.hide()
self.progbar.hide()
self.table.resize(3,1)
if numagents==0:
self.dialogMessage("Congratulations. You have a useless population with no agents in %s."%popfile)
else:
self.dialogMessage("Congratulations. Population instance is saved in %s, with %d agents in it (in %d seconds)."%(popfile,numagents,totaltime))
gtk.main_iteration_do(False)
class BasePopDialog:
def __init__(self,title,parent,width=400,height=500,swexpand=True,swfill=True):
#self.parent=parent
#popwindow = gtk.Dialog(title,parent,gtk.DIALOG_MODAL)
popwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
#popwindow.set_transient_for(parent.window.window)
popwindow.set_decorated(True)
popwindow.set_parent_window(parent.window)
popwindow.set_modal(True)
popwindow.set_default_size(width,height)
self.window=popwindow
popwindow.connect("destroy", self.destroy)
popwindow.set_title(title)
scrolled_window = gtk.ScrolledWindow()
scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
#popwindow.vbox.pack_start(scrolled_window, True, True, 0)
wbox=gtk.VBox(False, 0)
mbox=gtk.HBox(False,0)
bbox=gtk.HBox(False,0)
self.wbox=wbox
self.mbox=mbox
self.bbox=bbox
popwindow.add(wbox)
mbox.pack_end(scrolled_window, swexpand, swfill, 0)
wbox.pack_start(mbox, True, True, 0)
wbox.pack_end(bbox, False, False, 0)
scrolled_window.show()
self.scrolled=scrolled_window
cbutton = gtk.Button("Cancel")
cbutton.connect_object("clicked", self.destroy, popwindow)
cbutton.set_flags(gtk.CAN_DEFAULT)
#popwindow.action_area.pack_end(cbutton, True, True, 0)
bbox.pack_end(cbutton, False, False, 0)
cbutton.grab_default()
cbutton.show()
scbutton=gtk.Button("Update and close")
self.scbutton=scbutton
scbutton.connect("clicked",self.saveclose)
#popwindow.action_area.pack_start(scbutton)
bbox.pack_end(scbutton, False, False, 0)
scbutton.show()
bbox.show()
mbox.show()
wbox.show()
popwindow.set_decorated(True)
popwindow.show()
self.vadj=self.scrolled.get_vadjustment()
self.hadj=self.scrolled.get_hadjustment()
def focus_in(self,widget, event):
vadj=self.vadj
hadj=self.hadj
alloc = widget.get_allocation()
if alloc.y < vadj.value:
vadj.set_value(alloc.y)
elif alloc.y > (vadj.value + vadj.page_size-20):
vadj.set_value(vadj.upper-vadj.page_size+40)
#vadj.set_value(min(alloc.y, vadj.upper-vadj.page_size))
if alloc.x < hadj.value or alloc.x > (hadj.value + hadj.page_size-20):
hadj.set_value(min(alloc.x, hadj.upper-hadj.page_size))
def askYesNo(self,msg):
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK_CANCEL,msg)
response=dialog.run()
dialog.destroy()
if response == gtk.RESPONSE_OK:
return 1
return 0
def dialogMessage(self,msg):
dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK,msg)
#self.message(msg)
dialog.run()
dialog.destroy()
def destroy(self,*args,**kwargs):
self.window.destroy()
def saveclose(self,*args,**kwargs):
pass
class PopPropDialog_ImportSubModel(BasePopDialog):
def __init__(self,parentobj,parentpopprop,newpop,newmod,popfile):
title="Import Population"
self.parentobj=parentobj
self.parentpopprop=parentpopprop
self.newpop=newpop
self.newmod=newmod
self.popfile=popfile
self.proceed=0
BasePopDialog.__init__(self,title,parentpopprop.window)
self.window.set_transient_for(parentpopprop.window)
self.scbutton.hide()
donebutton=gtk.Button("Proceed with import")
donebutton.connect("clicked",self.done)
donebutton.show()
self.bbox.pack_end(donebutton, False, False, 0)#table.attach(importbutton,0,1,3,4,xoptions=0,yoptions=0)
table = gtk.Table(4, 2, False)
self.scrolled.add_with_viewport(table)
table.show()
lname=gtk.Label("The model of population imported has more than one nested model. Choose the whole population, or parts corresponding to a nested model.")
lname.set_line_wrap(True)
lname.show()
table.attach(lname,0,2,0,1)
self.checkAll=gtk.CheckButton(label="Use whole population")
self.checkAll.connect("clicked",self.checkAllClick)
self.checkAll.show()
table.attach(self.checkAll,1,2,1,2)
self.chooseLabel=gtk.Label("Choose nested-model:")
self.chooseLabel.show()
table.attach(self.chooseLabel,0,1,2,3)
self.choose=gtk.combo_box_new_text()
self.choose.show()
self.revmodmap={}
for sm in self.newmod.submodels.keys():
lab=sm
if self.newmod.submodels[sm]:
lab=self.newmod.submodels[sm]
self.revmodmap[lab]=sm
self.choose.append_text(lab)
self.choose.set_active(0)
table.attach(self.choose,1,2,2,3)
def checkAllClick(self,*args,**kw):
if self.checkAll.get_property("active"):
self.choose.hide()
self.chooseLabel.hide()
else:
self.choose.show()
self.chooseLabel.show()
def done(self,*args,**kw):
if self.checkAll.get_property("active"):
self.parentpopprop.doImport(self.newpop,self.popfile)
else:
i=self.choose.get_active_iter()
s=self.choose.get_model().get_value(i,0)
submodelfile=self.revmodmap[s]
self.parentpopprop.doImport(self.newpop,self.popfile,submodelfile=submodelfile)
self.window.destroy()
class PopPropDialog(BasePopDialog):
def __init__(self,parentobj):
title="Population properties"
self.parentobj=parentobj
BasePopDialog.__init__(self,title,parentobj.window)
table = gtk.Table(4, 2, False)
self.scrolled.add_with_viewport(table)
table.show()
lname=gtk.Label("Name of population")
table.attach(lname,0,1,0,1)
tname=gtk.Entry(max=50)
table.attach(tname,1,2,0,1)
lname.show()
tname.show()
lnumreg=gtk.Label("Number of regions")
table.attach(lnumreg,0,1,1,2)
tnumreg=gtk.Entry(max=5)
table.attach(tnumreg,1,2,1,2)
lnumreg.show()
tnumreg.show()
tname.set_text(parentobj.population.name)
tnumreg.set_text(str(parentobj.population.numregions))
lmodelfile=gtk.Label("Model file")
lmodelfile.show()
table.attach(lmodelfile,0,1,2,3)
lmodelfilename=gtk.Label(parentobj.population.modelfile)
lmodelfilename.show()
table.attach(lmodelfilename,1,2,2,3)
importbutton=gtk.Button("Import ...")
importbutton.connect("clicked",self.importPop)
importbutton.show()
self.bbox.pack_end(importbutton, False, False, 0)#table.attach(importbutton,0,1,3,4,xoptions=0,yoptions=0)
self.table=table
self.tnumreg=tnumreg
self.tname=tname
def importPop(self,*args,**kw):
filec=gtk.FileChooserDialog(title="Choose population to import from",parent=self.window,action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
filec.set_current_folder(CONFIG["LASTPOPDIR"])
filter = gtk.FileFilter()
filter.add_pattern("*.pop")
filter.set_name(".pop")
filec.add_filter(filter)
filterall=gtk.FileFilter()
filterall.add_pattern("*")
filterall.set_name("All files")
filec.add_filter(filterall)
response=filec.run()
if response == gtk.RESPONSE_OK:
popfile= filec.get_filename()
else:
popfile=""
filec.destroy()
if not popfile:return
pop=pickle.load(open(popfile,"rb"))
debug("Population is read")
#Now re-read the model to see if it is nested
try:
mod=pop.model#Model(pop.modelfile,xmlregistry=pop.getModelXMLRegistry())
except IOError:
self.parentobj.dialogMessage("Error when trying to access the model file (of the population to be imported from): %s"%pop.modelfile)
return
if mod.submodels:
print mod.submodels
PopPropDialog_ImportSubModel(self.parentobj,self,pop,mod,popfile)
return
else:
print "No submodels. Importing directly"
self.doImport(pop,popfile)
self.parentobj.dialogMessage("Import successful")
def doImport(self,pop,popfile,submodelfile=""):
if pop.getNumRegions()!=self.parentobj.population.getNumRegions():
self.dialogMessage("Number of regions (%d) is different from current population's (%d)"%(pop.getNumRegions(),self.parentobj.population.getNumRegions()))
return
debug("Number of regions match. Continuing import")
if submodelfile:
mod=Model(submodelfile,xmlregistry=pop.getModelXMLRegistry())
else:
mod=pop.model#self.parentobj.population.model
for r in range(0,self.parentobj.population.numregions):
regfrom=pop.regions[r]
regto=self.parentobj.population.regions[r]
for a in mod.agents:#self.parentobj.population.model.agents:
ato=regto.model.getAgentByName(a.name)
afrom=regfrom.model.getAgentByName(a.name)
if ato==None:
debug("Agent named %s is missing in the current population, skipping."% a.name)
continue
if not submodelfile:#do region setting only when global import is being done
regto.setNumAgents(a.name,regfrom.getNumAgents(a.name))
for mvto in ato.memvars:
mvcheck=a.getMemVarByName(mvto.name)
if mvcheck==None:continue
mvfrom=afrom.getMemVarByName(mvto.name)
if mvfrom==None:
debug("Memvar %s->%s is missing in imported population, skipping" %(a.name,mvto.name))
continue
self._copyMemVar(mvfrom,mvto)
for c in self.parentobj.population.model.constants:
x=mod.getConstantByName(c.name)#pop.model.getConstantByName(c.name)
if x==None:
debug("Constant %s is missing in the imported population"%c.name)
else:
self.parentobj.population.model.setConstant(c.name,str(x.getExpression()))
self.dialogMessage("Population specifications are imported successfully")
submsg=""
if submodelfile:
submsg=" (for nested-model %s only)"%submodelfile
self.parentobj.message("Population specifications are imported from %s%s successfully"%(popfile,submsg))
def doImportBAK(self,pop,popfile,submodelfile=""):
if pop.getNumRegions()!=self.parentobj.population.getNumRegions():
self.dialogMessage("Number of regions (%d) is different from current population's (%d)"%(pop.getNumRegions(),self.parentobj.population.getNumRegions()))
return
debug("Number of regions match. Continuing import")
for r in range(0,self.parentobj.population.numregions):
regfrom=pop.regions[r]
regto=self.parentobj.population.regions[r]
for a in self.parentobj.population.model.agents:
ato=regto.model.getAgentByName(a.name)
afrom=regfrom.model.getAgentByName(a.name)
if afrom==None:
debug("Agent named %s is missing in the imported population, skipping."% a.name)
continue
regto.setNumAgents(a.name,regfrom.getNumAgents(a.name))
for mvto in ato.memvars:
mvfrom=afrom.getMemVarByName(mvto.name)
if mvfrom==None:
debug("Memvar %s->%s is missing in imported population, skipping" %(a.name,mvto.name))
continue
self._copyMemVar(mvfrom,mvto)
for c in self.parentobj.population.model.constants:
x=pop.model.getConstantByName(c.name)
if x==None:
debug("Constant %s is missing in the imported population"%c.name)
else:
self.parentobj.population.model.setConstant(c.name,x.getValue())
self.dialogMessage("Population specifications are imported successfully")
self.parentobj.message("Population specifications are imported from %s successfully"%popfile)
def _copyMemVar(self,mvfrom,mvto):
for k in mvfrom.getKeys():
vname,vtype=k
fromform=mvfrom.getForm(vname)
try:
toform=mvto.getForm(vname)
except:
debug("Problem copying initform %s. Possibly missing from the current model."%vname)
continue
if isinstance(fromform,MemVar):#Will need to recurse into this var!
self._copyMemVar(fromform,toform)
else:
try:
toform.setFormStr(fromform.getFormStr())
except:
debug("Problem when copying initform %s"%vname)
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
def saveclose(self,*args,**kwargs):
try:
numreg=int(self.tnumreg.get_text())
except:
self.dialogMessage("Invalid number for regions")
return
self.parentobj.population.name=self.tname.get_text()
self.parentobj.population.setNumRegions(numreg)
self.window.destroy()
self.parentobj.modified=1
class EditRegionsDialog(BasePopDialog):
def __init__(self,parentobj):
title="Regions"
self.parentobj=parentobj
BasePopDialog.__init__(self,title,parentobj.window,width=800,height=600)
table = gtk.Table(len(self.parentobj.population.model.agents)+1, self.parentobj.population.numregions+1, False)
self.scrolled.add_with_viewport(table)
table.show()
l=gtk.Label("NUMBER OF AGENT\nIN EACH REGION:")
l.show()
table.attach(l,0,1,0,1)
for r in range(0,self.parentobj.population.numregions):
l=gtk.Label("Region %d"%(r+1))
#l.set_alignment(0,0)
l.show()
table.attach(l,r+1,r+2,0,1)
for a in range(len(self.parentobj.population.model.agents)):
aname=self.parentobj.population.model.agents[a].name
l=gtk.Label(aname)
#l.set_alignment(0,0)
l.show()
table.attach(l,0,1,a+1,a+2)
editwidgets={}
for r in range(0,self.parentobj.population.numregions):
for a in range(len(self.parentobj.population.model.agents)):
aname=self.parentobj.population.model.agents[a].name
reg=self.parentobj.population.regions[r]
t=gtk.Entry(max=10)
t.set_width_chars(5)
#t.set_alignment(0,0)
table.attach(t,r+1,r+2,a+1,a+2)
t.show()
t.set_text(str(reg.getNumAgents(aname)))
t.connect('focus_in_event', self.focus_in)
editwidgets[(r,aname)]=t
self.editwidgets=editwidgets
self.table=table
dupbutton=gtk.Button("Replicate 1st region")
dupbutton.connect("clicked",self.duplicate)
self.bbox.pack_end(dupbutton,False,False,0)
dupbutton.show()
def duplicate(self,*args,**kwargs):
for a in range(len(self.parentobj.population.model.agents)):
aname=self.parentobj.population.model.agents[a].name
numa=int(self.editwidgets[(0,aname)].get_text())
for r in range(1,self.parentobj.population.numregions):
self.editwidgets[(r,aname)].set_text(str(numa))
def saveclose(self,*args,**kwargs):
nums={}
for k in self.editwidgets.keys():
r,aname=k
reg=self.parentobj.population.regions[r]
try:
#print "WIDGET CONTENT:*%s*",self.editwidgets[k].get_text()
nums[k]=int(self.editwidgets[k].get_text())
if nums[k]<0:
self.dialogMessage("Entry for agent '%s' at region %d is a negative number"%(aname,(r+1)))
return
except:
self.dialogMessage("Entry for agent '%s' at region %d is not a number"%(aname,(r+1)))
return
for k in self.editwidgets.keys():
r,aname=k
self.parentobj.population.regions[r].setNumAgents(aname,nums[k])
#print "SET NUM AGENTS :",r,aname,nums[k]
self.window.destroy()
self.parentobj.modified=1
class RegionCopyDialog(BasePopDialog):
def __init__(self,parentobj,numregions):
title="Copy region"
self.parentobj=parentobj
self.numregions=numregions
BasePopDialog.__init__(self,title,parentobj.window,height=40,swexpand=True,swfill=True)
table = gtk.Table(1, 2, False)
self.scrolled.add_with_viewport(table)
table.show()
lf=gtk.Label("Copy from region ")
lf.show()
table.attach(lf,0,1,0,1)
tf=gtk.combo_box_entry_new_text()#gtk.Entry(max=5)
tf.show()
table.attach(tf,1,2,0,1)
tf.set_active(0)
lt=gtk.Label("Copy To region ")
lt.show()
table.attach(lt,0,1,1,2)
tt=gtk.combo_box_entry_new_text()#gtk.Entry(max=5)
tt.show()
tt.set_active(0)
table.attach(tt,1,2,1,2)
for r in range(numregions):
tf.append_text(str(r+1))
tt.append_text(str(r+1))
tt.append_text("All")
self.table=table
self.tt=tt
self.tf=tf
self.scbutton.set_label("Copy Region")
def saveclose(self,*args,**kwargs):
targets=[]
try:
tf=int(self.tf.get_active_text())
if tf>self.numregions:
self.dialogMessage("Invalid choice for source region")
return
if self.tt.get_active_text()=="All":
for i in range(self.numregions):
if i!=tf-1:
targets.append(i)
else:
tt=int(self.tt.get_active_text())
if tf==tt or tt>self.numregions:
self.dialogMessage("Invalid choice for target region")
return
targets.append(tt-1)
except:
i=sys.exc_info()
print i
print traceback.print_tb(i[2])
self.dialogMessage("Invalid choice")
return
#if tf==tt or tt>self.numregions or tf>self.numregions:
# self.dialogMessage("Invalid choice")
# return
self.window.destroy()
for t in targets:
self.parentobj.duplicateRegion(tf-1,t)
class EditMemVarsDialog(BasePopDialog):
def __init__(self,parentobj):
self.parentobj=parentobj
title="Memory Variables"