-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.py
3100 lines (2593 loc) · 148 KB
/
agent.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
'''
agent.py
Written by:
Seyla Wachlin
Igna Vermeulen
Updated by:
Jerome Mies
Jurjen Helmus
update contains
- failed connection attempts
Last updated August 2020
'''
import matplotlib
matplotlib.use("Pdf")
import matplotlib.pyplot as plt
import seaborn
import pandas
import numpy
import sys
import datetime
import pickle
import os
import time
import operator
import shapely
import bqplot
import ipywidgets
import ipyleaflet
import IPython
import random
import math
import number_of_choices_per_parameter
#sys.path.insert(0, 'nn/')
#from NN_utilities import load_model_sim
#from pprint import pprint
#from NN_SP_preprocess import preprocess_single_session
class Agent():
''' The Agent class deals with an agent using its three processes of
disconnecting, connecting and selecting charging stations.
Args:
args (Dict[str, Any]): Arguments which the agent needs. This contains:
'data_handler' (DataHandler): Instance of the DataHandler class;
'environment' (Environment): Instance of the Environment class;
'parameters' (Dict[str, Any]): The parameters of the agent that
were given in the input file;
'start_date_simulation' (DateTime): The start date of the
simulation;
'warmup_period' (TimeDelta): The duration of the warmup period;
'agent_initialization' (str): This attribute determines whether
to load agents from memory or to create new ones and store
them to memory. Options are 'create', 'create_and_use',
'create_and_store' and 'load_and_use'.
overwrite_parameters (Dict[str, Any]): Parameter values to use instead
of the values specified in the input file. Often used for
experiments. Parameters that can be overwritten can be found in the
readme.
info_printer (bool): Parameter to decide whether to print information
about run times.
agent_ID (str): The ID of the agent.
filepath_agent_database (str): Path to the agent database.
Kwargs:
measures (List[str]): A list of values to measure (usually for
experiments). Possible measures are number_of_centers,
number_of_charging_stations and walking_preparedness.
sim_sensors (Dict[str, List]): A dictionary containing measures as keys
and a list of their values of the run as value at that key.
Attributes:
ID (str): Unique identifier of the agent.
data_handler (DataHandler): Instance of DataHandler object.
environment (Environment): Instance of Environment object.
training_sessions (DataFrame): The training sessions of the agent.
test_sessions (DataFrame): The test sessions of the agent.
simulated_sessions (DataFrame): The simulated sessions of the agent.
is_connected (bool): Contains the state of the agent.
centers_css (Dict[Tuple[float, float], Dict[str, Any]]): Centers
(lon, lat) as keys and each center being a dictionary with the
keys 'habit' and 'distance'. The value of the habit key is a set
of charging stations (location keys), while the value of the
distance key is a dictionary with the charging stations
(location keys) as keys and their distance to the center
(in meters) as value.
original_centers_css (Dict[Tuple[float, float], Set]): Centers (lon, lat)
as keys and each value being a set of location keys of the charging
stations in that center.
centers_info (Dict[Tuple[float, float], Dict[str, Any]]): Centers
(lon, lat) as keys with their corresponding values a dictionary
with info about the center:
- nr_of_sessions_in_center: amount of sessions within center,
- center_nr: unique number of the center (for visualization),
disconnection_duration_dists (Dict[Tuple[float, float]: List[float]]): A
dictionary of disconnection duration distributions with centers as
keys and the distributions as values. The distributions are
lists of probabilities in each bin.
connection_duration_dists (Dict[Tuple[float, float]: List[float]]): A
dictionary of connection duration distributions with centers as
keys and the distributions as values. The distributions are
lists of probabilities in each bin.
arrival_dists (Dict[Tuple[float, float], List[float]]): A dictionary of
arrival distributions with the centers as keys. The distributions
are lists of probabilities in each bin.
activity_patterns_training (Dict[Tuple[float, float], List[float]]): A
dictionary of activity patterns based on the training data with the
centers as keys. The activity patterns are lists of probabilities
of activity in each bin.
activity_patterns_test (Dict[Tuple[float, float], List[float]]): A
dictionary of activity patterns based on the test data with the
centers as keys. The activity patterns are lists of probabilities
of activity in each bin.
preferences (Dict[Tuple[float, float], Dict[str, int]]): The tuples
(lon, lat) of the center as keys and as value a dictionary with
the preference for each charging station as value and the
charging station (location key) as key.
selection_process (str): 'habit_distance' or 'choice_model'.
selection_process_parameters (Dict[str, float] or
Dict[str, Dict[str, float]]): If selection_process is
'habit_distance', the key is 'habit_probability' and the value
the fraction of time the agent bases its
selection choice on its habitual preference (habit).
If the selection process is "choice_model" the dictionary
contains the a dictionary with keys "Amsterdam", "The Hague",
"Rotterdam" and "Utrecht". This dictionary should contain the
keys "intercept", "distance", "charging_speed", "charging_fee" and
"parking_fee" with the logit model coefficient values as values.
time_next_activity (DateTime): Time at which the next activity takes
place. The next activity can be either a disconnection or a
connection.
time_retry_center (int): Number of minutes to wait until retrying to
connect to a charging station in the active center when all
charging stations are currently occupied.
minimum_radius (float): Default maximum distance between
a center to a charging station in meters.
walking_preparedness (float): Maximum distance between a center to
a charging station in meters multiplied by 1.1. If this value is
lower than the minimum_radius, it default to the
minimum_radius
maximum_distance (float): Maximum distance between a center to
a charging station in meters.
active_center (Tuple[float, float]): Center (lon, lat) at which agent
is connected or plans to connect to.
active_cs (str): The location key of the charging station at which the
agent is connected.
history (List[Dict[str, Any]]): Each element of the history contains
a dictionary with information about the decision process for an
activity taken by the agent. The dictionary contains
the keys time, connected, next_center, disconnection_duration,
corrected_disconnection_duration, arrival_probs, time_next_activity,
centers.
start_date_simulation (DateTime): The start date of the simulation.
warmup_period (TimeDelta): The duration of the warmup period.
sensors (Dict[str, Any]): A dictionary containing observing information
about the agent. The keys and values are:
disconnection_duration_mistake_counters (List[int]): The number of
times a wrong disconnection duration was chosen in a run. This
duration is wrong when the agent tries to connect but all
centers have a probability of zero of starting to connect at
that time.
connection_duration_mistake_counters (List[int]): The number of
times a wrong connection duration was chosen in a run. This
duration is wrong when the agent has never disconnected at this
time (and therefore its disconnection duration distribution is
an empty distribution at this time).
selection_process_attempts (List[int]): The number of times per run
a charging station was selected which was already in use.
total_disconnections (List[int]): The number of times the agent
disconnected per run.
total_connections (List[int]): The number of times the agent
connected per run.
total_selections (List[int]): The number of times the agent selected
a charging station per run.
run_counter (int): The curent run number.
all_simulated_sessions (List[DataFrame]): A list containing the
simulated sessions (in form of a DataFrame) of all simulation runs
of the agent.
activity_patterns_training (List[float]): The activity patterns of
the training set of the agent.
activity_patterns_test (List[float]): The activity patterns of the
test set of the agent.
simulated_activity_patterns (List[float]): The activity
patterns simulated for the agent.
errors (Dict[str, Dict[Tuple[float, float], Dict[str, float]]]]): A
dictionary with the keys 'MEA' and 'relMAE'. Under these keys there
is a dictionary with centers (lon, lat) as keys and each of those
has a dictionary as value with as keys 'training' and 'test' and
as values the mean error of this data, center and error method.
car_type (str): The car type of the agent. Possible options are 'PHEV'
or 'FEV'.
transform_parameters (Dict[str, float]): Contains information about
which fractions of the (phev) population should be transformed to
either low battery fev or high battery fev agents. The keys are:
- prob_no_transform;
- prob_to_low_fev;
- prob_to_high_fev.
cs_zone_information (Dict[Tuple[float, float], Dict[str, str]])
'''
def __init__(self, args, info_printer, agent_ID, overwrite_parameters,
filepath_agent_database,
# cluster_model_1, cluster_model_2, cluster_model_3, cluster_model_4, cluster_model_5,
measures = [], sim_sensors = {}):
self.info_printer = info_printer
self.ID = agent_ID
self.simulation_parameters = args['simulation_parameters']
#self.previous_session = pandas.DataFrame(columns=current_columns)
# NOTE: feels like there should be a check_args() here
# NOTE 2: feels like a lot of the inits can be put here (environment, etc)
# NOTE one more: thought, with the 'load_and_use', should we check if the bin size fits the loaded agents?
self.data_handler = args['data_handler']
if not self._load_and_check_parameters(args['parameters'],
overwrite_parameters, args['agent_initialization']):
sys.exit()
self.cs_zone_information = {}
if 'time_per_initialization' in measures:
process_time_start = time.process_time()
if args['agent_initialization'] == 'create_and_use':
self.environment = args['environment']
self.warmup_period = args['warmup_period']
self.start_date_simulation = args['start_date_simulation']
if not self._load_and_check_parameters(args['parameters'],
overwrite_parameters,
args['agent_initialization']):
sys.exit()
if 'car2go' in self.ID:
self._load_sessions_car2go()
self._load_centers_car2go(args['parameters'])
self._load_distributions_car2go()
else:
self._load_sessions()
self._load_centers(args['parameters'])
self._load_distributions()
self.check_center_for_city()
self._load_additional_attributes()
self._reset_results()
transform_to = self._should_transform()
self._transform_agent(transform_to)
self.set_initial_state()
elif args['agent_initialization'] == 'create_and_store':
# print("Agent started to be created")
self.environment = args['environment']
self.warmup_period = args['warmup_period']
self.start_date_simulation = args['start_date_simulation']
if not self._load_and_check_parameters(args['parameters'],
overwrite_parameters,
args['agent_initialization']):
sys.exit()
if 'car2go' in self.ID:
self._load_sessions_car2go()
self._load_centers_car2go(args['parameters'])
self._load_distributions_car2go()
else:
self._load_sessions()
self._load_centers(args['parameters'])
self._load_distributions()
self.check_center_for_city()
self._load_additional_attributes()
my_agent_data = self._get_agent_data()
if self.simulation_parameters['agent_creation_method'] not in ['given', 'previous']:
# print(self.ID)
if 'car2go' in self.ID:
# print(self.ID)
# print(my_agent_data)
if not os.path.isfile(filepath_agent_database + str(self.ID)[:10] + '.pkl'):
with open(filepath_agent_database + str(self.ID)[:10] + '.pkl',
'wb') as agent_file:
pickle.dump(my_agent_data, agent_file)
else:
if not os.path.isfile(filepath_agent_database + str(self.ID) + '.pkl'):
with open(filepath_agent_database + str(self.ID) + '.pkl',
'wb') as agent_file:
pickle.dump(my_agent_data, agent_file)
elif args['agent_initialization'] == 'create':
self.data_handler = args['data_handler']
self.environment = args['environment']
self.warmup_period = args['warmup_period']
self.start_date_simulation = args['start_date_simulation']
if not self._load_and_check_parameters(args['parameters'],
overwrite_parameters,
args['agent_initialization']):
sys.exit()
if 'car2go' in self.ID:
self._load_sessions_car2go()
self._load_centers_car2go(args['parameters'])
self._load_distributions_car2go()
else:
self._load_sessions()
self._load_centers(args['parameters'])
self._load_distributions()
self._load_additional_attributes()
elif args['agent_initialization'] == 'load_and_use':
self.environment = args['environment']
self.warmup_period = args['warmup_period']
self.start_date_simulation = args['start_date_simulation']
if not self._load_and_check_parameters(args['parameters'],
overwrite_parameters,
args['agent_initialization']):
sys.exit()
# when loading data from pickle file, Car2go data is not always loaded and thus needs to come from
# folder with all individual agents, hence we have a different filepath_agent_database here
if not self.simulation_parameters['IDs_from_agent_database']:
filepath_agent_database_car2go = "data/agent_database/all_agents/"
if 'car2go' in self.ID:
self._load_sessions_car2go()
with open(filepath_agent_database_car2go + str(self.ID)[:10] + '.pkl', 'rb') \
as agent_file:
my_agent_data = pickle.load(agent_file)
self.start_date_agent = self.start_date_simulation
self._set_agent_data(my_agent_data)
self.check_center_for_city()
elif 'added' in self.ID:
pass
else:
raise Exception('WARNING: Load_and_use but not from agent_database but still this agent appears ' + \
'here: (%s). \n This should not happen.' % self.ID)
if self.simulation_parameters['IDs_from_agent_database']:
if self._agent_in_database(filepath_agent_database):
self._load_sessions()
agent_file = filepath_agent_database + str(self.ID) + '.pkl'
my_agent_data = pandas.read_pickle(agent_file)
self._set_agent_data(my_agent_data)
self._check_skip()
self.check_center_for_city()
elif 'car2go' in self.ID:
#last check if distances to cps are larger than the normal walking distance,
# if this is not the case, we need to redefine the centers_css of the car2go agent:
max_distance = 0
for center in self.centers_css:
for cs in self.centers_css[center]['distance']:
if self.centers_css[center]['distance'][cs] > max_distance:
max_distance = self.centers_css[center]['distance'][cs]
if max_distance < 501:
self._load_centers_car2go(args['parameters'])
elif 'car2go' not in self.ID:
raise Exception('WARNING: Agent (%s) does not exist in agent database.' %
self.ID)
self.start_date_agent = self.simulation_parameters['start_date_simulation']
self.end_date_agent = self.simulation_parameters['stop_condition_parameters']['max_time']
self._reset_results()
transform_to = self._should_transform()
self._transform_agent(transform_to)
self.set_initial_state()
else:
raise Exception('ERROR: Wrong input for agent_initialization.')
if 'number_of_centers' in measures:
sim_sensors['number_of_centers'].append(len(self.original_centers_css.keys()))
if 'number_of_centers_with_IDs' in measures:
sim_sensors['number_of_centers_with_IDs'].append((self.ID, len(self.original_centers_css.keys())))
if 'average_number_of_charging_stations' in measures:
average_nr_of_css = numpy.mean([len(css)
for center, css in self.original_centers_css.items()])
sim_sensors['average_number_of_charging_stations'].append(average_nr_of_css)
if 'average_number_of_charging_stations_with_IDs' in measures:
average_nr_of_css = numpy.mean([len(css)
for center, css in self.original_centers_css.items()])
sim_sensors['average_number_of_charging_stations_with_IDs'].append((self.ID, average_nr_of_css))
if 'walking_preparedness' in measures:
sim_sensors['walking_preparedness'].append(self.walking_preparedness)
if 'maximum_distance' in measures:
sim_sensors['maximum_distance'].append(self.maximum_distance)
if 'time_per_initialization' in measures:
sim_sensors['time_per_initialization'].append(time.process_time() - process_time_start)
if 'number_of_training_sessions_with_IDs' in measures:
sim_sensors['number_of_training_sessions_with_IDs'].append((self.ID, len(self.training_sessions)))
def _agent_in_database(self, filepath_agent_database):
''' This method checks if an agent is already in the agent database.
Args:
filepath_agent_database (str): Path to the agent database.
Returns:
(bool): True if the agent exists in the agent database.
'''
if 'car2go' in self.ID:
return os.path.isfile(filepath_agent_database + str(self.ID)[:10] + '.pkl')
else:
return os.path.isfile(filepath_agent_database + str(self.ID) + '.pkl')
def _load_sessions_car2go(self):
''' This method loads the sessions of the agent and stores them as
attributed.
Updates:
training_sessions
test_sessions
'''
self.training_sessions = self.data_handler.training_data.loc[
self.data_handler.training_data.ID == self.ID]
self.test_sessions = self.data_handler.test_data.loc[
self.data_handler.test_data.ID == self.ID]
self._get_disconnection_duration()
def _load_sessions(self):
''' This method loads the sessions of the agent and stores them as
attributed. Raises an exception when the agent has either too few
training sessions or too few test sessions.
Updates:
training_sessions
test_sessions
'''
agent_training_sessions = self.data_handler.training_data.loc[
self.data_handler.training_data.ID == self.ID]
self.test_sessions = self.data_handler.test_data.loc[
self.data_handler.test_data.ID == self.ID]
self.training_sessions = agent_training_sessions
# try:
# self.training_sessions = self.data_handler.check_gap_agent_sessions(
# agent_training_sessions)
# except:
# # NOTE: gap sessions checking fails when [NaT] comes out.
# raise Exception('WARNING: Failed to check gap agent sessions for %s.' %self.ID)
self.training_sessions = self.training_sessions.sort_values(
by = 'start_connection')
if len(self.training_sessions) < self.data_handler.minimum_nr_sessions_center:
raise Exception('WARNING: Too few sessions (%d) for agent ' %
len(self.training_sessions) + '(%s) in the training data.' %
self.ID)
if len(self.test_sessions) < self.data_handler.minimum_nr_sessions_center:
raise Exception('WARNING: Too few sessions (%d) for ' %
len(self.test_sessions) + 'agent (%s) in the test data.' %
self.ID)
self._get_disconnection_duration()
def _load_and_check_parameters(self, parameters, overwrite_parameters,
agent_initialization):
''' This method checks whether the parameters needed for the agent
contain correct values.
Args:
parameters (Dict[str, Any]): The parameters from the input file.
overwrite_parameters (Dict[str, Any]): The overwrite parameters.
agent_initialization (str): This attribute determines whether
to load agents from memory or to create new ones and store
them to memory. Options are 'create', 'create_and_use',
'create_and_store' and 'load_and_use'.
Updates:
selection_process
selection_process_parameters
time_retry_center
minimum_radius
Returns:
(bool): Returns True if all parameters are valid.
'''
if 'selection_process' in overwrite_parameters:
self.selection_process = overwrite_parameters['selection_process']
else:
self.selection_process = parameters['selection_process']
if 'selection_process_parameters' in overwrite_parameters:
self.selection_process_parameters = overwrite_parameters['selection_process_parameters']
else:
self.selection_process_parameters = parameters['selection_process_parameters']
if self.selection_process == 'habit_distance':
if not isinstance(self.selection_process_parameters, dict):
print('ERROR: selection_process_parameters (%s) is not a dictionary.' %
self.selection_process_parameters)
return False
if 'habit_probability' not in self.selection_process_parameters:
print('ERROR: habit_probability not in selection_process_parameters ' +
'when habit_distance is chosen as selection process.')
return False
if not isinstance(self.selection_process_parameters['habit_probability'], float):
print('ERROR: habit_probability (%s) is not a float.' %
str(self.selection_process_parameters['habit_probability']))
return False
if self.selection_process_parameters['habit_probability'] < 0 or \
self.selection_process_parameters['habit_probability'] > 1:
print('ERROR: habit_probability (%.2f) is not between 0 and 1.' %
self.selection_process_parameters['habit_probability'])
return False
elif self.selection_process == 'choice_model':
if not isinstance(self.selection_process_parameters, dict):
print('ERROR: selection_process_parameters (%s) is not a dictionary.' %
self.selection_process_parameters)
return False
for city in ['Amsterdam', 'The Hague', 'Rotterdam', 'Utrecht']:
if city not in self.selection_process_parameters:
print('ERROR: %s not in selection_process_parameters ' % city +
'when choice_model is chosen as selection process.')
return False
if not isinstance(self.selection_process_parameters[city], dict):
print('ERROR: selection_process_parameters[%s] (%s) is not a dictionary.' %
(city, self.selection_process_parameters))
return False
for key in ['intercept', 'distance', 'charging_speed', 'charging_fee', 'parking_fee']:
if key not in self.selection_process_parameters[city]:
print('ERROR: %s not in selection_process_parameters ' % key +
'when choice_model is chosen as selection process.')
return False
if not isinstance(self.selection_process_parameters[city][key], float) and \
not isinstance(self.selection_process_parameters[city][key], int):
print('ERROR: %s is not a float or int.' %
self.selection_process_parameters[city][key] +
'Its type is %s' % type(self.selection_process_parameters[city][key]))
return False
elif self.selection_process == 'strategy_model':
if not isinstance(self.selection_process_parameters, dict):
print('ERROR: selection_process_parameters (%s) is not a dictionary.' %
self.selection_process_parameters)
return False
if 'age_compensation' not in self.selection_process_parameters:
print('ERROR: age_compensation not in selection_process_parameters ' +
'when strategy_model is chosen as selection process.')
return False
if not isinstance(self.selection_process_parameters['age_compensation'], float):
print('ERROR: age_compensation (%s) is not a float.' %
str(self.selection_process_parameters['age_compensation']))
return False
if self.selection_process_parameters['age_compensation'] < 0 or \
self.selection_process_parameters['age_compensation'] > 1:
print('ERROR: age_compensation (%.2f) is not between 0 and 1.' %
self.selection_process_parameters['age_compensation'])
return False
elif self.selection_process == 'habit_nn':
pass
else:
print('ERROR: self.selection_process is not habit_distance nor choice_model.')
return False
if 'time_retry_center' in overwrite_parameters:
self.time_retry_center = overwrite_parameters['time_retry_center']
else:
self.time_retry_center = parameters['time_retry_center']
if not isinstance(self.time_retry_center, int):
print('ERROR: time_retry_center (%s) is not an int.' %
str(self.time_retry_center))
return False
if self.time_retry_center < 0:
print('ERROR: time_retry_center (%d) is negative.' %
self.time_retry_center)
return False
if self.time_retry_center < self.data_handler.bin_size_dist:
self.time_retry_center = self.data_handler.bin_size_dist
if 'minimum_radius' in overwrite_parameters:
self.minimum_radius = overwrite_parameters['minimum_radius']
else:
self.minimum_radius = parameters['minimum_radius']
if not isinstance(self.minimum_radius, int):
print('ERROR: minimum_radius (%s) is not an int.' %
str(self.minimum_radius))
return False
if self.minimum_radius < 0:
print('ERROR: minimum_radius (%d) is negative.' %
self.minimum_radius)
return False
try:
self.city_to_simulate
except AttributeError:
if 'city' in self.simulation_parameters:
self.city_to_simulate = self.simulation_parameters['city']
else:
print("WARNING: No specific city to simulate selected, will simulate all cities")
self.city_to_simulate = "all"
if self.city_to_simulate == ["Amsterdam", "The Hague", "Rotterdam", "Utrecht"]:
self.city_to_simulate == "all"
if not isinstance(self.city_to_simulate, str):
print('ERROR: city (%s) is not a string.' %
str(self.city_to_simulate))
return False
if self.city_to_simulate not in ["Amsterdam", "The Hague", "Rotterdam", "Utrecht", "all"]:
print("ERROR: Name of city unknown, not any of these: Amsterdam, The Hague, Rotterdam, Utrecht, all.")
return False
if 'transform_parameters' in overwrite_parameters:
transform_parameters = overwrite_parameters['transform_parameters']
elif 'transform_parameters' in parameters:
transform_parameters = parameters['transform_parameters']
else:
print('ERROR: No transform_parameters in parameters.')
return False
if 'prob_no_transform' not in transform_parameters:
print('ERROR: No prob_no_transform defined in transform_parameters.')
return False
if not isinstance(transform_parameters['prob_no_transform'], float):
print('ERROR: prob_no_transform in transform_parameters is not a float.')
return False
if 'prob_to_low_fev' not in transform_parameters and \
transform_parameters['prob_no_transform'] != 1.0:
print('ERROR: No prob_to_low_fev defined in transform_parameters.')
return False
if 'prob_to_high_fev' not in transform_parameters and \
transform_parameters['prob_no_transform'] != 1.0:
print('ERROR: No prob_to_high_fev defined in transform_parameters.')
return False
if not isinstance(transform_parameters['prob_to_low_fev'], float):
print('ERROR: prob_to_low_fev in transform_parameters is not a float.')
return False
if not isinstance(transform_parameters['prob_to_high_fev'], float):
print('ERROR: prob_to_high_fev in transform_parameters is not a float.')
return False
summed_probs = (transform_parameters['prob_no_transform'] +
transform_parameters['prob_to_low_fev'] +
transform_parameters['prob_to_high_fev'])
if abs(1.0 - summed_probs) > 0.001:
print('ERROR: The probabilities in transform parameters do not sum ' +
'to 1.0. Namely prob_no_transform (%.2f) + ' %
transform_parameters['prob_no_transform'] +
'prob_to_low_fev (%.2f) + ' %
transform_parameters['prob_to_low_fev'] +
'prob_to_high_fev (%.2f) is %.2f and does not equal 1.0.' %
(transform_parameters['prob_to_high_fev'], summed_probs))
return False
if agent_initialization not in (['load_and_use', 'create_and_use']) and \
transform_parameters['prob_no_transform'] < 1.0:
print('ERROR: Agent initalization method (%s) is not supported in ' %
agent_initialization + 'combination with transforming agents.' +
'If prob_no_transform (%.2f) is below 1.0, agent_initalization ' %
transform_parameters['prob_no_transform'] + 'should be either ' +
'load_and_use or create_and_use.')
return False
self.transform_parameters = transform_parameters
if 'skip_high_fev_agents' in overwrite_parameters:
skip_high_fev_agents = overwrite_parameters['skip_high_fev_agents']
elif 'skip_high_fev_agents' in parameters:
skip_high_fev_agents = parameters['skip_high_fev_agents']
else:
print('ERROR: No skip_high_fev_agents in parameters.')
return False
if not isinstance(skip_high_fev_agents, bool):
print('ERROR: skip_high_fev_agents is not a boolean.')
return False
if 'skip_low_fev_agents' in overwrite_parameters:
skip_low_fev_agents = overwrite_parameters['skip_low_fev_agents']
elif 'skip_high_fev_agents' in parameters:
skip_low_fev_agents = parameters['skip_low_fev_agents']
else:
print('ERROR: No skip_low_fev_agents in parameters.')
return False
if not isinstance(skip_low_fev_agents, bool):
print('ERROR: skip_low_fev_agents is not a boolean.')
return False
if 'skip_phev_agents' in overwrite_parameters:
skip_phev_agents = overwrite_parameters['skip_phev_agents']
elif 'skip_phev_agents' in parameters:
skip_phev_agents = parameters['skip_phev_agents']
else:
print('ERROR: No skip_phev_agents in parameters.')
return False
if not isinstance(skip_phev_agents, bool):
print('ERROR: skip_phev_agents is not a boolean.')
return False
if 'skip_unknown_agents' in overwrite_parameters:
skip_unknown_agents = overwrite_parameters['skip_unknown_agents']
elif 'skip_unknown_agents' in parameters:
skip_unknown_agents = parameters['skip_unknown_agents']
else:
print('ERROR: No skip_unknown_agents in parameters.')
return False
if not isinstance(skip_unknown_agents, bool):
print('ERROR: skip_unknown_agents is not a boolean.')
return False
if skip_phev_agents and self.transform_parameters['prob_no_transform'] != 1.0:
print('ERROR: skip_phev_agents is True while prob_no_transform is 1.0.')
return False
if (skip_low_fev_agents or skip_high_fev_agents) and agent_initialization != 'load_and_use':
print('ERROR: skip_low_fev_agents and skip_high_fev_agents is only supported for load_and_use agent initialization.')
return False
self.skip_phev_agents = skip_phev_agents
self.skip_low_fev_agents = skip_low_fev_agents
self.skip_high_fev_agents = skip_high_fev_agents
self.skip_unknown_agents = skip_unknown_agents
return True
def _load_centers_car2go(self, parameters):
''' This method loads the centers of the agent and updates the
relevant attributes. Raises an exception when the agent has
zero centers or when these centers are not used frequently in the
test data.
Args:
parameters (Dict[str, Any]): The parameters of the agent that were
given in the input file.
Updates:
centers_css
centers_info
original_centers_css
walking_preparedness
'''
if 'ams' in self.ID:
city = 'Amsterdam'
center_loc = (4.896253, 52.372356)
elif 'den' in self.ID:
city = 'Den Haag'
center_loc = (4.292700, 52.074588)
elif 'rot' in self.ID:
city = 'Rotterdam'
center_loc = (4.483730, 51.929376)
elif 'utr' in self.ID:
city = 'Utrecht'
center_loc = (5.120255, 52.093844)
else:
print('WARNING: unknown city, car2go in Amsterdam.')
city = 'Amsterdam'
center_loc = (4.896253, 52.372356)
self.centers_css = {center_loc: {'habit': [], 'distance': []}}
self.original_centers_css = {center_loc: {'habit': []}}
self.walking_preparedness = 10000
self.maximum_distance = 10000
for center in self.centers_css:
self.centers_css[center]['distance'] = \
self.environment.get_nearby_css(self.centers_css, center,
self.data_handler.training_data, self.walking_preparedness,
city = city)
self.centers_css[center]['habit'] = tuple(self.centers_css[center]['distance'].keys())
self.original_centers_css[center]['habit'] = self.centers_css[center]['habit']
self.centers_info = {}
self.centers_info[center_loc] = {'nr_of_sessions_in_center': len(self.training_sessions), 'center_nr': 0}
def _load_centers(self, parameters):
''' This method loads the centers of the agent and updates the
relevant attributes. Raises an exception when the agent has
zero centers or when these centers are not used frequently in the
test data.
Args:
parameters (Dict[str, Any]): The parameters of the agent that were
given in the input file.
Updates:
centers_css
centers_info
original_centers_css
walking_preparedness
'''
if self.city_to_simulate == "all":
self.centers_css, self.centers_info = self.data_handler.get_centers(
self.training_sessions)
else:
self.centers_css, self.centers_info = self.data_handler.get_centers(
self.training_sessions.loc[self.training_sessions['city'] == self.city_to_simulate])
self.check_center_for_city()
if len(self.centers_css.keys()) == 0:
raise Exception('WARNING: Agent (%s) does not have any centers.' %
self.ID)
self.original_centers_css = {center:
set(self.centers_css[center]['habit']) for center in self.centers_css}
if not self._enough_sessions_in_test():
raise Exception('WARNING: Too few sessions for agent ' +
'(%s) in test data for centers.' %
self.ID)
self.walking_preparedness = self._get_walking_preparedness()
for center in self.centers_css:
self.centers_css[center]['distance'] = \
self.environment.get_nearby_css(self.centers_css, center,
self.data_handler.training_data, self.walking_preparedness, city = self.centers_info[center]['city'])
def _enough_sessions_in_test(self):
''' This method checks if there are enough sessions in the test data
for each of the agent's centers.
Returns:
(bool): True if the centers have enough sessions in the test data
and False otherwise.
'''
for center in self.centers_css:
sessions_in_center = 0
for cs in self.centers_css[center]['habit']:
sessions_in_center += len(self.test_sessions.loc[
self.test_sessions['location_key'] == cs])
if sessions_in_center < self.data_handler.minimum_nr_sessions_center:
return False
return True
def _get_walking_preparedness(self):
''' This method determines the walking preparedness of the agent. We
define the walking preparedness as the maximum distance the agent
has anywhere from a center to a charging station in that center
multiplied with 1.1. If this results in something less than the
default walking preparedness, then we set the agent's walking
preparedness to this default value.
Updates:
maximum_distance (float)
Returns:
walking_preparedness (float): The walking preparedness for the agent.
'''
try:
self.maximum_distance = max([self.environment.get_distance(cs, center)
for center in self.centers_css
for cs in self.centers_css[center]['habit']])
except (ValueError, KeyError):
self.maximum_distance = self.minimum_radius
return self.minimum_radius
if self.maximum_distance < self.minimum_radius:
return self.minimum_radius
else:
return self.maximum_distance * 1.1
def _get_disconnection_duration(self):
''' This method will update the disconnection duration based on the times between connections.
Updates:
training_sessions
'''
self.training_sessions = self.training_sessions.sort_values(by='start_connection', inplace = False)
self.training_sessions.start_connection = self.training_sessions.start_connection.shift(-1)
if len(self.training_sessions) == 0:
self.training_sessions['disconnection_duration'] = []
else:
self.training_sessions['disconnection_duration'] = self.training_sessions.apply(lambda row:
row.start_connection - row.end_connection, axis = 1)
def _load_distributions_car2go(self):
''' This method loads the distributions of the agent based on its
training data and centers.
Updates:
activity_patterns_training
activity_patterns_test
overall_activity_pattern
disconnection_duration_dists
connection_duration_dists
arrival_dists
'''
path_to_file = 'data/car2go_behavior/car2go_behavior_dists.pkl'
with open(path_to_file, 'rb') as data_file:
[activity_pattern_norm, \
arrival_dist_norm, connection_duration_dists, \
disconnection_durations_for_car2go] = pandas.read_pickle(data_file, compression = None)
self.activity_patterns_training = {center: activity_pattern_norm for center in self.centers_css}
self.activity_patterns_test = {center: activity_pattern_norm for center in self.centers_css}
for center in self.centers_css:
self.activity_patterns_training[center] /= numpy.sum(
self.activity_patterns_training[center])
self.activity_patterns_test[center] /= numpy.sum(
self.activity_patterns_test[center])
# first_appearance = self.training_sessions['start_connection'].iloc[0].date()
# last_appearance = self.training_sessions['start_connection'].iloc[-1].date()
# number_of_days_active = (last_appearance - first_appearance).days
# self.overall_activity_pattern = self.data_handler.get_activity_pattern(
# self.training_sessions) / number_of_days_active
self.overall_activity_pattern = activity_pattern_norm
self.disconnection_duration_dists = disconnection_durations_for_car2go
self.connection_duration_dists = {center: connection_duration_dists for center in self.centers_css}
self.arrival_dists = {center: arrival_dist_norm for center in self.centers_css}
def _load_distributions(self):
''' This method loads the distributions of the agent based on its
training data and centers.
Updates:
activity_patterns_training
activity_patterns_test
overall_activity_pattern
disconnection_duration_dists
connection_duration_dists
arrival_dists
'''
self.activity_patterns_training = self.data_handler.get_activity_patterns_centers(
self.training_sessions, self.centers_css)
# print('got activity_patterns_training %s' % datetime.datetime.now())
self.activity_patterns_test = \
self.data_handler.get_activity_patterns_centers(self.test_sessions,
self.centers_css)
# print('got activity_patterns_test %s' % datetime.datetime.now())
for center in self.centers_css:
self.activity_patterns_training[center] /= numpy.sum(
self.activity_patterns_training[center])
# print('got activity_patterns_training for center %s' % datetime.datetime.now())
self.activity_patterns_test[center] /= numpy.sum(
self.activity_patterns_test[center])
# print('got activity_patterns_test for center %s' % datetime.datetime.now())
first_appearance = self.training_sessions['start_connection'].iloc[0].date()
last_appearance = self.training_sessions['start_connection'].iloc[-1].date()
number_of_days_active = (last_appearance - first_appearance).days
self.overall_activity_pattern = self.data_handler.get_activity_pattern(
self.training_sessions) / number_of_days_active
# print('norm activity_patterns_training %s' % datetime.datetime.now())
self.disconnection_duration_dists = self.data_handler.get_disconnection_duration_dists(
self.training_sessions)
# print('got disconnection_duration_dists %s' % datetime.datetime.now())
self.connection_duration_dists = self.data_handler.get_connection_duration_dists(
self.training_sessions, self.centers_css)
# print('got connection_duration_dists %s' % datetime.datetime.now())
self.arrival_dists = self.data_handler.get_arrival_dists(
self.training_sessions,self.centers_css)
# print('got arrival_dists at %s' % datetime.datetime.now())
def _load_additional_attributes(self):
''' This method updates additional attributes of the agent. This
includes updating the car type and battery category of the agent.
Updates:
car_type
battery_category
'''
self.car_type = "Unknown"
if 'car2go' in self.ID:
self.car_type = 'FEV'
self.battery_category = 'fev_low'
return
battery_size = numpy.percentile(self.training_sessions.kWh, 98)
if self.ID in self.data_handler.car_type_data.index:
self.car_type = self.data_handler.car_type_data.get_value(self.ID, 'TYPE')
if self.car_type == "PHEV":
self.battery_category = "phev"
elif self.car_type == "Unknown":
self.battery_category = "unknown"
elif self.car_type == "FEV":
if battery_size <= 33:
self.battery_category = "fev_low"
else:
self.battery_category = "fev_high"
def _reset_results(self):
''' This method sets the agent attributes containing info about the
simulated sessions and sensors of the run.
Updates:
all_simulated_sessions
sensors
'''
self.errors = {'MAE': {}, 'relMAE': {}}
self.all_simulated_sessions = []
self.sensors = {'disconnection_duration_mistake_counters': [],
'connection_duration_mistake_counters': [],
'selection_process_attempts': [], 'total_disconnections': [],