Path: blob/main/tools/contributed/sumopy/agilepy/lib_base/test_classman_classes.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 test_classman_classes.py15# @author Joerg Schweizer16# @date 20121718"""19Test for callsman20Provides test classes and some test functions for plugin.21"""2223from classman import *24from arrayman import *25import xmlman as xm262728def on_event_delattr(attrconfig):29print 'EVENT: Attribute', attrconfig.attrname, 'will be deleted!!'303132def on_event_setattr(attrconfig):33print 'EVENT: Attribute', attrconfig.attrname, 'has been set to a new value', attrconfig.format_value()343536def on_event_getattr(attrconfig):37print 'EVENT: Attribute', attrconfig.attrname, 'has been retrieved the value', attrconfig.format_value()383940def on_event_additem(attrconfig, keys):41print 'EVENT: Attribute', attrconfig.attrname, ':added keys:', keys424344def on_event_delitem(attrconfig, keys):45print 'EVENT: Attribute', attrconfig.attrname, ':delete keys:', keys464748def on_event_setitem(attrconfig, keys):49print 'EVENT: Attribute', attrconfig.attrname, ':set keys:', keys505152def on_event_getitem(attrconfig, keys):53print 'EVENT: Attribute', attrconfig.attrname, ':get keys:', keys545556class Segments(ArrayObjman):5758def __init__(self, ident='segments', parent=None, **kwargs):5960self._init_objman(ident, parent=parent, xmltag=('segments', 'segment', 'ids_ref'), **kwargs)6162self.add_col(ArrayConf('ids_ref', '',63dtype='object',64perm='r',65is_index=True,66name='ID Ref',67info='Ref ID',68xmltag='id_ref',69))7071self.add_col(ArrayConf('vertices', np.zeros((2, 3), float),72groupnames=['internal'],73perm='rw',74name='Vertex',75is_save=True,76info='Vertex coordinate vectors of points. with format [[[x11,y11,z11],[x12,y12,z12]],[[x21,y21,z21],[x22,y22,z122]],...]',77xmltag='vertex',78))7980self.add_col(IdsArrayConf('ids_parent', parent,81groupnames=['state'],82is_save=True,83name='ID '+parent.get_ident(),84info='ID of '+parent.get_name()+' object.',85xmltag='id_poly',86))878889class Polylines (ArrayObjman):90def __init__(self, ident='polyline', parent=None, name='Polyline',91info='Polyline [ segid11, segid12,...]', **kwargs):92self._init_objman(ident, parent=parent, xmltag=('polylines', 'polyline', 'ids_osm'), **kwargs)93# print '__init__',self.get_name(),self.format_ident()9495self.add_col(ArrayConf('ids_osm', '',96dtype='object',97perm='r',98is_index=True,99name='ID OSM',100info='Edge ID of OSM',101xmltag='id_osm',102))103104# initialize line segments105segments = Segments(parent=self)106self.add(ObjConf(segments, groupnames=['drawobjects']))107108# print ' segments',segments109# print ' self.segments',self.segments,type(self.segments)110# create table with id lists to segments111self.add_col(IdlistsArrayConf('ids_segments', segments,112groupnames=['elements'],113is_save=True,114name='IDs Segs',115info='List with IDs to Line segments.',116xmltag='segments',117))118119def draw(self, pointvertices, id_osm):120"""121pointvertices = [122[0.0,0.0,0.0],123[0.2,0.0,0.0],124]125"""126vertices = []127print 'draw', self.ident128for i in xrange(1, len(pointvertices)):129vertices.append([pointvertices[i-1], pointvertices[i]])130n_vert = len(vertices)131_id = self.add_row(ids_osm=id_osm)132cod = []133#import string134clist = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'], np.object)135print ' ', len(vertices), clist[:len(vertices)]136ids = self.segments.value.suggest_ids(len(vertices))137ids_segs = self.segments.value.add_rows(ids=ids, vertices=vertices, ids_parent=n_vert*[_id], ids_ref=clist[ids])138self.ids_segments[_id] = list(ids_segs) # put here list, otherwise numpy thinks it is a numeric array139return _id140141142class Lines(ArrayObjman):143144def __init__(self, ident, parent=None, **kwargs):145146self._init_objman(ident, parent=parent, **kwargs)147148self.add_col(ArrayConf('vertices', np.zeros((2, 3), float),149groupnames=['internal'],150perm='rw',151name='Vertex',152is_save=True,153info='Vertex coordinate vectors of points. with format [[[x11,y11,z11],[x12,y12,z12]],[[x21,y21,z21],[x22,y22,z122]],...]',154))155156self.add_col(ArrayConf('ids_sumo', '',157dtype='object',158perm='r',159is_index=True,160name='ID SUMO',161info='Edge ID of SUMO network',162))163164165class Selection(ArrayObjman):166def __init__(self, ident, parent=None, **kwargs):167self._init_objman(ident, parent=parent, **kwargs)168self.add_col(TabIdsArrayConf('obj_ids',169name='Object[id]',170info='Draw obj and ids',171))172173174class Collection(ArrayObjman):175def __init__(self, ident, parent=None, **kwargs):176self._init_objman(ident, parent=parent, **kwargs)177self.add_col(TabIdListArrayConf('tab_id_lists',178name='[Tab1[id1],Tab2[id1],...]',179info='Collection of different items from different tables.',180))181182183class TestClass(BaseObjman):184def __init__(self, ident='testobj', parent=None, name='Test Object'):185self._init_objman(ident, parent=parent, name=name, xmltag=ident)186attrsman = self.set_attrsman(Attrsman(self))187188self.netfilepath = attrsman.add(AttrConf('netfilepath', 'pathtofile',189groupnames=['state'],190perm='rw',191is_save=True,192name='Network file',193metatype='filepath',194info='Network file path',195xmltag='netfilepath',196))197198self.workdirpath = attrsman.add(AttrConf('workdirpath', 'pathtodir',199groupnames=['state'],200perm='rw',201is_save=True,202name='Workdir',203metatype='dirpath',204info='Working directory.',205xmltag='workdirpath',206))207208self.access = attrsman.add(ListConf('access', ['bus', 'bike', 'tram'],209groupnames=['state'],210perm='rw',211is_save=True,212name='Access list',213info='List with vehicle classes that have access',214xmltag='access',215))216217self.allowed = attrsman.add(AttrConf('allowed', 0, choices={'bus': 0, 'bike': 1, 'tram': 2},218groupnames=['state'],219perm='rw',220is_save=True,221name='Access list',222info='List with vehicle classes that have access',223xmltag='allowed',224))225226self.emissiontype = attrsman.add(AttrConf('emissiontype', 'Euro 0',227groupnames=['state'],228perm='rw',229is_save=True,230name='Emission type',231info='Emission type of vehicle',232xmltag='emissiontype',233))234235self.x = attrsman.add(NumConf('x', 1.0,236digits_integer=None, digits_fraction=4,237minval=0.0, maxval=None,238groupnames=['state'],239perm='rw',240is_save=True,241unit='m',242is_plugin=True,243name='position',244info='Test object x position',245xmltag='x',246))247248self.x_thresh = attrsman.add(NumConf('x_thresh', 0.0,249digits_integer=None, digits_fraction=4,250minval=0.0, maxval=None,251groupnames=['state'],252perm='rw',253is_save=True,254unit='m',255is_plugin=True,256name='position threshold',257info='Test object x position threshold',258xmltag='x_thesh',259))260261self.is_pos_ok = attrsman.add(FuncConf('is_pos_ok', 'on_is_pos_ok', False,262groupnames=['state'],263name='Pos OK',264info='True if position greater than thhreshold.',265))266self.testlist = attrsman.add(ListConf('testlist', ['1', 'dd', 'cvc'],267groupnames=['state'],268choices=['1', 'dd', 'cvc', 'dddd', 'eeeee'],269perm='rw',270is_save=True,271name='Test list',272info='This is a test list',273xmltag='testList',274))275276self.testlist_dict = attrsman.add(ListConf('testlist_dict', [1, 2, 3],277groupnames=['state'],278choices={'aa': 1, 'bb': 2, 'ccc': 3, 'dddd': 4, 'eeeee': 5},279perm='rw',280is_save=True,281name='Dictchoice Test list',282info='This is a Dictchoice test list',283xmltag='testList',284))285286self.testlist_read = attrsman.add(ListConf('testlist_read', [1, 2, 3],287groupnames=['state'],288choices={'aa': 1, 'bb': 2, 'ccc': 3, 'dddd': 4, 'eeeee': 5},289perm='r',290is_save=True,291name='Readonly Test list',292info='This is a readonly test list',293xmltag='testList',294))295296attrsman.print_attrs()297298def on_is_pos_ok(self):299"""300True if position greater than thhreshold.301"""302print 'on_is_pos_ok', self.x > self.x_thresh303return self.x > self.x_thresh304305306class TestClass3(BaseObjman):307def __init__(self, ident='testobj3', parent=None, name='Test Object3'):308self._init_objman(ident=ident, parent=parent, name=name, xmltag='testobj3')309attrsman = self.set_attrsman(Attrsman(self))310311self.child1 = attrsman.add(ObjConf(parent.child1, is_child=False))312313self.y = attrsman.add(AttrConf('y', 0.0,314groupnames=['state'],315perm='r',316is_save=True,317unit='m',318metatype='length',319is_plugin=True,320name='position',321info='Test object y position',322))323324325class TestClass2(BaseObjman):326def __init__(self, ident='testobj2', parent=None, name='Test Object2', xmltag='testobj2'):327self._init_objman(ident, parent=parent, name=name, xmltag=xmltag)328attrsman = self.set_attrsman(Attrsman(self))329330self.child1 = attrsman.add(ObjConf(TestClass('child1', self))331)332333print 'TestClass2.child1', self.child1334335self.child3 = attrsman.add(ObjConf(TestClass3('child3', self))336)337338339class TestTabman(BaseObjman):340def __init__(self, ident='test_tabman', parent=None, name='Test Table manage'):341self._init_objman(ident, parent=parent, name=name)342tm = Tabman(obj=self)343self.set_attrsman(tm)344self.surname = attrsman.add_col(ColConf('surname', 'xx',345groupnames=['state'],346perm='rw',347is_save=True,348name='Family name',349info='Name of Family',350))351352self.streetname = attrsman.add_col(ColConf('streetname', 'via della...',353groupnames=['state'],354perm='rw',355is_save=False,356name='Street name',357info='Name of the street',358))359360#_id = attrsman.suggest_id()361# print '_id =',_id362# self.attrman.add(_id)363364# print 'self.streetname',self.streetname,type(self.streetname)365# self.streetname[1]='yyy'366# print 'self.streetname',self.streetname,type(self.streetname)367attrsman.add_rows(5)368attrsman.streetname[3] = 'ssss'369attrsman.streetname[[1, 2]] = ['aa', 55]370print 'test get', attrsman.streetname[[1, 2]]371# self.streetname[1]+='zzz'372attrsman.del_rows([1, 3])373attrsman.del_row(5)374# attrsman.delete('streetname')375376377class TestTableObjMan(TableObjman):378def __init__(self, ident='test_tableobjman_simple', parent=None, name='Test Table Object Manager'):379self._init_objman(ident, parent=parent, name=name, xmltag=('testtab', 'row', None))380381# ATTENTION!!382# do not use x = self.add(...) or self.add_col(...)383# This would overwrite the configuration with the value384# because the attribute is the configuration, which is set by Attrman385# While the add method is returning the value386self.add(AttrConf('x', 0.0,387groupnames=['state'],388perm='r',389is_save=True,390unit='m',391metatype='length',392is_plugin=False,393name='position',394info='Test object x position',395xmltag='pos',396))397398self.add(AttrConf('is_pos_ok', False,399groupnames=['state'],400perm='rw',401is_save=True,402name='Pos OK',403info='True if position is OK',404xmltag='pos_ok',405))406407self.add_col(ColConf('surname', 'xx',408groupnames=['state'],409perm='r',410is_save=True,411name='Family name',412info='Name of Family',413xmltag='surname',414))415416self.add_col(ColConf('streetname', 'via della...',417groupnames=['state'],418perm='rw',419is_save=True,420name='Street name',421info='Name of the street',422xmltag='streetname',423))424425fruits = ['allpes', 'bananas', 'oranges']426self.add_col(ColConf('fruits', fruits[0],427groupnames=['state'],428choices=fruits,429perm='rw',430is_save=False,431name='Fruits',432info='Choose a fruit.',433))434435self.add_col(NumcolConf('distances', 0.0,436digits_integer=None, digits_fraction=4,437minval=0.0, maxval=None,438groupnames=['state'],439perm='rw',440is_save=True,441name='Distance',442unit='m',443info='Distance of the street',444xmltag='distances',445))446447self.add(FuncConf('new_row', 'on_new_row', None,448groupnames=['rowfunctions', '_private'],449name='New row',450info='Add a new row.',451))452self.add(FuncConf('delete_row', 'on_del_row', None,453groupnames=['rowfunctions', '_private'],454name='Del row',455#info = 'Delete a row.',456))457458#_id = attrsman.suggest_id()459# print '_id =',_id460# self.attrman.add(_id)461462# print 'self.streetname',self.streetname,type(self.streetname)463# self.streetname[1]='yyy'464# print 'self.streetname',self.streetname,type(self.streetname)465self.add_rows(5)466self.streetname[3] = 'ssss'467self.surname[[1, 2, 3, 4]] = ['a', 'bb', 'ccc', 'dddd']468self.streetname[[1, 2]] = ['vv', 'dd']469# print '\n\ntest get',self.streetname[[1,2,3]]470# self.streetname[1]+='zzz'471# self.del_rows([1,3])472# self.del_row(5)473# self.delete('streetname')474# self.delete('is_pos_ok')475# print 'dir',dir(self)476477def on_new_row(self, ids):478"""479True if position greater than thhreshold.480"""481self.add_row()482483def on_del_row(self, id_row):484"""485True if position greater than thhreshold.486"""487print 'on_del_row', id_row488self.del_row(id_row)489print ' ids after del', self.get_ids()490491492class TestTableObjManNocols(TableObjman):493"""494Table manager without columns...for test purposes495"""496497def __init__(self, ident='test_tableobjman_simple_nocols', parent=None, name='Test Table Object Manager'):498self._init_objman(ident, parent=parent, name=name)499500# ATTENTION!!501# do not use x = self.add(...) or c=self.add_col(...)502# This would overwrite the configuration with the value503# because the attribute is the configuration, which is set by Attrman504# While the add method is returning the value505self.add(AttrConf('x', 0.0,506groupnames=['state'],507perm='r',508is_save=True,509unit='m',510metatype='length',511is_plugin=False,512name='position',513info='Test object x position',514))515516self.add(AttrConf('is_pos_ok', False,517groupnames=['state'],518perm='rw',519is_save=True,520name='Pos OK',521info='True if position is OK',522))523524525class ZonesTab(ArrayObjman):526def __init__(self, ident, parent=None, **kwargs):527self._init_objman(ident, parent=parent, **kwargs)528529self.add_col(ColConf('zonetypes', 0,530choices={531"priority": 0,532"traffic_light": 1,533"right_before_left": 2,534"unregulated": 3,535"priority_stop": 4,536"traffic_light_unregulated": 5,537"allway_stop": 6,538"rail_signal": 7,539"zipper": 8,540"traffic_light_right_on_red": 9,541"rail_crossing": 10,542},543is_plugin=True,544#dtype = np.int32,545perm='rw',546#is_index = True,547name='Type',548info='Zone type.',549))550551self.add_col(NumcolConf('shapes', [],552groupnames=['state'],553perm='rw',554is_plugin=True,555is_save=True,556name='Shape',557info='Shape of zone which is a list of (x,y) coordinates',558))559560561class OdTripsTab(ArrayObjman):562def __init__(self, ident, parent, zones, **kwargs):563self._init_objman(ident, parent=parent, **kwargs)564565self.add_col(IdsArrayConf('ids_orig', zones,566groupnames=['state'],567is_save=True,568name='ID Orig',569info='ID of traffic assignment zone of origin of trip.',570))571572self.add_col(IdsConf('ids_dest', zones,573groupnames=['state'],574is_save=True,575name='ID Dest',576info='ID of traffic assignment zone of destination of trip.',577))578579self.add_col(NumArrayConf('tripnumbers', 0,580groupnames=['state'],581perm='rw',582is_save=True,583name='Trip number',584info='Number of trips from zone with ID Orig to zone with ID Dest.',585))586587588class OdModesTab(ArrayObjman):589def __init__(self, ident, parent=None, **kwargs):590self._init_objman(ident, parent=parent, **kwargs)591592self.add_col(ObjsConf('odtrips',593groupnames=['state'],594is_save=True,595name='OD matrix',596info='Matrix with trips from origin to destintion',597))598599600class OdIntervalsTab(ArrayObjman):601def __init__(self, ident, parent=None, **kwargs):602self._init_objman(ident, parent=parent, **kwargs)603604self.add_col(NumArrayConf('t_start', 0.0,605groupnames=['state'],606perm='rw',607is_save=True,608name='Start time',609unit='s',610info='Start time of interval',611))612613self.add_col(NumArrayConf('t_end', 3600.0,614groupnames=['state'],615perm='rw',616is_save=True,617name='End time',618unit='s',619info='End time of interval',620))621622self.add_col(ObjsConf('odmodes',623groupnames=['state'],624is_save=True,625name='Modes',626info='Transport mode',627))628629###########################################################################630# Instance creation631632633demand = BaseObjman('demand')634635zones = ZonesTab('zones', parent=demand)636demand.zones = demand.get_attrsman().add(ObjConf(zones))637EVTDELITEM = 20 # delete attribute638EVTSETITEM = 21 # set attribute639EVTGETITEM = 22 # get attribute640EVTADDITEM = 23 # add/create attribute641zones.shapes.plugin.add_event(EVTADDITEM, on_event_additem)642shapes = [[(0.0, 10.0), (10.0, 10.0), (10.0, 0.0)],643[(10.0, 20.0), (20.0, 20.0), (20.0, 10.0)],644[(20.0, 30.0), (30.0, 20.0), (30.0, 20.0)],645]646zones.add_rows(3, shapes=shapes)647648odintervals = OdIntervalsTab('odintervals', parent=demand, info='OD data for different time intervals')649demand.odintervals = demand.get_attrsman().add(ObjConf(odintervals))650odintervals.add_rows(2, t_start=[0, 3600], t_end=[3600, 7200])651for id_odmodes in odintervals.get_ids():652odmodes = OdModesTab((odintervals.odmodes.attrname, id_odmodes), parent=odintervals)653odintervals.odmodes[id_odmodes] = odmodes654655odmodes.add_rows(2)656for id_odtrips in odmodes.get_ids():657odtrips = OdTripsTab((odmodes.odtrips.attrname, id_odtrips), odmodes, zones)658odtrips.add_rows(3, ids_orig=[3, 2, 1], ids_dest=[3, 3, 3], tripnumbers=[10, 200, 555])659odmodes.odtrips[id_odtrips] = odtrips660661# demand.attrsman.print_attrs()662# odintervals.print_attrs()663664# -------------------------------------------------------------------------------665666667# vertices = [ [0.0,10.0,10.0,10.0,10.0,0.0],668# [10.0,20.0,20.0,20.0,20.0,10.0],669# [20.0,30.0,30.0,20.0,30.0,20.0],670# ]671672# vertices = [ [(0.0,10.0),(10.0,10.0)],673# [(10.0,20.0),(20.0,20.0)],674# [(20.0,30.0),(30.0,20.0)],675# ]676vertices = [677[[0.0, 0.0, 0.0], [0.2, 0.0, 0.0]], # 0678[[0.3, 0.0, 0.0], [0.9, 0.0, 0.0]], # 1679[[0.5, 0.0, 0.1], [1.9, 0.0, 0.0]], # 2680]681polygons = [682np.array([[0.0, 0.0, 0.0], [0.2, 0.0, 0.0], [0.2, 0.0, 0.1], [0.3, 0.3, 0.3]]), # 0683np.array([[0.3, 0.0, 0.0], [0.9, 0.0, 0.0]]), # 1684np.array([[0.5, 0.0, 0.1], [1.9, 0.0, 0.0], [0.2, 0.2, 0.2]]), # 2685]686ids_sumo = ['aa10', 'bb22', 'cc333']687# lines.add_rows(3)688drawing = BaseObjman('drawing')689690lines = Lines('lines', parent=drawing)691drawing.lines = drawing.get_attrsman().add(ObjConf(lines))692lines.add_rows(3, vertices=vertices, polygons=polygons, ids_sumo=ids_sumo)693694triangles = Lines('triangles', parent=drawing)695drawing.triangles = drawing.get_attrsman().add(ObjConf(triangles))696triangles.add_rows(3, vertices=2*vertices, polygons=polygons, ids_sumo=['xxx10', 'xx22', 'xx333'])697698selection = Selection('selection', parent=drawing)699drawing.selection = drawing.get_attrsman().add(ObjConf(selection))700selection.add_rows(2, obj_ids=[(lines, 2), (triangles, 1)])701702collections = Collection('collections', parent=drawing)703drawing.collections = drawing.get_attrsman().add(ObjConf(collections))704collections.add_rows(2, tab_id_lists=[[(lines, 2), (triangles, 1)],705[(lines, 2), (triangles, 1), (lines, 1)]]706)707708# -------------------------------------------------------------------------------709710pointvertices = [711[0.0, 0.0, 0.0],712[0.2, 0.0, 0.0],713[0.3, 0.5, 0.0],714[0.2, 0.5, 0.0],715[0.0, 0.5, 0.1],716[-1.5, -0.5, 0.0],717]718719pointvertices2 = [720[0.0, 0.3, 0.0],721[0.2, 0.3, 0.0],722[0.3, 0.8, 0.0],723[0.2, 0.8, 0.0],724[0.0, 0.8, 0.1],725[-1.5, -0.8, 0.0],726]727728pointvertices3 = [729[0.5, 0.3, 0.0],730[-1.5, -0.8, 0.0],731]732733734polylines = Polylines()735polylines.draw(pointvertices, 'aa10&1')736polylines.draw(pointvertices2, 'bb2210&1')737polylines.draw(pointvertices3, '5b2310&1')738polylines.print_attrs()739xm.write_obj_to_xml(polylines, 'test_polylines.xml')740741742