Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/tools/contributed/sumopy/agilepy/lib_base/imports.py
169689 views
1
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
2
# Copyright (C) 2016-2025 German Aerospace Center (DLR) and others.
3
# SUMOPy module
4
# Copyright (C) 2012-2021 University of Bologna - DICAM
5
# This program and the accompanying materials are made available under the
6
# terms of the Eclipse Public License 2.0 which is available at
7
# https://www.eclipse.org/legal/epl-2.0/
8
# This Source Code may also be made available under the following Secondary
9
# Licenses when the conditions for such availability set forth in the Eclipse
10
# Public License 2.0 are satisfied: GNU General Public License, version 2
11
# or later which is available at
12
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
13
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
14
15
# @file imports.py
16
# @author Joerg Schweizer
17
# @date 2012
18
19
20
import os
21
import sys
22
import types
23
import numpy as np
24
import agilepy.lib_base.classman as cm
25
import agilepy.lib_base.arrayman as am
26
27
from agilepy.lib_base.processes import Process
28
29
30
class CsvImporter(Process):
31
def __init__(self, obj, ident='csvimporter', name='CSV importer',
32
info='Import data from a CSV file into object',
33
logger=None, **kwargs):
34
print 'CsvImporter.__init__'
35
self._init_common(ident,
36
parent=obj,
37
name=name,
38
logger=logger,
39
info=info,
40
)
41
42
attrsman = self.set_attrsman(cm.Attrsman(self))
43
self.csvfilepath = attrsman.add(cm.AttrConf('csvfilepath', kwargs.get('csvfilepath', ''),
44
groupnames=['options'],
45
perm='rw',
46
name='CSV file',
47
wildcards='CSV file (*.csv)|*.csv|*.CSV',
48
metatype='filepath',
49
info="CSV plain text file path.",
50
))
51
52
self.sep = attrsman.add(cm.AttrConf('sep', kwargs.get('sep', ","),
53
groupnames=['options', ],
54
perm='rw',
55
name='Separator',
56
info="""Seperator used in SCV file. Exampe: ; , <space key>""",
57
))
58
59
self.is_use_default_for_invalid = attrsman.add(cm.AttrConf('is_use_default_for_invalid', kwargs.get('is_use_default_for_invalid', True),
60
groupnames=['options', ],
61
perm='rw',
62
name='Use default for invalid',
63
info="""Use default for invalid.""",
64
))
65
66
for attrconf in obj.get_colconfigs():
67
colattrname = self._get_colattrname(attrconf.attrname)
68
setattr(self, colattrname,
69
attrsman.add(cm.AttrConf(colattrname, attrconf.attrname,
70
groupnames=['options', 'colnames'],
71
perm='rw',
72
attrname_orig=attrconf.attrname,
73
name='Column name for %s' % attrconf.get_name(),
74
info='Name of column in CSV file for column %s. Include also hyphens and other delimiters when present in CSV file.' % attrconf.get_name(),
75
)))
76
77
def _get_colattrname(self, attrname):
78
return 'colname_'+attrname
79
80
def do(self):
81
print 'CsvImporter.do',
82
obj = self.parent
83
attrsman = self.get_attrsman()
84
sep = self.sep
85
logger = self._logger
86
87
aa = '\"'
88
emptycol = ("", "None", "NONE")
89
INTTYPE = 'i'
90
FLOATTYPE = 'f'
91
STRINGTYPE = 's'
92
BOOLTYPE = 'b'
93
is_use_nan = not self.is_use_default_for_invalid
94
95
#INTLISTTYPE = 'li'
96
#FLOATLISTTYPE = 'lf'
97
#STRINGLISTTYPE = 'ls'
98
filepath = self.csvfilepath
99
f = open(filepath, 'r')
100
101
INTTYPES = (types.IntType, np.int, np.int32, np.int64)
102
FLOATTYPES = (types.FloatType, types.LongType, types.ComplexType, np.float, np.float32, np.float64)
103
BOOLTYPES = (types.BooleanType, np.bool_)
104
105
#line = f.readline()
106
# print ' line[:-1] = *%s*'%(line[:-1],)
107
index_to_value = {}
108
index_to_type = {}
109
index_to_attrname = {}
110
i = 0
111
for csvattr_raw in f.readline().split(sep):
112
113
csvattr = self._get_colattrname(csvattr_raw.strip().strip(aa))
114
# print ' check csvattr *%s*, %d'%(csvattr,i),hasattr(self, csvattr)
115
116
if hasattr(self, csvattr):
117
colnameconf = attrsman.get_config(csvattr)
118
index_to_attrname[i] = colnameconf.attrname_orig
119
index_to_value[i] = []
120
attrconfig = obj.get_config(colnameconf.attrname_orig)
121
defaulttype = type(attrconfig.get_default())
122
# print ' defaulttype',defaulttype
123
if defaulttype in INTTYPES:
124
index_to_type[i] = INTTYPE
125
elif defaulttype in FLOATTYPES:
126
index_to_type[i] = FLOATTYPE
127
elif defaulttype in BOOLTYPES:
128
index_to_type[i] = BOOLTYPE
129
else:
130
index_to_type[i] = STRINGTYPE
131
i += 1
132
133
if len(index_to_type) == 0:
134
if logger:
135
logger.w('file %s does not contain valid column names.' % os.path.basename(filepath))
136
return False
137
138
# print 'index_to_attrname',index_to_attrname
139
# print 'index_to_value',index_to_value
140
# print 'index_to_type',index_to_type
141
#n_cols = len(attrsinds)
142
if logger:
143
logger.w('import CSV from %s' % os.path.basename(filepath))
144
n_imported = 0
145
ind_max = max(index_to_value.keys())
146
for line in f.readlines():
147
cols = line.split(sep)
148
if len(cols) > ind_max: # restrictive!
149
for ind, vals, valtype in zip(index_to_value.keys(), index_to_value.values(), index_to_type.values()):
150
val = cols[ind].strip()
151
if val not in emptycol:
152
if valtype == INTTYPE:
153
vals.append(int(val))
154
elif valtype == FLOATTYPE:
155
vals.append(float(val))
156
elif valtype == BOOLTYPE:
157
if val in TRUEVALS:
158
vals.append(True)
159
else:
160
vals.append(False)
161
else: # type == STRINGTYPE:
162
vals.append(val.strip(aa))
163
164
elif is_use_nan:
165
if valtype == INTTYPE:
166
vals.append(np.nan)
167
elif valtype == FLOATTYPE:
168
vals.append(np.nan)
169
elif valtype == BOOLTYPE:
170
vals.append(np.nan)
171
else: # type == STRINGTYPE:
172
vals.append("")
173
n_imported += 1
174
175
ids = obj.add_rows(n_imported)
176
for ind, values in index_to_value.iteritems():
177
getattr(obj, index_to_attrname[ind])[ids] = values
178
179
f.close()
180
return True
181
182