-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexperiments.py
1330 lines (1093 loc) · 62.1 KB
/
experiments.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
'''
experiments.py
Written by:
Seyla Wachlin
Igna Vermeulen
Last updated on June 2017
Description:
All implemented experiments can be found in this .py file. Examples of how to
run every experiment can be found in the main() function. Paralellism is
supported and the MAX_CPUs can be set to the number of cores to use. Note that
by default this should be 1 and that implies the code is run sequentially.
All results of the experiments are stored in matching directories within the
data/experiment_results/ directory.
'''
import simulation
import data_handler
import environment
import agent
import json
import pandas
import numpy
import datetime
import pickle
#import IPython
import ipywidgets
import bqplot
import multiprocessing
import os
import time
import random
import pandas as pd
MAX_CPUs = 2
def experiment_initialization(parameter, values, measures, experiment_name, number_of_agents = 30):
''' This function runs the initialization of the simulation for various
given values of the specified parameter. The given measures are the
output of the experiment. The results are stored in the
data/experiment_results directory. A subdirectory is created (if it does
not already exist), containing the measure names and parameter name, in
which the results are stored.
Args:
parameter (str): The parameter to vary for the experiment.
values (List[int or float]): A list of values the parameter can take.
measures (List[str]): A list of measure names. Possible measures are
number_of_centers, average_number_of_charging_stations and
walking_preparedness.
Kwargs:
number_of_agents (int): Amount of agents to run the experiment with.
Default is 30.
'''
values = list(values) # list(reversed(values)) old version new version ascending
print('INFO: Started experiment: Initialization which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, ['%0.2f' % val for val in values]) + '%d agents.' % \
number_of_agents)
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
parameters_file = 'data/input_parameters/parameters.json'
with open(parameters_file) as json_data:
parameters_json = json.load(json_data)
parameters = [(parameters_file, parameter, i, len(values), value,
number_of_agents, measures, experiment_name) for i, value in enumerate(values)]
p = multiprocessing.Pool(MAX_CPUs)
p.map(inner_loop_experiment_initialization, parameters)
print('INFO: Finished experiment: Initialization which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, ['%0.2f' % val for val in values]) + '%d agents.' % \
number_of_agents)
# print('INFO: Experiment took %s' %
# get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def inner_loop_experiment_initialization(args):
''' This function runs the initialization experiment for a single value
of a parameter measuring one or more measures. It is also in charge
of storing the results of the experiment for this value.
Args:
args (Tuple[Any]): Contains the arguments needed for the experiment,
namely in order:
- (str): The path to the parameters file;
- (str): The parameter to vary for the experiment;
- (int): The current experiment run number;
- (int): The total amount of values for the parameter;
- (int or float): The value of the parameter in this run;
- (int): Amount of agents to run the experiment with;
- (List(str)): A list of measure names. Possible measures are
number_of_centers, average_number_of_charging_stations and
walking_preparedness.
'''
parameters_file, parameter, i, max_runs, value, number_of_agents, measures, experiment_name = args
start_time = time.process_time()
print('INFO: Experiment run %d of %d (%s = %s, measuring %s)' % (i + 1,
max_runs, parameter, value, measures))
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {parameter: value,
'number_of_agents': number_of_agents,
'agent_initialization': 'create',
'filepath_agent_database': ''})
newpath = 'data/experiment_results/%s' % (experiment_name)
if not os.path.exists(newpath):
os.makedirs(newpath)
for m in measures:
experiment_dir = 'data/experiment_results/%s/experiment_initialization_measures_%s_varying_%s' % \
(experiment_name, m, parameter)
if not os.path.exists(experiment_dir):
os.makedirs(experiment_dir)
experiment_filename = experiment_dir + \
'/%0.2f_%s_%s_agents.pkl' % (value, parameter, str(number_of_agents))
with open(experiment_filename, 'wb') as experiment_file:
pickle.dump(sim.sensors[m], experiment_file)
print('INFO: Partial results stored in %s' % experiment_filename)
print('INFO: Experiment run %d (%s = %s, measuring %s) took %s' % (i + 1,
parameter, value, measures,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def experiment_simulation(parameter, values, measures, simulation_repeats = -1, experiment_name = 'Unnamed_experiment',
number_of_agents = 30, method = 'relMAE', hack_parameters_file = None):
''' This function runs the simulation for various given values of the
specified parameter. The given measures are the output of the
experiment. The results are stored in the data/experiment_results
directory. A subdirectory is created (if it does not already exist),
containing the measure names and parameter name, in which the results
are stored.
Args:
parameter (str): The parameter to vary for the experiment.
values (List[int or float]): A list of values the parameter can take.
measures (List[str]): A list of measure names. Possible measures are
charging_station_validation, agent_validation,
time_per_simulation.
Kwargs:
number_of_agents (int): Amount of agents to run the experiment with.
Default is 30.
simulation_repeats (int): Amount of repeats for the experiment. Default
is 30.
'''
values = list(values)
if parameter == 'number_of_agents':
print('INFO: Started experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d simulation_repeats.' % \
simulation_repeats)
else:
print('INFO: Started experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%s agents and %d simulation_repeats.' % \
(number_of_agents, simulation_repeats))
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
if hack_parameters_file != None:
parameters_file = hack_parameters_file
else:
parameters_file = 'data/input_parameters/parameters.json'
parameters = [(parameters_file, parameter, i, len(values), value, number_of_agents,
simulation_repeats, measures, experiment_name, method) for i, value in enumerate(values)]
p = multiprocessing.Pool(MAX_CPUs)
p.map(inner_loop_experiment_simulation, parameters)
if parameter == 'number_of_agents':
print('INFO: Finished experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d simulation_repeats.' % \
simulation_repeats)
else:
print('INFO: Finished experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%s agents and %d simulation_repeats.' % \
(number_of_agents, simulation_repeats))
# print('INFO: Experiment took %s' %
# get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def inner_loop_experiment_simulation(args):
''' This function runs the simulation experiment for a single value
of a parameter measuring one or more measures. It is also in charge
of storing the results of the experiment for this value.
Args:
args (Tuple[Any]): Contains the arguments needed for the experiment,
namely in order:
- (str): The path to the parameters file;
- (str): The parameter to vary for the experiment;
- (int): The current experiment run number;
- (int): The total amount of values for the parameter;
- (int or float): The value of the parameter in this run;
- (int): Amount of repeats for the experiment;
- (List(str)): A list of measure names. Possible measures are
number_of_centers, average_number_of_charging_stations and
walking_preparedness;
- (str): Method of validation, either MAE or relMAE.
'''
(parameters_file, parameter, i, max_runs, value, number_of_agents, simulation_repeats, measures, \
experiment_name, method) = args
start_time = time.process_time()
print('INFO: Experiment run %d of %d (%s = %s, measuring %s)' % (i + 1,
max_runs, parameter, value, measures))
if parameter == 'number_of_agents':
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {parameter: value}) #NOTE: changed this
elif parameter == "adding_non_habitual_agents":
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {'number_of_agents': number_of_agents,
'non_habitual_agents': {"Amsterdam": int(value),
"Den Haag": int(value),
"Rotterdam": int(value),
"Utrecht": int(value)}}) #NOTE: changed this
else:
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {parameter: value,
'number_of_agents': number_of_agents}) #NOTE: changed this
newpath = 'data/experiment_results/%s' % (experiment_name)
if not os.path.exists(newpath):
os.makedirs(newpath)
try:
if parameter == 'simulation_repeats':
simulation_repeats = value
sim.repeat_simulation(repeat = simulation_repeats, measures = measures,
method = method, display_progress = False)
for m in measures:
experiment_dir = 'data/experiment_results/%s/experiment_simulation_measures_%s_varying_%s' % \
(experiment_name, m, parameter)
if not os.path.exists(experiment_dir):
os.makedirs(experiment_dir)
if parameter == 'number_of_agents':
experiment_filename = experiment_dir + '/%s_%s_%s_simulation_repeats.pkl' % (str(value), parameter, str(simulation_repeats))
else:
experiment_filename = experiment_dir + '/%0.2f_%s_%s_agents_%s_simulation_repeats.pkl' % (value, parameter, str(number_of_agents), str(simulation_repeats))
with open(experiment_filename, 'wb') as experiment_file:
pickle.dump(sim.sensors[m], experiment_file)
print('INFO: Partial results stored in %s' % experiment_filename)
except Exception as e:
print(e)
print("WARNING: Thus failed")
print('INFO: Experiment run %d (%s = %s, measuring %s) took %s' %
(i + 1, parameter, value, measures,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def experiment_initialization_and_simulation(parameter, values, measures, experiment_name = 'Unnamed_experiment',
number_of_agents = 30, simulation_repeats = 30, method = 'relMAE', initialization_repeats = 1,ratio_unhabitual=0):
''' This function runs the experiment that requires initialization as well
as simulation. For various given values of the specified parameter the
given measures will be measured. The results are stored in the
data/experiment_results directory. A subdirectory is created (if it does
not already exist), containing the measure names and parameter name, in
which the results are stored.
Args:
parameter (str): The parameter to vary for the experiment.
values (List[int or float]): A list of values the parameter can take.
measures (List[str]): A list of measure names. Possible measures are
charging_station_validation, agent_validation,
time_per_simulation.
Kwargs:
number_of_agents (int) Amount of agents to do the experiment with.
Default is 30.
simulation_repeats (int): Amount of repeats for the experiment. Default
is 30.
'''
values = list(values)
print('INFO: Started experiment: initialization and simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d agents and %d simulation_repeats with %s unhabitual agents ratio.' % \
(number_of_agents, simulation_repeats, ratio_unhabitual))
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
parameters_file = 'data/input_parameters/parameters.json'
if initialization_repeats > 1:
parameters = [(parameters_file, parameter, i, len(values), value,
number_of_agents, simulation_repeats, measures, experiment_name+"_init_repeat_"+str(repeat), method, ratio_unhabitual)
for i, value in enumerate(values) for repeat in range(initialization_repeats)]
else:
parameters = [(parameters_file, parameter, i, len(values), value,
number_of_agents, simulation_repeats, measures, experiment_name, method, ratio_unhabitual)
for i, value in enumerate(values)]
p = multiprocessing.Pool(MAX_CPUs)
p.map(inner_loop_experiment_initialization_and_simulation, parameters)
print('INFO: Finished experiment: initialization and simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d agents and %d simulation_repeats with %s unhabitual agents ratio.' % \
(number_of_agents, simulation_repeats, ratio_unhabitual))
# print('INFO: Experiment took %s' %
# get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def inner_loop_experiment_initialization_and_simulation(args):
''' This function runs an experiment that requires initialization and
simulation. For a single value of a parameter measuring one or more
measures are measured. This function is also in charge of storing the
results of the experiment for this value.
Args:
args (Tuple[Any]): Contains the arguments needed for the experiment,
namely in order:
- (str): The path to the parameters file;
- (str): The parameter to vary for the experiment;
- (int): The current experiment run number;
- (int): The total amount of values for the parameter;
- (int or float): The value of the parameter in this run;
- (int): Amount of agents in the experiment;
- (int): Amount of repeats for the experiment;
- (List(str)): A list of measure names. Possible measures are
number_of_centers, average_number_of_charging_stations and
walking_preparedness;
- (str): Method of validation, either MAE or relMAE.
'''
(parameters_file, parameter, i, max_runs, value, number_of_agents, simulation_repeats, measures, \
experiment_name, method, ratio_unhabitual) = args
start_time = time.process_time()
print('INFO: Experiment run %d of %d (%s = %s, measuring %s)' % (i + 1,
max_runs, parameter, value, measures))
if "adding_habitual_agents" in experiment_name: # JM: Added for the experiment of adding habitual agents.
if parameter == "adding_extra_agents":
extra_agents = int(value)
print('this is the number of normal agents' + str(number_of_agents))
print('this is the number of extra_agents agents' + str(extra_agents))
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {'number_of_agents': number_of_agents,
'agent_initialization': 'load_and_use',
'add_agents_during_simulation':extra_agents,
"non_habitual_agents": {"Amsterdam": ratio_unhabitual,
"Den Haag": ratio_unhabitual,
"Rotterdam": ratio_unhabitual,
"Utrecht": ratio_unhabitual} })
#for agent_ID in agent_IDs:
# sim.agents[agent_ID].start_date_agent = sim.start_date_simulation
# sim.agents[agent_ID].end_date_agent = sim.stop_condition_parameters['max_time']
else:
extra_agents = 0
print('this is the number of normal agents' + str(value))
print('this is the number of extra_agents agents' + str(extra_agents))
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {'number_of_agents': value,
'agent_initialization': 'load_and_use',
'add_agents_during_simulation':extra_agents,
"non_habitual_agents": {"Amsterdam": ratio_unhabitual,
"Den Haag": ratio_unhabitual,
"Rotterdam": ratio_unhabitual,
"Utrecht": ratio_unhabitual} })
#agent_IDs = list(sim.agents.keys())
#agent_IDs = [agent_ID for agent_ID in agent_IDs if not 'car2go' in agent_ID]
#random.shuffle(agent_IDs)
#for j, agent_ID in enumerate(agent_IDs):
# if j > value:
# sim.agents[agent_ID].start_date_agent = sim.stop_condition_parameters['max_time']
# else:
# sim.agents[agent_ID].start_date_agent = sim.start_date_simulation
# sim.agents[agent_ID].end_date_agent = sim.stop_condition_parameters['max_time']
else:
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {parameter: value,
'number_of_agents': number_of_agents,
'agent_initialization': 'create_and_use'}) # JRH: here the create and use is selected as option since the experiment is about the initialization
print('INFO: Experiment run %d of %d is done with initialization at %s' %
((i + 1), max_runs, datetime.datetime.now()))
newpath = 'data/experiment_results/%s' % (experiment_name)
if not os.path.exists(newpath):
os.makedirs(newpath)
try:
sim.repeat_simulation(repeat = simulation_repeats, measures = measures, method = method,
display_progress = False)
for m in measures:
experiment_dir = 'data/experiment_results/%s/experiment_initialization_and_simulation_measures_%s_varying_%s' % \
(experiment_name, m, parameter)
if not os.path.exists(experiment_dir):
os.makedirs(experiment_dir)
experiment_filename = experiment_dir + '/%s_%s_%s_agents_%s_simulation_repeats_%s_unhabitual_agents.pkl' % (str(value), parameter, str(number_of_agents), str(simulation_repeats), str(ratio_unhabitual))
with open(experiment_filename, 'wb') as experiment_file:
pickle.dump(sim.sensors[m], experiment_file)
print('INFO: Partial results stored in %s' % experiment_filename)
except Exception as e:
print(e)
print("WARNING: Thus failed")
print('INFO: Experiment run %d (%s = %s, measuring %s) took %s' %
(i + 1, parameter, value, measures,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def create_agents_selection_process_extension(store_IDs = False):
''' This function creates all possible agents and stores them in the agent
database. Optionally a file all_agent_IDs.pkl is stored with all IDs of
valid agents.
Kwargs:
store_IDs (bool): If True the agent IDs of all agents are stored in a
pickle file.
'''
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters = {'agent_initialization': 'create_and_store',
'filepath_agent_database': 'data/agent_database/all_agents/',
'info_printer': True, 'IDs_from_memory': False,
'selection_process': 'choice_model',
'selection_process_parameters':
{'Amsterdam': {'intercept': 1.13,
'distance': -3.52,
'charging_speed': -0.89,
'charging_fee': -0.50,
'parking_fee': -0.77},
'The Hague': {'intercept': 1.64,
'distance': -3.98,
'charging_speed': -1.11,
'charging_fee': -0.88,
'parking_fee': -1.72},
'Rotterdam': {'intercept': 1.53,
'distance': -4.04,
'charging_speed': -1.08,
'charging_fee': -1.55,
'parking_fee': 0},
'Utrecht': {'intercept': 1.48,
'distance': -3.19,
'charging_speed': -0.87,
'charging_fee': -3.55,
'parking_fee': 0}}
})
if store_IDs:
with open ('data/experiment_results/all_agent_IDs.pkl', 'wb') as agents_file:
pickle.dump(list(sim.agents.keys()), agents_file)
def create_agents(store_IDs = False, filepath_store_pickle_file = "data/agent_database/all_agents.pkl"):
''' This function creates all possible agents and stores them in the agent
database. Optionally a file all_agent_IDs.pkl is stored with all IDs of
valid agents.
Kwargs:
store_IDs (bool): If True the agent IDs of all agents are stored in a
pickle file.
'''
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters = {'agent_initialization': 'create_and_store',
'filepath_agent_database': 'data/agent_database/all_agents/',
'info_printer': True })
previous_time = time.process_time()
if store_IDs:
with open (filepath_store_pickle_file, 'wb') as agents_file:
pickle.dump(sim.agents, agents_file, pickle.HIGHEST_PROTOCOL)
new_time = time.process_time() - previous_time
if new_time < 60:
print('\tINFO: Stored agents in pickle file in %.2f seconds' % new_time)
elif new_time < 3600:
print('\tINFO: Stored agents in pickle file in %.2f minutes' % (new_time/60))
else:
print('\tINFO: Stored agents in pickle file in %.2f hours' % (new_time/3600))
def create_agents_battery_extension(store_IDs = False):
''' This function creates all possible agents and stores them in the agent
database. Optionally a file all_agent_IDs.pkl is stored with all IDs of
valid agents.
Kwargs:
store_IDs (bool): If True the agent IDs of all agents are stored in a
pickle file.
'''
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters = {'agent_initialization': 'create_and_store',
'filepath_agent_database': 'data/agent_database/all_non_changing_agents_bin60/',
'info_printer': True, 'IDs_from_agent_database': False, \
'start_date_training_data': "01-01-2014", \
'end_date_training_data': "01-01-2018", \
'start_date_test_data': "01-01-2014", \
'end_date_test_data': "01-01-2018", \
'bin_size_dist': 60})
if store_IDs:
with open ('data/experiment_results/all_agent_IDs_bin60.pkl', 'wb') as agents_file:
pickle.dump(list(sim.agents.keys()), agents_file)
def create_unmerged_general_data_and_environment():
''' This function creates all possible agents and stores them in the agent
database. Optionally a file all_agent_IDs.pkl is stored with all IDs of
valid agents.
Kwargs:
store_IDs (bool): If True the agent IDs of all agents are stored in a
pickle file.
'''
sim = simulation.Simulation("data/input_parameters/parameters_unmerged.json",
overwrite_parameters = {'agent_initialization': 'create_and_store',
'number_of_agents': 0,
"IDs_from_agent_database": False,
'filepath_agent_database': 'data/agent_database/all_agents/',
'info_printer': True})
def create_general_data_and_environment():
''' This function does the general preprocessing '''
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters = {'agent_initialization': 'create_and_store',
'number_of_agents': 0,
'filepath_agent_database': 'data/agent_database/all_agents/',
'info_printer': True,
"IDs_from_agent_database": False,
'general_preprocess': True,
'environment_from_memory': False})
def incidental_agents_experiments(number_of_agents, simulation_repeats, step, min_, max_):
print('INFO: Started incidental agents experiments with %d agents and %d reps' % \
(number_of_agents, simulation_repeats))
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
parameters_file = 'data/input_parameters/parameters.json'
parameters = [(number_of_agents, simulation_repeats, i, value, len(numpy.arange(min_, max_ + step, step))) \
for i, value in enumerate(list(numpy.arange(min_, max_ + step, step))[::-1])]
p = multiprocessing.Pool(MAX_CPUs)
p.map(inner_loop_incidental_agents_experiments, parameters)
print('INFO: Finished incidental agents experiments with %d agents and %d reps' % \
(number_of_agents, simulation_repeats))
print('INFO: Experiment took %s' %
get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def inner_loop_incidental_agents_experiments(args):
number_of_agents, repeats, i, percentage_incidental_users, max_runs = args
start_time = time.process_time()
print('INFO: Experiment run %d of %d (percentage = %s, agents = %s, reps = %s)' % (i + 1,
max_runs, percentage_incidental_users, number_of_agents, repeats))
selection_process_parameters = {'Amsterdam': {'intercept': 1.13,
'distance': -3.52,
'charging_speed': -0.89,
'charging_fee': -0.50,
'parking_fee': -0.77},
'The Hague': {'intercept': 1.64,
'distance': -3.98,
'charging_speed': -1.11,
'charging_fee': -0.88,
'parking_fee': -1.72},
'Rotterdam': {'intercept': 1.53,
'distance': -4.04,
'charging_speed': -1.08,
'charging_fee': -1.55,
'parking_fee': 0},
'Utrecht': {'intercept': 1.48,
'distance': -3.19,
'charging_speed': -0.87,
'charging_fee': -3.55,
'parking_fee': 0}}
try:
simulation_agents = pd.read_pickle("data/agent_database/agents_temp.pkl")
simulation_agents = random.sample(simulation_agents, number_of_agents)
except Exception as e:
print(e)
raise e
print('File not found.')
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters={'filepath_agent_database': 'data/agent_database/all_agents_car2go/',
"agent_initialization": "create_and_use",
"agent_creation_method": "random",
'number_of_agents': number_of_agents,
'info_printer': True,
'agent_IDs': [],
'selection_process': 'choice_model',
'rollout_strategy_to_use': 'none',
'selection_process_parameters': selection_process_parameters,
"non_habitual_agents": {"Amsterdam": percentage_incidental_users,
"Den Haag": percentage_incidental_users,
"Rotterdam": percentage_incidental_users,
"Utrecht": percentage_incidental_users}})
print('INFO: Experiment run %d of %d (percentage = %s, agents = %s, reps = %s) initialized at %s' % (i + 1,
max_runs, percentage_incidental_users, number_of_agents, repeats, datetime.datetime.now()))
try:
sim.repeat_simulation(repeat = repeats, measures = [])
# validation_selection_process_data = []
agent_sensors = []
for agent in sim.agents.values():
for center in agent.centers_css:
# agent_id, center, training_score, test_score, nr_cps, data_percentages = \
# agent.validation_selection_process(center, plot = False)
# validation_selection_process_data.append((agent_id, center, training_score, test_score, nr_cps, data_percentages))
agent_sensors.append((agent.ID, agent.sensors))
# number_of_agents = len(sim.agents.values())
# with open('indicental_users_experiments/validation_selection_process_data_%d_agents_%d_repeats_%.1f.pkl' % (number_of_agents, repeats, percentage_incidental_users), 'wb') as agent_file:
# pickle.dump(validation_selection_process_data, agent_file)
with open('data/indicental_users_experiments_all/agent_sensors_%d_agents_%d_repeats_%.1f.pkl' % (number_of_agents, repeats, percentage_incidental_users), 'wb') as agent_file:
pickle.dump(agent_sensors, agent_file)
except Exception as e:
print(e)
print('Thus failed.')
print('INFO: Experiment run %d of %d (percentage = %s, agents = %s, reps = %s) took %s' % (i + 1,
max_runs, percentage_incidental_users, number_of_agents, repeats,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def rollout_strategies_experiments(number_of_agents, simulation_repeats, rollout_strategies_repeats,
rollout_strategies, percentage_incidental_users, number_of_CPs_to_add_min,
number_of_CPs_to_add_max, number_of_CPs_to_add_step):
print('INFO: Started rollout strategies experiments with %d agents and %d reps' % \
(number_of_agents, simulation_repeats))
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
parameters_file = 'data/input_parameters/parameters.json'
parameters = []
i = 0
total = len(rollout_strategies) * len(range(number_of_CPs_to_add_min,
number_of_CPs_to_add_max + number_of_CPs_to_add_step, number_of_CPs_to_add_step)) * rollout_strategies_repeats
for rollout_strategies_repeat in range(rollout_strategies_repeats):
for rollout_strategy in rollout_strategies:
for number_of_CPs_to_add in range(number_of_CPs_to_add_min, number_of_CPs_to_add_max + number_of_CPs_to_add_step, number_of_CPs_to_add_step):
parameters.append((i, total, number_of_agents, simulation_repeats, rollout_strategy, \
number_of_CPs_to_add, rollout_strategies_repeat, percentage_incidental_users))
i += 1
print('INFO: %d experiments to be run.' % total)
p = multiprocessing.Pool(MAX_CPUs)
p.map(inner_loop_rollout_strategies_experiments, parameters)
print('INFO: Finished rollout strategies experiments with %d agents and %d reps' % \
(number_of_agents, simulation_repeats))
print('INFO: Experiment took %s' %
get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def inner_loop_rollout_strategies_experiments(args):
i, total, number_of_agents, simulation_repeats, rollout_strategy, \
number_of_CPs_to_add, rollout_strategies_repeat, percentage_incidental_users = args
start_time = time.process_time()
if os.path.exists('rollout_strategies_experiments/agent_sensors_%s_strategy_%d_cps_added_%d_agents_%d_incidental_users_%d_sim_repeats_%d_rollout_strategies_repeat.pkl' % (rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, simulation_repeats, rollout_strategies_repeat)):
print('INFO: This experiment was already run (rollout strategy = %s, cps added = %s, agents = %s, non-habitual agents = %s, rollout_strategies_repeat = %s)' %
(rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, rollout_strategies_repeat))
return
print('INFO: Experiment run %d of %d (rollout strategy = %s, cps added = %s, agents = %s, non-habitual agents = %s, rollout_strategies_repeat = %s)' %
(i, total, rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, rollout_strategies_repeat))
selection_process_parameters = {'Amsterdam': {'intercept': 1.13,
'distance': -3.52,
'charging_speed': -0.89,
'charging_fee': -0.50,
'parking_fee': -0.77},
'The Hague': {'intercept': 1.64,
'distance': -3.98,
'charging_speed': -1.11,
'charging_fee': -0.88,
'parking_fee': -1.72},
'Rotterdam': {'intercept': 1.53,
'distance': -4.04,
'charging_speed': -1.08,
'charging_fee': -1.55,
'parking_fee': 0},
'Utrecht': {'intercept': 1.48,
'distance': -3.19,
'charging_speed': -0.87,
'charging_fee': -3.55,
'parking_fee': 0}}
try:
simulation_agents = pd.read_pickle("data/experiment_results/all_agent_IDs2018.pkl")
number_of_agents = len(list(simulation_agents.values()))
simulation_agents = random.sample(simulation_agents.keys(), number_of_agents)
except Exception as e:
print(e)
raise e
print('File not found.')
sim = simulation.Simulation("data/input_parameters/parameters.json",
overwrite_parameters={'filepath_agent_database': "data/experiment_results/all_agent_IDs2018.pkl",
"agent_initialization": "load_and_use",
'number_of_agents': number_of_agents,
'info_printer': True,
'agent_IDs': simulation_agents,
'selection_process': 'choice_model',
'selection_process_parameters': selection_process_parameters,
"non_habitual_agents": {"Amsterdam": percentage_incidental_users,
"Den Haag": percentage_incidental_users,
"Rotterdam": percentage_incidental_users,
"Utrecht": percentage_incidental_users},
"number_of_CPs_to_add": {"Amsterdam": number_of_CPs_to_add,
"Den Haag": number_of_CPs_to_add,
"Rotterdam": number_of_CPs_to_add,
"Utrecht": number_of_CPs_to_add},
"rollout_strategy_to_use": rollout_strategy})
print('INFO: Experiment run %d of %d (rollout strategy = %s, cps added = %s, agents = %s, non-habitual agents = %s, rollout_strategies_repeat = %s) initialized at %s' %
(i, total, rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, rollout_strategies_repeat,
datetime.datetime.now()))
try:
sim.repeat_simulation(repeat = simulation_repeats, measures = [])
# validation_selection_process_data = []
agent_sensors = []
for agent in sim.agents.values():
for center in agent.centers_css:
# agent_id, center, training_score, test_score, nr_cps, data_percentages = \
# agent.validation_selection_process(center, plot = False)
# validation_selection_process_data.append((agent_id, center, training_score, test_score, nr_cps, data_percentages))
agent_sensors.append((agent.ID, agent.sensors))
# number_of_agents = len(sim.agents.values())
# with open('indicental_users_experiments/validation_selection_process_data_%d_agents_%d_repeats_%.1f.pkl' % (number_of_agents, repeats, percentage_incidental_users), 'wb') as agent_file:
# pickle.dump(validation_selection_process_data, agent_file)
with open('data/rollout_strategies_experiments/agent_sensors_%s_strategy_%d_cps_added_%d_agents_%d_incidental_users_%d_sim_repeats_%d_rollout_strategies_repeat.pkl' % (rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, simulation_repeats, rollout_strategies_repeat), 'wb') as agent_file:
pickle.dump(agent_sensors, agent_file)
except Exception as e:
print(e)
raise e
print('Thus failed.')
print('INFO: Experiment run %d of %d (rollout strategy = %s, cps added = %s, agents = %s, non-habitual agents = %s, rollout_strategies_repeat = %s) took %s' %
(i, total, rollout_strategy, number_of_CPs_to_add, number_of_agents, percentage_incidental_users, rollout_strategies_repeat,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def get_time_string(seconds):
''' This method converts an float input of seconds to a string that
captures the duration in English.
Args:
seconds (float): Amount of seconds.
Returns:
(str): String that captures the duration in English.
'''
if seconds < 60:
return '%.2f seconds' % seconds
if seconds < 3600:
return '%.2f minutes' % (seconds / 60)
return '%.2f hours' % (seconds / 3600)
def case_study_experiment(parameter, values, measures, simulation_repeats = -1,
number_of_agents = 30, method = 'relMAE', hack_parameters_file = None):
''' This function runs the simulation for various given values of the
specified parameter. The given measures are the output of the
experiment. The results are stored in the data/experiment_results
directory. A subdirectory is created (if it does not already exist),
containing the measure names and parameter name, in which the results
are stored.
Args:
parameter (str): The parameter to vary for the experiment.
values (List[int or float]): A list of values the parameter can take.
measures (List[str]): A list of measure names. Possible measures are
charging_station_validation, agent_validation,
time_per_simulation.
Kwargs:
number_of_agents (int): Amount of agents to run the experiment with.
Default is 30.
simulation_repeats (int): Amount of repeats for the experiment. Default
is 30.
'''
values = list(values)
if parameter == 'number_of_agents':
print('INFO: Started experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d simulation_repeats.' % \
simulation_repeats)
else:
print('INFO: Started experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%s agents and %d simulation_repeats.' % \
(number_of_agents, simulation_repeats))
start_time = time.process_time()
print('INFO: Start time: %s' % datetime.datetime.now())
if hack_parameters_file != None:
parameters_file = hack_parameters_file
else:
parameters_file = 'data/input_parameters/parameters.json'
parameters = [(parameters_file, parameter, i, len(values), value, number_of_agents,
simulation_repeats, measures, method) for i, value in enumerate(values)]
p = multiprocessing.Pool(MAX_CPUs)
p.map(case_study_inner_loop_experiment_simulation, parameters)
if parameter == 'number_of_agents':
print('INFO: Finished experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%d simulation_repeats.' % \
simulation_repeats)
else:
print('INFO: Finished experiment: simulation which varies %s ' %
parameter + 'with %s as measures. Varying values are %s. ' %
(measures, [val for val in values]) + '%s agents and %d simulation_repeats.' % \
(number_of_agents, simulation_repeats))
# print('INFO: Experiment took %s' %
# get_time_string(time.process_time() - start_time))
print('INFO: End time: %s' % datetime.datetime.now())
def case_study_inner_loop_experiment_simulation(args):
''' This function runs the simulation experiment for a single value
of a parameter measuring one or more measures. It is also in charge
of storing the results of the experiment for this value.
Args:
args (Tuple[Any]): Contains the arguments needed for the experiment,
namely in order:
- (str): The path to the parameters file;
- (str): The parameter to vary for the experiment;
- (int): The current experiment run number;
- (int): The total amount of values for the parameter;
- (int or float): The value of the parameter in this run;
- (int): Amount of repeats for the experiment;
- (List(str)): A list of measure names. Possible measures are
number_of_centers, average_number_of_charging_stations and
walking_preparedness;
- (str): Method of validation, either MAE or relMAE.
'''
parameters_file, parameter, i, max_runs, value, number_of_agents, simulation_repeats, measures, method = args
start_time = time.process_time()
print('INFO: Experiment run %d of %d (%s = %s, measuring %s)' % (i + 1,
max_runs, parameter, value, measures))
# NOTE change the database to correct database of bin size
# NOTE change the bin_size to correct value
sim = simulation.Simulation(parameters_file, measures = measures,
overwrite_parameters = {parameter: value,
'agent_initialization': 'load_and_use',
'filepath_agent_database': 'data/agent_database/all_agents_car2go/',
'number_of_agents': number_of_agents,
'bin_size_dist': 20,
'skip_low_fev_agents': True,
'skip_high_fev_agents': True,
'skip_unknown_agents': True,
'start_date_training_data': "01-01-2014",
'end_date_training_data': "01-01-2018",
'start_date_test_data': "01-01-2014",
'end_date_test_data': "01-01-2018"})
try:
if parameter == 'simulation_repeats':
simulation_repeats = value
sim.repeat_simulation(repeat = simulation_repeats, measures = measures,
method = method, display_progress = False)
for m in measures:
experiment_dir = 'data/experiment_results/experiment_simulation_measures_%s_varying_%s' % \
(m, parameter)
if not os.path.exists(experiment_dir):
os.makedirs(experiment_dir)
if parameter == 'number_of_agents':
experiment_filename = experiment_dir + '/%s_%s_%s_simulation_repeats.pkl' % (str(value), parameter, str(simulation_repeats))
elif parameter == 'transform_parameters':
experiment_filename = experiment_dir + '/%s_%s_%s_agents_%s_simulation_repeats.pkl' % (str(value['prob_no_transform']), parameter, str(number_of_agents), str(simulation_repeats))
else:
experiment_filename = experiment_dir + '/%s_%s_%s_agents_%s_simulation_repeats.pkl' % (str(value['prob_no_transform']), parameter, str(number_of_agents), str(simulation_repeats))
with open(experiment_filename, 'wb') as experiment_file:
pickle.dump(sim.sensors[m], experiment_file)
print('INFO: Partial results stored in %s' % experiment_filename)
except Exception as e:
print(e)
print("WARNING: Thus failed")
print('INFO: Experiment run %d (%s = %s, measuring %s) took %s' %
(i + 1, parameter, value, measures,
get_time_string(time.process_time() - start_time)))
print('INFO: End time: %s' % datetime.datetime.now())
def do_case_study_battery_size():
parameter = 'transform_parameters'
probs_no_transform = numpy.arange(0.0, 1.2, 0.20)
# fracs_to_high = numpy.arange(0.0, 1.2, 0.2)
values = []
# for p_no_transform in probs_no_transform:
# for f_to_high in fracs_to_high:
# prob_to_high = ( 1.0 - p_no_transform ) * f_to_high
# prob_to_low = ( 1.0 - p_no_transform ) * (1.0 - f_to_high)
# values.append({"prob_no_transform": p_no_transform,
# "prob_to_low_fev": prob_to_low,
# "prob_to_high_fev": prob_to_high})
for prob in probs_no_transform:
values.append({"prob_no_transform": prob,
"prob_to_low_fev": 0.0,
"prob_to_high_fev": 1 - prob})
# values.append({"prob_no_transform": 1.0,
# "prob_to_low_fev": 0.0,
# "prob_to_high_fev": 0.0})
measures = ['simulated_sessions']
number_of_agents, simulation_repeats = 30, 10
case_study_experiment(parameter, values, measures,
simulation_repeats = simulation_repeats,
number_of_agents = number_of_agents,
method = 'relMAE')
return
def main():
''' Validation transformation experiment '''
# parameter = 'transform_parameters'
# val1 = {"prob_no_transform": 0.0, "prob_to_low_fev": 1.0, "prob_to_high_fev": 0.0 }
# val2 = {"prob_no_transform": 0.0, "prob_to_low_fev": 0.0, "prob_to_high_fev": 1.0 }
# values = [val1, val2]
# measures = ['simulated_agent_sessions']
# number_of_agents, simulation_repeats = 10, 2
#
# experiment_simulation(parameter, values, measures,
# simulation_repeats = simulation_repeats,
# number_of_agents = number_of_agents,
# method = 'relMAE',
# hack_parameters_file = 'data/input_parameters/hack_parameters_file.json')
''' Case study battery size '''
# do_case_study_battery_size()