/
GenStarGamaSurveyUtils.java
304 lines (263 loc) · 7.88 KB
/
GenStarGamaSurveyUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/*******************************************************************************************************
*
* GenStarGamaSurveyUtils.java, in espacedev.gaml.extensions.genstar, is part of the source code of the GAMA modeling
* and simulation platform (v.1.8.2).
*
* (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU)
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package espacedev.gaml.extensions.genstar.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import core.metamodel.attribute.Attribute;
import core.metamodel.value.IValue;
import msi.gama.common.util.FileUtils;
import msi.gama.runtime.IScope;
import msi.gama.util.file.GamaCSVFile;
import msi.gama.util.file.csv.CsvReader;
import msi.gama.util.file.csv.CsvReader.Stats;
import msi.gaml.types.IType;
import msi.gaml.types.Types;
import ummisco.gama.dev.utils.DEBUG;
/**
* The Class GenStarGamaSurveyUtils.
*/
/*
* Encapsulation (more a copy/past) of CsvReader utilities to explore csv files
*/
public class GenStarGamaSurveyUtils {
/**
* Instantiates a new gen star gama survey utils.
*
* @param scope
* the scope
* @param survey
* the survey
* @param atts
* the atts
* @throws FileNotFoundException
* the file not found exception
*/
public GenStarGamaSurveyUtils(final IScope scope, final GamaCSVFile survey,
final List<Attribute<? extends IValue>> atts) throws FileNotFoundException {
this.path = Paths.get(FileUtils.constructAbsoluteFilePath(scope, survey.getPath(scope), false));
this.stats = CsvReader.getStats(this.path.toString(), null);
this.atts = atts;
}
/** The stats. */
private final Stats stats;
/** The path. */
private final Path path;
/** The atts. */
private final List<Attribute<? extends IValue>> atts;
/** The row header number. */
// All is here
private final int[] rowHeaderNumber = { -1, -1 };
/** The column header number. */
private final int[] columnHeaderNumber = { -1, -1 };
/** The infered type. */
@SuppressWarnings ("rawtypes") private IType inferedType = null;
/** The total. */
private Double total = null;
/**
* TODO : find the number of row headers
*
* @return
*/
public int inferRowHeaders() {
if (rowHeaderNumber[0] == -1) {
CsvReader reader = null;
int first = rowHeaderNumber[0];
int headerLength = 0;
try {
reader = new CsvReader(path.toString(), stats.delimiter);
boolean isData = false;
do {
if (reader.readRecord()) {
List<String> vals = Arrays.asList(reader.getValues()).stream().filter(s -> !s.isBlank())
.collect(Collectors.toList());
Optional<Attribute<? extends IValue>> oa = atts.stream().filter(a -> a.getValueSpace()
.getValues().stream().allMatch(v -> vals.contains(v.getStringValue()))).findFirst();
if (oa.isPresent()) {
headerLength = oa.get().getValueSpace().getValues().size();
} else {
isData = true;
}
}
first += 1;
} while (!isData);
} catch (final IOException e) {}
reader.close();
rowHeaderNumber[0] = first;
columnHeaderNumber[1] = headerLength;
}
return rowHeaderNumber[0];
}
/**
* TODO : find the number of column headers
*
* @return
*/
public int inferColumnHeaders() {
if (columnHeaderNumber[0] == -1) {
CsvReader reader = null;
int first = 0;
int columnLength = 0;
try {
reader = new CsvReader(path.toString(), stats.delimiter);
int idx = inferRowHeaders();
do { reader.skipLine(); } while (--idx > 0);
boolean isData = false;
if (reader.readRecord()) {
List<String> vals = Arrays.asList(reader.getValues()).stream().filter(s -> !s.isBlank())
.collect(Collectors.toList());
int tmp = 0;
do {
String current = vals.get(tmp++);
Optional<Attribute<? extends IValue>> oa =
atts.stream().filter(a -> a.getValueSpace().contains(current)).findFirst();
if (oa.isPresent()) {
columnLength = oa.get().getValueSpace().getValues().size() > columnLength
? oa.get().getValueSpace().getValues().size() : columnLength;
} else {
isData = true;
first = vals.indexOf(current);
}
} while (!isData);
}
} catch (final IOException e) {}
reader.close();
columnHeaderNumber[0] = first;
rowHeaderNumber[1] = columnLength;
}
return columnHeaderNumber[0];
}
/**
* Infer the type of data contains in the csv file
*
* @return
*/
@SuppressWarnings ("rawtypes")
public IType inferDataType() {
if (inferedType != null) return inferedType;
inferedType = Types.NO_TYPE;
CsvReader reader = null;
try {
reader = new CsvReader(path.toString(), stats.delimiter);
int idx = inferRowHeaders();
do { reader.skipLine(); } while (--idx > 0);
if (reader.readRecord()) {
String[] firstLineData = reader.getValues();
inferedType = processRecordType(
Arrays.copyOfRange(firstLineData, inferColumnHeaders(), firstLineData.length));
}
} catch (final IOException e) {}
reader.close();
return inferedType;
}
/**
* Compute the sum of data contained in the csv file: if there is non numerical data, then
*
* @return
*/
public Double getTotalData() {
if (total != null) return total;
if (!inferedType.isNumber()) { total = -1d; }
CsvReader reader = null;
try {
reader = new CsvReader(path.toString(), stats.delimiter);
int[] min = { inferRowHeaders(), inferColumnHeaders() };
int[] max = { columnHeaderNumber[0] + columnHeaderNumber[1], rowHeaderNumber[0] + rowHeaderNumber[1] };
DEBUG.OUT("Data matrix is" + DEBUG.TO_STRING(min) + DEBUG.TO_STRING(max));
int idx = min[0];
do { reader.skipLine(); } while (--idx > 0);
int ldx = max[1];
while (ldx-- > 0) {
if (reader.readRecord()) {
String[] lineData = Arrays.copyOfRange(reader.getValues(), min[1], max[0]);
for (String element : lineData) { total += Double.valueOf(element); }
}
}
//System.out.println("Total value is " + total);
} catch (final IOException e) {}
reader.close();
return total;
}
/**
* The Class StringAnalysis.
*/
private static class StringAnalysis {
/** The is float. */
boolean isFloat = true;
/** The is int. */
boolean isInt = true;
/**
* Instantiates a new string analysis.
*
* @param s
* the s
*/
StringAnalysis(final String s) {
for (final char c : s.toCharArray()) {
final boolean isDigit = Character.isDigit(c);
if (!isDigit) {
if (c == '.') {
isInt = false;
} else if (Character.isLetter(c)) {
isInt = false;
isFloat = false;
break;
} else if (c == ',' || c == ';' || c == '|' || c == ':' || c == '/' || Character.isWhitespace(c)) {
isInt = false;
isFloat = false;
}
}
}
if (isInt && isFloat) { isFloat = false; }
}
}
/**
* Process record type.
*
* @param values
* the values
* @return the i type
*/
@SuppressWarnings ("rawtypes")
protected IType processRecordType(final String[] values) {
IType temp = null;
for (final String s : values) {
final StringAnalysis sa = new StringAnalysis(s);
if (sa.isInt) {
if (temp == null) { temp = Types.INT; }
} else if (sa.isFloat) {
if (temp == null || temp == Types.INT) { temp = Types.FLOAT; }
} else {
temp = Types.NO_TYPE;
}
}
// in case nothing has been read (i.e. empty file)
if (temp == null) { temp = Types.NO_TYPE; }
return temp;
}
/**
* Gets the path.
*
* @return the path
*/
public Path getPath() { return path; }
/**
* Gets the delimiter.
*
* @return the delimiter
*/
public Character getDelimiter() { return stats.delimiter; }
}