-
Notifications
You must be signed in to change notification settings - Fork 1
/
nlogo.py
executable file
·3259 lines (2893 loc) · 127 KB
/
nlogo.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
"""nlogo.py
This module contains classes for reading and working with a NetLogo model.
Run from the command line, it can be used to:
* Extract all the parameters from the model's GUI tab into a CSV file
(This can then be used in a subsequent call to create an experiment)
./nlogo.py <nlogo file> param <file to save parameters to>
* Print a list of the experiments from the model's behaviour space
./nlogo.py <nlogo file> expt
* Split an experiment's settings into individual experiments
./nlogo.py <nlogo file> split <experiment name> <experiment XML file>
* Prepare a script to run all the split experiments with Sun Grid Engine
./nlogo.py <nlogo file> splitq <experiment name> <experiment XML file>
<file to save SGE submission script to>
* Prepare a Monte Carlo sample of parameter space
./nlogo.py <nlogo file> monte <parameter file> <tick number to stop at>
<number of samples> <experiment XML file>
Note: if the number of samples is large, the XML library used by NetLogo
to read in the experiment file can cause out-of-memory and garbage
collection errors, or result in the model taking a long time to run. Use
number of samples > 10000 with caution.
The created experiment file automatically collects data from plot pens
and monitors each step.
* Prepare a Monte Carlo sample of parameter space with a shell script to
run all the options with Sun Grid Engine
./nlogo.py <nlogo file> montq <parameter file> <tick number to stop at>
<number of samples> <experiment XML file>
<file to save SGE submission script to>
You can then submit the jobs with qsub <SGE submission script>
A typical workflow would be to run this with param and then montq, before
qsubbing the submission script. Once you've extracted the results you want
from the outputs, you could then use, for example bruteABC.py to analyse
the results.
Other potentially useful tools (for future implementation)
* Extract and collate outputs from NetLogo experiments in an XML file
* Automatically split up large sample sizes for monte and montq into
chunks of, say, 20000 runs at a time. (DONE)
* Creata a qsub script to run a BehaviorSpace experiment in parallel (DONE)
* Parse code and do things with it, like extracting an ontology, or UML
diagrams
* Automatically add a licence (e.g. GNU GPL) section to the Info tab
* Check progress with experiment runs by looking for output files
"""
# Copyright (C) 2018 The James Hutton Institute & University of Edinburgh
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licence as published by
# the Free Software Foundation, either version 3 of the Licence, 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 Licence for more details.
#
# You should have received a copy of the GNU General Public Licence
# along with this program. If not, see <https://www.gnu.org/licences/>.
__version__ = "0.5"
__author__ = "Gary Polhill"
# Imports
import io
import os
import re
import sys
import math
import shutil
import random as rnd
import xml.etree.ElementTree as xml
def lineBreak(str, indent = "", tabstop = 8):
(width, height) = shutil.get_terminal_size(fallback = (80, 24))
indent = indent.replace("\t", " " * tabstop)
ret = []
line = 0
while len(str) > 0:
line += 1
ind = "" if line == 1 else indent
width_left = len(str) + len(ind)
if width_left <= width:
ret.append(ind + str)
str = ""
else:
lwd = width + len(ind)
lstr = str[:lwd]
str = str[lwd:]
space = lstr.rfind(" ")
if space < 0:
ret.append(ind + lstr)
else:
ret.append(ind + lstr[:space])
str = lstr[(space + 1):] + str
return ret
def parseBoolean(s):
if s == "True":
return True
elif s == "False":
return False
else:
sys.stderr.print("BUG! String \"{s}\" is not \"True\" or \"False\"".format(s = s))
sys.exit(1)
################################################################################
# NLogoError Class
#
# # # # ### #### ### ##### #### #### ### ####
# ## # # # # # # # # # # # # # # # #
# # # # # # # # ### # # #### #### #### # # ####
# # ## # # # # # # # # # # # # # # # #
# # # ##### ### ### ### ##### # # # # ### # #
#
################################################################################
class NLogoError(Exception):
"""
Bespoke error handler class, allowing tracking of cause, recovery options
for the user, and an indication of whether this is a bug. Using these
exceptions allows clean recovery when in GUI mode.
"""
pass
################################################################################
# Widget Class
#
# # # ### #### #### ##### #####
# # # # # # # # #
# # # # # # # # ### #### #
# ## ## # # # # # # #
# # # ### #### #### ##### #
#
################################################################################
class Widget:
"""
The Widget class is a top-level class for all of the items that you can
put on the GUI tab of a NetLogo model.
"""
type = "<<UNDEF>>"
def __init__(self, type, left, top, right, bottom, display, parameter,
output, info):
self.type = type
self.left = left
self.top = top
self.right = right
self.bottom = bottom
self.display = display
self.isParameter = parameter
self.isOutput = output
self.isInfo = info
@staticmethod
def read(fp):
"""
Reads the widgets section from a NetLogo file, returning an array
of widgets read
"""
typestr = fp.readline()
widgets = []
while(typestr[0:-1] != "@#$#@#$#@"):
typestr = typestr.strip()
if typestr == GraphicsWindow.type:
widgets.append(GraphicsWindow.read(fp))
elif typestr == Button.type:
widgets.append(Button.read(fp))
elif typestr == Plot.type:
widgets.append(Plot.read(fp))
elif typestr == TextBox.type:
widgets.append(TextBox.read(fp))
elif typestr == Switch.type:
widgets.append(Switch.read(fp))
elif typestr == Chooser.type:
widgets.append(Chooser.read(fp))
elif typestr == Slider.type:
widgets.append(Slider.read(fp))
elif typestr == Monitor.type:
widgets.append(Monitor.read(fp))
elif typestr == OutputArea.type:
widgets.append(OutputArea.read(fp))
elif typestr == InputBox.type:
widgets.append(InputBox.read(fp))
else:
sys.stderr.write("Unrecognized widget type: %s\n"%(typestr))
while(typestr.strip() != ""):
typestr = fp.readline()
typestr = fp.readline()
if typestr == "":
break
if typestr.strip() == '':
typestr = fp.readline()
return widgets
################################################################################
# GraphicsWindow Class
################################################################################
class GraphicsWindow(Widget):
"""
The GraphicsWindow class is a subclass of Widget that contains the space
"""
type = "GRAPHICS-WINDOW"
def __init__(self, left, top, right, bottom, patch_size, font_size, x_wrap,
y_wrap, min_pxcor, max_pxcor, min_pycor, max_pycor, update_mode,
show_ticks, tick_label, frame_rate):
Widget.__init__(self, GraphicsWindow.type, left, top, right, bottom, "",
False, True, False)
self.patchSize = patch_size
self.fontSize = font_size
self.xWrap = x_wrap
self.yWrap = y_wrap
self.minPXCor = min_pxcor
self.maxPXCor = max_pxcor
self.minPYCor = min_pycor
self.maxPYCor = max_pycor
self.updateMode = update_mode
self.showTicks = show_ticks
self.tickLabel = tick_label
self.frameRate = frame_rate
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
res1 = fp.readline()
res2 = fp.readline()
patch_size = float(fp.readline())
res3 = fp.readline()
font_size = int(fp.readline())
res4 = fp.readline()
res5 = fp.readline()
res6 = fp.readline()
res7 = fp.readline()
x_wrap = fp.readline().strip() == "1"
y_wrap = fp.readline().strip() == "1"
res8 = fp.readline()
min_pxcor = int(fp.readline())
max_pxcor = int(fp.readline())
min_pycor = int(fp.readline())
max_pycor = int(fp.readline())
update_mode = int(fp.readline())
res9 = fp.readline()
show_ticks = fp.readline().strip() == "1"
tick_label = fp.readline().strip()
frame_rate = float(fp.readline())
return GraphicsWindow(left, top, right, bottom, patch_size, font_size,
x_wrap, y_wrap, min_pxcor, max_pxcor, min_pycor,
max_pycor, update_mode, show_ticks, tick_label,
frame_rate)
################################################################################
# Button Class
################################################################################
class Button(Widget):
"""
The Button class is a subclass of Widget containing a button
"""
type = "BUTTON"
def __init__(self, left, top, right, bottom, display, code, forever,
button_type, action_key, always_enable):
Widget.__init__(self, Button.type, left, top, right, bottom, display,
False, False, False)
self.code = code
self.forever = forever
self.buttonType = button_type
self.actionKey = action_key
self.alwaysEnable = always_enable
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
code = fp.readline().strip()
forever = (fp.readline().strip() == "T")
res1 = fp.readline()
res2 = fp.readline()
button_type = fp.readline().strip()
res3 = fp.readline()
action_key = fp.readline().strip()
res4 = fp.readline()
res5 = fp.readline()
always_enable = (int(fp.readline()) == 1)
return Button(left, top, right, bottom, display, code, forever,
button_type, action_key, always_enable)
################################################################################
# Parameter Class
#
# #### # #### # # # ##### ##### ##### ####
# # # # # # # # # ## ## # # # # #
# #### # # #### # # # # # #### # #### ####
# # ##### # # ##### # # # # # # #
# # # # # # # # # # ##### # ##### # #
#
################################################################################
class Parameter(Widget):
"""
The Parameter class is an abstract subclass of Widget for all parameter widgets.
Subclasses include Slider, Switch, Chooser and InputBox
"""
def __init__(self, type, left, top, right, bottom, display):
Widget.__init__(self, type, left, top, right, bottom, display, True, False, False)
self.varname = '<<UNDEF>>'
self.default = 'NA'
self.value = 'NA'
self.datatype = 'string'
self.constrained = False
self.rangeConstraint = False
self.setConstraint = False
self.otherParamConstraint = False
def variable(self):
return self.varname
def settingStr(self):
return str(self.value)
def datatypeStr(self):
return str(self.datatype)
def setValue(self, value):
self.value = value
################################################################################
# Output Class
################################################################################
class Output(Widget):
"""
The Output class is an abstract subclass of Widget containing some output.
Subclasses include Plot, Monitor and OutputArea
"""
def __init__(self, type, left, top, right, bottom, display):
Widget.__init__(self, type, left, top, right, bottom, display, False, True, False)
################################################################################
# Info Class
################################################################################
class Info(Widget):
"""
The Info class is an abstract subclass of Widget containing information.
TextBox is the subclass of Info.
"""
def __init__(self, type, left, top, right, bottom, display):
Widget.__init__(self, type, left, top, right, bottom, display, False, False, True)
################################################################################
# Plot Class
################################################################################
class Plot(Output):
"""
Plot widget
"""
type = "PLOT"
def __init__(self, left, top, right, bottom, display, xaxis, yaxis, xmin,
xmax, ymin, ymax, autoplot_on, legend_on, code1, code2):
Output.__init__(self, Plot.type, left, top, right, bottom, display)
self.xaxis = xaxis
self.yaxis = yaxis
self.xmin = xmin
self.ymin = ymin
self.ymax = ymax
self.autoplotOn = autoplot_on
self.legendOn = legend_on
self.code1 = code1
self.code2 = code2
self.pens = {}
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
xaxis = fp.readline().strip()
yaxis = fp.readline().strip()
xmin = float(fp.readline())
xmax = float(fp.readline())
ymin = float(fp.readline())
ymax = float(fp.readline())
autoplot_on = (fp.readline().strip() == "true")
legend_on = (fp.readline().strip() == "true")
codes = (fp.readline().strip().split('" "'))
plot = Plot(left, right, top, bottom, display, xaxis, yaxis,
xmin, xmax, ymin, ymax, autoplot_on, legend_on,
codes[0][1:-1], codes[1][0:-2])
if fp.readline().strip() == "PENS":
penstr = fp.readline().strip()
while penstr != '':
plot.addPen(Pen.parse(penstr, display))
penstr = fp.readline().strip()
return plot
def addPen(self, pen):
self.pens[pen.display] = pen
def getPens(self):
return self.pens.values()
def getPenDict(self):
return self.pens
################################################################################
# Pen Class
################################################################################
class Pen:
"""
The Pen class contains data for each pen of a Plot
"""
def __init__(self, display, interval, mode, colour, in_legend, setup_code,
update_code, plot_name):
self.display = display
self.interval = interval
self.mode = mode
self.colour = colour
self.inLegend = in_legend
self.setupCode = setup_code
self.updateCode = update_code
self.plotName = plot_name
@staticmethod
def parse(penstr, plot_name):
words = penstr.split()
display = words[0]
i = 1
while not display.endswith('"'):
display = display + " " + words[i]
i = i + 1
interval = float(words[i])
mode = int(words[i + 1])
colour = int(words[i + 2])
in_legend = (words[i + 3] == "true")
setup_code = words[i + 4]
i = i + 5
while setup_code.endswith('\\"') or not setup_code.endswith('"'):
setup_code = setup_code + " " + words[i]
i = i + 1
update_code = " ".join(words[i:])
return Pen(display, interval, mode, colour, in_legend, setup_code, update_code, plot_name)
################################################################################
# TextBox Class
################################################################################
class TextBox(Info):
"""
TextBox is an Info containing some text
"""
type = "TEXTBOX"
def __init__(self, left, top, right, bottom, display, font_size, colour,
transparent):
Info.__init__(self, TextBox.type, left, top, right, bottom, display)
self.fontSize = font_size
self.colour = colour
self.transparent = transparent
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
font_size = int(fp.readline())
colour = float(fp.readline())
txt = fp.readline().strip()
transparent = (txt == 'true' or txt == '1' or txt == 'T')
return TextBox(left, top, right, bottom, display, font_size, colour,
transparent)
################################################################################
# Switch Class
################################################################################
class Switch(Parameter):
"""
Switch Parameter widget
"""
type = "SWITCH"
def __init__(self, left, top, right, bottom, display, varname, on):
Parameter.__init__(self, Switch.type, left, top, right, bottom, display)
self.varname = varname
self.isSwitchedOn = on
self.value = self.isSwitchedOn
self.datatype = 'boolean'
self.constrained = True
self.setConstraint = True
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
varname = fp.readline().strip()
txt = fp.readline().strip()
on = (txt == '0')
res1 = fp.readline()
res2 = fp.readline()
return Switch(left, top, right, bottom, display, varname, on)
def getConstraintSet(self):
return [True, False]
################################################################################
# Chooser Class
################################################################################
class Chooser(Parameter):
"""
Chooser Parameter widget
"""
type = "CHOOSER"
def __init__(self, left, top, right, bottom, display, varname, choices,
selection):
Parameter.__init__(self, Chooser.type, left, top, right, bottom, display)
self.varname = varname
self.choices = choices
self.selection = selection
self.value = self.selection
self.datatype = 'integer'
self.constrained = True
self.setConstraint = False
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
varname = fp.readline().strip()
txt = fp.readline().strip()
words = txt.split()
choices = []
choices.append(words[0])
i = 1
j = 0
while i < len(words):
while choices[j].startswith('"') and not choices[j].endswith('"'):
choices[j] = choices[j] + " " + words[i]
i = i + 1
if i >= len(words):
break
choices.append(words[i])
j = j + 1
i = i + 1
selection = int(fp.readline())
return Chooser(left, top, right, bottom, display, varname, choices,
selection)
def getSelectionStr(self):
return self.choices[self.selection]
def getConstraintSet(self):
return self.choices
def getOptionIndex(self, option):
if option in self.choices:
return self.choices.index(option)
elif ('"' + option + '"') in self.choices:
return self.choices.index('"' + option + '"')
elif option == "NA":
return "NA"
else:
opt = option
if not isinstance(option, int):
if not option.isdigit():
sys.stderr.write("Error: \"{value}\" is not an option for chooser {var} ({opts})\n".format(
value = option, var = self.varname,
opts = ", ".join([str(x) for x in self.choices])))
opt = int(option)
if opt < 0 or opt >= len(self.choices):
sys.stderr.write("Error: index {value} is not in the range of index values for chooser {var} ([0, {max}[)\n".format(
value = opt, var = self.varname, max = len(self.choices)
))
sys.exit(1)
return opt
def getOptionValue(self, ix):
if isinstance(ix, int) and ix >= 0 and ix < len(self.choices):
return self.choices[ix]
else:
sys.stderr.write("BUG! getOptionValue() sent \"{value}\" -- should be integer in range [0, {max}[\n".format(value = ix, max = len(self.choices)))
################################################################################
# Slider Class
################################################################################
class Slider(Parameter):
"""
Slider Parameter widget
"""
type = "SLIDER"
def __init__(self, left, top, right, bottom, display, varname, min, max,
default, step, units, orientation):
Parameter.__init__(self, Slider.type, left, top, right, bottom, display)
self.varname = varname
self.minimum = min
self.maximum = max
self.default = default
self.step = step
self.units = units
self.isHorizontal = (orientation == "HORIZONTAL")
self.value = self.default
self.datatype = 'numeric'
self.constrained = True # Strictly, you can set sliders outwith
# their range
self.rangeConstraint = True
self.minOther = False
self.maxOther = False
try:
float(min)
except ValueError:
self.otherParamConstraint = True
self.minOther = True
try:
float(max)
except ValueError:
self.otherParamConstraint = True
self.maxOther = True
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
varname = fp.readline().strip()
min = fp.readline().strip()
max = fp.readline().strip()
default = float(fp.readline())
step = fp.readline().strip()
res1 = fp.readline()
units = fp.readline().strip()
orientation = fp.readline().strip()
return Slider(left, top, right, bottom, display, varname, min, max,
default, step, units, orientation)
def getMinimumConstraint(self):
return self.minimum
def getMaximumConstraint(self):
return self.maximum
def getNumericalMinConstraint(self, param_dict):
if self.minOther:
if self.minimum in param_dict:
param = param_dict[self.minimum]
if isinstance(param, Slider):
dict_cpy = param_dict.copy()
dict_cpy.pop(self.minimum) # Stop infinite recursion
return param.getNumericalMinConstraint(dict_cpy)
elif isinstance(param, Parameter) and param.datatype == "numeric":
return float(param.value)
elif isinstance(param, float):
return param
elif isinstance(param, int):
return float(param)
return 'NA'
else:
return float(self.minimum)
def getNumericalMaxConstraint(self, param_dict):
if self.maxOther:
if self.maximum in param_dict:
param = param_dict[self.maximum]
if isinstance(param, Slider):
dict_cpy = param_dict.copy()
dict_cpy.pop(self.maximum) # Stop infinite recursion
return param.getNumericalMaxConstraint(dict_cpy)
elif isinstance(param, Parameter) and param.datatype == "numeric":
return float(param.value)
elif isinstance(param, float):
return param
elif isinstance(param, int):
return float(param)
return 'NA'
else:
return float(self.maximum)
################################################################################
# Monitor Class
################################################################################
class Monitor(Output):
"""
Monitor Output Widget
"""
type = "MONITOR"
def __init__(self, left, top, right, bottom, display, source, precision,
font_size):
Output.__init__(self, Monitor.type, left, top, right, bottom, display)
self.source = source
self.precision = precision
self.fontSize = font_size
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
display = fp.readline().strip()
source = fp.readline().strip().replace("\\\"", "\"")
precision = int(fp.readline())
res1 = fp.readline()
font_size = int(fp.readline())
return Monitor(left, top, right, bottom, display, source, precision,
font_size)
################################################################################
# OutputArea Class
################################################################################
class OutputArea(Output):
"""
OutputArea Output widget
"""
type = "OUTPUT"
def __init__(self, left, top, right, bottom, font_size):
Output.__init__(self, OutputArea.type, left, top, right, bottom, "")
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
font_size = int(fp.readline())
display = ""
return Output(left, top, right, bottom, font_size, display)
################################################################################
# InputBox Class
################################################################################
class InputBox(Parameter):
"""
InputBox Parameter widget
"""
type = "INPUTBOX"
def __init__(self, left, top, right, bottom, varname, value, multiline,
datatype):
Parameter.__init__(self, InputBox.type, left, top, right, bottom, "")
self.varname = varname
self.value = value
self.isMultiline = multiline
self.isNumeric = (datatype == "Number")
self.isString = (datatype == "String")
self.isCommand = (datatype == "String (command)")
self.isReporter = (datatype == "String (reporter)")
self.isColour = (datatype == "Color")
if self.isNumeric or self.isColour:
self.datatype = 'numeric'
if self.isString:
self.value = "\"" + value + "\""
@staticmethod
def read(fp):
left = int(fp.readline())
top = int(fp.readline())
right = int(fp.readline())
bottom = int(fp.readline())
varname = fp.readline().strip()
value = fp.readline().strip()
txt = fp.readline().strip()
multiline = (txt == 'true' or txt == '1' or txt == 'T')
res1 = fp.readline()
datatype = fp.readline().strip()
return InputBox(left, top, right, bottom, varname, value, multiline,
datatype)
################################################################################
# BehaviorSpaceXMLError Class
################################################################################
class BahaviorSpaceXMLError(Exception):
"""
Exception class for when there is unexpected content in the BehaviorSpace
section of a NetLogo file.
"""
def __init__(self, file, expected, found):
self.file = file
self.expected = expected
self.found = found
def __str__(self):
return "BehaviorSpace XML format error in file %s: expected \"%s\", found \"%s\""%(self.file, self.expected, self.found)
################################################################################
# SteppedValue Class
################################################################################
class SteppedValue:
"""
A class containing data from a stepped value parameter exploration in a
BehaviorSpace
"""
def __init__(self, variable, first, step, last):
if step < 0.0 and first < last:
raise ValueError("In BehaviorSpace, variable \"%s\" has negative step %f with start %f < stop %f"%(variable, step, first, last))
elif step > 0.0 and first > last:
raise ValueError("In BehaviorSpace, variable \"%s\" has step %f with start %f > stop %f"%(variable, step, first, last))
elif step == 0.0 and first != last:
raise ValueError("In BehaviorSpace, variable \"%s\" has step 0.0 with start %f != stop %f"%(variable, step, first, last))
self.variable = variable
self.first = first
self.step = step
self.last = last
self.values = []
self.values.append(first)
while self.values[-1] < self.last:
self.values.append(self.step + self.values[-1])
def getValues(self):
return self.values
def getNValues(self):
return len(self.values)
@staticmethod
def fromXML(xml, file_name):
if xml.tag != "steppedValueSet":
raise BehaviorSpaceXMLError(file_name, "steppedValueSet", xml.tag)
return SteppedValue(xml.get("variable"), float(xml.get("first")),
float(xml.get("step")), float(xml.get("last")))
################################################################################
# EnumeratedValue Class
################################################################################
class EnumeratedValue:
"""
A class containing data from an enumerated value parameter exploration
in a BehaviorSpace
"""
def __init__(self, variable, values):
self.variable = variable
if isinstance(values, list):
self.values = values
else:
self.values = []
self.values.append(values)
def getValues(self):
return self.values
def getNValues(self):
return len(self.values)
@staticmethod
def fromXML(xml, file_name):
if xml.tag != "enumeratedValueSet":
raise BehaviorSpaceXMLError(file_name, "enumeratedValueSet", xml.tag)
variable = xml.get("variable")
values = []
for value in xml:
if value.tag != "value":
raise BehaviorSpaceXMLError(file_name, "value", value.tag)
values.append(value.get("value"))
return EnumeratedValue(variable, values)
################################################################################
# Experiment Class
#
# ##### # # #### ##### #### ### # # ##### # # #####
# # # # # # # # # # ## ## # ## # #
# #### # #### #### #### # # # # #### # # # #
# # # # # # # # # # # # # ## #
# ##### # # # ##### # # ### # # ##### # # #
#
################################################################################
class Experiment:
param_comment = "; nlogo.py added this code to save parameters and metrics"
prog_comment = "; nlogo.py added this code to save progress"
"""
Class containing data from a single BehaviorSpace experiment
"""
def __init__(self, name, setup, go, final, time_limit, exit_condition,
metrics, stepped_values = [], enumerated_values = [],
repetitions = 1, sequential_run_order = True,
run_metrics_every_step = True, results = ".", metric_labels = []):
self.name = name
self.setup = setup
self.go = go
self.final = final
self.timeLimit = time_limit
self.exitCondition = exit_condition
self.metrics = metrics
if len(metric_labels) != len(metrics):
self.metricLabels = [x for x in metrics]
else:
self.metricLabels = metric_labels
self.steppedValueSet = stepped_values
self.enumeratedValueSet = enumerated_values
self.repetitions = int(repetitions)
self.sequentialRunOrder = sequential_run_order
self.runMetricsEveryStep = run_metrics_every_step
self.results = results # Directory where any output should be
self.addedProgress = (self.prog_comment in setup)
self.addedFinalParametrics = (self.param_comment in final)
def getMetrics(self):
return self.metrics
def getSteppedParameters(self):
return self.steppedValueSet
def getEnumeratedParameters(self):
return self.enumeratedValueSet
def getNRuns(self):
runs = self.repetitions
for param in self.steppedValueSet:
runs *= param.getNValues()
for param in self.enumeratedValueSet:
runs *= param.getNValues()
return runs
def uniqueSettings(self, opts):
"""
Return an array of all the runs in this experiment with unique
parameter settings
"""
experiments = []
counters = {}
maxes = {}
all_enum_names = {}
for param in self.steppedValueSet:
counters[param.variable] = 0
maxes[param.variable] = param.getNValues()
for param in self.enumeratedValueSet:
all_enum_names[param.variable] = param
if not opts.isParamSet(param.variable):
counters[param.variable] = 0
maxes[param.variable] = param.getNValues()
done = False
i = 1
n = self.getNRuns()
if not opts.split_reps:
n /= self.repetitions
use_metrics = [m for m in self.metrics]
if opts.rng_param != "" and not opts.rng_param in use_metrics:
use_metrics.append(opts.rng_param)