Path: blob/main/tools/contributed/sumopy/agilepy/lib_base/imports.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 imports.py15# @author Joerg Schweizer16# @date 2012171819import os20import sys21import types22import numpy as np23import agilepy.lib_base.classman as cm24import agilepy.lib_base.arrayman as am2526from agilepy.lib_base.processes import Process272829class CsvImporter(Process):30def __init__(self, obj, ident='csvimporter', name='CSV importer',31info='Import data from a CSV file into object',32logger=None, **kwargs):33print 'CsvImporter.__init__'34self._init_common(ident,35parent=obj,36name=name,37logger=logger,38info=info,39)4041attrsman = self.set_attrsman(cm.Attrsman(self))42self.csvfilepath = attrsman.add(cm.AttrConf('csvfilepath', kwargs.get('csvfilepath', ''),43groupnames=['options'],44perm='rw',45name='CSV file',46wildcards='CSV file (*.csv)|*.csv|*.CSV',47metatype='filepath',48info="CSV plain text file path.",49))5051self.sep = attrsman.add(cm.AttrConf('sep', kwargs.get('sep', ","),52groupnames=['options', ],53perm='rw',54name='Separator',55info="""Seperator used in SCV file. Exampe: ; , <space key>""",56))5758self.is_use_default_for_invalid = attrsman.add(cm.AttrConf('is_use_default_for_invalid', kwargs.get('is_use_default_for_invalid', True),59groupnames=['options', ],60perm='rw',61name='Use default for invalid',62info="""Use default for invalid.""",63))6465for attrconf in obj.get_colconfigs():66colattrname = self._get_colattrname(attrconf.attrname)67setattr(self, colattrname,68attrsman.add(cm.AttrConf(colattrname, attrconf.attrname,69groupnames=['options', 'colnames'],70perm='rw',71attrname_orig=attrconf.attrname,72name='Column name for %s' % attrconf.get_name(),73info='Name of column in CSV file for column %s. Include also hyphens and other delimiters when present in CSV file.' % attrconf.get_name(),74)))7576def _get_colattrname(self, attrname):77return 'colname_'+attrname7879def do(self):80print 'CsvImporter.do',81obj = self.parent82attrsman = self.get_attrsman()83sep = self.sep84logger = self._logger8586aa = '\"'87emptycol = ("", "None", "NONE")88INTTYPE = 'i'89FLOATTYPE = 'f'90STRINGTYPE = 's'91BOOLTYPE = 'b'92is_use_nan = not self.is_use_default_for_invalid9394#INTLISTTYPE = 'li'95#FLOATLISTTYPE = 'lf'96#STRINGLISTTYPE = 'ls'97filepath = self.csvfilepath98f = open(filepath, 'r')99100INTTYPES = (types.IntType, np.int, np.int32, np.int64)101FLOATTYPES = (types.FloatType, types.LongType, types.ComplexType, np.float, np.float32, np.float64)102BOOLTYPES = (types.BooleanType, np.bool_)103104#line = f.readline()105# print ' line[:-1] = *%s*'%(line[:-1],)106index_to_value = {}107index_to_type = {}108index_to_attrname = {}109i = 0110for csvattr_raw in f.readline().split(sep):111112csvattr = self._get_colattrname(csvattr_raw.strip().strip(aa))113# print ' check csvattr *%s*, %d'%(csvattr,i),hasattr(self, csvattr)114115if hasattr(self, csvattr):116colnameconf = attrsman.get_config(csvattr)117index_to_attrname[i] = colnameconf.attrname_orig118index_to_value[i] = []119attrconfig = obj.get_config(colnameconf.attrname_orig)120defaulttype = type(attrconfig.get_default())121# print ' defaulttype',defaulttype122if defaulttype in INTTYPES:123index_to_type[i] = INTTYPE124elif defaulttype in FLOATTYPES:125index_to_type[i] = FLOATTYPE126elif defaulttype in BOOLTYPES:127index_to_type[i] = BOOLTYPE128else:129index_to_type[i] = STRINGTYPE130i += 1131132if len(index_to_type) == 0:133if logger:134logger.w('file %s does not contain valid column names.' % os.path.basename(filepath))135return False136137# print 'index_to_attrname',index_to_attrname138# print 'index_to_value',index_to_value139# print 'index_to_type',index_to_type140#n_cols = len(attrsinds)141if logger:142logger.w('import CSV from %s' % os.path.basename(filepath))143n_imported = 0144ind_max = max(index_to_value.keys())145for line in f.readlines():146cols = line.split(sep)147if len(cols) > ind_max: # restrictive!148for ind, vals, valtype in zip(index_to_value.keys(), index_to_value.values(), index_to_type.values()):149val = cols[ind].strip()150if val not in emptycol:151if valtype == INTTYPE:152vals.append(int(val))153elif valtype == FLOATTYPE:154vals.append(float(val))155elif valtype == BOOLTYPE:156if val in TRUEVALS:157vals.append(True)158else:159vals.append(False)160else: # type == STRINGTYPE:161vals.append(val.strip(aa))162163elif is_use_nan:164if valtype == INTTYPE:165vals.append(np.nan)166elif valtype == FLOATTYPE:167vals.append(np.nan)168elif valtype == BOOLTYPE:169vals.append(np.nan)170else: # type == STRINGTYPE:171vals.append("")172n_imported += 1173174ids = obj.add_rows(n_imported)175for ind, values in index_to_value.iteritems():176getattr(obj, index_to_attrname[ind])[ids] = values177178f.close()179return True180181182