Path: blob/main/tools/contributed/sumopy/coremodules/scenario/scenario.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 scenario.py15# @author Joerg Schweizer16# @date 2012171819import numpy as np20from coremodules.misc import shapeformat21from coremodules.simulation import simulation22from coremodules.demand import demand23from coremodules.landuse import landuse24from coremodules.network import network25from agilepy.lib_base.processes import Process26import agilepy.lib_base.arrayman as am27import agilepy.lib_base.classman as cm28import os29import sys30if __name__ == '__main__':31try:32FILEDIR = os.path.dirname(os.path.abspath(__file__))33except:34FILEDIR = os.path.dirname(os.path.abspath(sys.argv[0]))35sys.path.append(os.path.join(FILEDIR, "..", ".."))3637# this is default scenario directory38DIRPATH_SCENARIO = os.path.join(os.path.expanduser("~"), 'Sumo')39# os.path.join(os.getcwd(),'testscenario')404142def load_scenario(filepath, logger=None):43scen = cm.load_obj(filepath, parent=None)44# scenario.set_workdirpath(os.path.dirname(filepath))45# this will set rootname and workdir46if scen is not None:47scen.set_filepath(filepath)48# print 'load_scenario', scen.get_rootfilepath(),'workdirpath',scen.workdirpath49if logger is not None:50scen.set_logger(logger)51return scen525354class ScenarioCreator(Process):55def __init__(self, rootname='myscenario', name_scenario='My Scenario', workdirpath=None, description='', logger=None):5657# init process58self._init_common('scenariocreator', name='New Scenario', logger=logger)5960if workdirpath is None:61#workdirpath = os.getcwd()62workdirpath = os.path.expanduser("~")63attrsman = self.get_attrsman()64self.rootname = attrsman.add(cm.AttrConf('rootname', rootname,65groupnames=['options'],66perm='rw',67name='Shortname',68info='Short name for scenario. This string is used as rootname for all files produced by this scenario. Please avoid special charracters, whitespace, accents etc. ASCII is recommented in order to remain compatible between operating systems.',69))7071self.name_scenario = attrsman.add(cm.AttrConf('name_scenario', name_scenario,72groupnames=['options'],73perm='rw',74name='Name',75info='Scenario name, used for documentation purposes only.',76))7778self.description = attrsman.add(cm.AttrConf('description', description,79groupnames=['options'],80perm='rw',81name='Description',82info='Short, free description of Scenario.',83))8485self.workdirpath = attrsman.add(cm.AttrConf('workdirpath', workdirpath,86groupnames=['options'],87perm='rw',88name='Workdir',89metatype='dirpath',90info='Working directory for this scenario.',91))9293def do(self):94# print 'do',self.newident95self._scenario = Scenario(self.rootname,96name_scenario=self.name_scenario,97description=self.description,98parent=None,99workdirpath=self.workdirpath,100logger=self.get_logger(),101)102return True103104def get_scenario(self):105return self._scenario106107# class OxScenariocreator(ScenarioCreator):108# def __init__(self, **kwargs):109##110# ScenarioCreator.__init__(self,**kwargs)111##112# nodeshapefilepath, edgeshapefilepath, polyshapefilepath,113## attrsman = self.get_attrsman()114# self.nodeshapefilepath = attrsman.add(115# cm.AttrConf('nodeshapefilepath',kwargs.get('nodeshapefilepath',''),116## groupnames = ['options'],117# perm='rw',118## name = 'Nodes shapefile',119## wildcards = 'Shape file (*.shp)|*.shp;*.SHP',120## metatype = 'filepaths',121## info = """Shapefile path for nodes.""",122# ))123##124# self.edgeshapefilepath = attrsman.add(125# cm.AttrConf('edgeshapefilepath',kwargs.get('edgeshapefilepath',''),126## groupnames = ['options'],127# perm='rw',128## name = 'Edge shapefile',129## wildcards = 'Shape file (*.shp)|*.shp;*.SHP',130## metatype = 'filepaths',131## info = """Shapefile path for edges.""",132# ))133##134# self.polyshapefilepath = attrsman.add(135# cm.AttrConf('polyshapefilepath',kwargs.get('polyshapefilepath',''),136## groupnames = ['options'],137# perm='rw',138## name = 'Poly shapefile',139## wildcards = 'Shape file (*.shp)|*.shp;*.SHP',140## metatype = 'filepaths',141## info = """Shapefile path for polygons.""",142# ))143##144##145# def do(self):146# print 'do',self.newident147# if ScenarioCreator.do(self):148##149## scenario = self.get_scenario()150# return shapeformat.OxImporter(scenario,151## self.nodeshapefilepath, self.edgeshapefilepath, self.polyshapefilepath,152## ident = 'oximporter',153## name = 'OSMnx importer',154## info = 'Import of network imported with the help of osmnx.',155## logger =self.get_logger()156# ).do()157# else:158# return False159##160161162class Scenario(cm.BaseObjman):163def __init__(self, rootname, name_scenario='myscenario',164description='', parent=None,165workdirpath=None, **kwargs):166167self._init_objman(ident='scenario', parent=parent,168name='Scenario', info='Main scenario instance.',169version=0.2,170**kwargs)171172attrsman = self.set_attrsman(cm.Attrsman(self))173174if workdirpath is not None:175# create a directory if path is given, but does not exist176if not os.path.isdir(workdirpath):177os.mkdir(workdirpath)178else:179workdirpath = os.getcwd()180#workdirpath = os.path.expanduser("~")181182self.name_scenario = attrsman.add(cm.AttrConf('name_scenario', name_scenario,183groupnames=['options'],184perm='rw',185name='Name',186info='Scenario name, used for documentation purposes only.',187))188189self.description = attrsman.add(cm.AttrConf('description', description,190groupnames=['options'],191perm='rw',192name='Description',193info='Short, free description of Scenario.',194))195196self.rootname = attrsman.add(cm.AttrConf('rootname', rootname,197groupnames=['options'],198perm='r',199is_save=True,200name='Shortname',201info='Short name for scenario. This string is defined when saving the scenario. It is used as rootname for all files produced by this scenario. Please avoid special charracters, whitespace, accents etc. ASCII is recommented in order to remain compatible between operating systems.',202))203204self.workdirpath = attrsman.add(cm.AttrConf('workdirpath', workdirpath,205groupnames=['options'],206perm='r',207is_save=True,208name='Workdir',209metatype='dirpath',210info='Working directory for this scenario and can be changed when saving the scenario. Please avoid special charracters, whitespace, accents etc. ASCII is recommented in order to remain compatible between operating systems.',211))212213self.net = attrsman.add(cm.ObjConf(network.Network(self)))214215self.landuse = attrsman.add(cm.ObjConf(landuse.Landuse(self, self.net)))216217self.demand = attrsman.add(cm.ObjConf(demand.Demand(self)))218# if self.get_version()<0.2:219# self.delete('simulation')220221self._init_attributes()222223def _init_attributes(self):224print 'Scenario._init_attributes' # ,dir(self)225226attrsman = self.get_attrsman()227self.simulation = attrsman.add(cm.ObjConf(simulation.Simulation(self)))228self.set_version(0.2)229230# print ' finish Scenario._init_attributes'231def set_filepath(self, filepath):232"""233A new filepath will set the shortname and workdir.234"""235names = os.path.basename(filepath).split('.')236dirname = os.path.dirname(filepath)237238if len(names) >= 3:239rootname = '.'.join(names[:-2])240elif len(names) <= 2:241rootname = names[0]242243self.set_workdirpath(dirname)244self.set_rootfilename(rootname)245246def save(self, filepath=None):247if filepath is None:248filepath = self.get_rootfilepath()+'.obj'249self.set_filepath(filepath)250cm.save_obj(self, filepath, is_not_save_parent=False)251return filepath252253def get_workdirpath(self):254return self.workdirpath255256def set_workdirpath(self, workdirpath):257self.workdirpath = workdirpath258259def set_rootfilename(self, filename):260self.rootname = filename261262def get_rootfilename(self):263"""264Centralized definition of filename bases.265"""266return self.rootname267268def get_rootfilepath(self):269return os.path.join(self.get_workdirpath(), self.get_rootfilename())270271def import_xml(self, is_clean_nodes=False):272"""273Try to import xml-type files into scenario.274"""275276# print 'import_xml'277netfilepath = self.net.get_filepath()278279if os.path.isfile(netfilepath):280# convert and import edg,nod,con,tll...281self.net.import_netxml(filepath=netfilepath, rootname=self.get_rootfilename())282else:283# import edg,nod,con,tll...284self.net.import_xml(self.get_rootfilename(), self.get_workdirpath(), is_clean_nodes=is_clean_nodes)285286self.landuse.import_polyxml(self.get_rootfilename(), self.get_workdirpath())287try:288self.demand.import_xml(self.get_rootfilename(), self.get_workdirpath())289except:290print 'WARNING: import of demand data failed. Please check for inconsistency with trip/route and network edge IDs.'291292def update_netoffset(self, deltaoffset):293"""294Called when network offset has changed.295Children may need to adjust theur coordinates.296"""297self.landuse.update_netoffset(deltaoffset)298self.demand.update_netoffset(deltaoffset)299300301if __name__ == '__main__':302###############################################################################303# print 'sys.path',sys.path304from agilepy.lib_wx.objpanel import objbrowser305from agilepy.lib_base.logger import Logger306if len(sys.argv) == 3:307rootname = sys.argv[1]308dirpath = sys.argv[2]309else:310rootname = 'facsp2'311dirpath = os.path.join(os.path.dirname(__file__), '..', 'network', 'testnet')312313scenario = Scenario(rootname, workdirpath=dirpath, logger=Logger())314315# net.import_nodes(os.path.join('test','facsp2.nod.xml'))316# net.import_edges(os.path.join('test','facsp2.edg.xml'))317objbrowser(scenario)318319320