Path: blob/main/tools/contributed/sumopy/coremodules/demand/virtualpop.py
169689 views
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo1# Copyright (C) 2016-2025 German Aerospace Center (DLR) and others.2# SUMOPy module3# Copyright (C) 2012-2021 University of Bologna - DICAM4# This program and the accompanying materials are made available under the5# terms of the Eclipse Public License 2.0 which is available at6# https://www.eclipse.org/legal/epl-2.0/7# This Source Code may also be made available under the following Secondary8# Licenses when the conditions for such availability set forth in the Eclipse9# Public License 2.0 are satisfied: GNU General Public License, version 210# or later which is available at11# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html12# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later1314# @file virtualpop.py15# @author Joerg Schweizer16# @date 20121718import os19import sys20import numpy as np21from numpy import random22import agilepy.lib_base.classman as cm23import agilepy.lib_base.arrayman as am24import agilepy.lib_base.xmlman as xm25from agilepy.lib_base.misc import random_choice, get_inversemap26from agilepy.lib_base.processes import Process2728#from coremodules.modules_common import *29from coremodules.network.network import SumoIdsConf, MODES30from coremodules.network import routing31from coremodules.simulation import results as res32from demandbase import *33import virtualpop_results as res343536GENDERS = {'male': 0, 'female': 1, 'unknown': -1}3738OCCUPATIONS = {'unknown': -1,39'worker': 1,40'student': 2,41'employee': 3,42'public employee': 4,43'selfemployed': 5,44'pensioneer': 6,45'other': 746}474849class Activities(am.ArrayObjman):50# https://sumo.dlr.de/docs/Networks/PlainXML.html#edge_descriptions51def __init__(self, ident, virtualpop, **kwargs):5253self._init_objman(ident=ident, parent=virtualpop, name='Activities',54info='Activity database of persons contains type, time, duration and location of activities.',55version=0.0,56**kwargs)5758self._init_attributes()5960def _init_attributes(self):6162# activity types now in demand63activitytypes = self.parent.get_demand().activitytypes64self.add_col(am.IdsArrayConf('ids_activitytype', activitytypes,65groupnames=['parameters'],66choices=activitytypes.names.get_indexmap(),67name='Type',68info='Type of activity performed during the stop.',69#xmltag = 'actType',70#xmlmap = get_inversemap( activitytypes.names.get_indexmap()),71))7273# attention, this may cause trouble during init if74# facilities are not yet initialized75self.add_col(am.IdsArrayConf('ids_facility', self.parent.get_scenario().landuse.facilities,76groupnames=['parameters'],77name='ID fac.',78info='Facility ID where activity takes place.',79#activitytype = 'home',80))8182# self.add_col(am.ArrayConf( 'descriptions', '',83# dtype = np.object,84# perm='rw',85# is_index = True,86# name = 'Description',87# info = 'Description of activity.',88# ))8990# self.add_col(am.IdlistsArrayConf( 'ids_landusetypes', self.parent.get_landuse().landusetypes,91# name = 'Landuse types',92# info = "Landuse type IDs, eher this activity type can take place.",93# ))9495self.add_col(am.ArrayConf('hours_begin_earliest', 0.0,96dtype=np.float32,97groupnames=['parameters'],98perm='rw',99name='Earliest hour begin',100unit='h',101info='Earliest hour when this activity can begin.',102))103104self.add_col(am.ArrayConf('hours_begin_latest', 1.0,105dtype=np.float32,106groupnames=['parameters'],107perm='rw',108name='Latest begin hour',109unit='h',110info='Latest hour when this activity can begin.',111))112113self.add_col(am.ArrayConf('durations_min', 6.0,114dtype=np.float32,115groupnames=['parameters'],116perm='rw',117name='Min. Duration',118unit='h',119info='Minimum activity duration for a person within a day.',120))121122self.add_col(am.ArrayConf('durations_max', 8.0,123dtype=np.float32,124groupnames=['parameters'],125perm='rw',126name='Max. Duration',127unit='h',128info='Maximum activity duration for a person within a day.',129))130131def get_hours_end_earliest(self, ids):132return self.hours_begin_earliest[ids]+self.durations_min[ids]133134def get_hours_end_latest(self, ids):135return self.hours_begin_latest[ids]+self.durations_max[ids]136137def get_durations(self, ids, pdf='unit'):138durations = np.zeros(len(ids), dtype=np.float32)139i = 0140for time_start, time_end in zip(141np.array(self.durations_min[ids]*3600, dtype=np.int32),142np.array(self.durations_max[ids]*3600, dtype=np.int32)):143144durations[i] = np.random.randint(time_start, time_end, 1)145i += 1146return durations147148def get_times_end(self, ids, pdf='unit'):149"""150Returns an array with activity ending time for the151given activity IDs.152The ending time is calculated by drawing random samples153from the departure interval.154The random samples are drawn according to the given probability155density function, pdf.156157Input arguments:158ids: integer array with activity IDs159pdf: probability density function 'unit'|'normal'160161Returned arguments:162times_end: integer array with departure times163"""164times_end = np.zeros(len(ids), dtype=np.float32)165i = 0166for time_start, time_end in zip(167np.array(self.get_hours_end_earliest(ids)*3600, dtype=np.int32),168np.array(self.get_hours_end_latest(ids)*3600, dtype=np.int32)):169170times_end[i] = np.random.randint(time_start, time_end, 1)171i += 1172173return times_end174175def get_times_begin(self, ids, pdf='unit'):176"""177Returns an array with beginning time for the178given activity IDs.179The begin time is calculated by drawing random samples180from the departure interval.181The random samples are drawn according to the given probability182density function, pdf.183184Input arguments:185ids: integer array with activity IDs186pdf: probability density function 'unit'|'normal'187188Returned arguments:189times_begin: integer array with departure times190"""191times_begin = np.zeros(len(ids), dtype=np.float32)192i = 0193for time_start, time_end in zip(194np.array(self.get_hours_begin_earliest(ids)*3600, dtype=np.int32),195np.array(self.get_hours_begin_latest(ids)*3600, dtype=np.int32)):196197times_begin[i] = np.random.randint(time_start, time_end, 1)198i += 1199200return times_begin201202def add_activities(self, ids_activitytype, ids_facility,203hours_begin_earliest=None,204hours_begin_latest=None,205durations_min=None,206durations_max=None):207208n_pers = len(ids_activitytype)209activitytypes = self.ids_activitytype.get_linktab()210211if hours_begin_earliest is None:212# np.ones(n_pers, dtype = np.float32)*213hours_begin_earliest = activitytypes.hours_begin_earliest[ids_activitytype]214215if hours_begin_latest is None:216hours_begin_latest = activitytypes.hours_begin_latest[ids_activitytype]217218if durations_min is None:219durations_min = activitytypes.durations_min[ids_activitytype]220221if durations_max is None:222durations_max = activitytypes.durations_max[ids_activitytype]223224ids = self.add_rows(n=n_pers,225ids_activitytype=ids_activitytype,226ids_facility=ids_facility,227hours_begin_earliest=hours_begin_earliest,228hours_begin_latest=hours_begin_latest,229durations_min=durations_min,230durations_max=durations_max,231)232233return ids234235236class IndividualAutos(am.ArrayObjman):237238def __init__(self, ident, population, **kwargs):239# print 'individualvehicle vtype id_default',vtypes.ids_sumo.get_id_from_index('passenger1')240self._init_objman(ident=ident,241parent=population,242name='Indiv. Autos',243info='Individual auto database. These are privately owned autos.',244**kwargs)245246self._init_attributes()247self._init_constants()248249def _init_constants(self):250251self.do_not_save_attrs(['mode', 'mode_prefix',252'_edges', '_lanes', '_individualvehicle', '_ids_vtype_sumo', '_ids_edge_sumo',253'_id_mode', '_get_laneid_allowed', '_get_sumoinfo_from_id_lane',254'_space_access', '_parking', '_time_after_unboarding',255])256257def def_mode(self):258self.mode = 'passenger'259self.mode_prefix = 'iauto'260261def _init_attributes(self):262vtypes = self.parent.get_demand().vtypes263self.def_mode()264265ids_vtype = vtypes.select_by_mode(mode=self.mode)266267self.add(cm.AttrConf('space_access', 0.5,268groupnames=['options'],269perm='rw',270name='Space access',271unit='m',272info='Space to access vehicles at parkings. This is typically less than the vehicle length.',273))274275self.add(cm.AttrConf('time_after_unboarding', 5,276groupnames=['options'],277perm='rw',278name='time after unboarding',279unit='s',280info='Time the vehicle waits before disappearing after unboarding.',281))282283self.add_col(am.IdsArrayConf('ids_vtype', vtypes,284id_default=ids_vtype[0],285groupnames=['state'],286name='Veh. type',287info='Vehicle type.',288#xmltag = 'type',289))290291self.add_col(am.IdsArrayConf('ids_person', self.parent,292groupnames=['state'],293name='ID person',294info='ID of person who ownes the vehicle.',295))296297self.add_col(am.ArrayConf('times_exec', 0.0,298name='Exec time',299info='Total route execution time from simulation run of last plan.',300unit='s',301))302303def get_virtualpop(self):304return self.parent305306def get_ids_veh_pop(self):307"""308To be overridden by other individual vehicle types.309"""310return self.get_virtualpop().ids_iauto311312def get_share(self, is_abs=False):313n_veh = len(self)314if is_abs:315return n_veh316else:317return float(n_veh)/float(len(self.get_virtualpop()))318319def get_stagetable(self):320return self.parent.get_plans().get_stagetable('autorides')321322def get_demand(self):323return self.parent.parent324325def clear_vehicles(self):326self.get_ids_veh_pop()[self.ids_person.get_value()] = -1327self.clear()328329def assign_to_persons(self, ids_person):330# print 'assign_to_persons',len(ids_person),self.mode331# self.clear_vehicles()332#ids_person_noveh = set(ids_person).difference(set(self.ids_person))333n_new = len(ids_person)334#335# this call is selecting a veh id aof the specific mode336# according to its share within this mode337ids_vtype = self.get_demand().vtypes.generate_vtypes_for_mode(n_new, mode=self.mode)338339# print ' ids_vtype',ids_vtype340ids_veh = self.add_rows(n=n_new,341ids_person=ids_person,342ids_vtype=ids_vtype,343)344self.get_ids_veh_pop()[ids_person] = ids_veh345return ids_veh346347def get_vtypes(self):348"""349Returns a set with all used vehicle types.350"""351# print 'Vehicles_individual.get_vtypes',self.cols.vtype352return set(self.ids_vtype.get_value())353354def get_id_veh_xml(self, id_veh, id_stage):355return self.mode_prefix + '.%s.%s' % (id_veh, id_stage)356357def get_id_line_xml(self, id_veh):358return self.mode_prefix + '.%s' % (id_veh)359360def get_id_from_id_sumo(self, id_veh_sumo):361# print 'get_id_from_id_sumo',id_veh_sumo,id_veh_sumo.split('.'),self.mode_prefix362if len(id_veh_sumo.split('.')) == 3:363prefix, id_veh, id_stage = id_veh_sumo.split('.')364if prefix == self.mode_prefix:365return int(id_veh)366else:367return -1368return -1369370def get_info_from_id_sumo(self, id_veh_sumo):371if len(id_veh_sumo.split('.')) == 3:372prefix, id_veh, id_stage = id_veh_sumo.split('.')373if prefix == self.mode_prefix:374return int(id_veh), int(id_stage)375else:376return -1, -1377return -1, -1378379# def append_ride(self, id_veh, id_ride):380# ids_ride = self.ids_rides[id_veh]381# if ids_ride is None:382# self.ids_rides[id_veh] = [id_ride]383# else:384# ids_ride.append(id_ride)385386def prepare_write_xml(self, is_route=True, is_plain=False):387"""388Prepare xml export. Must return export function.389"""390virtualpop = self.get_virtualpop()391scenario = virtualpop.get_scenario()392#plans = virtualpop.get_plans()393394self._rides = self.get_stagetable()395self._edges = scenario.net.edges396self._lanes = scenario.net.lanes397#self._individualvehicle = virtualpop.get_ibikes()398self._ids_vtype_sumo = scenario.demand.vtypes.ids_sumo399self._ids_edge_sumo = self._edges.ids_sumo400self._id_mode = scenario.net.modes.get_id_mode(self.mode)401self._get_laneid_allowed = self._edges.get_laneid_allowed402self._get_sumoinfo_from_id_lane = scenario.net.lanes.get_sumoinfo_from_id_lane403self._space_access = self.space_access.get_value()404#self._time_veh_wait_after_stop = 3600405self._parking = virtualpop.get_landuse().parking406self._time_after_unboarding = self.time_after_unboarding.get_value()407408# TODO: here we'd need also a case with is_plain and is_route409if is_plain:410return self.write_xml_no_line411412elif is_route:413return self.write_xml414else:415return self.write_xml_noroute416417def get_id_veh(self, id_stage):418return self._rides.ids_iauto[id_stage]419420def write_xml_no_line(self, fd, id_stage, time_begin, indent=2):421# same as write_xml, but without id_line, route and stops422423# TODO: actually this should go in individualvehicle424#time_veh_wait_after_stop = 3600425#plans = self.get_plans()426#walkstages = plans.get_stagetable('walks')427#rides = plans.get_stagetable('autorides')428#activitystages = plans.get_stagetable('activities')429430rides = self._rides431#lanes = self._lanes432parking = self._parking433#net = self.get_net()434#lanes = net.lanes435#edges = net.edges436#ind_ride = rides.get_inds(id_stage)437id_veh = self.get_id_veh(id_stage)438#individualvehicle = self._iveh439id_vtype = self.ids_vtype[id_veh]440441# id_veh_ride,442# ids_vtypes_iveh[id_veh],443# ids_edges_rides_arr[ind_ride],444# ids_parking_from_rides_arr[ind_ride],445# ids_parking_to_rides_arr[ind_ride],446447id_parking_from = rides.ids_parking_from[id_stage]448id_lane_from = parking.ids_lane[id_parking_from]449#laneindex_from = self._lanes.indexes[id_lane_from]450pos_from = parking.positions[id_parking_from]451452id_parking_to = rides.ids_parking_to[id_stage]453id_lane_to = parking.ids_lane[id_parking_to]454#laneindex_to = self._lanes.indexes[id_lane_to]455pos_to = parking.positions[id_parking_to]456457# write unique veh ID to prevent confusion with other veh declarations458fd.write(xm.start('trip id="%s"' % self.get_id_veh_xml(id_veh, id_stage), indent+2))459460# get start time of first stage of the plan461#id_plan = rides.ids_plan[id_stage]462#stages0, id_stage0 = self.get_plans().stagelists[id_plan][0]463464# this is the time when the vehicle appers in the scenario465fd.write(xm.num('depart', '%.d' % rides.times_init[id_stage]))466#fd.write(xm.num('depart', '%.d'%stages0.times_start[id_stage0]))467468fd.write(xm.num('type', self._ids_vtype_sumo[id_vtype]))469470# no line471#fd.write(xm.num('line', self.get_id_line_xml(id_veh) ))472473fd.write(xm.num('from', self._ids_edge_sumo[rides.ids_edges[id_stage]][0]))474fd.write(xm.num('to', self._ids_edge_sumo[rides.ids_edges[id_stage]][-1]))475476fd.write(xm.num('departPos', pos_from))477fd.write(xm.num('departLane', self._lanes.indexes[id_lane_from]))478479fd.write(xm.stop())480481# no route482# fd.write(xm.start('route',indent+4))483# print ' edgeindex[ids_edge]',edgeindex[ids_edge]484# fd.write(xm.arr('edges',self._ids_edge_sumo[rides.ids_edges[id_stage]]))485486# no stops487488fd.write(xm.end('trip', indent+2))489490def write_xml(self, fd, id_stage, time_begin, indent=2):491492# TODO: actually this should go in individualvehicle493#time_veh_wait_after_stop = 3600494#plans = self.get_plans()495#walkstages = plans.get_stagetable('walks')496#rides = plans.get_stagetable('autorides')497#activitystages = plans.get_stagetable('activities')498499rides = self._rides500#lanes = self._lanes501parking = self._parking502#net = self.get_net()503#lanes = net.lanes504#edges = net.edges505#ind_ride = rides.get_inds(id_stage)506id_veh = self.get_id_veh(id_stage)507#individualvehicle = self._iveh508id_vtype = self.ids_vtype[id_veh]509510# id_veh_ride,511# ids_vtypes_iveh[id_veh],512# ids_edges_rides_arr[ind_ride],513# ids_parking_from_rides_arr[ind_ride],514# ids_parking_to_rides_arr[ind_ride],515516id_parking_from = rides.ids_parking_from[id_stage]517id_lane_from = parking.ids_lane[id_parking_from]518#laneindex_from = self._lanes.indexes[id_lane_from]519pos_from = parking.positions[id_parking_from]520521id_parking_to = rides.ids_parking_to[id_stage]522id_lane_to = parking.ids_lane[id_parking_to]523#laneindex_to = self._lanes.indexes[id_lane_to]524pos_to = parking.positions[id_parking_to]525526# write unique veh ID to prevent confusion with other veh declarations527fd.write(xm.start('vehicle id="%s"' % self.get_id_veh_xml(id_veh, id_stage), indent+2))528529# get start time of first stage of the plan530#id_plan = rides.ids_plan[id_stage]531#stages0, id_stage0 = self.get_plans().stagelists[id_plan][0]532533# this is the time when the vehicle appers in the scenario534fd.write(xm.num('depart', '%.d' % rides.times_init[id_stage]))535#fd.write(xm.num('depart', '%.d'%stages0.times_start[id_stage0]))536537fd.write(xm.num('type', self._ids_vtype_sumo[id_vtype]))538fd.write(xm.num('line', self.get_id_line_xml(id_veh)))539fd.write(xm.num('departPos', pos_from))540fd.write(xm.num('departLane', self._lanes.indexes[id_lane_from]))541542fd.write(xm.stop())543544# write route545fd.write(xm.start('route', indent+4))546# print ' edgeindex[ids_edge]',edgeindex[ids_edge]547fd.write(xm.arr('edges', self._ids_edge_sumo[rides.ids_edges[id_stage]]))548549# does not seem to have an effect, always starts at base????550#fd.write(xm.num('departPos', pos_from))551#fd.write(xm.num('departLane', laneindex_from ))552fd.write(xm.stopit())553554# write depart stop555fd.write(xm.start('stop', indent+4))556#id_lane = self._lanes.ids_edge[id_lane_from]557fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane_from)))558# in 0.31 the vehicle will wait until after this duration559# so it will be removed unless it will get a timeout function560#fd.write(xm.num('duration', time_veh_wait_after_stop))561fd.write(xm.num('startPos', pos_from - parking.lengths[id_parking_from]))562fd.write(xm.num('endPos', pos_from))563fd.write(xm.num('triggered', "True"))564565# chrashes with parking=True in 0.30!566# however if not parked the vhcle is blocking the traffic567# while waiting: workaround: delay departure to be shure that person already arrived568569fd.write(xm.num('parking', "True")) # in windows 0.30 parked vehicles do not depart!!570#fd.write(xm.num('parking', "False"))571fd.write(xm.stopit())572573# write arrival stop574fd.write(xm.start('stop', indent+4))575fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane_to)))576fd.write(xm.num('duration', self._time_after_unboarding)) # for unboarding only577fd.write(xm.num('startPos', pos_to - parking.lengths[id_parking_to]))578fd.write(xm.num('endPos', pos_to))579#fd.write(xm.num('triggered', "True"))580fd.write(xm.stopit())581582fd.write(xm.end('vehicle', indent+2))583584def write_xml_noroute(self, fd, id_stage, time_begin, indent=2):585586# TODO: actually this should go in individualvehicle587#time_veh_wait_after_stop = 3600588#plans = self.get_plans()589#walkstages = plans.get_stagetable('walks')590#rides = plans.get_stagetable('autorides')591#activitystages = plans.get_stagetable('activities')592593rides = self._rides594#lanes = self._lanes595parking = self._parking596#net = self.get_net()597#lanes = net.lanes598#edges = net.edges599#ind_ride = rides.get_inds(id_stage)600id_veh = self.get_id_veh(id_stage)601#individualvehicle = self._iveh602id_vtype = self.ids_vtype[id_veh]603604# id_veh_ride,605# ids_vtypes_iveh[id_veh],606# ids_edges_rides_arr[ind_ride],607# ids_parking_from_rides_arr[ind_ride],608# ids_parking_to_rides_arr[ind_ride],609610id_parking_from = rides.ids_parking_from[id_stage]611id_lane_from = parking.ids_lane[id_parking_from]612#laneindex_from = self._lanes.indexes[id_lane_from]613pos_from = parking.positions[id_parking_from]614615id_parking_to = rides.ids_parking_to[id_stage]616id_lane_to = parking.ids_lane[id_parking_to]617#laneindex_to = self._lanes.indexes[id_lane_to]618pos_to = parking.positions[id_parking_to]619620# write unique veh ID to prevent confusion with other veh declarations621fd.write(xm.start('trip id="%s"' % self.get_id_veh_xml(id_veh, id_stage), indent+2))622623# get start time of first stage of the plan624#id_plan = rides.ids_plan[id_stage]625#stages0, id_stage0 = self.get_plans().stagelists[id_plan][0]626627# this is the time when the vehicle appers in the scenario628fd.write(xm.num('depart', '%.d' % rides.times_init[id_stage]))629#fd.write(xm.num('depart', '%.d'%stages0.times_start[id_stage0]))630631fd.write(xm.num('type', self._ids_vtype_sumo[id_vtype]))632fd.write(xm.num('line', self.get_id_line_xml(id_veh)))633634fd.write(xm.num('from', self._ids_edge_sumo[rides.ids_edges[id_stage]][0]))635fd.write(xm.num('to', self._ids_edge_sumo[rides.ids_edges[id_stage]][-1]))636637fd.write(xm.num('departPos', pos_from))638fd.write(xm.num('departLane', self._lanes.indexes[id_lane_from]))639640fd.write(xm.stop())641642# write route643# fd.write(xm.start('route',indent+4))644# print ' edgeindex[ids_edge]',edgeindex[ids_edge]645# fd.write(xm.arr('edges',self._ids_edge_sumo[rides.ids_edges[id_stage]]))646647# does not seem to have an effect, always starts at base????648#fd.write(xm.num('departPos', pos_from))649#fd.write(xm.num('departLane', laneindex_from ))650# fd.write(xm.stopit())651652# write depart stop653fd.write(xm.start('stop', indent+4))654#id_lane = self._lanes.ids_edge[id_lane_from]655fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane_from)))656# in 0.31 the vehicle will wait until after this duration657# so it will be removed unless it will get a timeout function658#fd.write(xm.num('duration', time_veh_wait_after_stop))659fd.write(xm.num('startPos', pos_from - parking.lengths[id_parking_from]))660fd.write(xm.num('endPos', pos_from))661fd.write(xm.num('triggered', "True"))662663# chrashes with parking=True in 0.30!664# however if not parked the vhcle is blocking the traffic665# while waiting: workaround: delay departure to be shure that person already arrived666667fd.write(xm.num('parking', "True")) # in windows 0.30 parked vehicles do not depart!!668#fd.write(xm.num('parking', "False"))669fd.write(xm.stopit())670671# write arrival stop672fd.write(xm.start('stop', indent+4))673fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane_to)))674fd.write(xm.num('duration', self._time_after_unboarding)) # for unboarding only675fd.write(xm.num('startPos', pos_to - parking.lengths[id_parking_to]))676fd.write(xm.num('endPos', pos_to))677#fd.write(xm.num('triggered', "True"))678fd.write(xm.stopit())679680fd.write(xm.end('trip', indent+2))681682683class IndividualBikes(IndividualAutos):684685def __init__(self, ident, population, **kwargs):686# print 'individualvehicle vtype id_default',vtypes.ids_sumo.get_id_from_index('passenger1')687self._init_objman(ident=ident,688parent=population,689name='Indiv. Bikes',690info='Individual bike database. These are privately owned bikes.',691**kwargs)692self._init_attributes()693self._init_constants()694695def _init_attributes(self):696697IndividualAutos._init_attributes(self)698699def _init_constants(self):700701self.do_not_save_attrs(['mode', 'mode_prefix',702'_edges', '_ids_vtype_sumo', '_ids_edge_sumo',703'_id_mode', '_get_laneid_allowed', '_get_sumoinfo_from_id_lane',704'_space_access',705])706707def def_mode(self):708self.mode = 'bicycle'709self.mode_prefix = 'ibike'710711def get_ids_veh_pop(self):712"""713To be overridden by other individual vehicle types.714"""715return self.parent.ids_ibike716717def get_stagetable(self):718return self.parent.get_plans().get_stagetable('bikerides')719720def get_id_veh(self, id_stage):721return self._rides.ids_ibike[id_stage]722723def prepare_write_xml(self, is_route=True, is_plain=False):724"""725Prepare xml export. Must return export function.726"""727virtualpop = self.get_virtualpop()728scenario = virtualpop.get_scenario()729#plans = virtualpop.get_plans()730self._rides = self.get_stagetable()731self._edges = scenario.net.edges732#self._individualvehicle = virtualpop.get_ibikes()733self._ids_vtype_sumo = scenario.demand.vtypes.ids_sumo734self._ids_edge_sumo = self._edges.ids_sumo735self._id_mode = scenario.net.modes.get_id_mode(self.mode)736self._get_laneid_allowed = self._edges.get_laneid_allowed737self._get_sumoinfo_from_id_lane = scenario.net.lanes.get_sumoinfo_from_id_lane738self._space_access = self.space_access.get_value()739if is_plain:740return self.write_xml_no_line741else:742return self.write_xml743744# def _limit_pos(self,pos,id_edge):745746def write_xml_no_line(self, fd, id_stage, time_begin, indent=2):747rides = self._rides748id_veh = self.get_id_veh(id_stage)749# print 'write_xml',id_stage, time_begin,self.get_id_veh_xml(id_veh, id_stage)750# print ' ids_edge_from,ids_edge_to',rides.ids_edge_from[id_stage],rides.ids_edge_to[id_stage],self._get_laneid_allowed( rides.ids_edge_from[id_stage], self._id_mode),self._get_laneid_allowed( rides.ids_edge_to[id_stage], self._id_mode)751752# TODO: actually this should go in individualvehicle753#time_veh_wait_after_stop = 3600754#plans = self.get_plans()755#walkstages = plans.get_stagetable('walks')756#rides = plans.get_stagetable('bikerides')757#activitystages = plans.get_stagetable('activities')758759# for debug only:760#virtualpop = self.get_virtualpop()761#ids_edge_sumo = virtualpop.get_net().edges.ids_sumo762763#parking = self.get_landuse().parking764#net = self.get_net()765#lanes = net.lanes766#edges = net.edges767768#ind_ride = rides.get_inds(id_stage)769770#individualvehicle = self.get_ibikes()771id_vtype = self.ids_vtype[id_veh]772773# id_veh_ride,774# ids_vtypes_iveh[id_veh],775# ids_edges_rides_arr[ind_ride],776# ids_parking_from_rides_arr[ind_ride],777# ids_parking_to_rides_arr[ind_ride],778779#id_parking_from = rides.ids_parking_from[id_stage]780#id_lane_from = parking.ids_lane[id_parking_from]781#laneindex_from = lanes.indexes[id_lane_from]782#pos_from = parking.positions[id_parking_from]783784#id_parking_to = rides.ids_parking_to[id_stage]785#id_lane_to = parking.ids_lane[id_parking_to]786#laneindex_to = lanes.indexes[id_lane_to]787#pos_to = parking.positions[id_parking_to]788789# write unique veh ID to prevent confusion with other veh declarations790fd.write(xm.start('trip id="%s"' % self.get_id_veh_xml(id_veh, id_stage), indent+2))791792# get start time of first stage of the plan793#id_plan = rides.ids_plan[id_stage]794#stages0, id_stage0 = self.get_plans().stagelists[id_plan][0]795796# this is the time when the vehicle appers in the scenario797#fd.write(xm.num('depart', '%.d'%rides.times_init[id_stage]))798fd.write(xm.num('depart', '%.d' % time_begin))799fd.write(xm.num('type', self._ids_vtype_sumo[id_vtype]))800#fd.write(xm.num('line', self.get_id_line_xml(id_veh) ))801#fd.write(xm.num('departPos', pos_from))802#fd.write(xm.num('departLane', laneindex_from ))803fd.write(xm.num('from', self._ids_edge_sumo[rides.ids_edge_from[id_stage]]))804fd.write(xm.num('to', self._ids_edge_sumo[rides.ids_edge_to[id_stage]]))805pos_from = rides.positions_from[id_stage]806pos_to = rides.positions_to[id_stage]807fd.write(xm.num('departPos', pos_from))808fd.write(xm.num('arrivalPos', pos_to))809fd.write(xm.num('departLane', 'best'))810811fd.write(xm.stop())812813# no route814815# no stops written here816817fd.write(xm.end('trip', indent+2))818819def write_xml(self, fd, id_stage, time_begin, indent=2):820rides = self._rides821id_veh = self.get_id_veh(id_stage)822# print 'write_xml',id_stage, time_begin,self.get_id_veh_xml(id_veh, id_stage)823# print ' ids_edge_from,ids_edge_to',rides.ids_edge_from[id_stage],rides.ids_edge_to[id_stage],self._get_laneid_allowed( rides.ids_edge_from[id_stage], self._id_mode),self._get_laneid_allowed( rides.ids_edge_to[id_stage], self._id_mode)824825# TODO: actually this should go in individualvehicle826#time_veh_wait_after_stop = 3600827#plans = self.get_plans()828#walkstages = plans.get_stagetable('walks')829#rides = plans.get_stagetable('bikerides')830#activitystages = plans.get_stagetable('activities')831832# for debug only:833#virtualpop = self.get_virtualpop()834#ids_edge_sumo = virtualpop.get_net().edges.ids_sumo835836#parking = self.get_landuse().parking837#net = self.get_net()838#lanes = net.lanes839#edges = net.edges840841#ind_ride = rides.get_inds(id_stage)842843#individualvehicle = self.get_ibikes()844id_vtype = self.ids_vtype[id_veh]845846# id_veh_ride,847# ids_vtypes_iveh[id_veh],848# ids_edges_rides_arr[ind_ride],849# ids_parking_from_rides_arr[ind_ride],850# ids_parking_to_rides_arr[ind_ride],851852#id_parking_from = rides.ids_parking_from[id_stage]853#id_lane_from = parking.ids_lane[id_parking_from]854#laneindex_from = lanes.indexes[id_lane_from]855#pos_from = parking.positions[id_parking_from]856857#id_parking_to = rides.ids_parking_to[id_stage]858#id_lane_to = parking.ids_lane[id_parking_to]859#laneindex_to = lanes.indexes[id_lane_to]860#pos_to = parking.positions[id_parking_to]861862# write unique veh ID to prevent confusion with other veh declarations863fd.write(xm.start('vehicle id="%s"' % self.get_id_veh_xml(id_veh, id_stage), indent+2))864865# get start time of first stage of the plan866#id_plan = rides.ids_plan[id_stage]867#stages0, id_stage0 = self.get_plans().stagelists[id_plan][0]868869# this is the time when the vehicle appers in the scenario870#fd.write(xm.num('depart', '%.d'%rides.times_init[id_stage]))871fd.write(xm.num('depart', '%.d' % time_begin))872fd.write(xm.num('type', self._ids_vtype_sumo[id_vtype]))873fd.write(xm.num('line', self.get_id_line_xml(id_veh)))874#fd.write(xm.num('departPos', pos_from))875#fd.write(xm.num('departLane', laneindex_from ))876fd.write(xm.num('from', self._ids_edge_sumo[rides.ids_edge_from[id_stage]]))877fd.write(xm.num('to', self._ids_edge_sumo[rides.ids_edge_to[id_stage]]))878pos_from = rides.positions_from[id_stage]879pos_to = rides.positions_to[id_stage]880fd.write(xm.num('departPos', pos_from))881fd.write(xm.num('arrivalPos', pos_to))882fd.write(xm.num('departLane', 'best'))883884fd.write(xm.stop())885886# write route887fd.write(xm.start('route', indent+4))888# print ' ids_edges',rides.ids_edges[id_stage]889# print ' ids_sumo',self._ids_edge_sumo[rides.ids_edges[id_stage]]890fd.write(xm.arr('edges', self._ids_edge_sumo[rides.ids_edges[id_stage]]))891# fd.write(xm.arr('edges',edges.ids_sumo[rides.ids_edges[id_stage]]))892893# does not seem to have an effect, always starts at base????894895#id_edge = rides.ids_edge_from[id_stage]896# print ' id_lane',id_lane,self._get_sumoinfo_from_id_lane(id_lane),'id_edge',id_edge,ids_edge_sumo[id_edge]897898fd.write(xm.stopit())899900# write depart stop901fd.write(xm.start('stop', indent+4))902id_lane = self._get_laneid_allowed(rides.ids_edge_from[id_stage], self._id_mode)903fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane)))904# in 0.31 the vehicle will wait until after this duration905# so it will be removed unless it will get a timeout function906#fd.write(xm.num('duration', time_veh_wait_after_stop))907if pos_from > self._space_access:908fd.write(xm.num('startPos', pos_from - self._space_access))909fd.write(xm.num('endPos', pos_from+self._space_access))910else:911fd.write(xm.num('startPos', 0.1*pos_from))912fd.write(xm.num('endPos', pos_from+self._space_access))913914fd.write(xm.num('triggered', "True"))915916# chrashes with parking=True in 0.30!917# however if not parked the vhcle is blocking the traffic918# while waiting: workaround: delay departure to be shure that person already arrived919920fd.write(xm.num('parking', 'True')) # in windows 0.30 parked vehicles do not depart!!921#fd.write(xm.num('parking', "False"))922fd.write(xm.stopit())923924# write arrival stop925fd.write(xm.start('stop', indent+4))926927id_lane = self._get_laneid_allowed(rides.ids_edge_to[id_stage], self._id_mode)928#id_edge = rides.ids_edge_to[id_stage]929# print ' id_lane',id_lane,self._get_sumoinfo_from_id_lane(id_lane),'id_edge',id_edge,ids_edge_sumo[id_edge]930931fd.write(xm.num('lane', self._get_sumoinfo_from_id_lane(id_lane)))932fd.write(xm.num('duration', 5)) # for unboarding only933if pos_to > self._space_access:934fd.write(xm.num('startPos', pos_to - self._space_access))935fd.write(xm.num('endPos', pos_to))936else:937fd.write(xm.num('startPos', 0.1*pos_to))938fd.write(xm.num('endPos', pos_to))939#fd.write(xm.num('triggered', "True"))940fd.write(xm.stopit())941942fd.write(xm.end('vehicle', indent+2))943944945class IndividualMotorcycles(IndividualBikes):946947def __init__(self, ident, population, **kwargs):948# print 'individualvehicle vtype id_default',vtypes.ids_sumo.get_id_from_index('passenger1')949self._init_objman(ident=ident,950parent=population,951name='Indiv. Moto',952info='Individual Motorcycle/moped database. These are privately owned motorcycles.',953**kwargs)954IndividualBikes._init_attributes(self)955IndividualBikes._init_constants(self)956957def def_mode(self):958self.mode = 'motorcycle'959self.mode_prefix = 'imoto'960961def get_ids_veh_pop(self):962"""963To be overridden by other individual vehicle types.964"""965return self.parent.ids_imoto966967def get_stagetable(self):968return self.parent.get_plans().get_stagetable('motorides')969970def get_id_veh(self, id_stage):971return self._rides.ids_imoto[id_stage]972973974class StrategyMixin(cm.BaseObjman):975def __init__(self, ident, parent=None,976name='Strategy mixin', info='Info on strategy.',977**kwargs):978"""979To be overridden.980"""981# attention parent is the Strategies table982self._init_objman(ident, parent, **kwargs)983attrsman = self.set_attrsman(cm.Attrsman(self))984985def _init_attributes(self, **kwargs):986# print 'StrategyMixin._init_attributes'987attrsman = self.get_attrsman()988989def get_id_strategy(self):990return self.parent.names.get_id_from_index(self.get_ident())991992def get_scenario(self):993return self.parent.parent.get_scenario()994995def get_activities(self):996return self.parent.parent.get_activities()997998def get_virtualpop(self):999return self.parent.parent10001001def get_plans(self):1002return self.parent.parent.plans10031004def clip_positions(self, positions, ids_edge):1005lengths = self.get_scenario().net.edges.lengths[ids_edge]1006# print 'clip_positions',positions.shape,ids_edge.shape,lengths.shape1007positions_clip = np.clip(positions, self.dist_node_min*np.ones(len(positions),1008dtype=np.float32), lengths-self.dist_node_min)1009inds = lengths < 2*self.dist_node_min1010# print ' inds.shape',inds.shape,positions_clip.shape1011positions_clip[inds] = 0.5*lengths[inds]1012return positions_clip10131014def _init_attributes_strategy(self, **kwargs):1015attrsman = self.get_attrsman()1016self.dist_node_min = attrsman.add(cm.AttrConf('dist_node_min', kwargs.get('dist_node_min', 40.0),1017groupnames=['options'],1018perm='rw',1019name='Min. dist to nodes',1020unit='m',1021info='Minimum distance between starting position and node center.',1022))10231024def get_utility_specific(self, id_plan):1025"""Method returns a strategy specific Utility. Here simly a constant is returned. This constant needs to be defined as attribute of the specific strategy"""10261027return 0.010281029# def _init_constants_strategy(self):1030# #print '_init_constants_strategy'1031# modes = self.get_virtualpop().get_scenario().net.modes1032# self._id_mode_bike = modes.get_id_mode('bicycle')1033# self._id_mode_auto = modes.get_id_mode('passenger')1034# self._id_mode_moto = modes.get_id_mode('motorcycle')1035# self.get_attrsman().do_not_save_attrs([1036# '_id_mode_bike','_id_mode_auto','_id_mode_moto',1037# ])1038# print ' _id_mode_auto',self._id_mode_auto10391040# def are_feasible(self, ids_person):1041# """1042# Returns a bool vector, with True values for1043# persons where this strategy can be applied.1044# """1045# return []10461047# def is_feasible(self, id_person):1048# """1049# Returns True if this strategy is feasible for this person.1050# Overriden by specific strategy.1051# """1052# return False10531054def preevaluate(self, ids_person):1055"""1056Preevaluation strategies for person IDs in vector ids_person.10571058Returns a preevaluation vector with a preevaluation value1059for each person ID. The values of the preevaluation vector are as follows:1060-1 : Strategy cannot be applied10610 : Stategy can be applied, but the preferred mode is not used10621 : Stategy can be applied, and preferred mode is part of the strategy10632 : Strategy uses predomunantly preferred mode10641065"""1066return zeros(len(ids_person), dtype=np.int32)10671068def plan(self, ids_person, logger=None, **kwargs):1069"""1070Generates a plan for these person according to this strategie.1071Overriden by specific strategy.1072"""1073pass107410751076class NoneStrategy(StrategyMixin):1077def __init__(self, ident, parent=None,1078name='None strategy',1079info='With this strategy, no mobility plan is generated.',1080**kwargs):10811082self._init_objman(ident, parent, name=name, info=info, **kwargs)1083attrsman = self.set_attrsman(cm.Attrsman(self))108410851086class WalkStrategy(StrategyMixin):1087def __init__(self, ident, parent=None,1088name='Walk Strategy',1089info='With this strategy, the person walks to all destinations.',1090version=0.1,1091**kwargs):10921093self._init_objman(ident, parent, name=name, info=info, **kwargs)1094attrsman = self.set_attrsman(cm.Attrsman(self))1095# specific init1096self._init_attributes()1097self._init_constants()10981099def _init_attributes(self, **kwargs):1100# print 'StrategyMixin._init_attributes'1101attrsman = self.get_attrsman()11021103self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', -0.0556),1104groupnames=['options'],1105perm='rw',1106name='Utility constant for walk strategy',1107info='Constant to calculate utility: U = Const + value_of_time*time_exec',1108))11091110self.is_walk_filter = attrsman.add(cm.AttrConf('is_walk_filter', kwargs.get('is_walk_filter', False),1111groupnames=['options'],1112name='Walk Filter',1113info=""" Enable the Walk filter.1114If it is True : Generate walk plans only for people who respect the max distance parameter.1115If it is False: Generate walk plans for all virtual population.1116""",1117))11181119# if hasattr(self,'max_dist_fac'):1120# dist_fac_max_default = self.max_dist_fac1121# attrsman.delete('max_dist_fac')1122# else:1123# dist_fac_max_default = kwargs.get('dist_fac_max',500.0)11241125self.dist_fac_max = attrsman.add(cm.AttrConf('dist_fac_max', kwargs.get('dist_fac_max', 500.0),1126groupnames=['options'],1127perm='rw',1128name='Max distance facilities',1129unit='m',1130info="""Max distance between origin and destination facilities corrisponding to the first and second activity.1131If the line of sight distance is greater than this distance, the walk plan will not be created.1132Will be only applied to those who have not walking as preferred mode.1133""",1134))11351136# if self.get_version() < 0.1:1137# self.set_version(0.1)11381139def _init_constants(self):1140#virtualpop = self.get_virtualpop()1141#stagetables = virtualpop.get_stagetables()11421143#self._walkstages = stagetables.get_stagetable('walks')1144#self._ridestages = stagetables.get_stagetable('rides')1145#self._activitystages = stagetables.get_stagetable('activities')11461147#self._plans = virtualpop.get_plans()1148#1149# print 'AutoStrategy._init_constants'1150# print dir(self)1151# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])11521153modes = self.get_virtualpop().get_scenario().net.modes1154self._id_mode_bike = modes.get_id_mode('bicycle')1155self._id_mode_auto = modes.get_id_mode('passenger')1156self._id_mode_moto = modes.get_id_mode('motorcycle')1157self._id_mode_bus = modes.get_id_mode('bus')1158self._id_mode_ped = modes.get_id_mode('pedestrian')1159self.get_attrsman().do_not_save_attrs([1160'_id_mode_bike', '_id_mode_auto', '_id_mode_moto',1161'_id_mode_bus', '_id_mode_ped',1162])11631164def get_utility_specific(self, id_plan):1165return self.utility_constant11661167def preevaluate(self, ids_person):1168"""1169Preevaluation strategies for person IDs in vector ids_person.11701171Returns a preevaluation vector with a preevaluation value1172for each person ID. The values of the preevaluation vector are as follows:1173-1 : Strategy cannot be applied11740 : Stategy can be applied, but the preferred mode is not used11751 : Stategy can be applied, and preferred mode is part of the strategy11762 : Strategy uses predomunantly preferred mode11771178"""1179n_pers = len(ids_person)1180persons = self.get_virtualpop()1181preeval = np.zeros(n_pers, dtype=np.int32)11821183# TODO: here we could exclude by age or distance facilities-stops11841185# put 0 for persons whose preference is not walking, but can walk (everybody can walk)1186preeval[persons.ids_mode_preferred[ids_person] != self._id_mode_ped] = 011871188# put 2 for persons whose preference is walking1189preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_ped] = 211901191# in case1192if self.is_walk_filter:11931194max_dist_fac_sqr = self.dist_fac_max**211951196vp = self.get_virtualpop()1197scenario = vp.get_scenario()11981199facilities = scenario.landuse.facilities1200centroids = facilities.centroids1201activities = vp.get_activities()12021203ids_pers_filter = ids_person[persons.ids_mode_preferred[ids_person] != self._id_mode_ped]1204for i, ids_activity in zip(xrange(len(ids_pers_filter)), vp.activitypatterns[ids_pers_filter]):12051206id_act1 = ids_activity[0]1207id_act2 = ids_activity[1]1208id_fac_from = activities.ids_facility[id_act1]1209id_fac_to = activities.ids_facility[id_act2]1210dist_fac_sqr = np.sum((centroids[id_fac_from] - centroids[id_fac_to])**2)1211if dist_fac_sqr > max_dist_fac_sqr:1212preeval[i] = -112131214print ' WalkStrategy.preevaluate', len(np.flatnonzero(preeval >= 0))1215return preeval12161217def plan(self, ids_person, logger=None, **kwargs):1218"""1219Generates a plan for these person according to this strategie.1220Overriden by specific strategy.1221"""1222print 'WalkStrategy.pan', len(ids_person)1223#make_plans_private(self, ids_person = None, mode = 'passenger')1224# routing necessary?1225virtualpop = self.get_virtualpop()1226plans = virtualpop.get_plans() # self._plans1227demand = virtualpop.get_demand()1228#ptlines = demand.ptlines12291230walkstages = plans.get_stagetable('walks')1231#transitstages = plans.get_stagetable('transits')1232activitystages = plans.get_stagetable('activities')12331234activities = virtualpop.get_activities()1235activitytypes = demand.activitytypes1236landuse = virtualpop.get_landuse()1237facilities = landuse.facilities1238#parking = landuse.parking12391240scenario = virtualpop.get_scenario()1241net = scenario.net1242edges = net.edges1243lanes = net.lanes1244modes = net.modes12451246#ptstops = net.ptstops12471248ids_laneedge = net.lanes.ids_edge12491250times_est_plan = plans.times_est1251# here we can determine edge weights for different modes12521253# this could be centralized to avoid redundance1254plans.prepare_stagetables(['walks', 'activities'])12551256ids_person_act, ids_act_from, ids_act_to\1257= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)12581259if len(ids_person_act) == 0:1260print 'WARNING in WalkStrategy.plan: no eligible persons found.'1261return False12621263# temporary maps from ids_person to other parameters1264nm = np.max(ids_person_act)+11265map_ids_plan = np.zeros(nm, dtype=np.int32)1266#ids_plan_act = virtualpop.add_plans(ids_person_act, id_strategy = self.get_id_strategy())1267map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())12681269map_times = np.zeros(nm, dtype=np.int32)1270map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')12711272# set start time to plans (important!)1273plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]12741275map_ids_fac_from = np.zeros(nm, dtype=np.int32)1276map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]12771278n_plans = len(ids_person_act)1279print 'TrasitStrategy.plan n_plans=', n_plans12801281# make initial activity stage1282ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]1283poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]1284# this is the time when first activity starts1285# first activity is normally not simulated12861287names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]1288durations_act_from = activities.get_durations(ids_act_from)1289times_from = map_times[ids_person_act]-durations_act_from1290#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')12911292for id_plan,\1293time,\1294id_act_from,\1295name_acttype_from,\1296duration_act_from,\1297id_edge_from,\1298pos_edge_from \1299in zip(map_ids_plan[ids_person_act],1300times_from,1301ids_act_from,1302names_acttype_from,1303durations_act_from,1304ids_edge_from,1305poss_edge_from):13061307id_stage_act, time = activitystages.append_stage(1308id_plan, time,1309ids_activity=id_act_from,1310names_activitytype=name_acttype_from,1311durations=duration_act_from,1312ids_lane=edges.ids_lanes[id_edge_from][0],1313positions=pos_edge_from,1314)13151316##13171318ind_act = 013191320# main loop while there are persons performing1321# an activity at index ind_act1322while len(ids_person_act) > 0:1323ids_plan = map_ids_plan[ids_person_act]13241325times_from = map_times[ids_person_act]13261327names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]1328durations_act_to = activities.get_durations(ids_act_to)13291330ids_fac_from = map_ids_fac_from[ids_person_act]1331ids_fac_to = activities.ids_facility[ids_act_to]13321333centroids_from = facilities.centroids[ids_fac_from]1334centroids_to = facilities.centroids[ids_fac_to]13351336# origin edge and position1337ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]1338poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]13391340# destination edge and position1341ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]1342poss_edge_to = facilities.positions_roadedge_closest[ids_fac_to]13431344#ids_stop_from = ptstops.get_closest(centroids_from)1345#ids_stop_to = ptstops.get_closest(centroids_to)13461347#ids_stopedge_from = ids_laneedge[ids_stoplane[ids_stop_from]]1348#ids_stopedge_to = ids_laneedge[ids_stoplane[ids_stop_to]]13491350# do random pos here1351# poss_stop_from = 0.5*( ptstops.positions_from[ids_stop_from]\1352# +ptstops.positions_to[ids_stop_from])13531354# poss_stop_to = 0.5*( ptstops.positions_from[ids_stop_to]\1355# +ptstops.positions_to[ids_stop_to])13561357i = 0.01358for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, \1359in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to):1360n_pers = len(ids_person_act)1361if logger:1362logger.progress(i/n_pers*100)1363i += 1.01364print 79*'_'1365print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)13661367id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,1368id_edge_from=id_edge_from,1369position_edge_from=pos_edge_from,1370id_edge_to=id_edge_to,1371position_edge_to=pos_edge_to, # -7.0,1372)13731374# update time for trips estimation for this plan1375plans.times_est[id_plan] += time-time_from13761377# define current end time without last activity duration1378plans.times_end[id_plan] = time13791380id_stage_act, time = activitystages.append_stage(1381id_plan, time,1382ids_activity=id_act_to,1383names_activitytype=name_acttype_to,1384durations=duration_act_to,1385ids_lane=edges.ids_lanes[id_edge_to][0],1386positions=pos_edge_to,1387)13881389# store time for next iteration in case other activities are1390# following1391map_times[id_person] = time13921393# select persons and activities for next setp1394ind_act += 11395ids_person_act, ids_act_from, ids_act_to\1396= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)139713981399class AutoStrategy(StrategyMixin):1400def __init__(self, ident, parent=None,1401name='Auto strategy',1402info='With this strategy, the person uses his private auto as main transport mode.',1403**kwargs):14041405self._init_objman(ident, parent, name=name, info=info, **kwargs)1406attrsman = self.set_attrsman(cm.Attrsman(self))1407# specific init1408self._init_attributes()1409self._init_constants()14101411def _init_attributes(self, **kwargs):1412# print 'StrategyMixin._init_attributes'1413attrsman = self.get_attrsman()14141415self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', 0.0),1416groupnames=['options'],1417perm='rw',1418name='Utility constant for auto strategy',1419info='Constant to calculate utility: U = Const + value_of_time*time_exec',1420))14211422modechoices = self.get_virtualpop().get_scenario().net.modes.names.get_indexmap()1423modechoices['No fallback'] = None1424# print ' modechoices',modechoices1425self.id_mode_fallback = attrsman.add(am.AttrConf('id_mode_fallback', modechoices['taxi'],1426groupnames=['options'],1427choices=modechoices,1428name='Fallback Mode for Auto strategy',1429info="""Transport mode to be used instead of "passenger" mode1430in case the origin and destination cannot be connected by a route.1431This is typically the case with origins or destinations1432in traffic restricted zones.1433Coose for example "taxi" to get access to traffic restricted Zones.1434""",1435))14361437def _init_constants(self):1438#virtualpop = self.get_virtualpop()1439#stagetables = virtualpop.get_stagetables()14401441#self._walkstages = stagetables.get_stagetable('walks')1442#self._ridestages = stagetables.get_stagetable('rides')1443#self._activitystages = stagetables.get_stagetable('activities')14441445#self._plans = virtualpop.get_plans()1446#1447# print 'AutoStrategy._init_constants'1448# print dir(self)1449# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])14501451modes = self.get_virtualpop().get_scenario().net.modes1452self._id_mode_bike = modes.get_id_mode('bicycle')1453self._id_mode_auto = modes.get_id_mode('passenger')1454self._id_mode_moto = modes.get_id_mode('motorcycle')1455self.get_attrsman().do_not_save_attrs([1456'_id_mode_bike', '_id_mode_auto', '_id_mode_moto',1457])14581459def get_utility_specific(self, id_plan):1460return self.utility_constant14611462def preevaluate(self, ids_person):1463"""1464Preevaluation strategies for person IDs in vector ids_person.14651466Returns a preevaluation vector with a preevaluation value1467for each person ID. The values of the preevaluation vector are as follows:1468-1 : Strategy cannot be applied14690 : Stategy can be applied, but the preferred mode is not used14701 : Stategy can be applied, and preferred mode is part of the strategy14712 : Strategy uses predomunantly preferred mode14721473"""1474n_pers = len(ids_person)1475print 'Autostrategy.preevaluate', n_pers, 'persons'1476persons = self.get_virtualpop()1477preeval = np.zeros(n_pers, dtype=np.int32)14781479# put -1 for persons without car access1480preeval[persons.ids_iauto[ids_person] == -1] = -11481print ' persons having no auto', len(np.flatnonzero(persons.ids_iauto[ids_person] == -1))14821483# put 0 for persons with car but with a different preferred mode1484preeval[(persons.ids_iauto[ids_person] > -1)1485& (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)] = 014861487print ' persons with car but with a different preferred mode', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_auto)))14881489# put 2 for persons with car access and who prefer the car1490preeval[(persons.ids_iauto[ids_person] > -1)1491& (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)] = 21492print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_iauto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_auto)))14931494return preeval14951496# def are_feasible(self, ids_person):1497# """1498# Returns a bool vector, with True values for1499# persons where this strategy can be applied.1500# """1501# persons = self.get_virtualpop()1502#1503# # check if person has a car1504# # one may also check if there is parking available1505# # at all desinations1506# return persons.ids_iautos[ids_person] >= 015071508def plan(self, ids_person, logger=None, **kwargs):1509"""1510Generates a plan for these person according to this strategie.1511Overriden by specific strategy.1512"""1513#make_plans_private(self, ids_person = None, mode = 'passenger')1514# routing necessary?1515virtualpop = self.get_virtualpop()1516plans = virtualpop.get_plans() # self._plans1517walkstages = plans.get_stagetable('walks')1518ridestages = plans.get_stagetable('autorides')1519activitystages = plans.get_stagetable('activities')15201521activities = virtualpop.get_activities()1522activitytypes = virtualpop.get_demand().activitytypes1523landuse = virtualpop.get_landuse()1524facilities = landuse.facilities1525parking = landuse.parking15261527scenario = virtualpop.get_scenario()1528edges = scenario.net.edges1529lanes = scenario.net.lanes1530modes = scenario.net.modes1531demand = scenario.demand1532vtyes = demand.vtypes15331534ids_mode = scenario.demand.vtypes.ids_mode1535iautos = virtualpop.get_iautos()15361537#times_est_plan = plans.times_est15381539# here we can determine edge weights for different modes1540plans.prepare_stagetables(['walks', 'autorides', 'activities'])15411542# get initial travel times for persons.1543# initial travel times depend on the initial activity15441545landuse.parking.clear_booking()15461547ids_person_act, ids_act_from, ids_act_to\1548= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)15491550if len(ids_person_act) == 0:1551print 'WARNING in Autostrategy.plan: no eligible persons found.'1552return False15531554# ok15551556# temporary maps from ids_person to other parameters15571558nm = np.max(ids_person_act)+11559map_ids_plan = np.zeros(nm, dtype=np.int32)1560#ids_plan_act = virtualpop.add_plans(ids_person_act, id_strategy = self.get_id_strategy())1561map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())15621563# err1564map_times = np.zeros(nm, dtype=np.int32)1565map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')15661567# set start time to plans (important!)1568plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]15691570map_ids_fac_from = np.zeros(nm, dtype=np.int32)1571map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]15721573# err1574map_ids_parking_from = np.zeros(nm, dtype=np.int32)1575map_are_fallback = np.zeros(nm, dtype=bool)1576ids_parking_from, are_fallback = parking.get_closest_parkings(virtualpop.ids_iauto[ids_person_act],1577ids_mode[iautos.ids_vtype[virtualpop.ids_iauto[ids_person_act]]],1578facilities.centroids[activities.ids_facility[ids_act_from]],1579dists_walk_max=virtualpop.dists_walk_max[ids_person_act],1580id_mode_fallback=self.id_mode_fallback,1581)1582#are_fallback = np.zeros(len(ids_person_act), dtype = bool)15831584if len(ids_parking_from) == 0:1585return False15861587# err15881589map_ids_parking_from[ids_person_act] = ids_parking_from1590map_are_fallback[ids_person_act] = are_fallback15911592n_plans = len(ids_person_act)1593print 'AutoStrategy.plan n_plans=', n_plans1594# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape1595# set initial activity1596# this is because the following steps start with travel1597# and set the next activity1598#names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]1599# for id_plan16001601ind_act = 016021603# make initial activity stage1604ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]1605poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]1606# this is the time when first activity starts1607# first activity is normally not simulated16081609names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]1610durations_act_from = activities.get_durations(ids_act_from)1611times_from = map_times[ids_person_act]-durations_act_from1612#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')16131614for id_plan,\1615time,\1616id_act_from,\1617name_acttype_from,\1618duration_act_from,\1619id_edge_from,\1620pos_edge_from \1621in zip(map_ids_plan[ids_person_act],1622times_from,1623ids_act_from,1624names_acttype_from,1625durations_act_from,1626ids_edge_from,1627poss_edge_from):16281629id_stage_act, time = activitystages.append_stage(1630id_plan,1631time,1632ids_activity=id_act_from,1633names_activitytype=name_acttype_from,1634durations=duration_act_from,1635ids_lane=edges.ids_lanes[id_edge_from][0],1636positions=pos_edge_from,1637)16381639# main loop while there are persons performing1640# an activity at index ind_act1641while len(ids_person_act) > 0:1642ids_plan = map_ids_plan[ids_person_act]1643ids_veh = virtualpop.ids_iauto[ids_person_act]16441645#ids_mode = vtypes.ids_mode[iautos.ids_vtype[ids_veh]]1646# print ids_veh1647#inds_pers = virtualpop.get_inds(ids_person)1648# self.persons.cols.mode_preferred[inds_pers]='private'16491650times_from = map_times[ids_person_act]16511652names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]1653durations_act_to = activities.get_durations(ids_act_to)16541655ids_fac_from = map_ids_fac_from[ids_person_act]1656ids_fac_to = activities.ids_facility[ids_act_to]16571658centroids_to = facilities.centroids[ids_fac_to]16591660# origin edge and position1661ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]1662poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]16631664# this method will find and occupy parking space1665ids_parking_from = map_ids_parking_from[ids_person_act]16661667# print ' ids_veh.shape',ids_veh.shape1668# print ' centroids_to.shape',centroids_to.shape1669ids_parking_to, are_fallback = parking.get_closest_parkings(ids_veh,1670ids_mode[iautos.ids_vtype[ids_veh]],1671centroids_to,1672dists_walk_max=virtualpop.dists_walk_max[ids_person_act],1673id_mode_fallback=self.id_mode_fallback,1674)16751676map_are_fallback[ids_person_act] |= are_fallback16771678ids_lane_parking_from = parking.ids_lane[ids_parking_from]1679ids_edge_parking_from = lanes.ids_edge[ids_lane_parking_from]1680poss_edge_parking_from = parking.positions[ids_parking_from]16811682# print ' ids_parking_to.shape',ids_parking_to.shape1683# print ' np.max(parking.get_ids()), np.max(ids_parking_to)',np.max(parking.get_ids()), np.max(ids_parking_to)1684ids_lane_parking_to = parking.ids_lane[ids_parking_to]1685ids_edge_parking_to = lanes.ids_edge[ids_lane_parking_to]1686poss_edge_parking_to = parking.positions[ids_parking_to]16871688# Fallback mode, if an auto can't run between origin and destination parkings, then the vehicle is changed with a taxy1689# print ' prepare routing'1690#fstar = edges.get_fstar(is_ignor_connections=False)1691#times_primary = edges.get_times(id_mode= self._id_mode_auto, is_check_lanes=True)16921693if self.id_mode_fallback is not None:1694ids_vtype_fallback, share_fallback = demand.vtypes.select_by_mode(self.id_mode_fallback, is_share=True)1695# print ' ids_vtype_fallback, share_fallback',ids_vtype_fallback, share_fallback16961697# for id_edge_orig, id_edge_dest, id_veh, i in zip(ids_edge_parking_from, ids_edge_parking_to, ids_veh, range(len(ids_veh))):1698# cost, route = routing.get_mincostroute_edge2edge(id_edge_orig,1699# id_edge_dest,1700# weights = times_primary,# mode dependent!1701# fstar=fstar1702# )1703# if route == []:1704# if self.id_mode_fallback != 1:1705# print 'fallback mode for vehicle %d of person %d'%(id_veh, virtualpop.get_iautos().ids_person[id_veh])1706# are_fallback[i] = True1707# virtualpop.get_iautos().ids_vtype[id_veh] = np.random.choice(id_vtype_mode[0], p = id_vtype_mode[1])1708# print ids_veh17091710# destination edge and position1711ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]1712poss_edge_to = facilities.positions_roadedge_closest[ids_fac_to]17131714i = 0.01715n_pers = len(ids_person_act)1716for id_person, id_mode, is_fallback, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_parking_from, pos_edge_parking_from, id_parking_from, id_parking_to, id_edge_parking_to, pos_edge_parking_to, id_edge_to, pos_edge_to\1717in zip(ids_person_act, ids_mode[iautos.ids_vtype[ids_veh]], map_are_fallback[ids_person_act], ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_parking_from, poss_edge_parking_from, ids_parking_from, ids_parking_to, ids_edge_parking_to, poss_edge_parking_to, ids_edge_to, poss_edge_to):1718if logger:1719logger.progress(i/n_pers*100)1720i += 1.01721#plans.set_row(id_plan, ids_person = id_person, ids_strategy = self.get_id_strategy())17221723# start creating stages for activity1724id_stage_walk1, time = walkstages.append_stage(1725id_plan, time_from,1726id_edge_from=id_edge_from,1727position_edge_from=pos_edge_from,1728id_edge_to=id_edge_parking_from,1729position_edge_to=pos_edge_parking_from-1.5, # wait 1.5 m before nose of parked car1730)17311732print ' id_person,id_veh', id_person, id_veh1733# ride from car parking to road edge near activity1734id_stage_car, time, is_fallback = ridestages.append_stage(1735id_plan,1736id_mode,1737is_fallback,1738self.id_mode_fallback,1739time_start=time,1740id_veh=id_veh,1741# delay to be sure that person arrived!(workaround in combination with parking=False)1742time_init=time+30, # time_from,1743id_parking_from=id_parking_from,1744id_parking_to=id_parking_to,1745# TODO: here we could use id_edge_to as via edge to emulate search for parking1746)17471748if is_fallback & (self.id_mode_fallback is not None):1749# now we are sure fallback mode is needed1750# set a fallback vtype for this id_veh1751iautos.ids_vtype[id_veh] = np.random.choice(ids_vtype_fallback, p=share_fallback)1752map_are_fallback[id_person] = True17531754if id_stage_car > -1:1755# print ' car ride successful'1756id_stage_walk2, time = walkstages.append_stage(1757id_plan, time,1758id_edge_from=id_edge_parking_to,1759position_edge_from=pos_edge_parking_to-1.5, # ecessary?1760id_edge_to=id_edge_to,1761position_edge_to=pos_edge_to,1762)1763else:1764# print ' parking not connected or distance too short, modify first walk and go directly to activity'1765# print ' id_stage_walk1',id_stage_walk1,type(id_stage_walk1)1766# print ' id_edge_from',id_edge_from1767# print ' position_edge_from',position_edge_from1768# print ' id_edge_to',id_edge_to1769# print ' position_edge_to',position_edge_to17701771time = walkstages.modify_stage(1772id_stage_walk1, time_from,1773id_edge_from=id_edge_from,1774position_edge_from=pos_edge_from,1775id_edge_to=id_edge_to,1776position_edge_to=pos_edge_to,1777)17781779# store time estimation for this plan1780# note that these are the travel times, no activity time1781plans.times_est[id_plan] += time-time_from17821783# define current end time without last activity duration1784plans.times_end[id_plan] = time17851786# finally add activity and respective duration17871788id_stage_act, time = activitystages.append_stage(1789id_plan, time,1790ids_activity=id_act_to,1791names_activitytype=name_acttype_to,1792durations=duration_act_to,1793ids_lane=edges.ids_lanes[id_edge_to][0],1794positions=pos_edge_to,1795)17961797map_times[id_person] = time1798# return time1799##18001801# prepare next activity (not yet tested)1802map_ids_parking_from[ids_person_act] = ids_parking_to18031804# select persons and activities for next setp1805ind_act += 11806ids_person_act, ids_act_from, ids_act_to\1807= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)1808# update timing with (random) activity duration!!18091810return True181118121813class BikeStrategy(StrategyMixin):1814def __init__(self, ident, parent=None,1815name='Bike strategy',1816info='With this strategy, the person uses his private bike as main transport mode.',1817**kwargs):18181819self._init_objman(ident, parent, name=name, info=info, **kwargs)1820attrsman = self.set_attrsman(cm.Attrsman(self))1821# specific init1822self._init_attributes(**kwargs)1823self._init_constants()18241825def _init_attributes(self, **kwargs):1826# print 'StrategyMixin._init_attributes'1827attrsman = self.get_attrsman()18281829self._init_attributes_strategy(**kwargs)1830self.n_iter_bikeacces_max = attrsman.add(cm.AttrConf('n_iter_bikeacces_max', kwargs.get('n_iter_bikeacces_max', 5),1831groupnames=['options'],1832perm='rw',1833name='Max. bike access search iterations',1834info='Max. number of iterations while searching an edge with bike access.',1835))18361837self.length_edge_min = attrsman.add(cm.AttrConf('length_edge_min', kwargs.get('length_edge_min', 20.0),1838groupnames=['options'],1839perm='rw',1840name='Min. edge length search',1841unit='m',1842info='Min. edge length when searching an edge with bike access.',1843))18441845self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', -0.5604),1846groupnames=['options'],1847perm='rw',1848name='Utility constant for bike strategy',1849info='Constant to calculate utility: U = Const + value_of_time*time_exec',1850))18511852def _init_constants(self):1853#virtualpop = self.get_virtualpop()1854#stagetables = virtualpop.get_stagetables()18551856#self._walkstages = stagetables.get_stagetable('walks')1857#self._ridestages = stagetables.get_stagetable('rides')1858#self._activitystages = stagetables.get_stagetable('activities')18591860#self._plans = virtualpop.get_plans()1861#1862# print 'AutoStrategy._init_constants'1863# print dir(self)1864# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])18651866modes = self.get_virtualpop().get_scenario().net.modes1867self._id_mode_ped = modes.get_id_mode('pedestrian')1868self._id_mode_bike = modes.get_id_mode('bicycle')1869self._id_mode_auto = modes.get_id_mode('passenger')1870self._id_mode_moto = modes.get_id_mode('motorcycle')1871self._edges = self.get_virtualpop().get_scenario().net.edges1872self.get_attrsman().do_not_save_attrs([1873'_id_mode_bike', '_id_mode_auto', '_id_mode_moto',1874'_id_mode_ped',1875'_edges'])18761877def get_utility_specific(self, id_plan):1878return self.utility_constant18791880def preevaluate(self, ids_person):1881"""1882Preevaluation strategies for person IDs in vector ids_person.18831884Returns a preevaluation vector with a preevaluation value1885for each person ID. The values of the preevaluation vector are as follows:1886-1 : Strategy cannot be applied18870 : Stategy can be applied, but the preferred mode is not used18881 : Stategy can be applied, and preferred mode is part of the strategy18892 : Strategy uses predomunantly preferred mode18901891"""1892n_pers = len(ids_person)1893print 'BikeStrategy.preevaluate', n_pers, 'persons'1894persons = self.get_virtualpop()1895preeval = np.zeros(n_pers, dtype=np.int32)18961897# put -1 for persons without car access1898preeval[persons.ids_ibike[ids_person] == -1] = -11899print ' persons having no bike', len(np.flatnonzero(persons.ids_ibike[ids_person] == -1))19001901# put 0 for persons with bike but with a different preferred mode1902preeval[(persons.ids_ibike[ids_person] > -1)1903& (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)] = 019041905print ' persons with bike but with a different preferred mode', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_bike)))19061907# put 2 for persons with bike access and who prefer the bike1908preeval[(persons.ids_ibike[ids_person] > -1)1909& (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)] = 21910print ' persons with car access and who prefer the car', len(np.flatnonzero((persons.ids_ibike[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)))19111912return preeval19131914def get_edge_bikeaccess(self, id_edge, is_search_backward=False, is_get_route=False, is_star=False, bstar=0, fstar=0, n_iter_bikeacces_max=None):1915# get firts edge allowing bikes and pedestrian, saving route, frontward or backward. You can include bstar or fstar:1916# check only connected links. You can obtain also the route.1917# print 'get_edge_bikeaccess',id_edge, is_search_backward,'id_sumo',self._edges.ids_sumo[id_edge]19181919if n_iter_bikeacces_max is None:1920n_iter_bikeacces_max = self.n_iter_bikeacces_max19211922id_mode = self._id_mode_bike1923id_mode_ped = self._id_mode_ped1924get_accesslevel = self._edges.get_accesslevel1925if is_star:1926if is_search_backward:1927get_next = bstar1928else:1929get_next = fstar1930else:1931if is_search_backward:1932get_next = self._edges.get_incoming1933else:1934get_next = self._edges.get_outgoing19351936edgelengths = self._edges.lengths1937#ids_tried = set()1938ids_current = [id_edge]1939id_bikeedge = -11940pos = 0.01941n = 01942ids = [id_edge]1943coll_ids = [0]1944route = []1945while (id_bikeedge < 0) & (n < n_iter_bikeacces_max):1946n += 119471948ids_new = []1949for id_edge_test, is_long_enough in zip(ids_current, edgelengths[ids_current] > self.length_edge_min):1950# print ' check id',id_edge_test, is_long_enough,get_accesslevel(id_edge_test, id_mode)1951if is_long_enough & (get_accesslevel(id_edge_test, id_mode) >= 0) & (get_accesslevel(id_edge_test, id_mode_ped) >= 0):1952id_bikeedge = id_edge_test19531954if is_get_route:1955if n == 1:1956route = []1957else:1958route.append(id_edge_test)1959if n > 2:1960route.append(coll_ids[ids.index(id_edge_test)])1961if n > 3:1962for n in range(n-3):1963route.append(coll_ids[ids.index(route[-1])])19641965if is_search_backward is not True:1966route.reverse()19671968# print ' found',id_bikeedge,self._edges.ids_sumo[id_bikeedge]1969break1970else:19711972if is_star:1973ids_new += get_next[id_edge_test]1974if is_get_route:1975ids += get_next[id_edge_test]1976for i in range(len(get_next[id_edge_test])):1977coll_ids.append(id_edge_test)19781979else:1980ids_new += get_next(id_edge_test)1981if is_get_route:1982ids += get_next(id_edge_test)1983for i in range(len(get_next(id_edge_test))):1984coll_ids += id_edge_test19851986ids_current = ids_new19871988if id_bikeedge > -1:1989if is_search_backward:1990pos = edgelengths[id_bikeedge]-0.5*self.length_edge_min1991else:1992pos = 0.5*self.length_edge_min19931994if id_bikeedge == -1:1995print 'WARNING in get_edge_bikeaccess no access for', id_edge, self._edges.ids_sumo[id_edge]19961997if is_get_route:1998return id_bikeedge, pos, route1999else:2000return id_bikeedge, pos20012002def plan_bikeride(self, id_plan, time_from, id_veh,2003id_edge_from, pos_edge_from,2004id_edge_to, pos_edge_to,2005dist_from_to, dist_walk_max,2006walkstages, ridestages):20072008# start creating stages2009id_stage_walk1 = -12010id_stage_bike = -120112012id_edge_from_bike, pos_from_bike = self.get_edge_bikeaccess(id_edge_from)2013id_edge_to_bike, pos_to_bike = self.get_edge_bikeaccess(id_edge_to, is_search_backward=True)20142015if (dist_from_to < dist_walk_max) | (id_edge_from_bike == -1) | (id_edge_to_bike == -1):2016# print ' go by foot because distance is too short or no bike access',dist_from_to,id_edge_from_bike,id_edge_to_bike2017id_stage_walk1, time = walkstages.append_stage(2018id_plan, time_from,2019id_edge_from=id_edge_from,2020position_edge_from=pos_edge_from,2021id_edge_to=id_edge_to,2022position_edge_to=pos_edge_to,2023)20242025else:2026# print ' try to take the bike',id_veh2027# print ' id_edge_from_bike',edges.ids_sumo[id_edge_from_bike],pos_from_bike2028# print ' id_edge_to_bike',edges.ids_sumo[id_edge_to_bike],pos_to_bike20292030if id_edge_from_bike != id_edge_from:2031# print ' must walk from origin to bikerack',time_from20322033id_stage_walk1, time = walkstages.append_stage(2034id_plan, time_from,2035id_edge_from=id_edge_from,2036position_edge_from=pos_edge_from,2037id_edge_to=id_edge_from_bike,2038position_edge_to=pos_from_bike,2039)20402041if id_edge_to_bike != id_edge_to:2042# print ' must cycle from bikerack to dest bike rack',time2043id_stage_bike, time = ridestages.append_stage(2044id_plan, time,2045id_veh=id_veh,2046# delay to be sure that person arrived!(workaround in combination with parking=False)2047time_init=time-10, # time_from,2048id_edge_from=id_edge_from_bike,2049position_edge_from=pos_from_bike,2050id_edge_to=id_edge_to_bike,2051position_edge_to=pos_to_bike,2052)2053if id_stage_bike > -1:2054# print ' must walk from dest bikerack to dest',time2055id_stage_walk2, time = walkstages.append_stage(2056id_plan, time,2057id_edge_from=id_edge_to_bike,2058position_edge_from=pos_to_bike,2059id_edge_to=id_edge_to,2060position_edge_to=pos_edge_to,2061)20622063else:2064# print ' cycle from bikerack to destination',time2065id_stage_bike, time = ridestages.append_stage(2066id_plan, time,2067id_veh=id_veh,2068# delay to be sure that person arrived!(workaround in combination with parking=False)2069time_init=time-10, # time_from,2070id_edge_from=id_edge_from_bike,2071position_edge_from=pos_from_bike,2072id_edge_to=id_edge_to,2073position_edge_to=pos_edge_to,2074)2075else:2076# print ' cycle directly from orign edge',time_from2077if id_edge_to_bike != id_edge_to:2078# print ' must cycle from origin to bikerack',time_from20792080#pos_to_bike = 0.1*edges.lengths[id_edge_to_bike]2081id_stage_bike, time = ridestages.append_stage(2082id_plan, time_from,2083id_veh=id_veh,2084# delay to be sure that person arrived!(workaround in combination with parking=False)2085time_init=time_from-10, # time_from,2086id_edge_from=id_edge_from,2087position_edge_from=pos_edge_from,2088id_edge_to=id_edge_to_bike,2089position_edge_to=pos_to_bike,2090)2091if id_stage_bike > -1:2092id_stage_walk2, time = walkstages.append_stage(2093id_plan, time,2094id_edge_from=id_edge_to_bike,2095position_edge_from=pos_to_bike,2096id_edge_to=id_edge_to,2097position_edge_to=pos_edge_to,2098)2099else:2100# print ' must cycle from origin to destination',time_from2101id_stage_bike, time = ridestages.append_stage(2102id_plan, time_from,2103id_veh=id_veh,2104# delay to be sure that person arrived!(workaround in combination with parking=False)2105time_init=time_from-10, # time_from,2106id_edge_from=id_edge_from,2107position_edge_from=pos_edge_from,2108id_edge_to=id_edge_to,2109position_edge_to=pos_edge_to,2110)21112112# here we should have created a bike ride2113# if not, for ehatever reason,2114# we walk from origin to destination2115if id_stage_bike == -1:2116# print ' walk because no ride stage has been planned',time_from2117if id_stage_walk1 == -1:2118# no walk stage has been planned2119id_stage_walk1, time = walkstages.append_stage(2120id_plan, time_from,2121id_edge_from=id_edge_from,2122position_edge_from=pos_edge_from,2123id_edge_to=id_edge_to,2124position_edge_to=pos_edge_to,2125)21262127elif time_from == time:2128# walking to bike has already been schedules,2129# but cycling failed. So walk the whole way2130time = walkstages.modify_stage(2131id_stage_walk1, time_from,2132id_edge_from=id_edge_from,2133position_edge_from=pos_edge_from,2134id_edge_to=id_edge_to,2135position_edge_to=pos_edge_to,2136)2137return time21382139def plan(self, ids_person, logger=None, **kwargs):2140"""2141Generates a plan for these person according to this strategie.2142Overriden by specific strategy.2143"""2144#make_plans_private(self, ids_person = None, mode = 'passenger')2145# routing necessary?2146virtualpop = self.get_virtualpop()2147plans = virtualpop.get_plans() # self._plans2148walkstages = plans.get_stagetable('walks')2149ridestages = plans.get_stagetable('bikerides')2150activitystages = plans.get_stagetable('activities')21512152activities = virtualpop.get_activities()2153activitytypes = virtualpop.get_demand().activitytypes2154landuse = virtualpop.get_landuse()2155facilities = landuse.facilities2156#parking = landuse.parking21572158scenario = virtualpop.get_scenario()2159edges = scenario.net.edges2160lanes = scenario.net.lanes2161modes = scenario.net.modes21622163#times_est_plan = plans.times_est21642165# here we can determine edge weights for different modes2166plans.prepare_stagetables(['walks', 'bikerides', 'activities'])21672168# get initial travel times for persons.2169# initial travel times depend on the initial activity21702171# landuse.parking.clear_booking()21722173ids_person_act, ids_act_from, ids_act_to\2174= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)21752176if len(ids_person_act) == 0:2177print 'WARNING in BikeStrategy.plan: no eligible persons found.'2178return False21792180# ok21812182# temporary maps from ids_person to other parameters2183nm = np.max(ids_person_act)+12184map_ids_plan = np.zeros(nm, dtype=np.int32)2185map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())21862187map_times = np.zeros(nm, dtype=np.int32)2188map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')21892190# set start time to plans (important!)2191plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]21922193map_ids_fac_from = np.zeros(nm, dtype=np.int32)2194map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]21952196#map_ids_parking_from = np.zeros(nm, dtype = np.int32)2197# ids_parking_from, inds_vehparking = parking.get_closest_parkings( virtualpop.ids_iauto[ids_person_act],2198# facilities.centroids[activities.ids_facility[ids_act_from]])2199# if len(ids_parking_from)==0:2200# return False22012202# err22032204#map_ids_parking_from[ids_person_act] = ids_parking_from22052206n_plans = len(ids_person_act)2207print 'BikeStrategy.plan n_plans=', n_plans2208# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape2209# set initial activity2210# this is because the following steps start with travel2211# and set the next activity2212#names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]2213# for id_plan22142215ind_act = 022162217# make initial activity stage2218ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]22192220poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]2221poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)22222223# this is the time when first activity starts2224# first activity is normally not simulated22252226names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]2227durations_act_from = activities.get_durations(ids_act_from)2228times_from = map_times[ids_person_act]-durations_act_from2229#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')22302231# do initial stage2232# could be common to all strategies2233for id_plan,\2234time,\2235id_act_from,\2236name_acttype_from,\2237duration_act_from,\2238id_edge_from,\2239pos_edge_from \2240in zip(map_ids_plan[ids_person_act],2241times_from,2242ids_act_from,2243names_acttype_from,2244durations_act_from,2245ids_edge_from,2246poss_edge_from):22472248id_stage_act, time = activitystages.append_stage(2249id_plan, time,2250ids_activity=id_act_from,2251names_activitytype=name_acttype_from,2252durations=duration_act_from,2253ids_lane=edges.ids_lanes[id_edge_from][0],2254positions=pos_edge_from,2255)22562257# main loop while there are persons performing2258# an activity at index ind_act2259while len(ids_person_act) > 0:2260ids_plan = map_ids_plan[ids_person_act]2261ids_veh = virtualpop.ids_ibike[ids_person_act]2262dists_walk_max = virtualpop.dists_walk_max[ids_person_act]2263times_from = map_times[ids_person_act]22642265names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]2266durations_act_to = activities.get_durations(ids_act_to)22672268ids_fac_from = map_ids_fac_from[ids_person_act]2269ids_fac_to = activities.ids_facility[ids_act_to]22702271# origin edge and position2272ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]2273poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]2274poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)22752276centroids_from = facilities.centroids[ids_fac_from]22772278# this method will find and occupy parking space2279#ids_parking_from = map_ids_parking_from[ids_person_act]22802281# print ' ids_veh.shape',ids_veh.shape2282# print ' centroids_to.shape',centroids_to.shape2283#ids_parking_to, inds_vehparking = parking.get_closest_parkings(ids_veh, centroids_to)22842285#ids_lane_parking_from = parking.ids_lane[ids_parking_from]2286#ids_edge_parking_from = lanes.ids_edge[ids_lane_parking_from]2287#poss_edge_parking_from = parking.positions[ids_parking_from]22882289# print ' ids_parking_to.shape',ids_parking_to.shape2290# print ' np.max(parking.get_ids()), np.max(ids_parking_to)',np.max(parking.get_ids()), np.max(ids_parking_to)2291#ids_lane_parking_to = parking.ids_lane[ids_parking_to]2292#ids_edge_parking_to = lanes.ids_edge[ids_lane_parking_to]2293#poss_edge_parking_to = parking.positions[ids_parking_to]22942295# destination edge and position2296ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]22972298poss_edge_to1 = facilities.positions_roadedge_closest[ids_fac_to]2299poss_edge_to = self.clip_positions(poss_edge_to1, ids_edge_to)2300centroids_to = facilities.centroids[ids_fac_to]23012302# debug poscorrection..OK2303# for id_edge, id_edge_sumo, length, pos_to1, pos in zip(ids_edge_to, edges.ids_sumo[ids_edge_to],edges.lengths[ids_edge_to],poss_edge_to1, poss_edge_to):2304# print ' ',id_edge, 'IDe%s'%id_edge_sumo, 'L=%.2fm'%length, '%.2fm'%pos_to1, '%.2fm'%pos23052306dists_from_to = np.sqrt(np.sum((centroids_to - centroids_from)**2, 1))23072308i = 0.02309n_pers = len(ids_person_act)2310for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, dist_from_to, dist_walk_max\2311in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, dists_from_to, dists_walk_max):2312if logger:2313logger.progress(i/n_pers*100)2314i += 1.02315print 79*'*'2316print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to2317print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]23182319time = self.plan_bikeride(id_plan, time_from, id_veh,2320id_edge_from, pos_edge_from,2321id_edge_to, pos_edge_to,2322dist_from_to, dist_walk_max,2323walkstages, ridestages)23242325################23262327# store time estimation for this plan2328# note that these are the travel times, no activity time2329plans.times_est[id_plan] += time-time_from23302331# define current end time without last activity duration2332plans.times_end[id_plan] = time23332334# finally add activity and respective duration23352336id_stage_act, time = activitystages.append_stage(2337id_plan, time,2338ids_activity=id_act_to,2339names_activitytype=name_acttype_to,2340durations=duration_act_to,2341ids_lane=edges.ids_lanes[id_edge_to][0],2342positions=pos_edge_to,2343)23442345map_times[id_person] = time2346# return time2347##23482349# select persons and activities for next setp2350ind_act += 12351ids_person_act, ids_act_from, ids_act_to\2352= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)2353# update timing with (random) activity duration!!23542355return True235623572358class TaxiStrategy(StrategyMixin):2359def __init__(self, ident, parent=None,2360name='taxi strategy',2361info='With this strategy, the person uses his private taxi as main transport mode.',2362**kwargs):23632364self._init_objman(ident, parent, name=name, info=info, **kwargs)2365attrsman = self.set_attrsman(cm.Attrsman(self))2366# specific init2367self._init_attributes(**kwargs)2368self._init_constants()23692370def _init_attributes(self, **kwargs):2371# print 'StrategyMixin._init_attributes'2372attrsman = self.get_attrsman()23732374self._init_attributes_strategy(**kwargs)2375self.n_iter_acces_max = attrsman.add(cm.AttrConf('n_iter_acces_max', kwargs.get('n_iter_acces_max', 5),2376groupnames=['options'],2377perm='rw',2378name='Max. access search iterations',2379info='Max. number of iterations while searching an edge with taxi access.',2380))23812382self.length_edge_min = attrsman.add(cm.AttrConf('length_edge_min', kwargs.get('length_edge_min', 20.0),2383groupnames=['options'],2384perm='rw',2385name='Min. edge length search',2386unit='m',2387info='Min. edge length when searching an edge with taxi access.',2388))23892390self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', 0.0),2391groupnames=['options'],2392perm='rw',2393name='Utility constant for taxi strategy',2394info='Constant to calculate utility: U = Const + value_of_time*time_exec',2395))23962397def _init_constants(self):2398#virtualpop = self.get_virtualpop()2399#stagetables = virtualpop.get_stagetables()24002401#self._walkstages = stagetables.get_stagetable('walks')2402#self._ridestages = stagetables.get_stagetable('rides')2403#self._activitystages = stagetables.get_stagetable('activities')24042405#self._plans = virtualpop.get_plans()2406#2407# print 'AutoStrategy._init_constants'2408# print dir(self)2409# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])24102411modes = self.get_virtualpop().get_scenario().net.modes2412self._id_mode_ped = modes.get_id_mode('pedestrian')2413#self._id_mode_bike = modes.get_id_mode('bicycle')2414#self._id_mode_auto = modes.get_id_mode('passenger')2415self._id_mode_taxi = modes.get_id_mode('taxi')2416self._edges = self.get_virtualpop().get_scenario().net.edges2417self.get_attrsman().do_not_save_attrs([2418'_id_mode_ped', '_id_mode_taxi',2419'_edges'])24202421def get_utility_specific(self, id_plan):2422return self.utility_constant24232424def preevaluate(self, ids_person):2425"""2426Preevaluation strategies for person IDs in vector ids_person.24272428Returns a preevaluation vector with a preevaluation value2429for each person ID. The values of the preevaluation vector are as follows:2430-1 : Strategy cannot be applied24310 : Stategy can be applied, but the preferred mode is not used24321 : Stategy can be applied, and preferred mode is part of the strategy24332 : Strategy uses predomunantly preferred mode24342435"""2436n_pers = len(ids_person)2437persons = self.get_virtualpop()2438preeval = np.zeros(n_pers, dtype=np.int32)24392440# TODO: here we could exclude by age or distance facilities-stops24412442# put 0 for persons whose preference is not public transport2443preeval[persons.ids_mode_preferred[ids_person] != self._id_mode_taxi] = 024442445# put 2 for persons with car access and who prefer cars2446preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_taxi] = 224472448print ' TaxiStrategy.preevaluate', len(np.flatnonzero(preeval))2449return preeval24502451def get_edge_access(self, id_edge, is_search_backward=False, is_get_route=False, is_star=False, bstar=0, fstar=0, n_iter_acces_max=None):2452# get firts edge allowing bikes and pedestrian, saving route, frontward or backward. You can include bstar or fstar:2453# check only connected links. You can obtain also the route.2454# print 'get_edge_bikeaccess',id_edge, is_search_backward,'id_sumo',self._edges.ids_sumo[id_edge]2455print 'get_edge_access id_edge', id_edge, 'is_search_backward', is_search_backward, 'n_iter_acces_max', self.n_iter_acces_max2456if n_iter_acces_max is None:2457n_iter_acces_max = self.n_iter_acces_max24582459id_mode = self._id_mode_taxi2460id_mode_ped = self._id_mode_ped2461get_accesslevel = self._edges.get_accesslevel2462if is_star:2463if is_search_backward:2464get_next = bstar2465else:2466get_next = fstar2467else:2468if is_search_backward:2469get_next = self._edges.get_incoming2470else:2471get_next = self._edges.get_outgoing24722473edgelengths = self._edges.lengths2474#ids_tried = set()2475ids_current = [id_edge]2476id_modeedge = -12477pos = 0.02478n = 02479ids = [id_edge]2480coll_ids = [0]2481route = []2482print 'start id_modeedge', id_modeedge, 'n', n, 'n_iter_acces_max', n_iter_acces_max, (id_modeedge < 0), (n < n_iter_acces_max)24832484while (id_modeedge < 0) & (n < n_iter_acces_max):2485print ' while id_modeedge', id_modeedge, 'n', n2486n += 124872488ids_new = []2489for id_edge_test, is_long_enough in zip(ids_current, edgelengths[ids_current] > self.length_edge_min):2490print ' check id', id_edge_test, is_long_enough, 'taxi access', get_accesslevel(id_edge_test, id_mode), 'ped access', get_accesslevel(id_edge_test, id_mode_ped)2491if is_long_enough & (get_accesslevel(id_edge_test, id_mode) >= 0) & (get_accesslevel(id_edge_test, id_mode_ped) >= 0):2492id_modeedge = id_edge_test24932494if is_get_route:2495if n == 1:2496route = []2497else:2498route.append(id_edge_test)2499if n > 2:2500route.append(coll_ids[ids.index(id_edge_test)])2501if n > 3:2502for n in range(n-3):2503route.append(coll_ids[ids.index(route[-1])])2504if is_search_backward is not True:2505route.reverse()25062507print ' found', id_modeedge, self._edges.ids_sumo[id_modeedge]2508break2509else:25102511if is_star:2512ids_new += get_next[id_edge_test]2513if is_get_route:2514ids += get_next[id_edge_test]2515for i in range(len(get_next[id_edge_test])):2516coll_ids.append(id_edge_test)25172518else:2519ids_new += get_next(id_edge_test)2520if is_get_route:2521ids += get_next(id_edge_test)2522for i in range(len(get_next(id_edge_test))):2523coll_ids += id_edge_test25242525ids_current = ids_new25262527if id_modeedge > -1:2528if is_search_backward:2529pos = edgelengths[id_modeedge]-0.5*self.length_edge_min2530else:2531pos = 0.5*self.length_edge_min25322533if id_modeedge == -1:2534print 'WARNING in TaxiStrategy.get_edge_access no access at id_edge', id_edge, self._edges.ids_sumo[id_edge]25352536if is_get_route:2537return id_modeedge, pos, route2538else:2539return id_modeedge, pos25402541def plan_taxiride(self, id_plan, time_from, id_veh,2542id_edge_from, pos_edge_from,2543id_edge_to, pos_edge_to,2544dist_from_to, dist_walk_max,2545walkstages, ridestages):25462547# start creating stages2548id_stage_walk1 = -12549id_stage_moto = -125502551id_edge_from_taxi, pos_from_taxi = self.get_edge_access(id_edge_from)2552id_edge_to_taxi, pos_to_taxi = self.get_edge_access(id_edge_to, is_search_backward=True)25532554if (dist_from_to < dist_walk_max) | (id_edge_from_taxi == -1) | (id_edge_to_taxi == -1):2555print ' go by foot because distance is too short or no taxi access', dist_from_to, id_edge_from_taxi, id_edge_to_taxi2556id_stage_walk1, time = walkstages.append_stage(2557id_plan, time_from,2558id_edge_from=id_edge_from,2559position_edge_from=pos_edge_from,2560id_edge_to=id_edge_to,2561position_edge_to=pos_edge_to,2562)25632564else:2565print ' try to take the taxi'2566# print ' id_edge_from_taxi',edges.ids_sumo[id_edge_from_taxi],pos_from_taxi2567# print ' id_edge_to_taxi',edges.ids_sumo[id_edge_to_taxi],pos_to_taxi25682569if id_edge_from_taxi != id_edge_from:2570print ' must walk from origin to taxi accessible edge, time_from', time_from2571# walk to taxi edge2572id_stage_walk1, time = walkstages.append_stage(2573id_plan, time_from,2574id_edge_from=id_edge_from,2575position_edge_from=pos_edge_from,2576id_edge_to=id_edge_from_taxi,2577position_edge_to=pos_from_taxi,2578)25792580if id_edge_to_taxi != id_edge_to:2581print ' must walk from taxi accessible edge to dest, time_from', time2582# take taxi2583id_stage_taxi, time = ridestages.append_stage(2584id_plan, time,2585id_veh=id_veh,2586# could book taxi here in advance?2587time_init=time-10, # needed with taxi??2588id_edge_from=id_edge_from_taxi,2589position_edge_from=pos_from_taxi,2590id_edge_to=id_edge_to_taxi,2591position_edge_to=pos_to_taxi,2592)2593if id_stage_taxi > -1:2594# walk to dest2595id_stage_walk2, time = walkstages.append_stage(2596id_plan, time,2597id_edge_from=id_edge_to_taxi,2598position_edge_from=pos_to_taxi,2599id_edge_to=id_edge_to,2600position_edge_to=pos_edge_to,2601)26022603else:2604print ' ride taxi from taxi edge to destination', time2605# take taxi2606id_stage_taxi, time = ridestages.append_stage(2607id_plan, time,2608id_veh=id_veh,2609# could book taxi here in advance?2610time_init=time, # time_from,2611id_edge_from=id_edge_from_taxi,2612position_edge_from=pos_from_taxi,2613id_edge_to=id_edge_to,2614position_edge_to=pos_edge_to,2615)2616else:2617print ' take taxi directly from edge of origin', time_from2618if id_edge_to_taxi != id_edge_to:2619print ' must walk from taxi accessible destination to destination', time_from26202621id_stage_taxi, time = ridestages.append_stage(2622id_plan, time_from,2623id_veh=id_veh,2624# could book taxi here in advance?2625time_init=time_from, # time_from,2626id_edge_from=id_edge_from,2627position_edge_from=pos_edge_from,2628id_edge_to=id_edge_to_taxi,2629position_edge_to=pos_to_taxi,2630)2631if id_stage_taxi > -1:2632id_stage_walk2, time = walkstages.append_stage(2633id_plan, time,2634id_edge_from=id_edge_to_taxi,2635position_edge_from=pos_to_taxi,2636id_edge_to=id_edge_to,2637position_edge_to=pos_edge_to,2638)2639else:2640print ' take taxi directly from origin to destination', time_from2641id_stage_taxi, time = ridestages.append_stage(2642id_plan, time_from,2643id_veh=id_veh,2644# could book taxi here in advance?2645time_init=time_from, # time_from,2646id_edge_from=id_edge_from,2647position_edge_from=pos_edge_from,2648id_edge_to=id_edge_to,2649position_edge_to=pos_edge_to,2650)26512652# here we should have created a taxi ride2653# if not, for whatever reason,2654# we walk from origin to destination2655if id_stage_taxi == -1:2656print ' walk because no ride stage has been planned', time_from2657if id_stage_walk1 == -1:2658# no walk stage has been planned2659id_stage_walk1, time = walkstages.append_stage(2660id_plan, time_from,2661id_edge_from=id_edge_from,2662position_edge_from=pos_edge_from,2663id_edge_to=id_edge_to,2664position_edge_to=pos_edge_to,2665)26662667elif time_from == time:2668# walking to taxi has already been schedules,2669# but taxi ride failed. So walk the whole way2670time = walkstages.modify_stage(2671id_stage_walk1, time_from,2672id_edge_from=id_edge_from,2673position_edge_from=pos_edge_from,2674id_edge_to=id_edge_to,2675position_edge_to=pos_edge_to,2676)2677return time26782679def plan(self, ids_person, logger=None):2680"""2681Generates a plan for these person according to this strategie.2682Overriden by specific strategy.2683"""2684#make_plans_private(self, ids_person = None, mode = 'passenger')2685# routing necessary?2686virtualpop = self.get_virtualpop()2687plans = virtualpop.get_plans() # self._plans2688walkstages = plans.get_stagetable('walks')2689ridestages = plans.get_stagetable('taxirides')2690activitystages = plans.get_stagetable('activities')26912692activities = virtualpop.get_activities()2693activitytypes = virtualpop.get_demand().activitytypes2694landuse = virtualpop.get_landuse()2695facilities = landuse.facilities2696#parking = landuse.parking26972698scenario = virtualpop.get_scenario()2699edges = scenario.net.edges2700lanes = scenario.net.lanes2701modes = scenario.net.modes27022703#times_est_plan = plans.times_est27042705# here we can determine edge weights for different modes2706plans.prepare_stagetables(['walks', 'taxirides', 'activities'])27072708# get initial travel times for persons.2709# initial travel times depend on the initial activity27102711# landuse.parking.clear_booking()27122713ids_person_act, ids_act_from, ids_act_to\2714= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)27152716if len(ids_person_act) == 0:2717print 'WARNING in TaxiStrategy.plan: no eligible persons found.'2718return False27192720# ok27212722# temporary maps from ids_person to other parameters2723nm = np.max(ids_person_act)+12724map_ids_plan = np.zeros(nm, dtype=np.int32)2725map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())27262727map_times = np.zeros(nm, dtype=np.int32)2728map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')27292730# set start time to plans (important!)2731plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]27322733map_ids_fac_from = np.zeros(nm, dtype=np.int32)2734map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]27352736#map_ids_parking_from = np.zeros(nm, dtype = np.int32)2737# ids_parking_from, inds_vehparking = parking.get_closest_parkings( virtualpop.ids_iauto[ids_person_act],2738# facilities.centroids[activities.ids_facility[ids_act_from]])2739# if len(ids_parking_from)==0:2740# return False27412742# err27432744#map_ids_parking_from[ids_person_act] = ids_parking_from27452746n_plans = len(ids_person_act)2747print 'TaxiStrategy.plan n_plans=', n_plans2748# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape2749# set initial activity2750# this is because the following steps start with travel2751# and set the next activity2752#names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]2753# for id_plan27542755ind_act = 027562757# make initial activity stage2758ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]27592760poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]2761poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)27622763# this is the time when first activity starts2764# first activity is normally not simulated27652766names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]2767durations_act_from = activities.get_durations(ids_act_from)2768times_from = map_times[ids_person_act]-durations_act_from2769#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')27702771# do initial stage2772# could be common to all strategies2773for id_plan,\2774time,\2775id_act_from,\2776name_acttype_from,\2777duration_act_from,\2778id_edge_from,\2779pos_edge_from \2780in zip(map_ids_plan[ids_person_act],2781times_from,2782ids_act_from,2783names_acttype_from,2784durations_act_from,2785ids_edge_from,2786poss_edge_from):27872788id_stage_act, time = activitystages.append_stage(2789id_plan, time,2790ids_activity=id_act_from,2791names_activitytype=name_acttype_from,2792durations=duration_act_from,2793ids_lane=edges.ids_lanes[id_edge_from][0],2794positions=pos_edge_from,2795)27962797# main loop while there are persons performing2798# an activity at index ind_act2799while len(ids_person_act) > 0:2800ids_plan = map_ids_plan[ids_person_act]2801ids_veh = virtualpop.ids_imoto[ids_person_act]2802dists_walk_max = virtualpop.dists_walk_max[ids_person_act]2803times_from = map_times[ids_person_act]28042805names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]2806durations_act_to = activities.get_durations(ids_act_to)28072808ids_fac_from = map_ids_fac_from[ids_person_act]2809ids_fac_to = activities.ids_facility[ids_act_to]28102811# origin edge and position2812ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]2813poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]2814poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)28152816centroids_from = facilities.centroids[ids_fac_from]28172818# destination edge and position2819ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]28202821poss_edge_to1 = facilities.positions_roadedge_closest[ids_fac_to]2822poss_edge_to = self.clip_positions(poss_edge_to1, ids_edge_to)2823centroids_to = facilities.centroids[ids_fac_to]28242825dists_from_to = np.sqrt(np.sum((centroids_to - centroids_from)**2, 1))28262827i = 0.02828n_pers = len(ids_person_act)2829for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, dist_from_to, dist_walk_max\2830in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, dists_from_to, dists_walk_max):2831if logger:2832logger.progress(i/n_pers*100)2833i += 1.02834print 79*'*'2835print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to2836print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]28372838time = self.plan_taxiride(id_plan, time_from, id_veh,2839id_edge_from, pos_edge_from,2840id_edge_to, pos_edge_to,2841dist_from_to, dist_walk_max,2842walkstages, ridestages)28432844################28452846# store time estimation for this plan2847# note that these are the travel times, no activity time2848plans.times_est[id_plan] += time-time_from28492850# define current end time without last activity duration2851plans.times_end[id_plan] = time28522853# finally add activity and respective duration28542855id_stage_act, time = activitystages.append_stage(2856id_plan, time,2857ids_activity=id_act_to,2858names_activitytype=name_acttype_to,2859durations=duration_act_to,2860ids_lane=edges.ids_lanes[id_edge_to][0],2861positions=pos_edge_to,2862)28632864map_times[id_person] = time2865# return time2866##28672868# select persons and activities for next setp2869ind_act += 12870ids_person_act, ids_act_from, ids_act_to\2871= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)2872# update timing with (random) activity duration!!28732874return True287528762877class MotorcycleStrategy(StrategyMixin):2878def __init__(self, ident, parent=None,2879name='motorcycle strategy',2880info='With this strategy, the person uses his private motorcycle as main transport mode.',2881**kwargs):28822883self._init_objman(ident, parent, name=name, info=info, **kwargs)2884attrsman = self.set_attrsman(cm.Attrsman(self))2885# specific init2886self._init_attributes(**kwargs)2887self._init_constants()28882889def _init_attributes(self, **kwargs):2890# print 'StrategyMixin._init_attributes'2891attrsman = self.get_attrsman()28922893self._init_attributes_strategy(**kwargs)2894self.n_iter_motoacces_max = attrsman.add(cm.AttrConf('n_iter_motoacces_max', kwargs.get('n_iter_motoacces_max', 5),2895groupnames=['options'],2896perm='rw',2897name='Max. motorcycle access search iterations',2898info='Max. number of iterations while searching an edge with motorcycle access.',2899))29002901self.length_edge_min = attrsman.add(cm.AttrConf('length_edge_min', kwargs.get('length_edge_min', 20.0),2902groupnames=['options'],2903perm='rw',2904name='Min. edge length search',2905unit='m',2906info='Min. edge length when searching an edge with motorcycle access.',2907))29082909self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', -0.0161),2910groupnames=['options'],2911perm='rw',2912name='Utility constant for moto strategy',2913info='Constant to calculate utility: U = Const + value_of_time*time_exec',2914))29152916def _init_constants(self):2917#virtualpop = self.get_virtualpop()2918#stagetables = virtualpop.get_stagetables()29192920#self._walkstages = stagetables.get_stagetable('walks')2921#self._ridestages = stagetables.get_stagetable('rides')2922#self._activitystages = stagetables.get_stagetable('activities')29232924#self._plans = virtualpop.get_plans()2925#2926# print 'AutoStrategy._init_constants'2927# print dir(self)2928# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])29292930modes = self.get_virtualpop().get_scenario().net.modes2931self._id_mode_ped = modes.get_id_mode('pedestrian')2932self._id_mode_bike = modes.get_id_mode('bicycle')2933self._id_mode_auto = modes.get_id_mode('passenger')2934self._id_mode_moto = modes.get_id_mode('motorcycle')2935self._edges = self.get_virtualpop().get_scenario().net.edges2936self.get_attrsman().do_not_save_attrs([2937'_id_mode_bike', '_id_mode_auto', '_id_mode_moto',2938'_id_mode_ped',2939'_edges'])29402941def get_utility_specific(self, id_plan):2942return self.utility_constant29432944def preevaluate(self, ids_person):2945"""2946Preevaluation strategies for person IDs in vector ids_person.29472948Returns a preevaluation vector with a preevaluation value2949for each person ID. The values of the preevaluation vector are as follows:2950-1 : Strategy cannot be applied29510 : Stategy can be applied, but the preferred mode is not used29521 : Stategy can be applied, and preferred mode is part of the strategy29532 : Strategy uses predomunantly preferred mode29542955"""2956n_pers = len(ids_person)2957print 'MotorcycleStrategy.preevaluate', n_pers, 'persons'2958persons = self.get_virtualpop()2959preeval = np.zeros(n_pers, dtype=np.int32)29602961# put -1 for persons without motorcycle access2962preeval[persons.ids_imoto[ids_person] == -1] = -12963print ' persons having no motorcycle', len(np.flatnonzero(persons.ids_imoto[ids_person] == -1))29642965# put 0 for persons with motorcycle but with a different preferred mode2966preeval[(persons.ids_imoto[ids_person] > -1)2967& (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)] = 029682969print ' persons with motorcycle but with a different preferred mode', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] != self._id_mode_moto)))29702971# put 2 for persons with motorcycle access and who prefer the car2972preeval[(persons.ids_imoto[ids_person] > -1)2973& (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)] = 22974print ' persons with motorcycle access and who prefer the car', len(np.flatnonzero((persons.ids_imoto[ids_person] > -1) & (persons.ids_mode_preferred[ids_person] == self._id_mode_moto)))29752976return preeval29772978def get_edge_motoaccess(self, id_edge, is_search_backward=False, is_get_route=False, is_star=False, bstar=0, fstar=0, n_iter_motoacces_max=None):2979# get firts edge allowing bikes and pedestrian, saving route, frontward or backward. You can include bstar or fstar:2980# check only connected links. You can obtain also the route.2981# print 'get_edge_bikeaccess',id_edge, is_search_backward,'id_sumo',self._edges.ids_sumo[id_edge]29822983if n_iter_motoacces_max is None:2984n_iter_motoacces_max = self.n_iter_motoacces_max29852986id_mode = self._id_mode_moto2987id_mode_ped = self._id_mode_ped2988get_accesslevel = self._edges.get_accesslevel2989if is_star:2990if is_search_backward:2991get_next = bstar2992else:2993get_next = fstar2994else:2995if is_search_backward:2996get_next = self._edges.get_incoming2997else:2998get_next = self._edges.get_outgoing29993000edgelengths = self._edges.lengths3001#ids_tried = set()3002ids_current = [id_edge]3003id_motoedge = -13004pos = 0.03005n = 03006ids = [id_edge]3007coll_ids = [0]3008route = []3009while (id_motoedge < 0) & (n < n_iter_motoacces_max):3010n += 130113012ids_new = []3013for id_edge_test, is_long_enough in zip(ids_current, edgelengths[ids_current] > self.length_edge_min):3014# print ' check id',id_edge_test, is_long_enough,get_accesslevel(id_edge_test, id_mode)3015if is_long_enough & (get_accesslevel(id_edge_test, id_mode) >= 0) & (get_accesslevel(id_edge_test, id_mode_ped) >= 0):3016id_motoedge = id_edge_test30173018if is_get_route:3019if n == 1:3020route = []3021else:3022route.append(id_edge_test)3023if n > 2:3024route.append(coll_ids[ids.index(id_edge_test)])3025if n > 3:3026for n in range(n-3):3027route.append(coll_ids[ids.index(route[-1])])3028if is_search_backward is not True:3029route.reverse()30303031# print ' found',id_motoedge,self._edges.ids_sumo[id_motoedge]3032break3033else:30343035if is_star:3036ids_new += get_next[id_edge_test]3037if is_get_route:3038ids += get_next[id_edge_test]3039for i in range(len(get_next[id_edge_test])):3040coll_ids.append(id_edge_test)30413042else:3043ids_new += get_next(id_edge_test)3044if is_get_route:3045ids += get_next(id_edge_test)3046for i in range(len(get_next(id_edge_test))):3047coll_ids += id_edge_test30483049ids_current = ids_new30503051if id_motoedge > -1:3052if is_search_backward:3053pos = edgelengths[id_motoedge]-0.5*self.length_edge_min3054else:3055pos = 0.5*self.length_edge_min30563057if id_motoedge == -1:3058print 'WARNING in get_edge_motoaccess no access for', id_edge, self._edges.ids_sumo[id_edge]30593060if is_get_route:3061return id_motoedge, pos, route3062else:3063return id_motoedge, pos30643065def plan_motoride(self, id_plan, time_from, id_veh,3066id_edge_from, pos_edge_from,3067id_edge_to, pos_edge_to,3068dist_from_to, dist_walk_max,3069walkstages, ridestages):30703071# start creating stages3072id_stage_walk1 = -13073id_stage_moto = -130743075id_edge_from_moto, pos_from_moto = self.get_edge_motoaccess(id_edge_from)3076id_edge_to_moto, pos_to_moto = self.get_edge_motoaccess(id_edge_to, is_search_backward=True)30773078if (dist_from_to < dist_walk_max) | (id_edge_from_moto == -1) | (id_edge_to_moto == -1):3079# print ' go by foot because distance is too short or no moto access',dist_from_to,id_edge_from_moto,id_edge_to_moto3080id_stage_walk1, time = walkstages.append_stage(3081id_plan, time_from,3082id_edge_from=id_edge_from,3083position_edge_from=pos_edge_from,3084id_edge_to=id_edge_to,3085position_edge_to=pos_edge_to,3086)30873088else:3089# print ' try to take the moto',id_veh3090# print ' id_edge_from_moto',edges.ids_sumo[id_edge_from_moto],pos_from_moto3091# print ' id_edge_to_moto',edges.ids_sumo[id_edge_to_moto],pos_to_moto30923093if id_edge_from_moto != id_edge_from:3094# print ' must walk from origin to motorack',time_from30953096id_stage_walk1, time = walkstages.append_stage(3097id_plan, time_from,3098id_edge_from=id_edge_from,3099position_edge_from=pos_edge_from,3100id_edge_to=id_edge_from_moto,3101position_edge_to=pos_from_moto,3102)31033104if id_edge_to_moto != id_edge_to:3105# print ' must ride from motorack to dest motorack',time3106id_stage_moto, time = ridestages.append_stage(3107id_plan, time,3108id_veh=id_veh,3109# delay to be sure that person arrived!(workaround in combination with parking=False)3110time_init=time-10, # time_from,3111id_edge_from=id_edge_from_moto,3112position_edge_from=pos_from_moto,3113id_edge_to=id_edge_to_moto,3114position_edge_to=pos_to_moto,3115)3116if id_stage_moto > -1:3117# print ' must walk from dest motorack to dest',time3118id_stage_walk2, time = walkstages.append_stage(3119id_plan, time,3120id_edge_from=id_edge_to_moto,3121position_edge_from=pos_to_moto,3122id_edge_to=id_edge_to,3123position_edge_to=pos_edge_to,3124)31253126else:3127# print ' ride from motorack to destination',time3128id_stage_moto, time = ridestages.append_stage(3129id_plan, time,3130id_veh=id_veh,3131# delay to be sure that person arrived!(workaround in combination with parking=False)3132time_init=time-10, # time_from,3133id_edge_from=id_edge_from_moto,3134position_edge_from=pos_from_moto,3135id_edge_to=id_edge_to,3136position_edge_to=pos_edge_to,3137)3138else:3139# print ' cycle directly from orign edge',time_from3140if id_edge_to_moto != id_edge_to:3141# print ' must ride from origin to motorack',time_from31423143#pos_to_bike = 0.1*edges.lengths[id_edge_to_bike]3144id_stage_moto, time = ridestages.append_stage(3145id_plan, time_from,3146id_veh=id_veh,3147# delay to be sure that person arrived!(workaround in combination with parking=False)3148time_init=time_from-10, # time_from,3149id_edge_from=id_edge_from,3150position_edge_from=pos_edge_from,3151id_edge_to=id_edge_to_moto,3152position_edge_to=pos_to_moto,3153)3154if id_stage_moto > -1:3155id_stage_walk2, time = walkstages.append_stage(3156id_plan, time,3157id_edge_from=id_edge_to_moto,3158position_edge_from=pos_to_moto,3159id_edge_to=id_edge_to,3160position_edge_to=pos_edge_to,3161)3162else:3163# print ' must ride from origin to destination',time_from3164id_stage_moto, time = ridestages.append_stage(3165id_plan, time_from,3166id_veh=id_veh,3167# delay to be sure that person arrived!(workaround in combination with parking=False)3168time_init=time_from-10, # time_from,3169id_edge_from=id_edge_from,3170position_edge_from=pos_edge_from,3171id_edge_to=id_edge_to,3172position_edge_to=pos_edge_to,3173)31743175# here we should have created a moto ride3176# if not, for ehatever reason,3177# we walk from origin to destination3178if id_stage_moto == -1:3179# print ' walk because no ride stage has been planned',time_from3180if id_stage_walk1 == -1:3181# no walk stage has been planned3182id_stage_walk1, time = walkstages.append_stage(3183id_plan, time_from,3184id_edge_from=id_edge_from,3185position_edge_from=pos_edge_from,3186id_edge_to=id_edge_to,3187position_edge_to=pos_edge_to,3188)31893190elif time_from == time:3191# walking to bike has already been schedules,3192# but cycling failed. So walk the whole way3193time = walkstages.modify_stage(3194id_stage_walk1, time_from,3195id_edge_from=id_edge_from,3196position_edge_from=pos_edge_from,3197id_edge_to=id_edge_to,3198position_edge_to=pos_edge_to,3199)3200return time32013202def plan(self, ids_person, logger=None):3203"""3204Generates a plan for these person according to this strategie.3205Overriden by specific strategy.3206"""3207#make_plans_private(self, ids_person = None, mode = 'passenger')3208# routing necessary?3209virtualpop = self.get_virtualpop()3210plans = virtualpop.get_plans() # self._plans3211walkstages = plans.get_stagetable('walks')3212ridestages = plans.get_stagetable('motorides')3213activitystages = plans.get_stagetable('activities')32143215activities = virtualpop.get_activities()3216activitytypes = virtualpop.get_demand().activitytypes3217landuse = virtualpop.get_landuse()3218facilities = landuse.facilities3219#parking = landuse.parking32203221scenario = virtualpop.get_scenario()3222edges = scenario.net.edges3223lanes = scenario.net.lanes3224modes = scenario.net.modes32253226#times_est_plan = plans.times_est32273228# here we can determine edge weights for different modes3229plans.prepare_stagetables(['walks', 'motorides', 'activities'])32303231# get initial travel times for persons.3232# initial travel times depend on the initial activity32333234# landuse.parking.clear_booking()32353236ids_person_act, ids_act_from, ids_act_to\3237= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)32383239if len(ids_person_act) == 0:3240print 'WARNING in MotorcycleStrategy.plan: no eligible persons found.'3241return False32423243# ok32443245# temporary maps from ids_person to other parameters3246nm = np.max(ids_person_act)+13247map_ids_plan = np.zeros(nm, dtype=np.int32)3248map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())32493250map_times = np.zeros(nm, dtype=np.int32)3251map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')32523253# set start time to plans (important!)3254plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]32553256map_ids_fac_from = np.zeros(nm, dtype=np.int32)3257map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]32583259#map_ids_parking_from = np.zeros(nm, dtype = np.int32)3260# ids_parking_from, inds_vehparking = parking.get_closest_parkings( virtualpop.ids_iauto[ids_person_act],3261# facilities.centroids[activities.ids_facility[ids_act_from]])3262# if len(ids_parking_from)==0:3263# return False32643265# err32663267#map_ids_parking_from[ids_person_act] = ids_parking_from32683269n_plans = len(ids_person_act)3270print 'MotorcycleStrategy.plan n_plans=', n_plans3271# print ' map_ids_parking_from[ids_person_act].shape',map_ids_parking_from[ids_person_act].shape3272# set initial activity3273# this is because the following steps start with travel3274# and set the next activity3275#names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]3276# for id_plan32773278ind_act = 032793280# make initial activity stage3281ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]32823283poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]3284poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)32853286# this is the time when first activity starts3287# first activity is normally not simulated32883289names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]3290durations_act_from = activities.get_durations(ids_act_from)3291times_from = map_times[ids_person_act]-durations_act_from3292#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')32933294# do initial stage3295# could be common to all strategies3296for id_plan,\3297time,\3298id_act_from,\3299name_acttype_from,\3300duration_act_from,\3301id_edge_from,\3302pos_edge_from \3303in zip(map_ids_plan[ids_person_act],3304times_from,3305ids_act_from,3306names_acttype_from,3307durations_act_from,3308ids_edge_from,3309poss_edge_from):33103311id_stage_act, time = activitystages.append_stage(3312id_plan, time,3313ids_activity=id_act_from,3314names_activitytype=name_acttype_from,3315durations=duration_act_from,3316ids_lane=edges.ids_lanes[id_edge_from][0],3317positions=pos_edge_from,3318)33193320# main loop while there are persons performing3321# an activity at index ind_act3322while len(ids_person_act) > 0:3323ids_plan = map_ids_plan[ids_person_act]3324ids_veh = virtualpop.ids_imoto[ids_person_act]3325dists_walk_max = virtualpop.dists_walk_max[ids_person_act]3326times_from = map_times[ids_person_act]33273328names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]3329durations_act_to = activities.get_durations(ids_act_to)33303331ids_fac_from = map_ids_fac_from[ids_person_act]3332ids_fac_to = activities.ids_facility[ids_act_to]33333334# origin edge and position3335ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]3336poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]3337poss_edge_from = self.clip_positions(poss_edge_from, ids_edge_from)33383339centroids_from = facilities.centroids[ids_fac_from]33403341# this method will find and occupy parking space3342#ids_parking_from = map_ids_parking_from[ids_person_act]33433344# print ' ids_veh.shape',ids_veh.shape3345# print ' centroids_to.shape',centroids_to.shape3346#ids_parking_to, inds_vehparking = parking.get_closest_parkings(ids_veh, centroids_to)33473348#ids_lane_parking_from = parking.ids_lane[ids_parking_from]3349#ids_edge_parking_from = lanes.ids_edge[ids_lane_parking_from]3350#poss_edge_parking_from = parking.positions[ids_parking_from]33513352# print ' ids_parking_to.shape',ids_parking_to.shape3353# print ' np.max(parking.get_ids()), np.max(ids_parking_to)',np.max(parking.get_ids()), np.max(ids_parking_to)3354#ids_lane_parking_to = parking.ids_lane[ids_parking_to]3355#ids_edge_parking_to = lanes.ids_edge[ids_lane_parking_to]3356#poss_edge_parking_to = parking.positions[ids_parking_to]33573358# destination edge and position3359ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]33603361poss_edge_to1 = facilities.positions_roadedge_closest[ids_fac_to]3362poss_edge_to = self.clip_positions(poss_edge_to1, ids_edge_to)3363centroids_to = facilities.centroids[ids_fac_to]33643365# debug poscorrection..OK3366# for id_edge, id_edge_sumo, length, pos_to1, pos in zip(ids_edge_to, edges.ids_sumo[ids_edge_to],edges.lengths[ids_edge_to],poss_edge_to1, poss_edge_to):3367# print ' ',id_edge, 'IDe%s'%id_edge_sumo, 'L=%.2fm'%length, '%.2fm'%pos_to1, '%.2fm'%pos33683369dists_from_to = np.sqrt(np.sum((centroids_to - centroids_from)**2, 1))33703371i = 0.03372n_pers = len(ids_person_act)3373for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, dist_from_to, dist_walk_max\3374in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, dists_from_to, dists_walk_max):3375if logger:3376logger.progress(i/n_pers*100)3377i += 1.03378print 79*'*'3379print ' plan id_plan', id_plan, 'time_from', time_from, 'from', id_edge_from, pos_edge_from, 'to', id_edge_to, pos_edge_to3380print ' id_edge_from', edges.ids_sumo[id_edge_from], 'id_edge_to', edges.ids_sumo[id_edge_to]33813382time = self.plan_motoride(id_plan, time_from, id_veh,3383id_edge_from, pos_edge_from,3384id_edge_to, pos_edge_to,3385dist_from_to, dist_walk_max,3386walkstages, ridestages)33873388################33893390# store time estimation for this plan3391# note that these are the travel times, no activity time3392plans.times_est[id_plan] += time-time_from33933394# define current end time without last activity duration3395plans.times_end[id_plan] = time33963397# finally add activity and respective duration33983399id_stage_act, time = activitystages.append_stage(3400id_plan, time,3401ids_activity=id_act_to,3402names_activitytype=name_acttype_to,3403durations=duration_act_to,3404ids_lane=edges.ids_lanes[id_edge_to][0],3405positions=pos_edge_to,3406)34073408map_times[id_person] = time3409# return time3410##34113412# select persons and activities for next setp3413ind_act += 13414ids_person_act, ids_act_from, ids_act_to\3415= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)3416# update timing with (random) activity duration!!34173418return True341934203421class TransitStrategy(StrategyMixin):3422def __init__(self, ident, parent=None,3423name='Public Transport Strategy',3424info='With this strategy, the person uses public transport.',3425**kwargs):34263427self._init_objman(ident, parent, name=name, info=info, **kwargs)3428attrsman = self.set_attrsman(cm.Attrsman(self))3429# specific init3430self._init_attributes()3431self._init_constants()34323433def _init_attributes(self, **kwargs):3434# print 'StrategyMixin._init_attributes'3435attrsman = self.get_attrsman()34363437self.utility_constant = attrsman.add(cm.AttrConf('utility_constant', kwargs.get('utility_constant', 0.3727),3438groupnames=['options'],3439perm='rw',3440name='Utility constant for transit strategy',3441info='Constant to calculate utility: U = Const + value_of_time*time_exec',3442))34433444def _init_constants(self):3445#virtualpop = self.get_virtualpop()3446#stagetables = virtualpop.get_stagetables()34473448#self._walkstages = stagetables.get_stagetable('walks')3449#self._ridestages = stagetables.get_stagetable('rides')3450#self._activitystages = stagetables.get_stagetable('activities')34513452#self._plans = virtualpop.get_plans()3453#3454# print 'AutoStrategy._init_constants'3455# print dir(self)3456# self.get_attrsman().do_not_save_attrs(['_activitystages','_ridestages','_walkstages','_plans'])34573458modes = self.get_virtualpop().get_scenario().net.modes3459self._id_mode_bike = modes.get_id_mode('bicycle')3460self._id_mode_auto = modes.get_id_mode('passenger')3461self._id_mode_moto = modes.get_id_mode('motorcycle')3462self._id_mode_bus = modes.get_id_mode('bus')3463self.get_attrsman().do_not_save_attrs([3464'_id_mode_bike', '_id_mode_auto', '_id_mode_moto', '_id_mode_bus'3465])34663467def preevaluate(self, ids_person):3468"""3469Preevaluation strategies for person IDs in vector ids_person.34703471Returns a preevaluation vector with a preevaluation value3472for each person ID. The values of the preevaluation vector are as follows:3473-1 : Strategy cannot be applied34740 : Stategy can be applied, but the preferred mode is not used34751 : Stategy can be applied, and preferred mode is part of the strategy34762 : Strategy uses predomunantly preferred mode34773478"""3479n_pers = len(ids_person)3480persons = self.get_virtualpop()3481preeval = np.zeros(n_pers, dtype=np.int32)34823483# TODO: here we could exclude by age or distance facilities-stops34843485# put 0 for persons whose preference is not public transport3486preeval[persons.ids_mode_preferred[ids_person] != self._id_mode_bus] = 034873488# put 2 for persons with car access and who prefer cars3489preeval[persons.ids_mode_preferred[ids_person] == self._id_mode_bus] = 234903491print ' TransitStrategy.preevaluate', len(np.flatnonzero(preeval))3492return preeval34933494def plan_transit(self, id_plan, time_from,3495id_edge_from, pos_edge_from,3496id_edge_to, pos_edge_to,3497id_stop_from, id_stopedge_from, pos_stop_from,3498id_stop_to, id_stopedge_to, pos_stop_to,3499#dist_from_to, dist_walk_max,3500walkstages, transitstages,3501ptlines, ptfstar, pttimes,3502stops_to_enter, stops_to_exit,3503ids_laneedge, ids_stoplane, ptstops):35043505edges = self.get_scenario().net.edges3506print 'plan_transit id_plan', id_plan, 'id_edge_from %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from]), 'id_edge_to %d (%s)' % (id_edge_to, edges.ids_sumo[id_edge_to])35073508# debug?3509is_debug = False # id_plan == 1498335103511if is_debug:35123513print ' id_stop_from', id_stop_from, 'id_stop_to', id_stop_to35143515ptlinks = ptlines.get_ptlinks()3516ptlinktypes = ptlinks.types.choices3517type_enter = ptlinktypes['enter']3518type_transit = ptlinktypes['transit']3519type_board = ptlinktypes['board']3520type_alight = ptlinktypes['alight']3521type_transfer = ptlinktypes['transfer']3522type_walk = ptlinktypes['walk']3523type_exit = ptlinktypes['exit']35243525if (id_edge_from == id_stopedge_from) & (abs(pos_edge_from-pos_stop_from) < 1.0):3526time = time_from3527id_stage_walk1 = None3528if is_debug:3529print ' no initial walk required.'3530print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]3531print ' pos_edge_from', pos_edge_from3532else:3533id_stage_walk1, time = walkstages.append_stage(id_plan, time_from,3534id_edge_from=id_edge_from,3535position_edge_from=pos_edge_from,3536id_edge_to=id_stopedge_from,3537position_edge_to=pos_stop_from, # -7.0,3538)3539if is_debug:3540print ' add initial walk stage'3541print ' id_edge_from', id_edge_from, edges.ids_sumo[id_edge_from]3542print ' pos_edge_from', pos_edge_from3543print ' IIIInitial walk'3544print ' id_stopedge_from', id_stopedge_from, edges.ids_sumo[id_stopedge_from]3545print ' pos_stop_from', pos_stop_from35463547if is_debug:3548print ' TTTransit'3549print ' id_stopedge_to', id_stopedge_to, edges.ids_sumo[id_stopedge_to]3550print ' pos_stop_to', pos_stop_to3551print ' ----------------------------------'3552print ' id_stop_from', id_stop_from3553print ' id_stop_to', id_stop_to35543555durations, linktypes, ids_line, ids_fromstop, ids_tostop =\3556ptlinks.route(id_stop_from, id_stop_to,3557fstar=ptfstar, times=pttimes,3558stops_to_enter=stops_to_enter,3559stops_to_exit=stops_to_exit)35603561if is_debug:3562print ' routing done. make plan, success', len(linktypes) > 035633564if is_debug:3565print ' ids_line ', ids_line3566print ' ids_fromstop', ids_fromstop3567print ' ids_tostop ', ids_tostop35683569if (type_transit in linktypes): # is there any public transport line to take?35703571# go though PT links and generate transits and walks to trasfer3572ids_stopedge_from = ids_laneedge[ids_stoplane[ids_fromstop]]3573ids_stopedge_to = ids_laneedge[ids_stoplane[ids_tostop]]3574poss_stop_from = 0.5*(ptstops.positions_from[ids_fromstop]3575+ ptstops.positions_to[ids_fromstop])3576poss_stop_to = 0.5*(ptstops.positions_from[ids_tostop]3577+ ptstops.positions_to[ids_tostop])35783579# this is wait time buffer to be added to the successive stage3580# as waiting is currently not modelled as an extra stage3581duration_wait = 0.035823583# check if initial walk needs to be modified3584if (id_stage_walk1 is not None) & (linktypes[0] == type_walk):3585if is_debug:3586print ' Modify initial walk from stop fromedge %d (%s) toedge %d (%s)' % (id_edge_from, edges.ids_sumo[id_edge_from], ids_stopedge_from[0], edges.ids_sumo[ids_stopedge_from[0]])35873588is_initial_walk_done = True3589time = walkstages.modify_stage(3590id_stage_walk1,3591id_edge_from=id_edge_from,3592position_edge_from=pos_edge_from,3593id_edge_to=ids_stopedge_to[0],3594position_edge_to=poss_stop_to[0],3595)3596else:3597is_initial_walk_done = False35983599# create stages for PT3600for i, linktype, id_line, duration,\3601id_stopedge_from, pos_fromstop,\3602id_stopedge_to, pos_tostop in\3603zip(xrange(len(linktypes)),3604linktypes,3605ids_line,3606durations,3607ids_stopedge_from, poss_stop_from,3608ids_stopedge_to, poss_stop_to,3609):3610if is_debug:3611print ' ...........................'3612print ' stage for linktype %2d fromedge %s toedge %s' % (linktype, edges.ids_sumo[id_stopedge_from], edges.ids_sumo[id_stopedge_to])3613print ' id_stopedge_from,id_stopedge_to', id_stopedge_from, id_stopedge_to36143615if linktype == type_transit: # transit!3616# check if last link type has also been a transit3617if i > 0:3618if linktypes[i-1] == type_transit:3619if is_debug:3620print ' add inter-transit walk stage'3621# introdice a walk stage to be sure that3622# person gets to the middle of the stop3623id_stage_transfer, time = walkstages.append_stage(3624id_plan, time,3625id_edge_from=ids_stopedge_to[i-1],3626position_edge_from=poss_stop_to[i-1],3627id_edge_to=ids_stopedge_to[i-1],3628position_edge_to=poss_stop_to[i-1],3629duration=0.0, # moving within stop area3630)36313632if is_debug:3633print ' add transit stage id_line', id_line3634id_stage_transit, time = transitstages.append_stage(3635id_plan, time,3636id_line=id_line,3637duration=duration+duration_wait,3638id_fromedge=id_stopedge_from,3639id_toedge=id_stopedge_to,3640)3641duration_wait = 0.036423643elif (linktype == type_walk) & ((i > 0) | (not is_initial_walk_done)):3644# walk to transfer, no initial walk if done3645if is_debug:3646print ' add walk to transfer'3647id_stage_transfer, time = walkstages.append_stage(3648id_plan, time,3649id_edge_from=id_stopedge_from,3650position_edge_from=pos_fromstop,3651id_edge_to=id_stopedge_to,3652position_edge_to=pos_tostop,3653duration=duration+duration_wait,3654)3655duration_wait = 0.036563657else: # all other link time are no modelld3658# do not do anything , just add wait time to next stage3659if is_debug:3660print ' do noting add duration', duration3661duration_wait += duration36623663# walk from final stop to activity3664i = len(linktypes)-1 # last link index36653666if is_debug:3667print ' linktypes', linktypes, 'i', i, 'linktypes[i]', linktypes[i], linktypes[i] == type_walk36683669if linktypes[i] == type_walk:3670if is_debug:3671print ' Modify final walk from stop fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])36723673time = walkstages.modify_stage(3674id_stage_transfer,3675id_edge_from=ids_stopedge_from[i],3676position_edge_from=poss_stop_from[i],3677id_edge_to=id_edge_to,3678position_edge_to=pos_edge_to,3679)36803681else:3682if is_debug:3683print ' Add final walk stage fromedge %d (%s) toedge %d (%s)' % (id_stopedge_to, edges.ids_sumo[id_stopedge_to], id_edge_to, edges.ids_sumo[id_edge_to])36843685id_stage_walk2, time = walkstages.append_stage(id_plan, time,3686id_edge_from=id_stopedge_to,3687position_edge_from=pos_tostop,3688id_edge_to=id_edge_to,3689position_edge_to=pos_edge_to,3690)36913692else:3693# there is no public transport line linking these nodes.3694if is_debug:3695print ' No PT lines used create direct walk stage'36963697if id_stage_walk1 is None:3698# Create first walk directly from home to activity3699id_stage_walk1, time = walkstages.append_stage(id_plan,3700time_from,3701id_edge_from=id_edge_from,3702position_edge_from=pos_edge_from,3703id_edge_to=id_edge_to,3704position_edge_to=pos_edge_to,3705)3706else:3707# Modify first walk directly from home to activity3708time = walkstages.modify_stage(id_stage_walk1, time_from,3709id_edge_from=id_edge_from,3710position_edge_from=pos_edge_from,3711id_edge_to=id_edge_to,3712position_edge_to=pos_edge_to,3713)37143715return time37163717def plan(self, ids_person, logger=None, **kwargs):3718"""3719Generates a plan for these person according to this strategie.3720Overriden by specific strategy.3721"""3722print 'TransitStrategy.plan', len(ids_person)3723#make_plans_private(self, ids_person = None, mode = 'passenger')3724# routing necessary?3725virtualpop = self.get_virtualpop()3726plans = virtualpop.get_plans() # self._plans3727demand = virtualpop.get_demand()3728ptlines = demand.ptlines37293730walkstages = plans.get_stagetable('walks')3731transitstages = plans.get_stagetable('transits')3732activitystages = plans.get_stagetable('activities')37333734activities = virtualpop.get_activities()3735activitytypes = demand.activitytypes3736landuse = virtualpop.get_landuse()3737facilities = landuse.facilities3738parking = landuse.parking37393740scenario = virtualpop.get_scenario()3741net = scenario.net3742edges = net.edges3743lanes = net.lanes3744modes = net.modes37453746ptstops = net.ptstops37473748# print ' demand',demand3749# print ' demand.ptlines',demand.ptlines,dir(demand.ptlines)3750# print ' demand.ptlines.get_ptlinks()',demand.ptlines.get_ptlinks()3751# print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)3752# print ' demand.trips',demand.trips,dir(demand.trips)3753if len(ptlines) == 0:3754print 'WARNING in TrasitStrategy.plan: no transit services available. Create public trasit services by connecting stops.'3755return False37563757ptlinks = ptlines.get_ptlinks()3758if len(ptlinks) == 0:3759print 'WARNING in TrasitStrategy.plan: no public transport links. Run methods: "create routes" and "build links" from public trasport services.'3760return False37613762ptlinktypes = ptlinks.types.choices37633764ptfstar = ptlinks.get_fstar()3765pttimes = ptlinks.get_times()3766stops_to_enter, stops_to_exit = ptlinks.get_stops_to_enter_exit()37673768ids_stoplane = ptstops.ids_lane3769ids_laneedge = net.lanes.ids_edge37703771times_est_plan = plans.times_est3772# here we can determine edge weights for different modes37733774# this could be centralized to avoid redundance3775plans.prepare_stagetables(['walks', 'transits', 'activities'])37763777ids_person_act, ids_act_from, ids_act_to\3778= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)37793780if len(ids_person_act) == 0:3781print 'WARNING in TrasitStrategy.plan: no eligible persons found.'3782return False37833784# temporary maps from ids_person to other parameters3785nm = np.max(ids_person_act)+13786map_ids_plan = np.zeros(nm, dtype=np.int32)3787#ids_plan_act = virtualpop.add_plans(ids_person_act, id_strategy = self.get_id_strategy())3788map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())37893790map_times = np.zeros(nm, dtype=np.int32)3791map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')37923793# set start time to plans (important!)3794plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]37953796map_ids_fac_from = np.zeros(nm, dtype=np.int32)3797map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]37983799n_plans = len(ids_person_act)3800print 'TrasitStrategy.plan n_plans=', n_plans38013802# make initial activity stage3803ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]3804poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]3805# this is the time when first activity starts3806# first activity is normally not simulated38073808names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]3809durations_act_from = activities.get_durations(ids_act_from)3810times_from = map_times[ids_person_act]-durations_act_from3811#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')38123813for id_plan,\3814time,\3815id_act_from,\3816name_acttype_from,\3817duration_act_from,\3818id_edge_from,\3819pos_edge_from \3820in zip(map_ids_plan[ids_person_act],3821times_from,3822ids_act_from,3823names_acttype_from,3824durations_act_from,3825ids_edge_from,3826poss_edge_from):38273828id_stage_act, time = activitystages.append_stage(3829id_plan, time,3830ids_activity=id_act_from,3831names_activitytype=name_acttype_from,3832durations=duration_act_from,3833ids_lane=edges.ids_lanes[id_edge_from][0],3834positions=pos_edge_from,3835)38363837##38383839ind_act = 038403841# main loop while there are persons performing3842# an activity at index ind_act3843while len(ids_person_act) > 0:3844ids_plan = map_ids_plan[ids_person_act]38453846times_from = map_times[ids_person_act]38473848names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]3849durations_act_to = activities.get_durations(ids_act_to)38503851ids_fac_from = map_ids_fac_from[ids_person_act]3852ids_fac_to = activities.ids_facility[ids_act_to]38533854centroids_from = facilities.centroids[ids_fac_from]3855centroids_to = facilities.centroids[ids_fac_to]38563857# origin edge and position3858ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]3859poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]38603861# destination edge and position3862ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]3863poss_edge_to = facilities.positions_roadedge_closest[ids_fac_to]38643865ids_stop_from = ptstops.get_closest(centroids_from)3866ids_stop_to = ptstops.get_closest(centroids_to)38673868ids_stopedge_from = ids_laneedge[ids_stoplane[ids_stop_from]]3869ids_stopedge_to = ids_laneedge[ids_stoplane[ids_stop_to]]38703871# do random pos here3872poss_stop_from = 0.5*(ptstops.positions_from[ids_stop_from]3873+ ptstops.positions_to[ids_stop_from])38743875poss_stop_to = 0.5*(ptstops.positions_from[ids_stop_to]3876+ ptstops.positions_to[ids_stop_to])38773878i = 0.03879for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, id_stop_from, id_stopedge_from, pos_stop_from, id_stop_to, id_stopedge_to, pos_stop_to\3880in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, ids_stop_from, ids_stopedge_from, poss_stop_from, ids_stop_to, ids_stopedge_to, poss_stop_to):3881n_pers = len(ids_person_act)3882if logger:3883logger.progress(i/n_pers*100)3884i += 1.03885print 79*'_'3886print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)38873888time = self.plan_transit(id_plan, time_from,3889id_edge_from, pos_edge_from,3890id_edge_to, pos_edge_to,3891id_stop_from, id_stopedge_from, pos_stop_from,3892id_stop_to, id_stopedge_to, pos_stop_to,3893#dist_from_to, dist_walk_max,3894walkstages, transitstages,3895ptlines, ptfstar, pttimes,3896stops_to_enter, stops_to_exit,3897ids_laneedge, ids_stoplane, ptstops)38983899# update time for trips estimation for this plan3900plans.times_est[id_plan] += time-time_from39013902# define current end time without last activity duration3903plans.times_end[id_plan] = time39043905id_stage_act, time = activitystages.append_stage(3906id_plan, time,3907ids_activity=id_act_to,3908names_activitytype=name_acttype_to,3909durations=duration_act_to,3910ids_lane=edges.ids_lanes[id_edge_to][0],3911positions=pos_edge_to,3912)39133914# store time for next iteration in case other activities are3915# following3916map_times[id_person] = time39173918# select persons and activities for next setp3919ind_act += 13920ids_person_act, ids_act_from, ids_act_to\3921= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)392239233924class BikeTransitStrategy(BikeStrategy, TransitStrategy):3925def __init__(self, ident, parent=None,3926name='Bike+Public Transport Strategy',3927info='With this strategy, the person combines bike and public transport.',3928**kwargs):39293930self._init_objman(ident, parent, name=name, info=info, **kwargs)3931attrsman = self.set_attrsman(cm.Attrsman(self))3932# specific init3933self._init_attributes()3934self._init_constants()39353936def _init_attributes(self):3937# print 'StrategyMixin._init_attributes'3938BikeStrategy._init_attributes(self)3939TransitStrategy._init_attributes(self)39403941def _init_constants(self):39423943BikeStrategy._init_constants(self)3944TransitStrategy._init_constants(self)39453946def preevaluate(self, ids_person):3947"""3948Preevaluation strategies for person IDs in vector ids_person.39493950Returns a preevaluation vector with a preevaluation value3951for each person ID. The values of the preevaluation vector are as follows:3952-1 : Strategy cannot be applied39530 : Stategy can be applied, but the preferred mode is not used39541 : Stategy can be applied, and preferred mode is part of the strategy39552 : Strategy uses predomunantly preferred mode39563957"""3958n_pers = len(ids_person)3959persons = self.get_virtualpop()3960preeval = np.zeros(n_pers, dtype=np.int32)39613962inds_prefer = (persons.ids_mode_preferred[ids_person] == self._id_mode_bus)\3963| (persons.ids_mode_preferred[ids_person] == self._id_mode_bike)\39643965inds_avail = persons.ids_ibike[ids_person] > -13966preeval[np.logical_not(inds_avail)] = -13967# TODO: here we could exclude by age or distance facilities-stops39683969# put 0 for persons whose preference is not public transport3970preeval[inds_avail & np.logical_not(inds_prefer)] = 039713972# put 2 for persons with bike access and who prefer bike or bus3973preeval[inds_avail & inds_prefer] = 139743975print ' BikeTransitStrategy.preevaluate', len(np.flatnonzero(preeval))3976return preeval39773978def plan(self, ids_person, logger=None, **kwargs):3979"""3980Generates a plan for these person according to this strategie.3981Overriden by specific strategy.3982"""3983print 'TransitStrategy.plan', len(ids_person)3984#make_plans_private(self, ids_person = None, mode = 'passenger')3985# routing necessary?3986virtualpop = self.get_virtualpop()3987plans = virtualpop.get_plans() # self._plans3988demand = virtualpop.get_demand()3989ptlines = demand.ptlines39903991walkstages = plans.get_stagetable('walks')3992transitstages = plans.get_stagetable('transits')3993ridestages = plans.get_stagetable('bikerides')3994activitystages = plans.get_stagetable('activities')39953996activities = virtualpop.get_activities()3997activitytypes = demand.activitytypes3998landuse = virtualpop.get_landuse()3999facilities = landuse.facilities4000#parking = landuse.parking40014002scenario = virtualpop.get_scenario()4003net = scenario.net4004edges = net.edges4005lanes = net.lanes4006modes = net.modes40074008ptstops = net.ptstops40094010# print ' demand',demand4011# print ' demand.ptlines',demand.ptlines,dir(demand.ptlines)4012# print ' demand.ptlines.get_ptlinks()',demand.ptlines.get_ptlinks()4013# print ' demand.virtualpop',demand.virtualpop,dir(demand.virtualpop)4014# print ' demand.trips',demand.trips,dir(demand.trips)4015if len(ptlines) == 0:4016print 'WARNING in TrasitStrategy.plan: no transit services available.'4017return False40184019ptlinks = ptlines.get_ptlinks()4020ptlinktypes = ptlinks.types.choices40214022ptfstar = ptlinks.get_fstar()4023pttimes = ptlinks.get_times()4024stops_to_enter, stops_to_exit = ptlinks.get_stops_to_enter_exit()40254026ids_stoplane = ptstops.ids_lane4027ids_laneedge = net.lanes.ids_edge40284029times_est_plan = plans.times_est4030# here we can determine edge weights for different modes40314032# this could be centralized to avoid redundance4033plans.prepare_stagetables(['walks', 'bikerides', 'transits', 'activities'])40344035ids_person_act, ids_act_from, ids_act_to\4036= virtualpop.get_activities_from_pattern(0, ids_person=ids_person)40374038if len(ids_person_act) == 0:4039print 'WARNING in TrasitStrategy.plan: no eligible persons found.'4040return False40414042# temporary maps from ids_person to other parameters4043nm = np.max(ids_person_act)+14044map_ids_plan = np.zeros(nm, dtype=np.int32)4045#ids_plan_act = virtualpop.add_plans(ids_person_act, id_strategy = self.get_id_strategy())4046map_ids_plan[ids_person_act] = virtualpop.add_plans(ids_person_act, id_strategy=self.get_id_strategy())40474048map_times = np.zeros(nm, dtype=np.int32)4049map_times[ids_person_act] = activities.get_times_end(ids_act_from, pdf='unit')40504051# set start time to plans (important!)4052plans.times_begin[map_ids_plan[ids_person_act]] = map_times[ids_person_act]40534054map_ids_fac_from = np.zeros(nm, dtype=np.int32)4055map_ids_fac_from[ids_person_act] = activities.ids_facility[ids_act_from]40564057n_plans = len(ids_person_act)4058print 'TrasitStrategy.plan n_plans=', n_plans40594060# make initial activity stage4061ids_edge_from = facilities.ids_roadedge_closest[map_ids_fac_from[ids_person_act]]4062poss_edge_from = facilities.positions_roadedge_closest[map_ids_fac_from[ids_person_act]]4063# this is the time when first activity starts4064# first activity is normally not simulated40654066names_acttype_from = activitytypes.names[activities.ids_activitytype[ids_act_from]]4067durations_act_from = activities.get_durations(ids_act_from)4068times_from = map_times[ids_person_act]-durations_act_from4069#times_from = activities.get_times_end(ids_act_from, pdf = 'unit')40704071for id_plan,\4072time,\4073id_act_from,\4074name_acttype_from,\4075duration_act_from,\4076id_edge_from,\4077pos_edge_from \4078in zip(map_ids_plan[ids_person_act],4079times_from,4080ids_act_from,4081names_acttype_from,4082durations_act_from,4083ids_edge_from,4084poss_edge_from):40854086id_stage_act, time = activitystages.append_stage(4087id_plan, time,4088ids_activity=id_act_from,4089names_activitytype=name_acttype_from,4090durations=duration_act_from,4091ids_lane=edges.ids_lanes[id_edge_from][0],4092positions=pos_edge_from,4093)40944095##40964097ind_act = 040984099# main loop while there are persons performing4100# an activity at index ind_act4101while len(ids_person_act) > 0:4102ids_plan = map_ids_plan[ids_person_act]41034104times_from = map_times[ids_person_act]41054106ids_veh = virtualpop.ids_ibike[ids_person_act]4107dists_walk_max = virtualpop.dists_walk_max[ids_person_act]4108names_acttype_to = activitytypes.names[activities.ids_activitytype[ids_act_to]]4109durations_act_to = activities.get_durations(ids_act_to)41104111ids_fac_from = map_ids_fac_from[ids_person_act]4112ids_fac_to = activities.ids_facility[ids_act_to]41134114centroids_from = facilities.centroids[ids_fac_from]4115centroids_to = facilities.centroids[ids_fac_to]41164117# origin edge and position4118ids_edge_from = facilities.ids_roadedge_closest[ids_fac_from]4119poss_edge_from = facilities.positions_roadedge_closest[ids_fac_from]41204121# destination edge and position4122ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]4123poss_edge_to = facilities.positions_roadedge_closest[ids_fac_to]41244125ids_stop_from = ptstops.get_closest(centroids_from)4126ids_stop_to = ptstops.get_closest(centroids_to)41274128ids_stopedge_from = ids_laneedge[ids_stoplane[ids_stop_from]]4129ids_stopedge_to = ids_laneedge[ids_stoplane[ids_stop_to]]41304131centroids_stop_from = ptstops.centroids[ids_stop_from]4132centroids_stop_to = ptstops.centroids[ids_stop_to]4133# do random pos here4134poss_stop_from = 0.5*(ptstops.positions_from[ids_stop_from]4135+ ptstops.positions_to[ids_stop_from])41364137poss_stop_to = 0.5*(ptstops.positions_from[ids_stop_to]4138+ ptstops.positions_to[ids_stop_to])41394140dists_from_to = np.sqrt(np.sum((centroids_to - centroids_from)**2, 1))4141dists_from_stop_from = np.sqrt(np.sum((centroids_stop_from - centroids_from)**2, 1))4142dists_stop_to_to = np.sqrt(np.sum((centroids_to - centroids_stop_to)**2, 1))41434144i = 0.04145for id_person, id_plan, time_from, id_act_from, id_act_to, name_acttype_to, duration_act_to, id_veh, id_edge_from, pos_edge_from, id_edge_to, pos_edge_to, id_stop_from, id_stopedge_from, pos_stop_from, id_stop_to, id_stopedge_to, pos_stop_to, dists_from_to, dist_from_stop_from, dist_stop_to_to, dist_walk_max\4146in zip(ids_person_act, ids_plan, times_from, ids_act_from, ids_act_to, names_acttype_to, durations_act_to, ids_veh, ids_edge_from, poss_edge_from, ids_edge_to, poss_edge_to, ids_stop_from, ids_stopedge_from, poss_stop_from, ids_stop_to, ids_stopedge_to, poss_stop_to, dists_from_to, dists_from_stop_from, dists_stop_to_to, dists_walk_max):4147n_pers = len(ids_person_act)4148if logger:4149logger.progress(i/n_pers*100)4150i += 1.04151print 79*'_'4152print ' id_plan=%d, id_person=%d, ' % (id_plan, id_person)4153#dist_from_stop_from, dist_stop_to_to41544155time = self.plan_bikeride(id_plan, time_from, id_veh,4156id_edge_from, pos_edge_from,4157id_stopedge_from, pos_stop_from,4158dist_from_stop_from, dist_walk_max,4159walkstages, ridestages)41604161time = self.plan_transit(id_plan, time,4162id_stopedge_from, pos_stop_from,4163id_stopedge_to, pos_stop_to,4164id_stop_from, id_stopedge_from, pos_stop_from,4165id_stop_to, id_stopedge_to, pos_stop_to,4166#dist_from_to, dist_walk_max,4167walkstages, transitstages,4168ptlines, ptfstar, pttimes,4169stops_to_enter, stops_to_exit,4170ids_laneedge, ids_stoplane, ptstops)41714172time = self.plan_bikeride(id_plan, time, id_veh,4173id_stopedge_to, pos_stop_to,4174id_edge_to, pos_edge_to,4175dist_stop_to_to, dist_walk_max,4176walkstages, ridestages)41774178# update time for trips estimation for this plan4179plans.times_est[id_plan] += time-time_from41804181# define current end time without last activity duration4182plans.times_end[id_plan] = time41834184id_stage_act, time = activitystages.append_stage(4185id_plan, time,4186ids_activity=id_act_to,4187names_activitytype=name_acttype_to,4188durations=duration_act_to,4189ids_lane=edges.ids_lanes[id_edge_to][0],4190positions=pos_edge_to,4191)41924193# store time for next iteration in case other activities are4194# following4195map_times[id_person] = time41964197# select persons and activities for next setp4198ind_act += 14199ids_person_act, ids_act_from, ids_act_to\4200= virtualpop.get_activities_from_pattern(ind_act, ids_person=ids_person_act)420142024203class Strategies(am.ArrayObjman):4204def __init__(self, ident, virtualpop, **kwargs):4205self._init_objman(ident,4206parent=virtualpop,4207name='Mobility Strategies',4208info="""Contains different mobility strategies.4209A strategy has methods to identify whether a strategy is applicaple to a person4210and to make a plan fo a person.4211""",4212version=0.3,4213**kwargs)42144215self.add_col(am.ArrayConf('names',4216default='',4217dtype='object',4218perm='r',4219is_index=True,4220name='Short name',4221info='Strategy name. Must be unique, used as index.',4222))4223self._init_attributes()4224self._init_constants()42254226def _init_attributes(self):42274228self.add_col(cm.ObjsConf('strategies',4229groupnames=['state'],4230name='Strategy',4231info='Strategy object.',4232))42334234if hasattr(self, 'vot'): # self.get_version() < 0.3:4235value_of_time_default = self.vot.get_value()4236self.delete('vot')4237else:4238value_of_time_default = 0.07/60 # here in euro per second42394240self.add(cm.AttrConf('value_of_time', value_of_time_default,4241groupnames=['parameters'],4242name='Value of time (VOT)',4243unit='1/s',4244perm='rw',4245info="This parameter weights the travel time in each strategies utility function: utility = utility_strategy_specific + value_of_time*time_exec +noise",4246))42474248self.add_col(am.ArrayConf('colors', np.ones(4, np.float32),4249dtype=np.float32,4250groupnames=['parameters'],4251metatype='color',4252perm='rw',4253name='Color',4254info="Route color. Color as RGBA tuple with values from 0.0 to 1.0",4255xmltag='color',4256))42574258if self.get_version() < 0.2:4259self._set_colors_default()42604261if self.get_version() < 0.3:4262self.set_version(0.3)42634264def format_ids(self, ids):4265return ', '.join(self.names[ids])42664267def get_id_from_formatted(self, idstr):4268return self.names.get_id_from_index(idstr)42694270def get_ids_from_formatted(self, idstrs):4271return self.names.get_ids_from_indices_save(idstrs.split(','))42724273def add_default(self):42744275self.add_strategy('walk', WalkStrategy)4276self.add_strategy('auto', AutoStrategy)4277self.add_strategy('bike', BikeStrategy)4278self.add_strategy('transit', TransitStrategy)4279self.add_strategy('biketransit', BikeTransitStrategy)4280self.add_strategy('motorcycle', MotorcycleStrategy)4281self.add_strategy('taxi', TaxiStrategy)4282self._set_colors_default()42834284def _set_colors_default(self):4285colors_default = {'walk': np.array([160, 72, 0, 220], np.float32)/255,4286'auto': np.array([250, 213, 0, 220], np.float32)/255,4287'bike': np.array([8, 191, 73, 210], np.float32)/255,4288'transit': np.array([8, 77, 191, 220], np.float32)/255,4289'biketransit': np.array([8, 201, 223, 220], np.float32)/255,4290'motorcycle': np.array([170, 200, 0, 220], np.float32)/255,4291'taxi': np.array([40, 240, 240, 220], np.float32)/255,4292}4293ids = self.names.get_ids_from_indices_save(colors_default.keys())4294self.colors[ids] = colors_default.values() # np.array(colors_default.values(), np.float32).reshape(-1,4)42954296#self.colors.indexset(colors_default.keys(), colors_default.values())42974298def add_strategy(self, ident, Strategyclass, color=(0.0, 0.0, 0.0, 1.0)):4299# print 'add_strategy', ident4300if not self.names.has_index(ident):4301strategy = Strategyclass(ident, self)4302self.add_row(names=ident,4303strategies=strategy,4304colours=color,4305)4306return strategy4307else:4308# print 'WARNING in add_strategy: strategy %s already initialized'%ident4309return self.strategies[self.names.get_id_from_index(ident)]43104311def preevaluate(self, ids_person):4312"""4313Preevaluation of strategies for person IDs in vector ids_person.43144315Returns a vector with strategy IDs and a preevaluation matrix.4316The rows of the matrix corrispond to each person ID.4317The columns corrsopond to reck strategy ID.4318The values of the preevaluation matrix are as follows:4319-1 : Strategy cannot be applied43200 : Stategy can be applied, but the preferred mode is not used43211 : Stategy can be applied, and preferred mode is part of the strategy43222 : Strategy uses predomunantly preferred mode43234324"""4325print 'preevaluate strategies'4326ids_strat = self.get_ids()4327n_pers = len(ids_person)4328n_strat = len(ids_strat)43294330preeval = np.zeros((n_pers, n_strat), dtype=np.int32)4331for i, strategy in zip(range(n_strat), self.strategies[ids_strat]):4332print ' preevaluate strategiy', strategy.ident4333preeval[i, :] = strategy.preevaluate(ids_person)43344335return ids_strat, preeval433643374338class StageTypeMixin(am.ArrayObjman):4339def init_stagetable(self, ident, stages, name='', info="Stage of Plan"):43404341self._init_objman(ident=ident, parent=stages, name=name,4342info=info,4343version=0.2,4344)43454346self.add_col(am.IdsArrayConf('ids_plan', self.get_plans(),4347#groupnames = ['state'],4348name='ID plan',4349info='ID of plan.',4350xmltag='type',4351))43524353self.add_col(am.ArrayConf('times_start', -1.0,4354groupnames=['parameters'], # new4355name='Start time',4356unit='s',4357info='Planned or estimated time when this stage starts. Value -1 means unknown.',4358))43594360self.add_col(am.ArrayConf('durations', -1.0,4361name='Duration',4362groupnames=['parameters'], # new4363unit='s',4364info='Planned or estimated duration for this stage starts. Value -1 means unknown.',4365xmltag='type',4366))43674368def _init_constants(self):4369self._fstarmap = {}4370self._timesmap = {}4371self._distancesmap = {}4372self.get_attrsman().do_not_save_attrs(['_fstarmap', '_timesmap', '_distancesmap'])4373self._init_constants_specific()43744375def _init_constants_specific(self):4376# to be overridden4377pass43784379def get_plans(self):4380return self.parent43814382def get_ids_from_ids_plan(self, ids_plan):4383"""4384Returns only stage IDs which are part of the given plans IDs.4385"""4386# print 'get_ids_from_ids_plan for',type(ids_plan),ids_plan43874388ids = self.get_ids()4389#ids_plan_part = self.ids_plan[ids]4390are_selected = np.zeros(len(ids), dtype=np.bool)4391for ind, id_plan_part in zip(xrange(len(ids)), self.ids_plan[ids]):4392are_selected[ind] = id_plan_part in ids_plan4393return ids[are_selected]4394# print ' ids_plan_part',type(ids_plan_part),ids_plan_part4395# print ' ids_selected',type(ids_plan_part.intersection(ids_plan)),ids_plan_part.intersection(ids_plan)4396# return np.array(list(ids_plan_part.intersection(ids_plan)), dtype = np.int32)43974398def get_virtualpop(self):4399# print 'get_virtualpop '4400return self.parent.parent44014402def prepare_planning(self):4403pass44044405def append_stage(self, id_plan, time_start, **kwargs):44064407# try to fix timing4408# if time_start<0:4409# time_start_prev, duration_prev = self.parent.plans.get_timing_laststage(id_plan)4410# if (duration_prev>=0)&(time_start_prev>=0):4411# time_start = time_start_prev+duration_prev44124413id_stage = self.add_row(ids_plan=id_plan, times_start=time_start, **kwargs)4414# print 'STAGE.appended stage %s id_plan=%d, id_stage=%d, t=%d'%(self.get_name(),id_plan,id_stage,time_start)4415# for key in kwargs.keys():4416# print ' %s=%s'%(key,kwargs[key])4417# print ' --id_plan, self, id_stage',id_plan, self, id_stage#,self.ids_plan.get_linktab()44184419self.parent.append_stage(id_plan, self, id_stage)4420# print ' plan appended',id_plan, self, id_stage44214422return id_stage, time_start+self.durations[id_stage]44234424def modify_stage(self, id_stage, time_start=None, **kwargs):4425if time_start is None:4426time_start = self.times_start[id_stage]4427self.set_row(id_stage, **kwargs)4428return time_start+self.durations[id_stage]44294430def get_timing(self, id_stage):4431#ind = self.get_ind(id_stage)4432return self.times_start[id_stage], self.durations[id_stage]44334434def get_times(self, id_mode):4435"""4436Returns a vector mapping id_edge to edge travel times4437for given mode id_mode4438"""4439print 'get_times', self._timesmap.keys()44404441if not self._timesmap.has_key(id_mode):4442edges = self.get_virtualpop().get_scenario().net.edges4443self._timesmap[id_mode] = edges.get_times(id_mode=id_mode,4444is_check_lanes=True,4445)44464447return self._timesmap[id_mode]44484449def get_distances(self, id_mode):4450"""4451Returns a vector mapping id_edge to edge distances4452for given mode id_mode4453"""4454print 'get_distances', self._distancesmap.keys()44554456if not self._distancesmap.has_key(id_mode):4457edges = self.get_virtualpop().get_scenario().net.edges4458self._distancesmap[id_mode] = edges.get_distances(id_mode=id_mode,4459is_check_lanes=True,4460)44614462return self._distancesmap[id_mode]44634464def get_fstar(self, id_mode, is_return_arrays=True, is_ignor_connections=False):4465"""4466Returns a fstar4467for given mode id_mode4468"""4469print 'get_fstar', self._fstarmap.keys()44704471if not self._fstarmap.has_key(id_mode):4472edges = self.get_virtualpop().get_scenario().net.edges4473self._fstarmap[id_mode] = edges.get_fstar(id_mode=id_mode,4474is_ignor_connections=is_ignor_connections,4475is_return_arrays=is_return_arrays,4476)4477return self._fstarmap[id_mode]44784479def to_xml(self, id_stage, fd, indent=0):4480"""4481To be overridden by specific stage class.4482"""4483pass448444854486class TransitStages(StageTypeMixin):4487def __init__(self, ident, stages, name='Transit rides', info='Ride on a single public transport line (no transfers).'):4488self.init_stagetable(ident,4489stages, name=name,4490info=info,4491)4492self._init_attributes()44934494def _init_attributes(self):4495#ptstops = self.parent.get_ptstops()4496edges = self.get_virtualpop().get_net().edges4497if hasattr(self, 'ids_fromstop'):4498self.delete('ids_fromstop')4499self.delete('ids_tostop')45004501self.add_col(am.IdsArrayConf('ids_line', self.get_virtualpop().get_ptlines(),4502groupnames=['parameters'],4503name='ID line',4504info='ID of public transport line.',4505))45064507self.add_col(am.IdsArrayConf('ids_fromedge', edges,4508groupnames=['parameters'],4509name='Edge ID from',4510info='Edge ID of departure bus stop or station.',4511))45124513self.add_col(am.IdsArrayConf('ids_toedge', edges,4514groupnames=['parameters'],4515name='Edge ID to',4516info='Edge ID of destination bus stop or station.',4517))45184519def _init_constants_specific(self):4520self.get_attrsman().do_not_save_attrs(['_costs', '_fstar', ])45214522def prepare_planning(self):4523ptlinks = self.ids_line.get_linktab().ptlinks.get_value()4524if len(ptlinks) == 0:4525# no links built...built them4526ptlinks.build()45274528self._costs = ptlinks.get_times()4529self._fstar = ptlinks.get_fstar()45304531def append_stage(self, id_plan, time_start=-1.0,4532id_line=-1, duration=0.0,4533id_fromedge=-1, id_toedge=-1, **kwargs):4534"""4535Appends a transit stage to plan id_plan.45364537"""4538# print 'TransitStages.append_stage',id_stage45394540id_stage, time_end = StageTypeMixin.append_stage(self,4541id_plan,4542time_start,4543durations=duration,4544ids_line=id_line,4545ids_fromedge=id_fromedge,4546ids_toedge=id_toedge,4547)45484549# add this stage to the vehicle database4550# ind_ride gives the index of this ride (within the same plan??)4551#ind_ride = self.parent.get_iautos().append_ride(id_veh, id_stage)4552return id_stage, time_end45534554def to_xml(self, id_stage, fd, indent=0):4555# <ride from="1/3to0/3" to="0/4to1/4" lines="train0"/>4556net = self.get_virtualpop().get_net()4557#ids_stoplane = net.ptstops.ids_lane4558#ids_laneedge = net.lanes.ids_edge4559ids_sumoedge = net.edges.ids_sumo45604561#ind = self.get_ind(id_stage)4562fd.write(xm.start('ride', indent=indent))4563fd.write(xm.num('from', ids_sumoedge[self.ids_fromedge[id_stage]]))4564fd.write(xm.num('to', ids_sumoedge[self.ids_toedge[id_stage]]))4565fd.write(xm.num('lines', self.ids_line.get_linktab().linenames[self.ids_line[id_stage]]))4566# if self.cols.pos_edge_from[ind]>0:4567# fd.write(xm.num('departPos', self.cols.pos_edge_from[ind]))4568# if self.cols.pos_edge_to[ind]>0:4569# fd.write(xm.num('arrivalPos', self.cols.pos_edge_to[ind]))45704571fd.write(xm.stopit()) # ends stage457245734574class AutorideStages(StageTypeMixin):45754576def __init__(self, ident, population,4577name='Auto rides',4578info='Rides with privately owned auto.',4579version=1.1,4580):45814582self.init_stagetable(ident, population, name=name, info=info)4583# print 'Rides.__init__',self.get_name()4584self._init_attributes()45854586def _init_attributes(self):4587# TODO: this structure needs review: the private vehicle is part of a person, not a stage4588# street parking at home and work could be in stage. Private garage is part of person...4589# print '_init_attributes',self.parent.get_iautos(), self.ident,self.parent.get_landuse().parking45904591self.add_col(am.IdsArrayConf('ids_iauto', self.get_virtualpop().get_iautos(),4592groupnames=['parameter'],4593name='ID vehicle',4594info='ID of private vehicle.',4595))45964597self.add_col(am.ArrayConf('times_init', -1.0,4598groupnames=['parameter'],4599name='Init. time',4600unit='s',4601info='Initialization time, which is the time when the vehicle appears in the scenario. Value -1 means unknown.',4602))46034604self.add_col(am.IdsArrayConf('ids_parking_from', self.get_virtualpop().get_landuse().parking,4605groupnames=['parameter'],4606name='ID dep. parking',4607info='Parking ID at the departure of the ride starts.',4608))46094610self.add_col(am.IdsArrayConf('ids_parking_to', self.get_virtualpop().get_landuse().parking,4611groupnames=['parameter'],4612name='ID arr. parking',4613info='Parking ID at the arrival of the ride.',4614))46154616self.add_col(am.IdlistsArrayConf('ids_edges', self.get_virtualpop().get_net().edges,4617groupnames=['parameter'],4618name='Route',4619info="The vehicle's route as a sequence of edge IDs.",4620))46214622if self.get_version() < 1.1:4623self.ids_edges.del_groupname('_private')46244625self.add(cm.AttrConf('dist_ride_min', 400.0,4626groupnames=['options'],4627perm='rw',4628name='Min ride dist.',4629info='Minimum ride distance. If the distanve between parkings is less, then the person will walk.',4630))46314632self.set_version(1.1)4633# if hasattr(self,'parking'):4634# self.delete('parking')46354636def prepare_planning(self):4637# now in _init_constants4638pass4639#net = self.get_virtualpop().get_net()4640#id_mode = net.modes.get_id_mode('passenger')4641#self._costs = {}4642# self._costs[id_mode] = net.edges.get_times( id_mode = id_mode,4643# is_check_lanes = True)4644#self._fstars = {}4645#self._fstars[id_mode] = net.edges.get_fstar(is_ignor_connections = False, id_mode = id_mode)4646#self._fstar = net.edges.get_fstar(is_ignor_connections = False)46474648def append_stage(self, id_plan, id_mode,4649is_fallback=False, id_mode_fallback=None,4650time_start=-1.0, id_veh=-1, time_init=-1,4651id_parking_from=.1, id_parking_to=-1, **kwargs):4652"""4653Appends a ride stage to plan id_plan in case the ride is feasible.4654The ride is feasible if from parking and to parking are connected.46554656If feasible, the stage ID and estimated time when stage is finished4657will be returned.46584659If not feasible -1 and start time will be returned.4660"""4661print 'Rides.append_stage id_plan', id_plan, is_fallback46624663route, dist, duration, is_fallback = self.get_route_between_parking(4664id_parking_from, id_parking_to, id_mode,4665is_fallback, id_mode_fallback,)46664667print ' after routing: is_fallback', is_fallback, 'route', route46684669if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection4670# create stage4671id_stage, time_end = StageTypeMixin.append_stage(self,4672id_plan,4673time_start,4674durations=duration,4675times_init=time_init,4676ids_iauto=id_veh,4677ids_parking_from=id_parking_from,4678ids_parking_to=id_parking_to,4679ids_edges=route,4680)46814682# add this stage to the vehicle database4683# ind_ride gives the index of this ride (within the same plan??)4684#ind_ride = self.parent.get_iautos().append_ride(id_veh, id_stage)4685return id_stage, time_end, is_fallback46864687else:4688# not connected or too short of a distance4689return -1, time_start, is_fallback # no stage creation took place46904691def get_route_between_parking(self, id_parking_from, id_parking_to, id_mode,4692is_fallback=False, id_mode_fallback=None):4693"""4694Return route and distance of ride with vehicle type vtype4695between id_parking_from and id_parking_to469646974698"""4699print 'get_route_between_parking', id_parking_from, id_parking_to, 'is_fallback', is_fallback, 'id_mode_fallback', id_mode_fallback4700scenario = self.get_virtualpop().get_scenario()4701edges = scenario.net.edges4702lanes = scenario.net.lanes47034704# print self.get_demand().getVehicles().cols.maxSpeed4705#v_max = self.get_demand().getVehicles().maxSpeed.get(vtype)4706parking = scenario.landuse.parking47074708ids_lanes = parking.ids_lane[[id_parking_from, id_parking_to]]4709id_edge_from, id_edge_to = lanes.ids_edge[ids_lanes]4710pos_from, pos_to = parking.positions[[id_parking_from, id_parking_to]]47114712if is_fallback & (id_mode_fallback is not None):4713print ' use id_mode_fallback', id_mode_fallback4714id_mode_current = id_mode_fallback47154716else:4717print ' use id_mode', id_mode4718id_mode_current = id_mode47194720# print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to4721duration_approx, route = routing.get_mincostroute_edge2edge(4722id_edge_from,4723id_edge_to,4724weights=self.get_times(id_mode_current),4725fstar=self.get_fstar(id_mode_current),4726)47274728if (len(route) == 0) & (not is_fallback) & (id_mode_fallback is not None):4729is_fallback = True4730id_mode_current = id_mode_fallback4731print ' no route found with normal mode, try fallback', is_fallback4732# now retry with fallback4733duration_approx, route = routing.get_mincostroute_edge2edge(4734id_edge_from,4735id_edge_to,4736weights=self.get_times(id_mode_current),4737fstar=self.get_fstar(id_mode_current),4738)4739if len(route) > 0:4740print ' fallback has been successful'47414742# here is a big problem: starting with the successive node of edge_from4743# may result that the first edge of the route is not connected with edge_from4744# And arriving at the preceding node of edge_to may result that from4745# the last edge in route the edge_to is not connected.47464747#route = [edge_from]+route+[edge_to]4748dist = np.sum(edges.lengths[route])4749dist = dist - pos_from - (edges.lengths[id_edge_to] - pos_to)4750# if 0:4751# if len(route)>0:4752# print ' dist,duration',dist,duration_approx4753# else:4754# print ' no route found'47554756return route, dist, duration_approx, is_fallback47574758# def make_id_veh_ride(self, id_stage, i_ride):4759# # make a unique vehicle ID for this stage4760# self.inds_ride[id_stage] = i_ride4761# return str(self.ids_veh[id_stage])+'.'+str(i_ride)47624763def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):4764print 'AutorideStages.get_writexmlinfo', len(ids_plan), is_route, 'is_plain', is_plain4765iautos = self.get_virtualpop().get_iautos()4766writefunc = iautos.prepare_write_xml(is_route, is_plain)47674768# not all auto plans contain autoride stages!4769ids = self.get_ids_from_ids_plan(ids_plan)4770writefuncs = np.zeros(len(ids), dtype=np.object)4771writefuncs[:] = writefunc4772return self.times_init[ids], writefuncs, ids47734774def to_xml(self, id_stage, fd, indent=0):4775#lanes = self.parent.get_scenario().net.lanes4776scenario = self.get_virtualpop().get_scenario()47774778edges = scenario.net.edges4779edgeindex = edges.ids_sumo4780parking = scenario.landuse.parking47814782ind = self.get_ind(id_stage)4783fd.write(xm.start('ride', indent=indent))47844785id_edge_from, pos_from = parking.get_edge_pos_parking(self.ids_parking_from.value[ind])4786id_edge_to, pos_to = parking.get_edge_pos_parking(self.ids_parking_to.value[ind])47874788# edgeindex.get_index_from_id(self.ids_edge_to.value[ind])4789fd.write(xm.num('from', edgeindex[id_edge_from]))4790fd.write(xm.num('to', edgeindex[id_edge_to]))4791fd.write(xm.num('lines', self.ids_iauto.get_linktab().get_id_line_xml(4792self.ids_iauto[id_stage]))) # mode specific47934794fd.write(xm.stopit()) # ends stage479547964797class BikerideStages(StageTypeMixin):47984799def __init__(self, ident, population,4800name='Bike rides',4801info='Rides with privately owned bike.',4802version=1.0,4803):48044805self.init_stagetable(ident, population, name=name, info=info)4806# print 'Rides.__init__',self.get_name()4807self._init_attributes()48084809def _init_attributes(self):4810# TODO: this structure needs review: the private vehicle is part of a person, not a stage4811# street parking at home and work could be in stage. Private garage is part of person...4812# print '_init_attributes',self.parent.get_iautos(), self.ident,self.parent.get_landuse().parking48134814self.add_col(am.IdsArrayConf('ids_ibike', self.get_virtualpop().get_ibikes(),4815groupnames=['state'],4816name='ID bike',4817info='ID of private, individual bike.',4818))48194820self.add_col(am.ArrayConf('times_init', -1.0,4821name='Init. time',4822unit='s',4823info='Initialization time, which is the time when the vehicle appears in the scenario. Value -1 means unknown.',4824))48254826edges = self.get_virtualpop().get_net().edges48274828self.add_col(am.IdsArrayConf('ids_edge_from', edges,4829groupnames=['state'],4830name='ID Dep. edge',4831info='Edge ID at departure of walk.',4832))48334834self.add_col(am.IdsArrayConf('ids_edge_to', edges,4835groupnames=['state'],4836name='ID Arr. edge',4837info='Edge ID where walk finishes.',4838))48394840self.add_col(am.ArrayConf('positions_from', 0.0,4841dtype=np.float32,4842#choices = OPTIONMAP_POS_DEPARTURE,4843perm='r',4844name='Depart pos',4845unit='m',4846info="Position on edge at the moment of departure.",4847#xmltag = 'departPos',4848#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),4849))48504851self.add_col(am.ArrayConf('positions_to', 0.0,4852dtype=np.float32,4853#choices = OPTIONMAP_POS_ARRIVAL,4854perm='r',4855name='Arrival pos',4856unit='m',4857info="Position on edge at the moment of arrival.",4858#xmltag = 'arrivalPos',4859#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),4860))48614862self.add_col(am.IdlistsArrayConf('ids_edges', self.get_virtualpop().get_net().edges,4863groupnames=['_private'],4864name='Route',4865info="The vehicle's route as a sequence of edge IDs.",4866))48674868def _init_constants_specific(self):4869net = self.get_virtualpop().get_net()4870self.id_mode_bike = net.modes.get_id_mode('bicycle')4871self.get_attrsman().do_not_save_attrs(['id_mode_bike', ])48724873def prepare_planning(self):4874pass48754876def append_stage(self, id_plan, time_start=-1.0, id_veh=-1,4877time_init=-1,4878id_edge_from=-1, id_edge_to=-1,4879position_edge_from=0.0, position_edge_to=0.0,4880is_route=True, route=-1, duration_approx=-1,4881**kwargs):4882"""4883Appends a ride stage to plan id_plan in case the ride is feasible.4884The ride is feasible if from parking and to parking are connected.48854886If feasible, the stage ID and estimated time when stage is finished4887will be returned.48884889If not feasible -1 and start time will be returned.4890"""4891# print 'BikeRides.append_stage',id_plan,time_start,time_init4892#edges = self.get_virtualpop().get_net().edges4893# check feasibility4894#route, dist, duration = self.get_route_between_parking(id_parking_from, id_parking_to)48954896# print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to48974898if is_route:4899duration_approx, route = routing.get_mincostroute_edge2edge(4900id_edge_from,4901id_edge_to,4902weights=self.get_times(self.id_mode_bike),4903fstar=self.get_fstar(self.id_mode_bike),4904)49054906#route = [edge_from]+route+[edge_to]49074908#dist = np.sum(edges.lengths[route])4909#dist = dist - pos_from - ( edges.lengths[id_edge_to] - pos_to)49104911if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection4912# create stage4913id_stage, time_end = StageTypeMixin.append_stage(self,4914id_plan,4915time_start,4916durations=duration_approx,4917times_init=time_init,4918ids_ibike=id_veh,4919ids_edge_from=id_edge_from,4920positions_from=position_edge_from,4921ids_edge_to=id_edge_to,4922positions_to=position_edge_to,4923ids_edges=route,4924)49254926# print ' route = ',route4927# print ' ids_edges = ',self.ids_edges[id_stage]4928# add this stage to the vehicle database4929# ind_ride gives the index of this ride (within the same plan??)4930#ind_ride = self.parent.get_iautos().append_ride(id_veh, id_stage)4931return id_stage, time_end49324933else:4934# not connected or too short of a distance4935return -1, time_start # no stage creation took place49364937def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):4938print 'BikerideStages.get_writexmlinfo', len(ids_plan), is_plain4939ibikes = self.get_virtualpop().get_ibikes()4940bikewritefunc = ibikes.prepare_write_xml(is_plain=is_plain)4941ids = self.get_ids_from_ids_plan(ids_plan)49424943bikewritefuncs = np.zeros(len(ids), dtype=np.object)4944bikewritefuncs[:] = bikewritefunc4945return self.times_init[ids], bikewritefuncs, ids49464947def to_xml(self, id_stage, fd, indent=0):4948#lanes = self.parent.get_scenario().net.lanes4949scenario = self.get_virtualpop().get_scenario()49504951edges = scenario.net.edges4952edgeindex = edges.ids_sumo49534954#parking = scenario.landuse.parking49554956#ind = self.get_ind(id_stage)4957fd.write(xm.start('ride', indent=indent))49584959#id_edge_from, pos_from = parking.get_edge_pos_parking(self.ids_parking_from.value[ind])4960#id_edge_to, pos_to = parking.get_edge_pos_parking(self.ids_parking_to.value[ind])49614962# edgeindex.get_index_from_id(self.ids_edge_to.value[ind])4963id_edge_from = self.ids_edge_from[id_stage]4964fd.write(xm.num('from', edgeindex[self.ids_edge_from[id_stage]]))4965fd.write(xm.num('to', edgeindex[self.ids_edge_to[id_stage]]))4966fd.write(xm.num('lines', self.ids_ibike.get_linktab().get_id_line_xml(4967self.ids_ibike[id_stage]))) # mode specific49684969fd.write(xm.stopit()) # ends stage497049714972class MotorcyclerideStages(StageTypeMixin):49734974def __init__(self, ident, population,4975name='Motorcycle rides',4976info='Rides with privately owned motorcycle.',4977version=1.0,4978):49794980self.init_stagetable(ident, population, name=name, info=info)4981# print 'Rides.__init__',self.get_name()4982self._init_attributes()49834984def _init_attributes(self):4985# TODO: this structure needs review: the private vehicle is part of a person, not a stage4986# street parking at home and work could be in stage. Private garage is part of person...4987# print '_init_attributes',self.parent.get_iautos(), self.ident,self.parent.get_landuse().parking49884989self.add_col(am.IdsArrayConf('ids_imoto', self.get_virtualpop().get_imotos(),4990groupnames=['state'],4991name='ID moto',4992info='ID of private, individual motorcycle.',4993))49944995self.add_col(am.ArrayConf('times_init', -1.0,4996name='Init. time',4997unit='s',4998info='Initialization time, which is the time when the vehicle appears in the scenario. Value -1 means unknown.',4999))50005001edges = self.get_virtualpop().get_net().edges50025003self.add_col(am.IdsArrayConf('ids_edge_from', edges,5004groupnames=['state'],5005name='ID Dep. edge',5006info='Edge ID at departure of walk.',5007))50085009self.add_col(am.IdsArrayConf('ids_edge_to', edges,5010groupnames=['state'],5011name='ID Arr. edge',5012info='Edge ID where walk finishes.',5013))50145015self.add_col(am.ArrayConf('positions_from', 0.0,5016dtype=np.float32,5017#choices = OPTIONMAP_POS_DEPARTURE,5018perm='r',5019name='Depart pos',5020unit='m',5021info="Position on edge at the moment of departure.",5022#xmltag = 'departPos',5023#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5024))50255026self.add_col(am.ArrayConf('positions_to', 0.0,5027dtype=np.float32,5028#choices = OPTIONMAP_POS_ARRIVAL,5029perm='r',5030name='Arrival pos',5031unit='m',5032info="Position on edge at the moment of arrival.",5033#xmltag = 'arrivalPos',5034#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5035))50365037self.add_col(am.IdlistsArrayConf('ids_edges', self.get_virtualpop().get_net().edges,5038groupnames=['_private'],5039name='Route',5040info="The vehicle's route as a sequence of edge IDs.",5041))50425043def _init_constants_specific(self):5044net = self.get_virtualpop().get_net()5045self.id_mode_moto = net.modes.get_id_mode('motorcycle')5046self.get_attrsman().do_not_save_attrs(['id_mode_moto', ])50475048def prepare_planning(self):5049pass50505051def append_stage(self, id_plan, time_start=-1.0, id_veh=-1,5052time_init=-1,5053id_edge_from=-1, id_edge_to=-1,5054position_edge_from=0.0, position_edge_to=0.0,5055is_route=True, route=-1, duration_approx=-1,5056**kwargs):5057"""5058Appends a ride stage to plan id_plan in case the ride is feasible.5059The ride is feasible if from parking and to parking are connected.50605061If feasible, the stage ID and estimated time when stage is finished5062will be returned.50635064If not feasible -1 and start time will be returned.5065"""5066# print 'BikeRides.append_stage',id_plan,time_start,time_init5067#edges = self.get_virtualpop().get_net().edges5068# check feasibility5069#route, dist, duration = self.get_route_between_parking(id_parking_from, id_parking_to)50705071# print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to5072if is_route:5073duration_approx, route = routing.get_mincostroute_edge2edge(5074id_edge_from,5075id_edge_to,5076weights=self.get_times(self.id_mode_moto),5077fstar=self.get_fstar(self.id_mode_moto),5078)50795080#route = [edge_from]+route+[edge_to]50815082#dist = np.sum(edges.lengths[route])5083#dist = dist - pos_from - ( edges.lengths[id_edge_to] - pos_to)50845085if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection5086# create stage5087id_stage, time_end = StageTypeMixin.append_stage(self,5088id_plan,5089time_start,5090durations=duration_approx,5091times_init=time_init,5092ids_imoto=id_veh,5093ids_edge_from=id_edge_from,5094positions_from=position_edge_from,5095ids_edge_to=id_edge_to,5096positions_to=position_edge_to,5097ids_edges=route,5098)50995100# print ' route = ',route5101# print ' ids_edges = ',self.ids_edges[id_stage]5102# add this stage to the vehicle database5103# ind_ride gives the index of this ride (within the same plan??)5104#ind_ride = self.parent.get_iautos().append_ride(id_veh, id_stage)5105return id_stage, time_end51065107else:5108# not connected or too short of a distance5109return -1, time_start # no stage creation took place51105111def get_writexmlinfo(self, ids_plan, is_route=True, is_plain=False):5112print 'MotorcyclerideStages.get_writexmlinfo', len(ids_plan), is_plain5113imotos = self.get_virtualpop().get_imotos()5114motowritefunc = imotos.prepare_write_xml(is_plain=is_plain)5115ids = self.get_ids_from_ids_plan(ids_plan)51165117motowritefuncs = np.zeros(len(ids), dtype=np.object)5118motowritefuncs[:] = motowritefunc5119return self.times_init[ids], motowritefuncs, ids51205121def to_xml(self, id_stage, fd, indent=0):5122#lanes = self.parent.get_scenario().net.lanes5123scenario = self.get_virtualpop().get_scenario()51245125edges = scenario.net.edges5126edgeindex = edges.ids_sumo51275128#parking = scenario.landuse.parking51295130#ind = self.get_ind(id_stage)5131fd.write(xm.start('ride', indent=indent))51325133#id_edge_from, pos_from = parking.get_edge_pos_parking(self.ids_parking_from.value[ind])5134#id_edge_to, pos_to = parking.get_edge_pos_parking(self.ids_parking_to.value[ind])51355136# edgeindex.get_index_from_id(self.ids_edge_to.value[ind])5137id_edge_from = self.ids_edge_from[id_stage]5138fd.write(xm.num('from', edgeindex[self.ids_edge_from[id_stage]]))5139fd.write(xm.num('to', edgeindex[self.ids_edge_to[id_stage]]))5140fd.write(xm.num('lines', self.ids_imoto.get_linktab().get_id_line_xml(5141self.ids_imoto[id_stage]))) # mode specific51425143fd.write(xm.stopit()) # ends stage514451455146class TaxirideStages(StageTypeMixin):51475148def __init__(self, ident, population,5149name='Taxi rides',5150info='Rides with Taxi.',5151version=1.0,5152):51535154self.init_stagetable(ident, population, name=name, info=info)5155# print 'Rides.__init__',self.get_name()5156self._init_attributes()51575158def _init_attributes(self):51595160self.add_col(am.ArrayConf('times_init', -1.0,5161name='Init. time',5162unit='s',5163info='Initialization time, which is the time when the vehicle appears in the scenario. Value -1 means unknown.',5164))51655166edges = self.get_virtualpop().get_net().edges51675168self.add_col(am.IdsArrayConf('ids_edge_from', edges,5169groupnames=['state'],5170name='ID Dep. edge',5171info='Edge ID at departure of walk.',5172))51735174self.add_col(am.IdsArrayConf('ids_edge_to', edges,5175groupnames=['state'],5176name='ID Arr. edge',5177info='Edge ID where walk finishes.',5178))51795180self.add_col(am.ArrayConf('positions_from', 0.0,5181dtype=np.float32,5182#choices = OPTIONMAP_POS_DEPARTURE,5183perm='r',5184name='Depart pos',5185unit='m',5186info="Position on edge at the moment of departure.",5187#xmltag = 'departPos',5188#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5189))51905191self.add_col(am.ArrayConf('positions_to', 0.0,5192dtype=np.float32,5193#choices = OPTIONMAP_POS_ARRIVAL,5194perm='r',5195name='Arrival pos',5196unit='m',5197info="Position on edge at the moment of arrival.",5198#xmltag = 'arrivalPos',5199#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5200))52015202def _init_constants_specific(self):5203net = self.get_virtualpop().get_net()5204self.id_mode_taxi = net.modes.get_id_mode('taxi')5205self.get_attrsman().do_not_save_attrs(['id_mode_taxi', ])52065207def prepare_planning(self):5208pass52095210def append_stage(self, id_plan, time_start=-1.0,5211time_init=-1,5212id_edge_from=-1, id_edge_to=-1,5213position_edge_from=0.0, position_edge_to=0.0,5214duration_approx=-1,5215is_route=True,5216route=[],5217**kwargs):5218"""5219Appends a ride stage to plan id_plan in case the ride is feasible.522052215222If feasible, the stage ID and estimated time when stage is finished5223will be returned.52245225If not feasible -1 and start time will be returned.5226"""52275228# print ' id_edge_from, id_edge_to=',id_edge_from, id_edge_to5229if is_route:5230duration_approx, route = routing.get_mincostroute_edge2edge(5231id_edge_from,5232id_edge_to,5233weights=self.get_times(self.id_mode_taxi),5234fstar=self.get_fstar(self.id_mode_taxi),5235)52365237if (len(route) > 0): # |(dist > self.dist_ride_min.get_value()): # is there a connection5238# create stage5239id_stage, time_end = StageTypeMixin.append_stage(self,5240id_plan,5241time_start,5242durations=duration_approx,5243times_init=time_init,5244ids_edge_from=id_edge_from,5245positions_from=position_edge_from,5246ids_edge_to=id_edge_to,5247positions_to=position_edge_to,5248)52495250# print ' route = ',route5251# print ' ids_edges = ',self.ids_edges[id_stage]5252# add this stage to the vehicle database5253# ind_ride gives the index of this ride (within the same plan??)5254#ind_ride = self.parent.get_iautos().append_ride(id_veh, id_stage)5255return id_stage, time_end52565257else:5258# not connected or too short of a distance5259return -1, time_start # no stage creation took place52605261def to_xml(self, id_stage, fd, indent=0):5262scenario = self.get_virtualpop().get_scenario()52635264edges = scenario.net.edges5265edgeindex = edges.ids_sumo52665267fd.write(xm.start('ride', indent=indent))52685269id_edge_from = self.ids_edge_from[id_stage]5270fd.write(xm.num('from', edgeindex[self.ids_edge_from[id_stage]]))5271fd.write(xm.num('to', edgeindex[self.ids_edge_to[id_stage]]))5272fd.write(xm.num('lines', 'taxi')) # mode specific52735274fd.write(xm.stopit()) # ends stage527552765277class WalkStages(StageTypeMixin):5278def __init__(self, ident, stages, name='WalkStages',5279info='walk from a position on a lane to another position of another lane.'):52805281self.init_stagetable(ident, stages, name=name, info=info)52825283edges = self.get_virtualpop().get_scenario().net.edges5284self.add_col(am.IdsArrayConf('ids_edge_from', edges,5285groupnames=['state'],5286name='ID Dep. edge',5287info='Edge ID at departure of walk.',5288))52895290self.add_col(am.IdsArrayConf('ids_edge_to', edges,5291groupnames=['state'],5292name='ID Arr. edge',5293info='Edge ID where walk finishes.',5294))52955296self.add_col(am.ArrayConf('positions_from', 0.0,5297dtype=np.float32,5298#choices = OPTIONMAP_POS_DEPARTURE,5299perm='r',5300name='Depart pos',5301unit='m',5302info="Position on edge at the moment of departure.",5303#xmltag = 'departPos',5304#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5305))5306self.positions_from.set_xmltag(None)53075308self.add_col(am.ArrayConf('positions_to', 0.0,5309dtype=np.float32,5310#choices = OPTIONMAP_POS_ARRIVAL,5311perm='r',5312name='Arrival pos',5313unit='m',5314info="Position on edge at the moment of arrival.",5315#xmltag = 'arrivalPos',5316#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5317))53185319self.positions_to.set_xmltag(None)53205321def append_stage(self, id_plan, time_start=-1.0,5322id_edge_from=-1, id_edge_to=-1,5323position_edge_from=0.1, position_edge_to=0.0,5324**kwargs):5325# print 'WalkStages.append_stage',id_stage5326if kwargs.has_key('duration'):5327duration = kwargs['duration']5328else:5329dist, duration = self.plan_walk(id_edge_from, id_edge_to,5330position_edge_from, position_edge_to)53315332id_stage, time_end = StageTypeMixin.append_stage(self,5333id_plan,5334time_start,5335durations=duration,5336ids_edge_from=id_edge_from,5337ids_edge_to=id_edge_to,5338positions_from=position_edge_from,5339positions_to=position_edge_to,5340)53415342return id_stage, time_end53435344def modify_stage(self, id_stage, time_start=None,5345id_edge_from=-1, id_edge_to=-1,5346position_edge_from=0.1, position_edge_to=0.0):53475348dist, duration = self.plan_walk(id_edge_from, id_edge_to,5349position_edge_from, position_edge_to)53505351time_end = StageTypeMixin.modify_stage(self, id_stage, time_start,5352durations=duration,5353ids_edge_from=id_edge_from,5354ids_edge_to=id_edge_to,5355positions_from=position_edge_from,5356positions_to=position_edge_to,5357)53585359return time_end53605361def plan_walk(self, id_edge_from, id_edge_to, pos_from, pos_to, id_mode=1):5362"""5363Routing for pedestrians.5364Currently limited to estimation of line of sight distance5365and walk time.5366"""5367# print 'plan_walk',id_edge_from, id_edge_to,id_mode, pos_from, pos_to5368scenario = self.get_virtualpop().get_scenario()5369edges = scenario.net.edges53705371coord_from = edges.get_coord_from_pos(id_edge_from, pos_from)5372coord_to = edges.get_coord_from_pos(id_edge_to, pos_to)53735374# from lanes, more precis, but less efficient and less robust5375# lanes = scenario.net.lanes5376#coord_from = lanes.get_coord_from_pos(edges.ids_lane[id_edge_from][0], pos_from)5377#coord_to = lanes.get_coord_from_pos(edges.ids_lane[id_edge_to][0], pos_to)53785379# print ' coord_from',coord_from,type(coord_from)5380# print ' coord_to',coord_from,type(coord_to)5381# print ' delta',coord_to-coord_from5382# line of sight distance5383dist = np.sqrt(np.sum((coord_to-coord_from)**2))53845385duration_approx = dist/scenario.net.modes.speeds_max[id_mode]5386# print ' dist,duration',dist,duration_approx,scenario.net.modes.speeds_max[id_mode]53875388return dist, duration_approx53895390def to_xml(self, id_stage, fd, indent=0):5391#scenario = self.parent.get_scenario()5392#edges = scenario.net.edges5393edges = self.ids_edge_from.get_linktab()5394edgeindex = edges.ids_sumo53955396ind = self.get_ind(id_stage)53975398id_edge_from = self.ids_edge_from.value[ind]5399id_edge_to = self.ids_edge_to.value[ind]5400fd.write(xm.start('walk', indent=indent))5401fd.write(xm.num('from', edgeindex[id_edge_from]))5402fd.write(xm.num('to', edgeindex[id_edge_to]))54035404pos = self.positions_from.value[ind]5405length = max(edges.lengths[id_edge_from]-4.0, 0.0)54065407# depricated5408# if (pos>0) & (pos < length ):5409# fd.write(xm.num('departPos', pos))5410#5411# elif pos < 0:5412# fd.write(xm.num('departPos', 0.0))5413#5414# else:5415# fd.write(xm.num('departPos', length))54165417pos = self.positions_to.value[ind]5418length = max(edges.lengths[id_edge_to]-4.0, 0.0)5419if (pos > 0) & (pos < length):5420fd.write(xm.num('arrivalPos', pos))54215422elif pos < 0:5423fd.write(xm.num('arrivalPos', 0.0))54245425else:5426fd.write(xm.num('arrivalPos', length))54275428fd.write(xm.stopit()) # ends walk542954305431class ActivityStages(StageTypeMixin):5432def __init__(self, ident, stages, name='Activities'):5433self.init_stagetable(ident, stages, name=name, info='Do some activity at a position of a lane.')54345435self._init_attributes()54365437def _init_attributes(self):54385439# TODO: this structure needs review: the private vehicle is part of a person, not a stage5440# street parking at home and work could be in stage. Private garage is part of person...54415442activities = self.get_virtualpop().get_activities()5443self.add_col(am.IdsArrayConf('ids_activity', activities,5444groupnames=['parameters'],5445name='Activity ID',5446info='Scheduled activity ID. This is the activity which schould be carried out in this stage.',5447))54485449# this is redundant information but here for speed when writing xml5450self.add_col(am.ArrayConf('names_activitytype', '',5451groupnames=['parameters'],5452dtype=np.object,5453perm='r',5454name='Type name',5455info="Name of activity type.",5456xmltag='actType',5457#xmlmap = get_inversemap( activitytypes.names.get_indexmap()),5458))54595460# self.add_col(am.IdsArrayConf( 'ids_facility', self.get_virtualpop().get_landuse().facilities,5461# groupnames = ['parameters'],5462# name = 'ID facility',5463# info = 'Facility where activity takes place.',5464# ))54655466# lane and position can be computed from facility5467self.add_col(am.IdsArrayConf('ids_lane', self.get_virtualpop().get_net().lanes,5468groupnames=['parameters'],5469name='Lane ID',5470info='Lane ID where activity takes place.',5471#xmltag = 'lane',5472))5473# for update..can be removed5474self.ids_lane.set_xmltag(None)54755476self.add_col(am.ArrayConf('positions', 0.0,5477groupnames=['parameters'],5478dtype=np.float32,5479perm='r',5480name='Lane pos',5481unit='m',5482info="Position on lane nearby where activity takes place.",5483#xmltag = 'startPos',5484#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5485))54865487self.positions.set_xmltag(None)54885489self.add_col(am.ArrayConf('durations', 0.0,5490groupnames=['parameters'],5491dtype=np.int32,5492perm='r',5493name='Duration',5494unit='s',5495info="Duration of activity.",5496xmltag='duration',5497#xmlmap = get_inversemap(OPTIONMAP_POS_ARRIVAL),5498))54995500self.durations.set_xmltag('duration')55015502def get_edges_positions(self, ids_stage):5503"""5504Returns road edge and positions of activity.5505"""5506return self.ids_lane.get_linktab().ids_edge[self.ids_lane[ids_stage]],\5507self.positions[ids_stage]55085509def _init_constants(self):5510#self._activities = self.get_virtualpop().get_activities()5511#self._activitytypes = self.get_virtualpop().get_demand().activitytypes5512# self.do_not_save_attrs(['_activities','_activitytypes'])5513pass55145515# def del_row(self, id_stage):5516# # actually this should no happen, activities should not be5517# # copied for each plan5518# print 'ActivityStages.del_row id_stage',id_stage,'id_activity',self.ids_activity[id_stage]5519# self.get_virtualpop().get_activities().del_row(self.ids_activity[id_stage])5520# am.ArrayObjman.del_row(self, id_stage)55215522def to_xml(self, id_stage, fd, indent=0):55235524# <stop lane="1/4to2/4_0" duration="20" startPos="40" actType="singing"/>55255526#ind = self.get_ind(id_stage)5527fd.write(xm.start('stop', indent=indent))55285529lanes = self.get_virtualpop().get_net().lanes5530id_lane = self.ids_lane[id_stage]5531# get all xml configs and damp to fd5532for attrconf in self.get_group('parameters'):5533# this will write only if a xmltag is defined5534attrconf.write_xml(fd, id_stage)5535fd.write(xm.num('lane', lanes.get_id_sumo(id_lane)))5536#fd.write(xm.num('duration', self.durations[id_stage]))55375538pos = self.positions[id_stage]5539length = max(lanes.get_lengths(id_lane)-4.0, 0.0)55405541if (pos > 0) & (pos < length):5542fd.write(xm.num('startPos', pos))55435544elif pos < 0:5545fd.write(xm.num('startPos', 0.0))55465547else:5548fd.write(xm.num('startPos', length))55495550#fd.write(xm.num('lane', self.cols.id_lane[ind]))5551#fd.write(xm.num('startPos', self.cols.pos_lane[ind]))5552#fd.write(xm.num('duration', self.cols.duration[ind]))5553# fd.write(xm.num('actType', self._activitytypes.names[self._activities.)55545555fd.write(xm.stopit()) # ends activity555655575558class Plans(am.ArrayObjman):5559def __init__(self, population, **kwargs):5560"""Plans database."""5561self._init_objman(ident='plans',5562parent=population,5563name='Plans',5564info='Mobility plan for virtual population.',5565#xmltag = ('plans','plan',None),5566version=0.1,5567**kwargs)55685569self._init_attributes()5570self._init_constants()55715572def _init_attributes(self):55735574# upgrade5575if self.get_version() < 0.1:5576pass55775578self.set_version(0.1)5579persons = self.parent55805581#self.add(cm.ObjConf(StageTables('stagetables',self)) )55825583self.add_stagetable('walks', WalkStages)5584self.add_stagetable('autorides', AutorideStages)5585self.add_stagetable('bikerides', BikerideStages)5586self.add_stagetable('motorides', MotorcyclerideStages)5587self.add_stagetable('transits', TransitStages)5588self.add_stagetable('taxirides', TaxirideStages)5589self.add_stagetable('activities', ActivityStages)55905591self.add_col(am.IdsArrayConf('ids_person', persons,5592groupnames=['links'],5593name='Person ID',5594info='Person ID to who this plan belongs to.',5595))55965597self.add_col(am.IdsArrayConf('ids_strategy', persons.get_strategies(),5598groupnames=['links'],5599name='Stategy ID',5600info='Stategy ID with which this plan has been generated.',5601))56025603self.add_col(am.ArrayConf('times_begin', -np.inf,5604dtype=np.float32,5605name='Begin time',5606info='Time when active travelling begins. This is the time in the simulation when the person appears. The first activity is not simulated.',5607unit='s',5608))56095610self.add_col(am.ArrayConf('times_end', -np.inf,5611dtype=np.float32,5612name='End time',5613info='Time when active travelling ends. This is the time in the simulation when the person disappears. The last activity is not simulated.',5614unit='s',5615))56165617self.add_col(am.ArrayConf('times_est', 0.0,5618dtype=np.float32,5619name='Estim. time',5620info='Estimated time duration to execute travel plan. Activity times are excluded.',5621unit='s',5622))56235624self.add_col(am.ArrayConf('times_exec', 0.0,5625dtype=np.float32,5626name='Exec. time',5627info='Last plan execution time from simulation run.',5628unit='s',5629))56305631self.add_col(am.ArrayConf('utilities', 0.0,5632dtype=np.float32,5633name='utility',5634info='Utility of plan.',5635))56365637self.add_col(am.ArrayConf('probabilities', 1.0,5638dtype=np.float32,5639name='Probability',5640info='Probability that the plan is selected out of all plans available for one person.',5641))56425643self.add_col(am.TabIdListArrayConf('stagelists',5644name='Stages',5645info='Sequence of stages of this plan.',5646))56475648def _init_constants(self):5649#self._id_mode_bike = self.parent.get_scenario().net.modes.get_id_mode('bicycle')5650# self.do_not_save_attrs([])5651pass56525653def clear_plans(self):5654print 'Plans.clear_plans'5655for stagetable in self.get_stagetables():5656# print ' stagetable',stagetable5657stagetable.clear()56585659self.clear_rows()5660# for attrconfig in self.get_attrsman().get_colconfigs():5661# print ' clear attrconfig',attrconfig.attrname5662# attrconfig.clear()5663# no: self.clear()56645665def add_stagetable(self, ident, StagesClass, **kwargs):5666if not hasattr(self, ident):5667self.add(cm.ObjConf(StagesClass(ident, self, **kwargs),5668groupnames=['stagetables']))5669return getattr(self, ident).get_value()56705671def get_stagetable(self, ident):5672return getattr(self, ident).get_value()56735674def get_stagetables(self):5675"""Return a list of with all stage objects"""5676stageobjs = []5677# print 'get_stagetables',self.get_group('stagetables')5678for stageobj in self.get_group('stagetables'):5679stageobjs.append(stageobj)5680return stageobjs56815682def prepare_stagetables(self, idents_stagetable):5683# print 'prepare_stages',stagenames5684#ids = self.names.get_ids_from_indices_save(stagenames)5685# print ' ids',ids5686# print ' self.stagetables[ids]',self.stagetables[ids]5687for indent in idents_stagetable:5688self.get_stagetable(indent).prepare_planning()56895690def get_stages(self, id_plan):5691stages = self.stagelists[id_plan]5692if stages is None:5693return []5694else:5695return stages56965697def append_stage(self, id_plan, stage, id_stage):5698# test: stage = cm.TableEntry(stagetable, id_plan)5699# print 'Plans.append_stage',self,id_plan, stage, id_stage57005701if self.stagelists[id_plan] is None:5702self.stagelists[id_plan] = [(stage, id_stage)]5703else:5704self.stagelists[id_plan].append((stage, id_stage))5705# print ' after append stagelists[id_plan]',type(self.stagelists[id_plan]),self.stagelists[id_plan]57065707# def prepare_stages(self,stagenames):5708# self.get_stagetables().prepare_stages(stagenames)57095710def get_timing_laststage(self, id_plan):5711"""5712Return time_start and duration of last stage of plan id_plan5713"""5714stages_current = self.stagelists[id_plan]57155716if stages_current is not None:5717stage_last, id_stage_last = stages_current[-1]5718return stage_last.get_timing(id_stage_last)5719else:5720return -1, -1572157225723class Virtualpopulation(DemandobjMixin, am.ArrayObjman):5724def __init__(self, ident, demand, **kwargs):5725self._init_objman(ident=ident,5726parent=demand,5727name='Virtual population',5728info='Contains information of each individual of the virtual population.',5729version=0.2, # only for new scenarios5730**kwargs)5731self._init_attributes()5732self._init_constants()57335734def _init_attributes(self):57355736# update here57375738#5739self.set_version(0.2)57405741demand = self.parent5742scenario = demand.get_scenario()57435744# --------------------------------------------------------------------5745# individual vehicles tables57465747self.add(cm.ObjConf(IndividualAutos('iautos', self)))5748self.add(cm.ObjConf(IndividualBikes('ibikes', self)))5749self.add(cm.ObjConf(IndividualMotorcycles('imotos', self)))57505751# --------------------------------------------------------------------5752# activity table5753#self.add(cm.ObjConf(ActivityTypes('activitytypes', self)) )5754self.add(cm.ObjConf(Activities('activities', self)))57555756# --------------------------------------------------------------------5757# strategies table (must be before plans)57585759self.add(cm.ObjConf(Strategies('strategies', self)))57605761# --------------------------------------------------------------------5762# plans table5763self.add(cm.ObjConf(Plans(self)))57645765self.get_strategies().add_default()57665767# ===================================================================5768# Add person attributes57695770# --------------------------------------------------------------------5771# socio economic parameters5772self.add_col(am.ArrayConf('identifications', '',5773dtype=np.object,5774groupnames=['socioeconomic'],5775name='Name',5776info='Identification or name of person. Does not need to be unique.',5777))57785779self.add_col(am.ArrayConf('ids_gender', default=-1,5780dtype=np.int32,5781groupnames=['socioeconomic'],5782choices=GENDERS,5783name='Gender',5784info='Gender of person.',5785))57865787self.add_col(am.ArrayConf('years_birth', default=-1,5788dtype=np.int32,5789groupnames=['socioeconomic'],5790name='Birth year',5791info='Year when person has been born.',5792))57935794self.add_col(am.ArrayConf('ids_occupation', default=OCCUPATIONS['unknown'],5795dtype=np.int32,5796choices=OCCUPATIONS,5797groupnames=['socioeconomic'],5798name='Occupation',5799info='Type of occupation.',5800))58015802# --------------------------------------------------------------------5803# household parameters5804self.add_col(am.ArrayConf('numbers_houehold', default=1,5805dtype=np.int32,5806groupnames=['household'],5807name='Number in household',5808info='Number of persons in household.',5809))58105811self.add_col(am.ArrayConf('numbers_minor', default=0,5812dtype=np.int32,5813groupnames=['household'],5814name='Number minors',5815info='Number of minor in household. In the context of traffic simulations minors are persons who need to be accompaigned by adulds when travelling.',5816))58175818# --------------------------------------------------------------------5819# activity parameters5820# lists with activity patterns58215822self.add_col(am.IdlistsArrayConf('activitypatterns', self.activities.get_value(),5823groupnames=['activity'],5824name='Activity IDs',5825info="Sequence of activity IDs to be accomplished by the person.",5826))58275828# --------------------------------------------------------------------5829# mobility parameters5830# --------------------------------------------------------------------58315832# give a pedestrian vtype to each person5833vtypes = self.get_demand().vtypes5834self.add_col(am.IdsArrayConf('ids_vtype', vtypes,5835id_default=vtypes.select_by_mode(mode='pedestrian')[0],5836groupnames=['mobility'],5837name='Ped. type',5838info='The pedestrian type ID specifies the walking characteristics and visual representation of the person. In SUMO terminology, this is the vehicle type.',5839#xmltag = 'type',5840))58415842self.add_col(am.ArrayConf('traveltimebudgets', default=55*60,5843dtype=np.int32,5844groupnames=['mobility'],5845name='time budget',5846unit='s',5847info='Daily time budget used for traveling.',5848))58495850self.add_col(am.IdsArrayConf('ids_mode_preferred', scenario.net.modes,5851groupnames=['mobility'],5852name='ID preferred mode',5853info='ID of preferred transport mode of person.',5854))58555856self.add_col(am.IdsArrayConf('ids_iauto', self.get_iautos(),5857groupnames=['mobility'],5858name='ID auto',5859info='ID of individual auto. Negative value means no bile available.',5860))58615862self.add_col(am.IdsArrayConf('ids_ibike', self.get_ibikes(),5863groupnames=['mobility'],5864name='ID bike',5865info='ID of individual bicycle. Negative value means no bike available.',5866))58675868self.add_col(am.IdsArrayConf('ids_imoto', self.get_imotos(),5869groupnames=['mobility'],5870name='ID motorcycle',5871info='ID of individual motorcycle. Negative value means no motorcycle available.',5872))58735874self.add_col(am.ArrayConf('dists_walk_max', default=400.0,5875dtype=np.float32,5876groupnames=['mobility'],5877name='Max. walk dist',5878info='Maximum acceptable walking distance between origin and destination or for transfers between modes.',5879))58805881# --------------------------------------------------------------------5882# plans5883self.add_col(am.IdsArrayConf('ids_plan', self.get_plans(),5884groupnames=['plans'],5885name='ID Plan',5886info='Currently selected mobility plan ID of person. This is the plan which will be simulated.',5887))58885889self.add_col(am.IdlistsArrayConf('lists_ids_plan', self.get_plans(),5890groupnames=['plans'],5891name='Plan IDs',5892info='List with alternative, feasible mobility plan IDs for each person.',5893))58945895def _init_constants(self):5896modes = self.get_scenario().net.modes5897self.id_mode_bike = modes.get_id_mode('bicycle')5898self.id_mode_auto = modes.get_id_mode('passenger')5899self.id_mode_moto = modes.get_id_mode('motorcycle')5900self._edges = self.get_net().edges5901self.do_not_save_attrs(['id_mode_bike', 'id_mode_auto', 'id_mode_moto',5902'_edges'])59035904def get_demand(self):5905return self.parent59065907def clear_population(self):5908# self.clear()5909self.clear_plans()5910self.clear_ivehicles()5911self.get_activities().clear_rows()5912# TODO: this should disappear5913self.get_landuse().parking.clear_booking()59145915# for attrconfig in self.get_attrsman().get_colconfigs():5916# attrconfig.clear()5917self.clear_rows()59185919def del_persons(self, ids_pers_delete):5920print 'delete', len(ids_pers_delete), 'persons'5921ids_plans_all = set()5922ids_activity_del = set()5923lists_ids_plan = self.lists_ids_plan[ids_pers_delete]5924for id_pers, ids_plan in zip(ids_pers_delete, self.lists_ids_plan[ids_pers_delete]):5925ids_plans_all.update(ids_plan)5926for stageinfo in self.get_plans().stagelists[ids_plan]:5927for stages, id_stage in stageinfo:5928# print ' id_pers ',id_pers,'del',stages,'id_stage',id_stage,stages.__class__,id_stage,stages.__class__== ActivityStages59295930# if stages.__class__ == ActivityStages:5931# print ' ids_activity',stages.ids_activity[id_stage]5932# ids_activity_del.add(stages.ids_activity[id_stage])59335934stages.del_row(id_stage)5935# print ' check',id_stage in stages59365937ids_plans_delete_all = list(ids_plans_all)5938# print 'len(plans)', len(plans),'delete ',len(ids_plans_delete_all)5939self.get_plans().del_rows(ids_plans_delete_all)5940# print ' ',len(self.get_activities()),'activities'5941#ids_activity_del = []5942for ids_activity in self.activitypatterns[ids_pers_delete]:5943ids_activity_del.update(ids_activity)59445945ids_activity_del = list(ids_activity_del)5946# print ' del',len(ids_activity_del),'of',len(self.get_activities()),'activities'5947self.get_activities().del_rows(ids_activity_del)59485949self.get_iautos().del_rows(self.ids_iauto[ids_pers_delete])5950self.get_ibikes().del_rows(self.ids_ibike[ids_pers_delete])5951self.get_imotos().del_rows(self.ids_imoto[ids_pers_delete])59525953# print 'len(virtualpop)', len(virtualpop),'delete ',len(ids_pers_delete)5954self.del_rows(ids_pers_delete)59555956def clear_plans(self):5957# print 'clear_plans',self.get_stagetables()5958self.ids_plan.reset()5959self.lists_ids_plan.reset()5960self.get_plans().clear_plans()59615962# TODO: this should disappear5963self.get_landuse().parking.clear_booking()59645965def clear_ivehicles(self):5966"""5967Clear all individually owned vehicles.5968"""5969print 'clear_ivehicles'5970self.get_iautos().clear_vehicles()5971self.get_ibikes().clear_vehicles()5972self.get_imotos().clear_vehicles()59735974def get_activities(self):5975return self.activities.get_value()59765977def get_strategies(self):5978return self.strategies.get_value()59795980def get_plans(self):5981return self.plans.get_value()59825983def get_iautos(self):5984return self.iautos.get_value()59855986def get_ibikes(self):5987return self.ibikes.get_value()59885989def get_imotos(self):5990return self.imotos.get_value()59915992def get_stagetables(self):5993return self.get_plans().get_stagetables()59945995def get_landuse(self):5996return self.parent.get_scenario().landuse59975998def get_scenario(self):5999return self.parent.get_scenario()60006001def get_net(self):6002return self.parent.get_scenario().net60036004def get_ptlines(self):6005return self.get_demand().ptlines60066007def get_ptstops(self):6008return self.get_net().ptstops60096010def get_id_sumo_from_id(self, id_sumo):6011return u'vp.%s' % id_sumo60126013def get_id_from_id_sumo(self, id_veh_sumo):6014if len(id_veh_sumo.split('.')) == 2:6015prefix, id_pers = id_veh_sumo.split('.')6016if prefix == 'vp':6017return int(id_pers)6018else:6019return -16020return -160216022def get_ids_from_ids_sumo(self, ids_sumo):6023ids = np.zeros(len(ids_sumo), dtype=int32)6024for id_sumo in ids_sumo:6025ids[i] = self.get_id_from_id_sumo(id_sumo)6026return ids60276028def get_time_depart_first(self):6029# print 'Virtualpop.get_time_depart_first'6030if len(self.get_plans()) > 0:6031plans = self.get_plans()6032ids = self.select_ids(self.ids_plan.get_value() >= 0)6033# print ' ids',ids6034return float(np.min(plans.times_begin[self.ids_plan[ids]]))6035else:6036return 0.060376038def get_time_depart_last(self):6039if len(self.get_plans()) > 0:6040# todo: this can be improved by adding plan execution time6041plans = self.get_plans()6042ids = self.select_ids(self.ids_plan.get_value() >= 0)60436044return float(np.max(plans.times_end[self.ids_plan[ids]]))6045else:6046return 0.060476048# def add_stagetable(self,ident,StageClass, **kwargs):6049# print 'add_stagetable',ident,StageClass#,kwargs6050# if not hasattr(self,ident):6051# #print ' StageClass',StageClass(ident, self, **kwargs)6052# #print ' ObjConf',cm.ObjConf(StageClass(ident, self, **kwargs), goupnames = ['stages'])6053# self.add(cm.ObjConf(StageClass(ident, self, **kwargs), goupnames = ['stages']) )6054# return getattr(self, ident).get_value()60556056# def get_stagetable(self, ident):6057# return getattr(self, ident).get_value()60586059# def get_stagetables(self):6060# """Return a list of with all stage objects"""6061# stageobjs = []6062# #print 'get_stagetables',self.get_group('stages')6063# for stageobj in self.get_group('stages'):6064# stageobjs.append(stageobj)6065# return stageobjs60666067def make_multiple(self, n, **kwargs):6068return self.add_rows(n=n, **kwargs)60696070def disaggregate_odflow(self, time_start, time_end, id_mode,6071ids_fac,6072probs_fac_orig, probs_fac_dest,6073tripnumber_tot,6074id_activitytype_orig,6075id_activitytype_dest,6076hour_begin_earliest_orig,6077hour_begin_earliest_dest,6078hour_begin_latest_orig,6079hour_begin_latest_dest,6080duration_min_orig,6081duration_min_dest,6082duration_max_orig,6083duration_max_dest,6084scale=1.0,6085hour_offset=8.0, # 08:006086hour_tripbudget=25.0/60, # 25min6087dist_walk_max=400, # scalar!6088**kwargs6089):6090"""6091Disaggregation of demand dem from taz id_zone_orig to id_zone_dest with id_mode6092during time interval time_start,time_end, and creation of persons6093which are parameterized accordingly.6094The facility type at origin will be landusetype_orig6095and at destination landusetype_dest.609660976098"""6099tripnumber = int(scale*tripnumber_tot)6100print 'disaggregate_odflow', time_start, time_end, id_mode, tripnumber61016102print ' id_activitytype_orig,id_activitytype_dest', id_activitytype_orig, id_activitytype_dest61036104# print ' probs_orig',sum(probs_fac_orig)#,'\n',probs_fac_orig6105# print ' probs_dest',sum(probs_fac_dest)#,'\n',probs_fac_dest61066107# is there a chance to find facilities to locate persons in6108# origin and destination zone61096110#activitytypes= self.get_scenario().demand.activitytypes6111#ctivitynames = self.activitytypes.names6112#get_id_act = activitynames.get_id_from_index61136114if (np.sum(probs_fac_orig) > 0) & (np.sum(probs_fac_dest) > 0):6115# if id_mode == self._id_mode_bike:6116# are_bikeowner = np.ones(tripnumber, dtype=np.bool)6117# else:6118# # TODO: assign a default percentage of bike owners6119# are_bikeowner = np.zeros(tripnumber, dtype=np.bool)6120#times_start = np.random.randint(time_start,time_end,tripnumber)6121ids_person = self.make_multiple(tripnumber,6122ids_mode_preferred=id_mode * np.ones(tripnumber, dtype=np.int32),6123dists_walk_max=dist_walk_max * np.ones(tripnumber, dtype=np.int32),6124#times_start = times_start,6125)61266127unitvec_int = np.ones(tripnumber, dtype=np.int32)6128unitvec_float = np.ones(tripnumber, dtype=np.int32)61296130# activity timing6131#hours_start = hour_offset + np.array(times_start,dtype = np.float32)/36006132#tol_orig = hour_begin_latest_orig+duration_max_orig-(hour_begin_earliest_orig+duration_min_orig)61336134# print ' hours_start[:3]',hours_start[:3]6135# print ' tol_orig',tol_orig61366137#hours_end_est = hours_start + hour_tripbudget6138#tol_dest = hour_begin_latest_dest-hour_begin_earliest_dest61396140# print ' hours_end_est[:3]',hours_end_est[:3]6141# print ' tol_dest',tol_dest61426143#self.map_id_act_to_ids_facattrconf[id_activitytype_orig][ids_person] = ids_fac[random_choice(tripnumber, probs_fac_orig)]6144#self.map_id_act_to_ids_facattrconf[id_activitytype_dest][ids_person] = ids_fac[random_choice(tripnumber, probs_fac_dest)]6145activities = self.get_activities()61466147# fix first departure hours for first activity imposed by6148# OD flow data6149hours_end_earliest_orig = (hour_offset+float(time_start)/3600)*unitvec_float6150hours_end_latest_orig = (hour_offset+float(time_end)/3600)*unitvec_float61516152duration_mean_orig = 0.5 * duration_min_orig+duration_max_orig6153hours_begin_earliest_orig = hours_end_earliest_orig-duration_mean_orig6154hours_begin_latest_orig = hours_end_latest_orig-duration_mean_orig61556156# this estimate could be *optionally* replaced by preliminary routing6157hours_begin_earliest_dest = hours_end_earliest_orig+hour_tripbudget6158hours_begin_latest_dest = hours_end_latest_orig+hour_tripbudget61596160#hours_end_earliest_dest = hours_begin_earliest_dest+duration_min_dest6161#hours_end_latest_dest = hours_begin_latest_dest+duration_max_dest61626163ids_activity_orig = activities.add_rows(6164n=tripnumber,6165ids_activitytype=id_activitytype_orig * unitvec_int,6166ids_facility=ids_fac[random_choice(tripnumber, probs_fac_orig)],6167hours_begin_earliest=hours_begin_earliest_orig,6168hours_begin_latest=hours_begin_latest_orig,6169durations_min=duration_mean_orig-1.0/60.0 * unitvec_float, # min mast be less than max to prevent crash6170durations_max=duration_mean_orig * unitvec_float,6171)61726173ids_activity_dest = activities.add_rows(6174n=tripnumber,6175ids_activitytype=id_activitytype_dest * unitvec_int,6176ids_facility=ids_fac[random_choice(tripnumber, probs_fac_dest)],6177hours_begin_earliest=hours_begin_earliest_dest,6178hours_begin_latest=hours_begin_latest_dest,6179durations_min=duration_min_dest*unitvec_float,6180durations_max=duration_max_dest*unitvec_float,6181)61826183for id_person, id_activity_orig, id_activity_dest in zip(ids_person, ids_activity_orig, ids_activity_dest):6184self.activitypatterns[id_person] = [id_activity_orig, id_activity_dest]61856186#activitypatterns = np.zeros((tripnumber,2), dtype = np.int32)6187#activitypatterns[:,0]= ids_activity_orig6188#activitypatterns[:,1]= ids_activity_dest6189# try convert in this way to lists6190# print ' activitypatterns',activitypatterns.tolist()6191#self.activitypatterns[ids_person] = activitypatterns.tolist()6192# for id_person, act_pattern in zip(ids_person,activitypatterns.tolist()):6193# self.activitypatterns[id_person] = act_pattern61946195return ids_person6196else:6197print 'WARNING in disaggregate_odflow: no probabilities', np.sum(probs_fac_orig), np.sum(probs_fac_dest)61986199return []62006201def create_pop_from_odflows(self, is_use_landusetypes=False, **kwargs):6202"""6203Creates a population and defines home and activity facility6204according to OD matrix defined in odflows.6205The population is distributed within the zones according to6206the area of the facility.6207if landusetype_orig and landusetype_dest also landuse types6208of facilities of origin and destination are taken into account.6209"""6210print 'create_pop_from_odflows'62116212demand = self.parent6213odflowtab = demand.odintervals.generate_odflows()6214landuse = self.get_landuse()6215activitytypes = demand.activitytypes6216log = kwargs.get('logger', self.get_logger())62176218# self._make_map_id_act_to_ids_facattrconf()6219ids_flow = odflowtab.get_ids()6220n_flows = len(ids_flow)62216222ids_activitytype_orig = odflowtab.ids_activitytype_orig[ids_flow]6223ids_activitytype_dest = odflowtab.ids_activitytype_dest[ids_flow]62246225if is_use_landusetypes:62266227# TODO: not tested and works only for one landusetype per activity6228#activitytypes = self.activitytypes.get_value()6229#id_landusetype_orig = activitytypes.ids_landusetypes[kwargs['id_activitytype_orig']][0]6230#id_landusetype_dest = activitytypes.ids_landusetypes[kwargs['id_activitytype_dest']][0]62316232# TODO: get activitypes from activity6233#probs_fac, ids_fac = self.get_landuse().facilities.get_departure_probabilities_landuse()6234probs_activitytype_fac_area = {}6235ids_acttype = activitytypes.get_ids()6236for id_acttype, ids_landusetype in zip(ids_acttype, activitytypes.ids_landusetypes[ids_acttype]):6237# print 50*'-'6238# print ' id_acttype',id_acttype,'ids_landusetype',ids_landusetype6239probs_activitytype, ids_fac = landuse.facilities.get_departure_probabilities_landuse2(ids_landusetype)6240probs_activitytype_fac_area[id_acttype] = probs_activitytype6241# print ' probs_activitytype_fac_area',probs_activitytype_fac_area[id_acttype]6242else:6243probs_fac_area, ids_fac = landuse.facilities.get_departure_probabilities()62446245i = 0.06246for id_flow,\6247id_orig,\6248id_dest,\6249id_mode,\6250time_start,\6251time_end,\6252tripnumber,\6253id_activitytype_orig,\6254id_activitytype_dest,\6255hour_begin_earliest_orig,\6256hour_begin_earliest_dest,\6257hour_begin_latest_orig,\6258hour_begin_latest_dest,\6259duration_min_orig,\6260duration_min_dest,\6261duration_max_orig,\6262duration_max_dest\6263in zip(ids_flow,6264odflowtab.ids_orig[ids_flow],6265odflowtab.ids_dest[ids_flow],6266odflowtab.ids_mode[ids_flow],6267odflowtab.times_start[ids_flow],6268odflowtab.times_end[ids_flow],6269odflowtab.tripnumbers[ids_flow],6270ids_activitytype_orig,6271ids_activitytype_dest,6272activitytypes.hours_begin_earliest[ids_activitytype_orig],6273activitytypes.hours_begin_earliest[ids_activitytype_dest],6274activitytypes.hours_begin_latest[ids_activitytype_orig],6275activitytypes.hours_begin_latest[ids_activitytype_dest],6276activitytypes.durations_min[ids_activitytype_orig],6277activitytypes.durations_min[ids_activitytype_dest],6278activitytypes.durations_max[ids_activitytype_orig],6279activitytypes.durations_max[ids_activitytype_dest],6280):62816282log.progress(i/n_flows*100)6283# print ' disagg between zones',id_orig,id_dest6284i += 16285if is_use_landusetypes:6286# TODO: not tested and works only for one landusetype per activity6287# but in activity typrs several landuse types are defined62886289# idea: add the probabilities for landuse types of origin and dest6290#probs_fac_orig = probs_fac[id_orig][id_landusetype_orig]6291#probs_fac_dest = probs_fac[id_dest][id_landusetype_dest]6292probs_fac_orig = probs_activitytype_fac_area[id_activitytype_orig][id_orig]6293probs_fac_dest = probs_activitytype_fac_area[id_activitytype_dest][id_dest]62946295else:6296probs_fac_orig = probs_fac_area[id_orig]6297probs_fac_dest = probs_fac_area[id_dest]62986299self.disaggregate_odflow(time_start,6300time_end,6301id_mode,6302ids_fac,6303probs_fac_orig,6304probs_fac_dest,6305tripnumber,6306id_activitytype_orig,6307id_activitytype_dest,6308hour_begin_earliest_orig,6309hour_begin_earliest_dest,6310hour_begin_latest_orig,6311hour_begin_latest_dest,6312duration_min_orig,6313duration_min_dest,6314duration_max_orig,6315duration_max_dest,6316**kwargs6317)63186319# return odflowtab63206321def add_plans(self, ids_person, id_strategy=-1):6322print 'add_plans n, id_strategy', len(ids_person), id_strategy6323n_plans = len(ids_person)6324# print ' get_plans',self.get_plans()6325# print ' stagetables',self.get_plans().get_stagetables().get_ident_abs()6326# print ' stagetables',self.get_plans().get_stagetables().stagetables.get_value()6327ids_plan = self.get_plans().add_rows(n=n_plans,6328ids_person=ids_person,6329ids_strategy=id_strategy*np.ones(n_plans, dtype=np.int32),6330)63316332# print ' post stagetables',self.get_plans().get_stagetables().get_ident_abs()6333# print ' post stagetables',self.get_plans().get_stagetables().stagetables.get_value()63346335# return ids_plan6336self.ids_plan[ids_person] = 1*ids_plan63376338for id_person, id_plan in zip(ids_person, ids_plan):6339if self.lists_ids_plan[id_person] is None:6340self.lists_ids_plan[id_person] = [id_plan]6341else:6342self.lists_ids_plan[id_person].append(id_plan)6343return ids_plan63446345def plan_with_strategy(self, id_strategy, evalcrit=0, is_plan_no_preferred=False, is_substitute=False, logger=None):6346strategy = self.get_strategies().strategies[id_strategy]6347plans = self.get_plans()63486349ids_person = self.get_ids()63506351evals = strategy.preevaluate(ids_person)63526353if is_plan_no_preferred: # considering only people with vehicle but with another preferred mode6354inds_preeval = (evals == 0) | (evals == 1)6355else:6356inds_preeval = evals >= evalcrit63576358# if is_substitute:6359# for i, id_strat_pers in zip(xrange(len(inds_preeval)), self.plans.ids_strategy[ids_person[inds_preeval]]):6360# if id_strat_pers63616362ids_person_preeval = ids_person[inds_preeval]6363print 'plan_with_strategy', strategy.ident, 'n_pers', len(ids_person_preeval)63646365# TODO: is_substitute = is_substitute could be an argument to plan()6366# and then passed to the centralized add_plan() method of the VP.63676368strategy.plan(ids_person_preeval, logger=logger)63696370# def get_times(self, ind, ids_person = None, pdf = 'unit'):6371# """6372# Returns person IDs, activity IDs and initial times6373# for persons with at least one acivity.6374#6375# ids_person: array of preselected person IDs6376#6377# pdf: gives the probability density function to be chosen to determin6378# the departure times within the initial time intervals given by6379# initial activity attributes.6380# """6381# ids_person, ids_activity = self.get_activity_from_pattern(0,ids_person)6382# times_init = self.get_activities().get_times_init(ids_activity, pdf)6383#6384# return ids_person, ids_activity, times_init63856386def get_activities_from_pattern(self, ind, ids_person=None):6387"""6388Returns person IDs and from/to activity IDs for persons who perform an activity6389at the given activity index ind.6390Returns arrays: ids_person, ids_activity_from, ids_activity_to63916392ind: index of activity in activity pattern, starting with 06393ids_person: array of preselected person IDs639463956396"""63976398ids_person_activity = []6399ids_activity_from = []6400ids_activity_to = []6401if ids_person is None:6402ids_person = self.get_ids()64036404for id_person, activitypattern in zip(ids_person, self.activitypatterns[ids_person]):6405# has person activity at index ind?6406if len(activitypattern) > ind+1:6407ids_person_activity.append(id_person)6408ids_activity_from.append(activitypattern[ind])6409ids_activity_to.append(activitypattern[ind+1])64106411return ids_person_activity, ids_activity_from, ids_activity_to64126413# activities.hours_begin_earliest[ids_person_activity],6414# activities.hours_begin_latest[ids_person_activity],6415# activities.durations_min[ids_person_activity],6416# activities.durations_max[ids_person_activity],64176418def get_vtypes(self):64196420ids_vtypes = set()6421# get individual vehicle types6422ids_vtypes.update(self.get_iautos().ids_vtype.get_value())6423ids_vtypes.update(self.get_imotos().ids_vtype.get_value())6424ids_vtypes.update(self.get_ibikes().ids_vtype.get_value())64256426# add public transport6427ids_vtypes.update(self.get_ptlines().ids_vtype.get_value())64286429# add pedestrian types6430ids_vtypes.update(self.ids_vtype.get_value())64316432return ids_vtypes64336434def select_plans_preferred_mode(self, fraction=0.1, **kwargs):6435"""6436Selects current plant to satisfy best the preferred mode.6437"""64386439strategies = self.get_strategies()6440ids_strat = strategies.get_ids()6441n_strat = len(ids_strat)6442ids_pers_all = self.get_ids()6443ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6444n_pers = len(ids_pers)6445preevals = -1*np.ones((np.max(ids_pers)+1, np.max(ids_strat)+1), dtype=np.int32)6446for ind, id_strategy, strategy in zip(range(n_strat), ids_strat, strategies.strategies[ids_strat]):6447preevals[ids_pers, id_strategy] = strategy.preevaluate(ids_pers)64486449preferred = 26450plans = self.get_plans()6451self.ids_plan.reset()6452for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):6453if ids_plan is not None:6454if len(ids_plan) > 0:6455print ' id_pers,ids_plan', id_pers, ids_plan6456print ' ids_strat, preeval', plans.ids_strategy[ids_plan], preevals[id_pers, plans.ids_strategy[ids_plan]]6457inds_sel = np.flatnonzero(preevals[id_pers, plans.ids_strategy[ids_plan]] == preferred)6458print ' inds_sel', inds_sel, inds_sel.dtype6459if len(inds_sel) > 0:6460#ids_plan_sel = np.array(ids_plan)[inds_sel]6461# print ' ids_plan_sel',ids_plan_sel6462# at least one plan contains preferred mode6463self.ids_plan[id_pers] = np.array(ids_plan)[inds_sel][0] # whu [1]?6464# else:6465# assumption: a plan for the preferred mode always exists6466# # no preferred mode found try to satisfy best possible6467# #ids_plan[preevals[id_pers,plans.ids_strategy[ids_plan]] == preferred]6468# self.ids_plan[id_pers] = -16469return True64706471def select_plans_min_time_est(self, fraction=1.0, timedev=-1.0, c_probit=-1.0, **kwargs):6472"""6473Select plan with minimum estimated travel time as current plant.6474"""6475ids_pers_all = self.get_ids()6476ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6477times_est = self.get_plans().times_est6478# self.ids_plan.reset()6479for id_pers, ids_plan_all in zip(ids_pers, self.lists_ids_plan[ids_pers]):6480ids_plan = np.array(ids_plan_all, dtype=np.int32)[times_est[ids_plan_all] > 0.1]6481if len(ids_plan) > 0:6482# print ' id_pers,ids_plan',id_pers,ids_plan6483if timedev > 0.1:6484times_rand = np.random.normal(0.0, timedev, len(ids_plan))6485elif c_probit > 0:6486times_rand = np.zeros(len(ids_plan), dtype=np.float32)6487for i, t in zip(xrange(len(ids_plan)), times_est[ids_plan]):6488times_rand[i] = np.random.normal(0.0, c_probit * t, 1)64896490else:6491times_rand = np.zeros(len(ids_plan), dtype=np.float32)6492self.ids_plan[id_pers] = np.array(ids_plan)[np.argmin(times_est[ids_plan]+times_rand)]6493return True64946495def select_plans_random(self, fraction=0.1, **kwargs):6496"""6497A fraction of the population changes a plan.6498The new plans are chosen randomly.6499"""65006501ids_pers_all = self.get_ids()6502print 'select_plans_random', len(ids_pers_all), fraction6503times_est = self.get_plans().times_est6504# self.ids_plan.reset()6505# ids_mode[random_choice(n,shares/np.sum(shares))]65066507ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6508print ' ids_pers', ids_pers6509for id_pers, ids_plan in zip(ids_pers, self.lists_ids_plan[ids_pers]):6510if len(ids_plan) > 0:6511# print ' id_pers,ids_plan',id_pers,ids_plan6512self.ids_plan[id_pers] = ids_plan[np.random.randint(len(ids_plan))]6513return True65146515def select_plans_min_time_exec(self, fraction=0.1, timedev=-1, c_probit=-1, **kwargs):6516"""6517Select plan with minimum executed travel time as current plant.6518"""6519ids_pers_all = self.get_ids()6520# print 'select_plans_random',len(ids_pers_all),fraction6521ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6522times_exec = self.get_plans().times_exec6523# self.ids_plan.reset()6524for id_pers, ids_plan_all in zip(ids_pers, self.lists_ids_plan[ids_pers]):6525# print ' ids_plan_all',ids_plan_all,type(ids_plan_all)6526ids_plan = np.array(ids_plan_all, dtype=np.int32)[times_exec[ids_plan_all] > 0.1]6527if len(ids_plan) > 0:6528# print ' id_pers,ids_plan',id_pers,ids_plan6529if timedev > 0.1:6530times_rand = np.random.normal(0.0, timedev, len(ids_plan))6531elif c_probit > 0:6532times_rand = np.zeros(len(ids_plan), dtype=np.float32)6533for i, t in zip(xrange(len(ids_plan)), times_exec[ids_plan]):6534times_rand[i] = np.random.normal(0.0, c_probit * t, 1)65356536else:6537times_rand = np.zeros(len(ids_plan), dtype=np.float32)65386539self.ids_plan[id_pers] = np.array(ids_plan)[np.argmin(times_exec[ids_plan]+times_rand)]6540return True65416542def select_plans_min_time_exec_est(self, fraction=0.1, timedev=-1, c_probit=-1, **kwargs):6543"""6544Select plan with minimum executed or estimated (if executed doesn't exist) travel time as current plant.6545"""6546n_analyzed_persons = 06547ids_pers_all = self.get_ids()6548ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6549times_exec = self.get_plans().times_exec6550times_est = self.get_plans().times_est6551ids_plans = self.get_plans().get_ids()6552for id_pers, ids_plan_all in zip(ids_pers, self.lists_ids_plan[ids_pers]):6553ids_plan_est = np.array(ids_plan_all, dtype=np.int32)[times_est[ids_plan_all] > 0.1]6554ids_plan_exec = np.array(ids_plan_all, dtype=np.int32)[times_exec[ids_plan_all] > 0.1]6555if len(ids_plan_est) > 0:6556if len(ids_plan_est) == len(ids_plan_exec):6557ids_plan_est = []6558else:6559c = np.zeros(len(ids_plan_est))6560for x in range(len(ids_plan_est)):6561for y in range(len(ids_plan_exec)):6562if ids_plan_est[x] == ids_plan_exec[y]:6563c[x] = 16564d = np.delete(ids_plan_est, np.flatnonzero(c))6565ids_plan_est = d65666567n_analyzed_persons += 165686569if timedev > 0.1:6570if len(ids_plan_est) > 0:6571times_rand_est = np.random.normal(0.0, timedev, len(ids_plan_est))6572if len(ids_plan_exec) > 0:6573times_rand_exec = np.random.normal(0.0, timedev, len(ids_plan_exec))65746575elif c_probit > 0:6576if len(ids_plan_est) > 0:6577times_rand_est = np.zeros(len(ids_plan_est), dtype=np.float32)6578for i, t in zip(xrange(len(ids_plan_est)), times_est[ids_plan_est]):6579times_rand_est[i] = np.random.normal(0.0, c_probit * t, 1)6580if len(ids_plan_exec) > 0:6581times_rand_exec = np.zeros(len(ids_plan_exec), dtype=np.float32)6582for i, t in zip(xrange(len(ids_plan_exec)), times_exec[ids_plan_exec]):6583times_rand_exec[i] = np.random.normal(0.0, c_probit * t, 1)65846585else:6586if len(ids_plan_exec) > 0:6587times_rand_exec = np.zeros(len(ids_plan_exec), dtype=np.float32)6588if len(ids_plan_est) > 0:6589times_rand_est = np.zeros(len(ids_plan_est), dtype=np.float32)65906591if len(ids_plan_exec) > 0 and len(ids_plan_est) > 0:6592if min(times_exec[ids_plan_exec]+times_rand_exec) < min(times_est[ids_plan_est]+times_rand_est):6593self.ids_plan[id_pers] = np.array(ids_plan_exec)[np.argmin(6594times_exec[ids_plan_exec]+times_rand_exec)]6595else:6596self.ids_plan[id_pers] = np.array(6597ids_plan_est)[np.argmin(times_est[ids_plan_est]+times_rand_est)]6598elif len(ids_plan_exec) == 0:6599self.ids_plan[id_pers] = np.array(ids_plan_est)[np.argmin(times_est[ids_plan_est]+times_rand_est)]66006601else:66026603self.ids_plan[id_pers] = np.array(ids_plan_exec)[np.argmin(6604times_exec[ids_plan_exec]+times_rand_exec)]66056606print 'were analyzed %d persons' % (n_analyzed_persons)6607return True66086609def select_plans_next(self, fraction=0.1, **kwargs):6610"""6611Select next plan in the plan list as current plant.6612"""6613# print 'select_plans_next'6614ids_pers_all = self.get_ids()6615ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6616for id_pers, id_plan_current, ids_plan in zip(ids_pers, self.ids_plan[ids_pers], self.lists_ids_plan[ids_pers]):6617n_plan = len(ids_plan)6618if n_plan > 0:6619# print ' id_pers,id_plan_current',id_pers,id_plan_current,ids_plan,id_plan_current != -16620if id_plan_current != -1:6621ind = ids_plan.index(id_plan_current)6622# print ' ind',ind,ind +1 < n_plan6623if ind + 1 < n_plan:6624ind += 16625else:6626ind = 06627else:6628ind = 066296630# print ' ind,n_plan',ind,n_plan,'ids_plan[ind]', ids_plan[ind]6631self.ids_plan[id_pers] = ids_plan[ind]6632# print ' finally: ids_plan=',self.ids_plan.get_value()6633return True66346635def select_plans_utility_function(self, fraction=0.1, timedev=-1, c_probit=-1, **kwargs):6636"""6637Select plan with utility function, which is based on the minimum executed travel time selection method6638but considering also a constant (different for each plan strategy) and a multiplicative parameter (the6639same for every strategy).6640"""6641strategies = self.get_strategies()6642value_of_time = strategies.value_of_time.get_value()66436644plans = self.get_plans()6645ids_pers_all = self.get_ids()66466647print 'select_plans_utility_function', len(ids_pers_all)66486649ids_pers = ids_pers_all[np.random.random(len(ids_pers_all)) > (1.0-fraction)]6650times_exec = self.get_plans().times_exec6651times_est = self.get_plans().times_est6652ids_plans_all = self.lists_ids_plan[ids_pers]66536654for id_pers, ids_plan_all in zip(ids_pers, ids_plans_all):66556656# print ' ids_plan_all',ids_plan_all,type(ids_plan_all)6657n_plan = len(ids_plan)66586659# if cycle necessary to apply a casual variation on plans executive times (in addition or in reduction)6660if n_plan > 0:6661traveltimes = np.zeros(n_plan, dtype=np.float32)6662traveltimes_noise = np.zeros(n_plan, dtype=np.float32)66636664inds_exec = times_exec[ids_plan_all] > 0.6665inds_est = times_exec[ids_plan_all] <= 0.66666667traveltimes[inds_exec] = times_exec[ids_plan_all[inds_exec]]6668traveltimes[inds_est] = times_est[ids_plan_all[inds_est]]66696670if timedev > 0:6671# noise is normal distributed with deviation timedev6672traveltimes_noise = np.random.normal(0.0, timedev, n_plan)66736674elif c_probit > 0:6675# noise is normal distributed with deviation c_probit *traveltimes6676traveltimes_noise = np.random.normal(0.0, c_probit * traveltimes, n_plan)66776678else:6679# no travel time noise6680traveltimes_noise = np.zeros(n_plan, dtype=np.float32)66816682for id_plan, strategy, traveltime, timetime_noise in zip(ids_plan_all,6683strategies.strategies[plans.ids_strategy[ids_plan_all]],6684traveltimes,6685traveltimes_noise):66866687utility = strategy.get_utility_specific(id_plan) - value_of_time * (traveltime + timetime_noise)66886689plans.utilities[id_plan] = utility66906691# set current plan of person to the one with the maximum utility6692self.ids_plan[id_pers] = ids_plan_all[np.argmax(plans.utilities[ids_plan_all])]66936694return True66956696def prepare_sim(self, process):6697return [] # [(steptime1,func1),(steptime2,func2),...]66986699def get_trips(self):6700# returns trip object, method common to all demand objects6701return self.get_iautos()67026703def get_writexmlinfo(self, is_route=False, is_plain=False, **kwargs):6704"""6705Returns three array where the first array is the6706begin time of the first vehicle and the second array is the6707write function to be called for the respectice vehicle and6708the third array contains the vehicle ids67096710Method used to sort trips when exporting to route or trip xml file6711"""6712print 'Virtualpop.get_writexmlinfo is_plain', is_plain6713plans = self.get_plans()67146715ids_pers = self.select_ids(self.ids_plan.get_value() >= 0)6716n_pers = len(ids_pers)6717ids_plans = self.ids_plan[ids_pers]67186719# get vehicle trip info6720times_depart_bike, writefuncs_bike, ids_rides_bike = plans.get_stagetable(6721'bikerides').get_writexmlinfo(ids_plans, is_route, is_plain)6722times_depart_auto, writefuncs_auto, ids_rides_auto = plans.get_stagetable(6723'autorides').get_writexmlinfo(ids_plans, is_route, is_plain)6724times_depart_moto, writefuncs_moto, ids_rides_moto = plans.get_stagetable(6725'motorides').get_writexmlinfo(ids_plans, is_route, is_plain)67266727#self.add_stagetable('walks', WalkStages)6728#self.add_stagetable('autorides', AutorideStages)6729#self.add_stagetable('bikerides', BikerideStages)6730#self.add_stagetable('transits', TransitStages)6731#self.add_stagetable('activities', ActivityStages)67326733#rides = plans.get_stagetable('autorides')67346735if not is_plain:6736# do persons67376738times_depart_pers = plans.times_begin[ids_plans]6739writefuncs_pers = np.zeros(n_pers, dtype=np.object)6740writefuncs_pers[:] = self.write_person_xml67416742# assemble vectors6743print ' times_depart_pers.shape', times_depart_pers.shape6744print ' times_depart_bike.shape', times_depart_bike.shape6745print ' times_depart_auto.shape', times_depart_auto.shape6746times_depart = np.concatenate((times_depart_pers,6747times_depart_auto,6748times_depart_bike,6749times_depart_moto,6750))67516752writefuncs = np.concatenate((writefuncs_pers,6753writefuncs_auto,6754writefuncs_bike,6755writefuncs_moto,6756))67576758ids = np.concatenate((ids_pers,6759ids_rides_auto,6760ids_rides_bike,6761ids_rides_moto,6762))6763else:6764times_depart = np.concatenate((times_depart_auto,6765times_depart_bike,6766times_depart_moto,6767))67686769writefuncs = np.concatenate((writefuncs_auto,6770writefuncs_bike,6771writefuncs_moto,6772))67736774ids = np.concatenate((ids_rides_auto,6775ids_rides_bike,6776ids_rides_moto,6777))67786779return times_depart, writefuncs, ids67806781def write_person_xml(self, fd, id_pers, time_begin, indent=2):67826783stages = self.get_plans().get_stages(self.ids_plan[id_pers])67846785fd.write(xm.start('person', indent=indent+2))6786fd.write(xm.num('id', self.get_id_sumo_from_id(id_pers)))6787# fd.write(xm.num('depart',self.times_start[id_pers]))6788fd.write(xm.num('depart', time_begin))6789fd.write(xm.num('type', self.parent.vtypes.ids_sumo[self.ids_vtype[id_pers]]))67906791activity_init, id_stage_init = stages[0]6792id_edge_init, pos_init = activity_init.get_edges_positions(id_stage_init)67936794# self.ids_edge_depart.write_xml(fd,id_trip)6795# self.positions_depart.write_xml(fd,id_trip)6796fd.write(xm.num('from', self._edges.ids_sumo[id_edge_init]))6797fd.write(xm.num('departPos', pos_init))67986799fd.write(xm.stop())68006801# write stages of this person.6802# Attention!! first and last stage, which are activities,6803# will NOT be exportes , therefore [1:-1]6804for stage, id_stage in stages[1:-1]:6805stage.to_xml(id_stage, fd, indent+4)68066807fd.write(xm.end('person', indent=indent+2))68086809def config_results(self, results):68106811results.add_resultobj(res.Personresults('virtualpersonresults', results,6812self,6813self.get_net().edges,6814name='Virtual person results',6815info='Table with simulation results for person of the virtual population. The results refer to all trips made by the person during the entire simulation period.',6816), groupnames=['Trip results'])68176818results.add_resultobj(res.Vehicleresults('iautotripresults', results,6819self.get_iautos(),6820self.get_net().edges,6821name='Auto trip results',6822info='Table with trip results made by individual autos. The results refer to all trips made by a specific vehicle during the entire simulation period.',6823), groupnames=['Trip results'])68246825results.add_resultobj(res.Vehicleresults('ibiketripresults', results,6826self.get_ibikes(),6827self.get_net().edges,6828name='Bike trip results',6829info='Table with trip results made by individual bikes. The results refer to all trips made by a specific vehicle during the entire simulation period.',6830), groupnames=['Trip results'])68316832results.add_resultobj(res.Vehicleresults('imototripresults', results,6833self.get_imotos(),6834self.get_net().edges,6835name='Motorcycle trip results',6836info='Table with trip results made by individual motorcycles. The results refer to all trips made by a specific vehicle during the entire simulation period.',6837), groupnames=['Trip results'])68386839# def process_results(self, results, process = None):6840# print 'process_results'6841# ## copy total travel into plan execution time6842# personresults = results.virtualpersonresults6843# self.update_plans(personresults)68446845def update_results(self, personresults):6846"""6847Updates plans with results from previous6848simulation run, and updates plan choice6849"""68506851ids_res = personresults.get_ids()6852print 'update_results', len(ids_res)6853ids_person = personresults.ids_person[ids_res]6854ids_plan = self.ids_plan[ids_person]6855self.get_plans().times_exec[ids_plan] = personresults.times_travel_total[ids_res]6856# change mobility plan based on updated travel times6857pass68586859def import_routes_xml(self, filepath, is_clear_trips=False,6860ids_strategy=None,6861is_generate_ids=True, is_add=False,6862is_overwrite_only=True):6863"""Reads route information of vehicles, and overwrites existing routes in stages.6864Used for example read results from Duaiterate process.6865"""6866print 'Virtualop.import_routes_xml from %s' % (filepath)6867if is_clear_trips:6868self.clear_trips()68696870counter = RouteCounter()6871parse(filepath, counter)6872reader = RouteReaderVp(self, counter)6873if 1: # try:6874parse(filepath, reader)6875print ' call make_routes', is_generate_ids, 'is_add', is_add6876reader.insert_routes(ids_strategy=ids_strategy)68776878else: # except KeyError:6879print >> sys.stderr, "Error: Problems with reading routes!"6880raise688168826883class DuarouterVp(routing.RouterMixin):6884def __init__(self, ident='vpduarouter', virtualpop=None,6885netfilepath=None,6886routefilepaths=None,6887outfilepath=None,6888is_export_net=True,6889is_export_trips=True,6890logger=None,6891**kwargs):6892print 'DuarouterVp.__init__ '68936894self._init_common(ident, name='Virtual Population DUA router',6895parent=virtualpop,6896logger=logger,6897info='DUA router for virtual population.',6898)6899cml = 'duarouter'6900self.init_cml(cml) # pass main shell command69016902scenario = virtualpop.get_scenario()6903demand = virtualpop.parent6904net = scenario.net6905attrsman = self.get_attrsman()69066907if routefilepaths is None:6908routefilepaths = demand.get_routefilepath()69096910print ' default routefilepaths', routefilepaths6911self.add_option('routefilepaths', routefilepaths,6912groupnames=['files'],6913cml='--route-files',6914perm='rw',6915name='Route file(s)',6916wildcards='Route XML files (*.rou.xml)|*.rou.xml',6917metatype='filepaths',6918info='SUMO route files in XML format.',6919)69206921self.is_virtualpop_only = attrsman.add(cm.AttrConf('is_virtualpop_only', kwargs.get('is_virtualpop_only', False),6922groupnames=['options'],6923name='Consider only virtualpop demand',6924info="""Consider only virtualpop demand.""",6925))69266927#strategychoices = {}6928strategies = virtualpop.get_strategies()6929#ids_strat = strategies.get_ids()6930# for id_strat, name_strat in zip(ids_strat, strategies.names[ids_strat]):6931# strategychoices[name_strat] = id_strat6932strategychoices = strategies.names.get_indexmap()6933self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', kwargs.get('ids_strategy', strategychoices.values()),6934choices=strategychoices,6935groupnames=['options'],6936name='Rerouted strategies',6937info="""Strategies to be rerouted. Note that the entire demand will be used for routing, but only the selected routes will be reimported in the virtual population.""",6938))69396940self.is_export_net = is_export_net69416942if netfilepath is None:6943netfilepath = net.get_filepath()69446945self.add_option('netfilepath', netfilepath,6946groupnames=['_private'],6947cml='--net-file',6948perm='r',6949name='Net file',6950wildcards='Net XML files (*.net.xml)|*.net.xml',6951metatype='filepath',6952info='SUMO Net file in XML format.',6953)69546955if outfilepath is None:6956outfilepath = scenario.get_rootfilepath()+'.dua.rou.xml'69576958self.add_option('outfilepath', outfilepath,6959groupnames=['_private'],6960cml='--output-file',6961perm='r',6962name='Output routefile',6963wildcards='Route XML files (*.rou.xml)|*.rou.xml',6964metatype='filepath',6965info='Output file of the routing process, which is a SUMO route file in XML format.',6966)69676968self.init_options_time(**kwargs)6969self.init_options_methods(**kwargs)6970self.init_options_processing_common(**kwargs)6971self.init_options_processing_dua(**kwargs)6972routing.init_random(self, **kwargs)69736974def do(self):6975virtualpop = self.parent6976scenario = virtualpop.get_scenario()6977demand = virtualpop.parent6978net = scenario.net69796980if self.is_export_net:6981net.export_netxml(self.netfilepath)69826983if self.is_virtualpop_only:6984demandobjects = [virtualpop]6985else:6986demandobjects = None # means entire demand is exported by default69876988demand.export_routes_xml(filepath=self.routefilepaths,6989encoding='UTF-8',6990demandobjects=demandobjects,6991is_route=False, # allow True if route export is implemened in virtual population self.is_skip_first_routing,# produce routes only if first dua routing is skipped6992vtypeattrs_excluded=['times_boarding', 'times_loading'], # bug of duaiterate!!6993is_plain=True, # this will prevent exporting stops and plans which causes routing errors with stops6994)69956996self.update_params()6997cml = self.get_cml()69986999self.run_cml(cml)7000if self.status == 'success':7001print ' DUA routing done.'7002if os.path.isfile(self.outfilepath):7003print ' outfile exists, start importing routes'7004virtualpop.import_routes_xml(self.outfilepath, ids_strategy=self.ids_strategy)70057006return True7007else:7008return False7009return False701070117012class RouteReaderVp(RouteReader):7013def insert_routes(self, ids_strategy=None):70147015virtualpop = self._trips # parent is called trips here need to be changed7016print 'RouteReaderVp.insert_routes found %d routes.' % (len(self.ids_sumo))7017plans = virtualpop.get_plans()7018strategies = virtualpop.get_strategies()7019id_strat_auto = strategies.names.get_id_from_index('auto')7020id_strat_bike = strategies.names.get_id_from_index('bike')7021id_strat_motorcycle = strategies.names.get_id_from_index('motorcycle')7022n_change_route = 07023if (ids_strategy is None):7024ids_strategy = [id_strat_auto, id_strat_bike, id_strat_motorcycle]70257026if id_strat_auto in ids_strategy:7027iautos = virtualpop.get_iautos()7028stages = iautos.get_stagetable()7029for id_sumo, ids_edge in zip(self.ids_sumo, self.routes):7030id_veh, id_stage = iautos.get_info_from_id_sumo(id_sumo)7031if (id_veh > -1) & (id_stage > 1):7032# print ' iauto: id_sumo %s id_veh %d id_stage %d'%(id_sumo,id_veh,id_stage)7033# print ' before:',stages.ids_edges[id_stage]7034if stages.ids_edges[id_stage] != ids_edge:7035n_change_route += 17036print ' route change of id_veh', id_veh, 'id_stage', id_stage7037stages.ids_edges[id_stage] = ids_edge7038# print ' after :',stages.ids_edges[id_stage]70397040if id_strat_bike in ids_strategy:7041ibikes = virtualpop.get_ibikes()7042stages = ibikes.get_stagetable()7043for id_sumo, ids_edge in zip(self.ids_sumo, self.routes):7044id_veh, id_stage = ibikes.get_info_from_id_sumo(id_sumo)7045if (id_veh > -1) & (id_stage > 1):7046# print ' ibike: id_sumo %s id_veh %d id_stage %d'%(id_sumo,id_veh,id_stage)7047# print ' before:',stages.ids_edges[id_stage]7048if stages.ids_edges[id_stage] != ids_edge:7049n_change_route += 17050print ' route change of id_veh', id_veh, 'id_stage', id_stage7051stages.ids_edges[id_stage] = ids_edge7052# print ' after :',stages.ids_edges[id_stage]70537054if id_strat_motorcycle in ids_strategy:7055imotos = virtualpop.get_imotos()7056stages = imotos.get_stagetable()7057for id_sumo, ids_edge in zip(self.ids_sumo, self.routes):7058id_veh, id_stage = imotos.get_info_from_id_sumo(id_sumo)7059if (id_veh > -1) & (id_stage > 1):7060# print ' ibike: id_sumo %s id_veh %d id_stage %d'%(id_sumo,id_veh,id_stage)7061# print ' before:',stages.ids_edges[id_stage]7062if stages.ids_edges[id_stage] != ids_edge:7063n_change_route += 17064print ' route change of id_veh', id_veh, 'id_stage', id_stage7065stages.ids_edges[id_stage] = ids_edge7066# print ' after :',stages.ids_edges[id_stage]7067print ' RouteReaderVp: Total number of changed routes:', n_change_route706870697070class PopGenerator(Process):7071def __init__(self, ident='virtualpopgenerator', virtualpop=None, logger=None, **kwargs):7072print 'PopFromOdfGenerator.__init__ ', ident, virtualpop70737074# TODO: let this be independent, link to it or child??7075#7076scenario = virtualpop.get_scenario()7077self._init_common(ident,7078parent=virtualpop,7079name='Population generator',7080logger=logger,7081info='Create virtual population from basic statistical data.',7082)70837084attrsman = self.set_attrsman(cm.Attrsman(self))70857086# make for each possible pattern a field for prob7087activitytypes = self.parent.get_scenario().demand.activitytypes70887089self.n_person = attrsman.add(cm.AttrConf('n_person', kwargs.get('n_person', 1000),7090groupnames=['options'],7091perm='rw',7092name='Number of person',7093info='Number of adult persons.',7094))70957096self.ids_acttype_default = activitytypes.get_ids_from_formatted('home,work')7097# self.ids_acttype = attrsman.add(cm.AttrConf( 'ids_acttype',kwargs.get('id_acttype',activitytypes.get_id_from_formatted('home')),7098# groupnames = ['options'],7099# choices = activitytypes.names.get_indexmap(),7100# perm='rw',7101# name = 'Activity type',7102# info = 'Initial activity type.',7103# ))71047105self.ttb_mean = attrsman.add(cm.AttrConf('ttb_mean', kwargs.get('ttb_mean', 55*60),7106groupnames=['options'],7107perm='rw',7108name='Avg. of 24h travel time budget',7109unit='s',7110info="""Average travel time budget for one day.7111This time excludes time for activities.7112""",7113))7114self.ttb_dev = attrsman.add(cm.AttrConf('ttb_dev', kwargs.get('ttb_dev', 10*60),7115groupnames=['options'],7116perm='rw',7117name='Std. of 24h travel time budget',7118unit='s',7119info="""Standard deviation of travel time budget for one day.7120""",7121))71227123mode_to_id = self.parent.get_scenario().net.modes.get_id_mode7124self.share_pedestrian = attrsman.add(cm.AttrConf('share_pedestrian', kwargs.get('share_pedestrian', 0.1),7125groupnames=['options', 'modal split'],7126perm='rw',7127id_mode=mode_to_id('pedestrian'),7128name='Pedestrian share',7129info="""Share of pedestrians.""",7130))71317132self.share_autouser = attrsman.add(cm.AttrConf('share_autouser', kwargs.get('share_autouser', 0.5),7133groupnames=['options', 'modal split'],7134perm='rw',7135id_mode=mode_to_id('passenger'),7136name='Auto user share',7137info="""Share of auto users.""",7138))71397140self.share_motorcycleuser = attrsman.add(cm.AttrConf('share_motorcycleuser', kwargs.get('share_motorcycleuser', 0.1),7141groupnames=['options', 'modal split'],7142perm='rw',7143id_mode=mode_to_id('motorcycle'),7144name='Motorcycle user share',7145info="""Share of Motorcycle users.""",7146))71477148self.share_bikeuser = attrsman.add(cm.AttrConf('share_bikeuser', kwargs.get('share_bikeuser', 0.1),7149groupnames=['options', 'modal split'],7150perm='rw',7151id_mode=mode_to_id('bicycle'),7152name='Bike user share',7153info="""Share of bike users.""",7154))71557156self.share_ptuser = attrsman.add(cm.AttrConf('share_ptuser', kwargs.get('share_ptuser', 0.2),7157groupnames=['options', 'modal split'],7158id_mode=mode_to_id('bus'),7159perm='rw',7160name='PT share',7161info="""Share of public transport user.""",7162))7163self.is_delete_existing_pop = attrsman.add(cm.AttrConf('is_delete_existing_pop', kwargs.get('is_delete_existing_pop', True),7164groupnames=['options'],7165name='Delete existing Virtual Population',7166info='If it is True: Delete existing virtual population. If it is False: keep existing virtual population',7167))71687169#self.modeshares = attrsman.add( cm.ObjConf(ModeShares('modeshares',self,scenario.net.modes),groupnames = ['options']) )71707171def do(self):7172print 'PopGenerator.do'7173# links71747175virtualpop = self.parent7176if self.is_delete_existing_pop == True:7177virtualpop.clear_population()7178logger = self.get_logger()7179#logger.w('Update Landuse...')7180scenario = virtualpop.get_scenario()7181activitytypes = scenario.demand.activitytypes7182facilities = scenario.landuse.facilities7183edges = scenario.net.edges71847185ids_fac = facilities.get_ids()7186map_id_edge_to_ids_fac = {}7187for id_fac, id_edge in zip(ids_fac, facilities.ids_roadedge_closest[ids_fac]):7188if map_id_edge_to_ids_fac.has_key(id_edge):7189map_id_edge_to_ids_fac[id_edge].append(id_fac)7190else:7191map_id_edge_to_ids_fac[id_edge] = [id_fac, ]71927193n_pers = self.n_person7194unitvec_int = np.ones(n_pers, dtype=np.int32)71957196ids_person = virtualpop.make_multiple(n_pers)7197virtualpop.traveltimebudgets[ids_person] = self.get_ttb(ids_person)71987199virtualpop.ids_mode_preferred[ids_person] = self.get_modes_random(n_pers)72007201# here we could preselect correct landuse based on7202# percentage of workers, students, employees7203prob_fac_to = facilities.capacities[ids_fac].astype(np.float32)7204prob_fac_to /= np.sum(prob_fac_to)7205# print ' np.sum(prob_fac_to)',np.sum(prob_fac_to)7206ids_fac_to = ids_fac[random_choice(n_pers, prob_fac_to)]72077208# determine id_fac_from by backward routing from id_fac_to7209ids_edge_to = facilities.ids_roadedge_closest[ids_fac_to]72107211# pre calculate backward star and mode dependent link travel times7212bstar = edges.get_bstar()7213edgetimes = {}7214ids_mode = self.get_ids_mode()7215# idea: do also consider gradient of house prices7216for id_mode, speed_max in zip(ids_mode, scenario.net.modes.speeds_max[ids_mode]):7217edgetimes[id_mode] = edges.get_times(id_mode=id_mode,7218speed_max=speed_max,7219is_check_lanes=True7220)7221# determine home facilities by backwards tracking from work facility7222ids_fac_from = np.ones(n_pers, dtype=np.int32)7223i = 07224for id_person, id_edge_to, id_mode, ttb\7225in zip(ids_person,7226ids_edge_to,7227virtualpop.ids_mode_preferred[ids_person],7228virtualpop.traveltimebudgets[ids_person],7229):72307231# print ' Backsearch',id_person,'id_edge_to',id_edge_to,edges.ids_sumo[id_edge_to],'ttb[s]',0.5*ttb7232ids_edge_from, costs, btree = routing.edgedijkstra_backwards(id_edge_to,72330.5*ttb, # to be specified better7234weights=edgetimes[id_mode],7235bstar=bstar,7236)7237if len(ids_edge_from) == 0:7238# routing failed to deliver edges of origins7239# put work and home on same edge7240ids_edge_from = [id_edge_to, ]72417242# look at all edges of origin and pick most likely facility7243ids_fac_lim = []7244for id_edge_from in ids_edge_from:72457246#id_from_check = id_edge_from7247# print ' check from',id_from_check,'back to',id_edge_to,'time =%.2fs'%costs[id_from_check]7248# while id_from_check != id_edge_to:7249# id_from_check = btree[id_from_check]7250# #print ' id_edge = ',id_from_check7251# print ' success = ',id_from_check==id_edge_to7252if map_id_edge_to_ids_fac.has_key(id_edge_from):7253ids_fac_lim += map_id_edge_to_ids_fac[id_edge_from]72547255if len(ids_fac_lim) == 0:7256# no facilities at all destinations found7257# go edges backawards and search there7258# this will reduce travel time7259for id_edge_from in ids_edge_from:7260# verify if id_edge_from has facilities.7261while not map_id_edge_to_ids_fac.has_key(id_edge_from):7262# print ' no facility, go backward'7263id_edge_from = btree[id_edge_from]72647265ids_fac_lim = np.array(ids_fac_lim, dtype=np.int32)72667267prob_fac_from = facilities.capacities[ids_fac_lim].astype(np.float32)7268prob_fac_from /= np.sum(prob_fac_from)7269# print ' np.sum(prob_fac_to)',np.sum(prob_fac_to)7270ids_fac_from[i] = ids_fac[random_choice(1, prob_fac_to)]7271i += 172727273# idea: adjust wake-up time with employment type7274activities = virtualpop.get_activities()7275ids_activity_from = activities.add_activities(7276self.ids_acttype_default[0] * unitvec_int,7277ids_fac_from,7278# use default7279#hours_begin_earliest = None,7280#hours_begin_latest = None,7281#durations_min = None,7282#durations_max = None,7283)72847285ids_activity_to = activities.add_activities(7286self.ids_acttype_default[1] * unitvec_int,7287ids_fac_to,7288# use default7289#hours_begin_earliest = None,7290#hours_begin_latest = None,7291#durations_min = None,7292#durations_max = None,7293)72947295for id_person, id_activity_from, ids_activity_to in zip(ids_person, ids_activity_from, ids_activity_to):7296virtualpop.activitypatterns[id_person] = [id_activity_from, ids_activity_to, ]72977298return True72997300def get_ids_mode(self):7301modesplitconfigs = self.get_attrsman().get_group('modal split')7302ids_mode = np.zeros(len(modesplitconfigs), dtype=np.int32)7303i = 07304for modeconfig in modesplitconfigs:7305ids_mode[i] = modeconfig.id_mode7306i += 17307return ids_mode73087309def get_modes_random(self, n):7310"""7311Return a vector with mode IDs of length n.7312"""7313# print 'get_modes_random',n7314modesplitconfigs = self.get_attrsman().get_group('modal split')7315ids_mode = np.zeros(len(modesplitconfigs), dtype=np.int32)7316shares = np.zeros(len(modesplitconfigs), dtype=np.float32)7317i = 07318for modeconfig in modesplitconfigs:7319ids_mode[i] = modeconfig.id_mode7320shares[i] = modeconfig.get_value()7321i += 17322# print ' ids_mode',ids_mode7323# print ' shares',shares7324return ids_mode[random_choice(n, shares/np.sum(shares))]73257326def get_ttb(self, ids_pers):7327n_pers = len(ids_pers)73287329# Truncated Normal dist with scipy7330# load libraries7331#import scipy.stats as stats7332# lower, upper, mu, and sigma are four parameters7333#lower, upper = 0.5, 17334#mu, sigma = 0.6, 0.17335# instantiate an object X using the above four parameters,7336#X = stats.truncnorm((lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)7337# generate 1000 sample data7338#samples = X.rvs(1000)73397340return np.random.normal(self.ttb_mean, self.ttb_dev, n_pers).clip(0, 2*3600)734173427343class PopFromOdfGenerator(Process):7344def __init__(self, ident, virtualpop, logger=None, **kwargs):7345print 'PopFromOdfGenerator.__init__'73467347# TODO: let this be independent, link to it or child??73487349self._init_common(ident,7350parent=virtualpop,7351name='Pop from OD-flow generator',7352logger=logger,7353info='Create virtual population from origin-to-destination zone flows by disaggregation.',7354)73557356attrsman = self.set_attrsman(cm.Attrsman(self))73577358# make for each possible pattern a field for prob7359activitytypes = self.parent.get_scenario().demand.activitytypes73607361self.hour_offset = attrsman.add(cm.AttrConf('hour_offset', kwargs.get('hour_offset', 8.0),7362groupnames=['options'],7363perm='rw',7364name='Offset hours',7365unit='h',7366info='Hour when simulation starts. This is the hour (of the day) when simulation time shows zero seconds.',7367))73687369self.dist_walk_max = attrsman.add(cm.AttrConf('dist_walk_max', kwargs.get('dist_walk_max', 400),7370groupnames=['options'],7371perm='rw',7372name='Max. walking dist',7373unit='m',7374info="""Maximum distance that a person accepts to walk,7375either to reach the destination or to access any sort of vehicle (tranfers at bus stops, walking to carparking, etc).7376""",7377))73787379self.hour_tripbudget = attrsman.add(cm.AttrConf('hour_tripbudget', kwargs.get('hour_tripbudget', 0.5),7380groupnames=['options'],7381perm='rw',7382name='Triptime budget',7383unit='h',7384info="""Time budget for this trip. This time is used7385to initially estimate the time in hours between7386the activity at origin and the activity7387at destination.7388""",7389))73907391self.scale = attrsman.add(cm.AttrConf('scale', kwargs.get('scale', 1.0),7392groupnames=['options'],7393perm='rw',7394name='Scale',7395info='Global scale factor. Scales the number of all OD trips.',7396))73977398self.is_use_landusetypes = attrsman.add(cm.AttrConf('is_use_landusetypes', kwargs.get('is_use_landusetypes', False),7399groupnames=['options'],7400perm='rw',7401name='use landuse types',7402info="""If True, use the landuse type of7403facilities when assigning the origin and destination facility.7404The landuse type is selected according to the activity type.7405Use this option only if landuse types have been correctly defined for7406all facilities.7407""",7408))74097410self.is_update_landuse = attrsman.add(cm.AttrConf('is_update_landuse', kwargs.get('is_update_landuse', True),7411groupnames=['options'],7412perm='rw',7413name='update Landuse',7414info="""If True, update land use database (zones, facilities, parking) before generating the population. Updating means identifying edges and facilities within zones.7415""",7416))74177418def do(self):7419print 'PopFromOdfGenerator.do'7420# links74217422virtualpop = self.parent7423logger = self.get_logger()7424if self.is_update_landuse:7425logger.w('Update Landuse...')7426scenario = virtualpop.get_scenario()7427scenario.landuse.zones.refresh_zoneedges()7428scenario.landuse.facilities.identify_taz()7429scenario.landuse.facilities.identify_closest_edge()7430scenario.landuse.facilities.update()74317432logger.w('Create population...')7433virtualpop.create_pop_from_odflows(logger=logger, **self.get_kwoptions())7434#activitytypes = virtualpop.activitytypes7435return True743674377438class Planner(Process):7439def __init__(self, ident='planner', virtualpop=None, ids_strategy=None, logger=None, **kwargs):7440print 'Planner.__init__'7441# TODO: let this be independent, link to it or child??74427443self._init_common(ident,7444parent=virtualpop,7445name='Planner',7446logger=logger,7447info='Generates mobility plan for population for a specific mobility strategy. Plans are only generated for persons for whome the strategy is applicable.',7448)74497450attrsman = self.set_attrsman(cm.Attrsman(self))74517452# make for each possible pattern a field for prob7453strategies = virtualpop.get_strategies()74547455strategychoices = strategies.names.get_indexmap()74567457if (ids_strategy is None):7458# no info given, select all7459ids_strategy_default = strategychoices.values()74607461elif ids_strategy is not None:7462ids_strategy_default = ids_strategy74637464print ' ids_strategy_default', ids_strategy_default7465self.ids_strategy = attrsman.add(cm.ListConf('ids_strategy', ids_strategy_default,7466groupnames=['options'],7467choices=strategychoices,7468perm='rw',7469name='Strategies',7470info='Strategies to be used to create mobility plans.',7471))74727473evalcrits = {'apply to all persons if feasible': 0,7474'apply only if preferred mode is used': 1,7475'apply only if exclusively preferred mode is used': 2,7476}7477self.evalcrit = attrsman.add(cm.AttrConf('evalcrit', kwargs.get('evalcrit', evalcrits['apply to all persons if feasible']),7478groupnames=['options'],7479choices=evalcrits,7480perm='rw',7481name='Application criteria',7482info=""" Value that determines for which persons the plans will be generated.7483Apply to all persons if feasible:07484Apply only if preferred mode is used:17485Apply only if exclusively preferred mode is used:27486""",7487))74887489self.is_plan_no_preferred = attrsman.add(cm.AttrConf('is_plan_no_preferred', kwargs.get('is_plan_no_preferred', False),7490groupnames=['options'],7491name='Plan for no preferred',7492info=""" If it is True: Generate new plans only for strategies that are different from the preferred strategies.7493If it is False: Generate new plans for all strategies7494""",7495))74967497def do(self):7498print 'Planner.do', len(self.ids_strategy)7499# links75007501virtualpop = self.parent7502logger = self.get_logger()7503#logger.w('Check applicability')7504#strategies = virtualpop.strategies.get_value()75057506# if self.id_strategy != -1:7507# virtualpop.plan_with_strategy(self.id_strategy, evalcrit = self.evalcrit, is_npm = self.is_new_planner_method, logger = logger)7508#7509# else: #plan with all strategies75107511i = 17512strategies = virtualpop.get_strategies()7513print ' strategies:', self.ids_strategy, strategies.names[self.ids_strategy]7514print ' instances', strategies.strategies[self.ids_strategy]75157516n_strat = len(self.ids_strategy)7517for id_strategy, strategy in zip(self.ids_strategy, strategies.strategies[self.ids_strategy]):7518print ' current strategy', strategy, id(strategy)7519logger.w('Plan with '+strategy.get_name()+' (%d/%d)' % (i, n_strat))7520virtualpop.plan_with_strategy(id_strategy, evalcrit=self.evalcrit,7521is_plan_no_preferred=self.is_plan_no_preferred, logger=logger)7522i += 175237524return True752575267527class PlanSelector(Process):7528def __init__(self, ident='planselector', virtualpop=None,7529ids_strategy=None, # not yet implemeted7530methodname='plan with shortest estim. time',7531logger=None, **kwargs):75327533print 'PlanSelector.__init__'75347535# TODO: let this be independent, link to it or child??75367537self._init_common(ident,7538parent=virtualpop,7539name='Plan Selector',7540logger=logger,7541info='Selects the plan for each person which will be executed during the next simulation run according to a defined selection method.',7542)75437544attrsman = self.set_attrsman(cm.Attrsman(self))75457546# make for each possible pattern a field for prob7547strategies = virtualpop.get_strategies()7548# strategychoices.update(strategies.names.get_indexmap())75497550strategychoices = strategies.names.get_indexmap()75517552# if (ids_strategy is None):7553# # no info given, select all7554# ids_strategy_default = strategychoices.values()7555#7556# elif ids_strategy is not None:7557# ids_strategy_default = ids_strategy75587559# print ' ids_strategy_default',ids_strategy_default7560# self.ids_strategy = attrsman.add(cm.ListConf( 'ids_strategy',ids_strategy_default,7561# groupnames = ['options'],7562# choices = strategychoices,7563# perm='rw',7564# name = 'Strategies',7565# info = 'Set of strategies from which one is selected per person for the next simulation run.',7566# ))75677568methods = {'plan with shortest estim. time': virtualpop.select_plans_min_time_est,7569'plan with shortest exec. time': virtualpop.select_plans_min_time_exec,7570'plan with preferred mode': virtualpop.select_plans_preferred_mode,7571'next plan in list': virtualpop.select_plans_next,7572'random plan': virtualpop.select_plans_random,7573'plan with shortest exec. time or est. time': virtualpop.select_plans_min_time_exec_est,7574'plan with utility function': virtualpop.select_plans_utility_function7575}75767577self.method = attrsman.add(cm.AttrConf('method', methods[methodname],7578groupnames=['options'],7579choices=methods,7580perm='rw',7581name='Selection method',7582info='Selection method used to select current plans.',7583))75847585self.fraction = attrsman.add(cm.AttrConf('fraction', kwargs.get('fraction', 1.0),7586groupnames=['options'],7587perm='rw',7588name='Change fraction',7589info="""Fraction of persons that are randomly chosen to change plans according to the defined method.7590A value of 1.0 mens that the plans of oll persons will be changed.""",7591))75927593self.timedev = attrsman.add(cm.AttrConf('timedev', kwargs.get('timedev', 0.0),7594groupnames=['options'],7595perm='rw',7596name='Time deviation',7597info="""Time deviation of random time component of estimated or effective time. If zero, no random time is added.7598Alternatively the probit constant can be given to quantify the amount of noise.7599""",7600))76017602self.c_probit = attrsman.add(cm.AttrConf('c_probit', kwargs.get('c_probit', 0.0),7603groupnames=['options'],7604perm='rw',7605name='Probit const',7606info="""Probit constant used to determine the deviation of the normal distributed random time component.7607The deviation is the product of this constant and the travel time. If zero, no random time is added.7608This is an alternative to explicitely giving the time deviation.""",7609))76107611def do(self):7612print 'Planner.do'7613# links76147615#virtualpop = self.parent7616logger = self.get_logger()7617#logger.w('Check applicability')7618return self.method(logger=logger,7619#ids_strategy = self.ids_strategy,7620**self.get_kwoptions()7621)762276237624class VehicleProvider(Process):7625def __init__(self, ident='vehicleprovider', virtualpop=None, logger=None, **kwargs):7626print 'VehicleProvider.__init__'76277628# TODO: let this be independent, link to it or child??76297630self._init_common(ident,7631parent=virtualpop,7632name='Vehicle Provider',7633logger=logger,7634info='Provides individual vehicles to persons according to preferred mode and giveb statistical data.',7635)76367637attrsman = self.set_attrsman(cm.Attrsman(self))76387639# make for each possible pattern a field for prob76407641self.share_autoowner = attrsman.add(cm.AttrConf('share_autoowner', kwargs.get('share_autoowner', 0.8),7642groupnames=['options'],7643perm='rw',7644name='Car auto share',7645info="""Share of auto owners. This specifies the share of auto owners and a car will be created for each car owner.7646Attention if prefeered mode has been already defined: persons who have bicicle as preferred mode get automatically a bike assigned.7647""",7648))76497650self.share_motorcycleowner = attrsman.add(cm.AttrConf('share_motorcycleowner', kwargs.get('share_motorcycleowner', 0.3),7651groupnames=['options'],7652perm='rw',7653name='Motorcycle owner share',7654info="""Share of Motorcycle owners. This specifies the share of Motorcycle owners and a bike will be created for each Motorcycle owner.7655Attention if prefeered mode has been already defined: persons who have Motorcycle as preferred mode get automatically a Motorcycle assigned.7656""",7657))76587659self.share_bikeowner = attrsman.add(cm.AttrConf('share_bikeowner', kwargs.get('share_bikeowner', 0.5),7660groupnames=['options'],7661perm='rw',7662name='Bike owner share',7663info="""Share of bike owners. This specifies the share of bike owners and a bike will be created for each bike owner.7664Attention if prefeered mode has been already defined: persons who have bicicle as preferred mode get automatically a bike assigned.7665""",7666))76677668def do(self):7669print 'VehicleProvider.do'7670# links76717672virtualpop = self.parent7673logger = self.get_logger()7674logger.w('Provide vehicles...')76757676ids_person = virtualpop.get_ids()7677n_person = len(ids_person)7678modes = virtualpop.get_scenario().net.modes7679id_mode_bike = modes.get_id_mode('bicycle')7680id_mode_auto = modes.get_id_mode('passenger')7681id_mode_moto = modes.get_id_mode('motorcycle')76827683iautos = virtualpop.get_iautos()7684ibikes = virtualpop.get_ibikes()7685imotos = virtualpop.get_imotos()76867687logger.w('generate individual vehicles for prefered modes')7688ids_prefer_auto = virtualpop.select_ids(7689(virtualpop.ids_mode_preferred.get_value() == id_mode_auto) & (virtualpop.ids_iauto.get_value() == -1))7690ids_iauto = iautos.assign_to_persons(ids_prefer_auto)76917692n_current = iautos.get_share(is_abs=True)7693#n_none = int(self.share_autoowner*n_person)-(n_person-n_current)7694n_need = int(self.share_autoowner*n_person)-n_current7695if n_need > 0:7696ids_pers_miss = np.flatnonzero(virtualpop.ids_iauto.get_value() == -1)+17697# print ' n_person,n_current,n_target,n_need,len(ids_pers_miss)',n_person,n_current,int(self.share_autoowner*n_person),n_need,len(ids_pers_miss)7698ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)7699ids_iauto = iautos.assign_to_persons(ids_pers_assign)77007701print ' created %d autos, target share=%.2f, share = %.2f' % (iautos.get_share(is_abs=True), iautos.get_share(), self.share_autoowner)77027703ids_prefer_bike = virtualpop.select_ids(7704(virtualpop.ids_mode_preferred.get_value() == id_mode_bike) & (virtualpop.ids_ibike.get_value() == -1))7705ids_ibikes = ibikes.assign_to_persons(ids_prefer_bike)77067707n_current = ibikes.get_share(is_abs=True)7708n_need = int(self.share_bikeowner*n_person)-n_current7709if n_need > 0:7710ids_pers_miss = np.flatnonzero(virtualpop.ids_ibike.get_value() == -1)+17711# print ' n_person,n_current,n_target,n_need,len(ids_pers_miss)',n_person,n_current,int(self.share_autoowner*n_person),n_need,len(ids_pers_miss)7712ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)7713ids_ibike = ibikes.assign_to_persons(ids_pers_assign)77147715print ' created %d bikes, target share=%.2f, share = %.2f' % (ibikes.get_share(is_abs=True), ibikes.get_share(), self.share_bikeowner)77167717ids_prefer_moto = virtualpop.select_ids(7718(virtualpop.ids_mode_preferred.get_value() == id_mode_moto) & (virtualpop.ids_imoto.get_value() == -1))7719ids_imoto = imotos.assign_to_persons(ids_prefer_moto)77207721n_current = imotos.get_share(is_abs=True)7722n_need = int(self.share_motorcycleowner*n_person)-n_current7723if n_need > 0:7724ids_pers_miss = np.flatnonzero(virtualpop.ids_imoto.get_value() == -1)+17725ids_pers_assign = np.random.choice(ids_pers_miss, n_need, replace=False)7726ids_imoto = imotos.assign_to_persons(ids_pers_assign)77277728print ' created %d moto, target share=%.2f, share = %.2f' % (imotos.get_share(is_abs=True), imotos.get_share(), self.share_motorcycleowner)7729return True77307731# TODO: generate and assign additional vehicles7732# to satisfy prescribes ownership773377347735