-
Notifications
You must be signed in to change notification settings - Fork 4
/
SaveStatement.java
1224 lines (1120 loc) · 47.8 KB
/
SaveStatement.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************************************
*
* msi.gaml.statements.SaveStatement.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and
* simulation platform (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gaml.statements;
import static msi.gama.common.util.FileUtils.constructAbsoluteFilePath;
import static msi.gama.util.graph.writer.GraphExporters.getAvailableWriters;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.media.jai.RasterFactory;
import org.apache.commons.lang.ArrayUtils;
import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.coverage.grid.GridCoverageFactory;
import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.gce.geotiff.GeoTiffFormat;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geometry.Envelope2D;
import org.geotools.referencing.CRS;
import org.jgrapht.nio.GraphExporter;
import org.locationtech.jts.algorithm.Orientation;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.impl.CoordinateArraySequenceFactory;
import org.opengis.coverage.grid.GridCoverageWriter;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.geometry.Envelope;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import msi.gama.common.geometry.GeometryUtils;
import msi.gama.common.interfaces.IGamlIssue;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.common.interfaces.ITyped;
import msi.gama.common.preferences.GamaPreferences;
import msi.gama.metamodel.agent.IAgent;
import msi.gama.metamodel.population.IPopulation;
import msi.gama.metamodel.shape.IShape;
import msi.gama.metamodel.topology.grid.GamaSpatialMatrix.GridPopulation;
import msi.gama.metamodel.topology.projection.IProjection;
import msi.gama.metamodel.topology.projection.SimpleScalingProjection;
import msi.gama.precompiler.GamlAnnotations.doc;
import msi.gama.precompiler.GamlAnnotations.example;
import msi.gama.precompiler.GamlAnnotations.facet;
import msi.gama.precompiler.GamlAnnotations.facets;
import msi.gama.precompiler.GamlAnnotations.inside;
import msi.gama.precompiler.GamlAnnotations.symbol;
import msi.gama.precompiler.GamlAnnotations.usage;
import msi.gama.precompiler.IConcept;
import msi.gama.precompiler.ISymbolKind;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.GamaColor;
import msi.gama.util.GamaListFactory;
import msi.gama.util.GamaMapFactory;
import msi.gama.util.IList;
import msi.gama.util.IModifiableContainer;
import msi.gama.util.file.IGamaFile;
import msi.gama.util.graph.IGraph;
import msi.gama.util.graph.writer.GraphExporters;
import msi.gama.util.matrix.GamaField;
import msi.gaml.compilation.IDescriptionValidator;
import msi.gaml.compilation.annotations.validator;
import msi.gaml.descriptions.IDescription;
import msi.gaml.descriptions.SpeciesDescription;
import msi.gaml.descriptions.StatementDescription;
import msi.gaml.expressions.ConstantExpression;
import msi.gaml.expressions.IExpression;
import msi.gaml.expressions.IExpressionFactory;
import msi.gaml.expressions.data.MapExpression;
import msi.gaml.operators.Cast;
import msi.gaml.operators.Comparison;
import msi.gaml.operators.Maths;
import msi.gaml.operators.Strings;
import msi.gaml.skills.GridSkill.IGridAgent;
import msi.gaml.species.ISpecies;
import msi.gaml.statements.SaveStatement.SaveValidator;
import msi.gaml.types.GamaFileType;
import msi.gaml.types.GamaKmlExport;
import msi.gaml.types.IType;
import msi.gaml.types.Types;
@symbol (
name = IKeyword.SAVE,
kind = ISymbolKind.SINGLE_STATEMENT,
concept = { IConcept.FILE, IConcept.SAVE_FILE },
with_sequence = true, // necessary to allow declaring the attributes facet as remote itself
// with_args = true,
remote_context = true)
@inside (
kinds = { ISymbolKind.BEHAVIOR, ISymbolKind.ACTION })
@facets (
value = { @facet (
name = IKeyword.TYPE,
type = IType.ID,
optional = true,
values = { "shp", "text", "csv", "asc", "geotiff", "image", "kml", "kmz", "json", "dimacs", "dot",
"gexf", "graphml", "gml", "graph6" },
doc = @doc ("an expression that evaluates to an string, the type of the output file (it can be only \"shp\", \"asc\", \"geotiff\", \"image\", \"text\" or \"csv\") ")),
@facet (
name = IKeyword.DATA,
type = IType.NONE,
optional = true,
doc = @doc ("the data that will be saved to the file")),
@facet (
name = IKeyword.REWRITE,
type = IType.BOOL,
optional = true,
doc = @doc ("a boolean expression specifying whether to erase the file if it exists or append data at the end of it. Only applicable to \"text\" or \"csv\" files. Default is true")),
@facet (
name = IKeyword.HEADER,
type = IType.BOOL,
optional = true,
doc = @doc ("an expression that evaluates to a boolean, specifying whether the save will write a header if the file does not exist")),
@facet (
name = IKeyword.TO,
type = IType.STRING,
optional = true,
doc = @doc ("an expression that evaluates to an string, the path to the file, or directly to a file")),
@facet (
name = "crs",
type = IType.NONE,
optional = true,
doc = @doc ("the name of the projection, e.g. crs:\"EPSG:4326\" or its EPSG id, e.g. crs:4326. Here a list of the CRS codes (and EPSG id): http://spatialreference.org")),
@facet (
name = IKeyword.ATTRIBUTES,
type = { IType.MAP, IType.LIST },
remote_context = true,
optional = true,
doc = @doc (
value = "Allows to specify the attributes of a shape file or GeoJson file where agents are saved. Can be expressed as a list of string or as a literal map. When expressed as a list, each value should represent the name of an attribute of the shape or agent. The keys of the map are the names of the attributes that will be present in the file, the values are whatever expressions neeeded to define their value. ")),
@facet (
name = IKeyword.WITH,
type = { IType.MAP },
optional = true,
doc = @doc (
deprecated = "Please use 'attributes:' instead",
value = "Allows to define the attributes of a shape file. Keys of the map are the attributes of agents to save, values are the names of attributes in the shape file")) },
omissible = IKeyword.DATA)
@doc (
value = "Allows to save data in a file. The type of file can be \"shp\", \"asc\", \"geotiff\", \"text\" or \"csv\".",
usages = { @usage (
value = "Its simple syntax is:",
examples = { @example (
value = "save data to: output_file type: a_type_file;",
isExecutable = false) }),
@usage (
value = "To save data in a text file:",
examples = { @example (
value = "save (string(cycle) + \"->\" + name + \":\" + location) to: \"save_data.txt\" type: \"text\";") }),
@usage (
value = "To save the values of some attributes of the current agent in csv file:",
examples = { @example (
value = "save [name, location, host] to: \"save_data.csv\" type: \"csv\";") }),
@usage (
value = "To save the values of all attributes of all the agents of a species into a csv (with optional attributes):",
examples = { @example (
value = "save species_of(self) to: \"save_csvfile.csv\" type: \"csv\" header: false;") }),
@usage (
value = "To save the geometries of all the agents of a species into a shapefile (with optional attributes):",
examples = { @example (
value = "save species_of(self) to: \"save_shapefile.shp\" type: \"shp\" attributes: ['nameAgent'::name, 'locationAgent'::location] crs: \"EPSG:4326\";") }),
@usage (
value = "To save the grid_value attributes of all the cells of a grid into an ESRI ASCII Raster file:",
examples = { @example (
value = "save grid to: \"save_grid.asc\" type: \"asc\";") }),
@usage (
value = "To save the grid_value attributes of all the cells of a grid into geotiff:",
examples = { @example (
value = "save grid to: \"save_grid.tif\" type: \"geotiff\";") }),
@usage (
value = "To save the grid_value attributes of all the cells of a grid into png (with a worldfile):",
examples = { @example (
value = "save grid to: \"save_grid.png\" type: \"image\";") }),
@usage (
value = "The save statement can be use in an init block, a reflex, an action or in a user command. Do not use it in experiments.") })
@validator (SaveValidator.class)
@SuppressWarnings ({ "rawtypes" })
public class SaveStatement extends AbstractStatementSequence implements IStatement.WithArgs {
public static class SaveValidator implements IDescriptionValidator<StatementDescription> {
/**
* Method validate()
*
* @see msi.gaml.compilation.IDescriptionValidator#validate(msi.gaml.descriptions.IDescription)
*/
@Override
public void validate(final StatementDescription description) {
final StatementDescription desc = description;
final Facets with = desc.getPassedArgs();
final IExpression att = desc.getFacetExpr(ATTRIBUTES);
final boolean isMap = att instanceof MapExpression;
if (att != null) {
if (!isMap && !att.getGamlType().isTranslatableInto(Types.LIST.of(Types.STRING))) {
desc.error("attributes must be expressed as a map<string, unknown> or as a list<string>",
IGamlIssue.WRONG_TYPE, ATTRIBUTES);
return;
}
if (isMap) {
final MapExpression map = (MapExpression) att;
if (map.getGamlType().getKeyType() != Types.STRING) {
desc.error(
"The type of the keys of the attributes map must be string. These will be used for naming the attributes in the file",
IGamlIssue.WRONG_TYPE, ATTRIBUTES);
return;
}
}
if (with.exists()) {
desc.warning(
"'with' and 'attributes' are mutually exclusive. Only the first one will be considered",
IGamlIssue.CONFLICTING_FACETS, ATTRIBUTES, WITH);
}
final IExpression type = desc.getFacetExpr(TYPE);
if (type == null || !"shp".equals(type.literalValue()) && !"json".equals(type.literalValue())) {
desc.warning("Attributes can only be defined for shape or json files", IGamlIssue.WRONG_TYPE,
ATTRIBUTES);
}
}
final IExpression data = desc.getFacetExpr(DATA);
if (data == null) return;
final IType<?> t = data.getGamlType().getContentType();
final SpeciesDescription species = t.getSpecies();
if (att == null && !with.exists()) return;
if (species == null) {
if (with.exists() || isMap) {
desc.error("Attributes of geometries can only be specified with a list of attribute names",
IGamlIssue.UNKNOWN_FACET, att == null ? WITH : ATTRIBUTES);
}
// Error deactivated for fixing #2982.
// desc.error("Attributes can only be saved for agents", IGamlIssue.UNKNOWN_FACET,
// att == null ? WITH : ATTRIBUTES);
} else {
with.forEachFacet((name, exp) -> {
if (!species.hasAttribute(name)) {
desc.error("Attribute " + name + " is not defined for the agents of " + data.serialize(false),
IGamlIssue.UNKNOWN_VAR, WITH);
return false;
}
return true;
});
}
}
}
private Arguments withFacet;
private final IExpression attributesFacet;
private final IExpression crsCode, item, file, rewriteExpr, header;
public SaveStatement(final IDescription desc) {
super(desc);
crsCode = desc.getFacetExpr("crs");
item = desc.getFacetExpr(IKeyword.DATA);
file = getFacet(IKeyword.TO);
rewriteExpr = getFacet(IKeyword.REWRITE);
header = getFacet(IKeyword.HEADER);
attributesFacet = getFacet(IKeyword.ATTRIBUTES);
}
private boolean shouldOverwrite(final IScope scope) {
if (rewriteExpr == null) return true;
return Cast.asBool(scope, rewriteExpr.value(scope));
}
// TODO rewrite this with the GamaFile framework
@SuppressWarnings ("unchecked")
@Override
public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException {
if (item == null) return null;
// First case: we have a file as item;
if (file == null) {
if (Types.FILE.isAssignableFrom(item.getGamlType())) {
final IGamaFile file = (IGamaFile) item.value(scope);
if (file != null) {
// Passes directly the facets of the statement, like crs, etc.
file.save(scope, description.getFacets());
}
return file;
} else
return null;
}
final String typeExp = getLiteral(IKeyword.TYPE);
// Second case: a filename is indicated but not the type. In that case,
// we try to build a new GamaFile from it and save it
if (file != null && typeExp == null) {
final String name = Cast.asString(scope, file.value(scope));
final Object contents = item.value(scope);
if (contents instanceof IModifiableContainer) {
final IGamaFile f = GamaFileType.createFile(scope, name, (IModifiableContainer) contents);
f.save(scope, description.getFacets());
return f;
}
}
// These statements will need to be completely rethought because of the
// possibility to now use the GamaFile infrastructure for this.
// For instance, TYPE is not needed anymore (the name of the file / its
// inner type will be enough), like in save json_file("ddd.json",
// my_map); which we can probably allow to be written save my_map to:
// json_file("ddd.json"); see #1362
try {
final String path = constructAbsoluteFilePath(scope, Cast.asString(scope, file.value(scope)), false);
if (path == null || "".equals(path)) return null;
final File fileToSave = new File(path);
createParents(fileToSave);
boolean exists = fileToSave.exists();
final String type = (typeExp != null ? typeExp : "text").trim().toLowerCase();
//
switch (type) {
case "shp":
case "json":
Object agents = item.value(scope);
if (agents instanceof ISpecies) {
agents = scope.getAgent().getPopulationFor((ISpecies) agents);
} else if (agents instanceof IShape) {
// see Issue #2857
agents = GamaListFactory.wrap(item.getGamlType(), agents);
} else if (!(agents instanceof IList)) return null;
saveShape((IList<? extends IShape>) agents, fileToSave, scope, "json".equals(type));
break;
case "text":
case "csv":
final boolean rewrite = shouldOverwrite(scope);
if (rewrite && exists) {
fileToSave.delete();
exists = false;
}
fileToSave.createNewFile();
final boolean addHeader = !exists && (header == null || Cast.asBool(scope, header.value(scope)));
saveText(type, fileToSave, addHeader, scope);
break;
case "asc":
Object v = item.value(scope);
if (v instanceof GamaField) {
saveAsc((GamaField) v, fileToSave, scope);
} else {
final ISpecies species1 = Cast.asSpecies(scope, v);
if (species1 == null || !species1.isGrid()) return null;
saveAsc(species1, fileToSave, scope);
}
break;
case "geotiff":
case "image":
v = item.value(scope);
if (v instanceof GamaField) {
saveRasterImage((GamaField) v, path, scope, "geotiff".equals(type));
} else {
final ISpecies species2 = Cast.asSpecies(scope, v);
if (species2 == null || !species2.isGrid()) return null;
saveRasterImage(species2, path, scope, "geotiff".equals(type));
}
break;
case "kml":
case "kmz":
final Object kml = item.value(scope);
if (!(kml instanceof GamaKmlExport)) return null;
if ("kml".equals(type)) {
((GamaKmlExport) kml).saveAsKml(scope, path);
} else {
((GamaKmlExport) kml).saveAsKmz(scope, path);
}
break;
default:
if (getAvailableWriters().contains(type)) {
final IGraph g = Cast.asGraph(scope, item);
if (g == null) return null;
this.saveGraph(g, fileToSave, type, scope);
} else
throw GamaRuntimeException.error("Format is not recognized ('" + type + "')", scope);
}
} catch (final GamaRuntimeException e) {
throw e;
} catch (final IOException e) {
throw GamaRuntimeException.create(e, scope);
}
return Cast.asString(scope, file.value(scope));
}
private static void createParents(final File outputFile) {
final File parent = outputFile.getParentFile();
if (!parent.exists()) { parent.mkdirs(); }
}
public void saveAsc(final GamaField field, final File f, final IScope scope) {
if (field == null || field.isEmpty(scope)) return;
if (f.exists()) { f.delete(); }
try (FileWriter fw = new FileWriter(f)) {
StringBuilder header = new StringBuilder();
final int nbCols = field.numCols;
final int nbRows = field.numRows;
header.append("ncols ").append(nbCols).append(Strings.LN);
header.append("nrows ").append(nbRows).append(Strings.LN);
savePrj(scope, f.getAbsolutePath());
final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null;
header.append("xllcorner ")
.append(nullProjection ? "0"
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinX())
.append(Strings.LN);
header.append("yllcorner ")
.append(nullProjection ? "0"
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinY())
.append(Strings.LN);
final double dx = scope.getSimulation().getEnvelope().getWidth() / nbCols;
final double dy = scope.getSimulation().getEnvelope().getHeight() / nbRows;
if (Comparison.equal(dx, dy)) {
header.append("cellsize ").append(dx).append(Strings.LN);
} else {
header.append("dx ").append(dx).append(Strings.LN);
header.append("dy ").append(dy).append(Strings.LN);
}
fw.write(header.toString());
for (int i = 0; i < nbRows; i++) {
StringBuilder val = new StringBuilder();
for (int j = 0; j < nbCols; j++) {
val.append(field.get(scope, j, i)).append(" ");
}
fw.write(val.append(Strings.LN).toString());
}
fw.close();
} catch (final IOException e) {}
}
public void saveAsc(final ISpecies species, final File f, final IScope scope) {
if (f.exists()) { f.delete(); }
try (FileWriter fw = new FileWriter(f)) {
StringBuilder header = new StringBuilder();
final GridPopulation gp = (GridPopulation) species.getPopulation(scope);
final int nbCols = gp.getNbCols();
final int nbRows = gp.getNbRows();
header.append("ncols ").append(nbCols).append(Strings.LN);
header.append("nrows ").append(nbRows).append(Strings.LN);
savePrj(scope, f.getAbsolutePath());
final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null;
header.append("xllcorner ")
.append(nullProjection ? "0"
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinX())
.append(Strings.LN);
header.append("yllcorner ")
.append(nullProjection ? "0"
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinY())
.append(Strings.LN);
final double dx = scope.getSimulation().getEnvelope().getWidth() / nbCols;
final double dy = scope.getSimulation().getEnvelope().getHeight() / nbRows;
if (Comparison.equal(dx, dy)) {
header.append("cellsize ").append(dx).append(Strings.LN);
} else {
header.append("dx ").append(dx).append(Strings.LN);
header.append("dy ").append(dy).append(Strings.LN);
}
fw.write(header.toString());
for (int i = 0; i < nbRows; i++) {
StringBuilder val = new StringBuilder();
for (int j = 0; j < nbCols; j++) {
val.append(gp.getGridValue(j, i)).append(" ");
}
fw.write(val.append(Strings.LN).toString());
}
fw.close();
} catch (final IOException e) {}
}
public void saveRasterImage(final ISpecies species, final String p, final IScope scope, final boolean toGeotiff) {
String path = p;
if (!toGeotiff && !path.contains("png")) { path += ".png"; }
final File f = new File(path);
if (f.exists()) { f.delete(); }
CoordinateReferenceSystem crs = savePrj(scope, path);
final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null;
final GridPopulation gp = (GridPopulation) species.getPopulation(scope);
final int cols = gp.getNbCols();
final int rows = gp.getNbRows();
double x = nullProjection ? 0
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinX();
double y = nullProjection ? 0
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinY();
if (!toGeotiff) {
final BufferedImage image = new BufferedImage(cols, rows, BufferedImage.TYPE_INT_RGB);
for (final Object g : gp.getAgents(scope).iterable(scope)) {
final IGridAgent ag = (IGridAgent) g;
image.setRGB(ag.getX(), rows - 1 - ag.getY(), ag.getColor().getRGB());
}
try {
ImageIO.write(image, "png", f);
final double cw = gp.getAgent(0).getGeometry().getWidth();
final double ch = gp.getAgent(0).getGeometry().getHeight();
x += cw / 2;
y += ch / 2;
try (final FileWriter fw = new FileWriter(path.replace(".png", ".pgw"));) {
fw.write(cw + "\n0.0\n0.0\n" + ch + "\n" + x + "\n" + y);
}
} catch (final IOException e) {
e.printStackTrace();
}
} else {
final float[][] imagePixelData = new float[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
imagePixelData[row][col] = gp.getGridValue(col, row).floatValue();
}
}
final double width = scope.getSimulation().getEnvelope().getWidth();
final double height = scope.getSimulation().getEnvelope().getHeight();
Envelope2D refEnvelope;
refEnvelope = new Envelope2D(crs, x, y, width, height);
// In order to fix issue #2793, it seems that (before the GAMA 1.8 release), GAMA is only able,
// to read GeoTiff files with Byte format data.
// The use of the following create from org.geotools.coverage.grid.GridCoverageFactory, will produce a
// dataset of floats.
// This is perfectly possible for the GeoTiff, but as GAMA can only read Byte format GeoTiff files, we limit
// the save to this
// specific format of data.
final GridCoverage2D coverage = new GridCoverageFactory().create("data", imagePixelData, refEnvelope);
// final GridCoverage2D coverage = createCoverageByteFromFloat("data", imagePixelData, refEnvelope);
try {
final GeoTiffFormat format = new GeoTiffFormat();
final GridCoverageWriter writer = format.getWriter(f);
writer.write(coverage, (GeneralParameterValue[]) null);
/*
* final WorldImageWriter writer = new WorldImageWriter(f); writer.write(coverage, null);
*/
} catch (final Exception e) {
e.printStackTrace();
}
}
}
CoordinateReferenceSystem savePrj(final IScope scope, final String path) {
CoordinateReferenceSystem crs = null;
final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null;
try {
crs = nullProjection ? CRS.decode("EPSG:3857")
: scope.getSimulation().getProjectionFactory().getWorld().getTargetCRS(scope);
} catch (final Exception e1) {
GAMA.reportAndThrowIfNeeded(scope, GamaRuntimeException.create(e1, scope), false);
return crs;
}
try (FileWriter fw =
new FileWriter(path.replace(".png", ".prj").replace(".tif", ".prj").replace(".asc", ".prj"))) {
fw.write(crs.toString());
fw.close();
} catch (final IOException e) {
e.printStackTrace();
}
return crs;
}
public void saveRasterImage(final GamaField field, final String p, final IScope scope, final boolean toGeotiff) {
if (field == null || field.isEmpty(scope)) return;
String path = p;
if (!toGeotiff && !path.contains("png")) { path += ".png"; }
final File f = new File(path);
if (f.exists()) { f.delete(); }
CoordinateReferenceSystem crs = savePrj(scope, path);
final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null;
final int cols = field.numCols;
final int rows = field.numRows;
double x = nullProjection ? 0
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinX();
double y = nullProjection ? 0
: scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getMinY();
if (!toGeotiff) {
final BufferedImage image = new BufferedImage(cols, rows, BufferedImage.TYPE_INT_RGB);
double[] minmaxVal = field.getMinMax(null);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
double v = field.get(scope, col, row);
int vRef = Maths.round((v - minmaxVal[0]) / (minmaxVal[1] - minmaxVal[0]) * 255);
image.setRGB(col, rows - 1 - row, new GamaColor(vRef, vRef, vRef).getRGB());
}
}
try {
ImageIO.write(image, "png", f);
final double cw =
scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getWidth()
/ cols;
final double ch =
scope.getSimulation().getProjectionFactory().getWorld().getProjectedEnvelope().getHeight()
/ rows;
x += cw / 2;
y += ch / 2;
try (final FileWriter fw = new FileWriter(path.replace(".png", ".pgw"));) {
fw.write(cw + "\n0.0\n0.0\n" + ch + "\n" + x + "\n" + y);
}
} catch (final IOException e) {
e.printStackTrace();
}
} else {
final float[][] imagePixelData = new float[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
imagePixelData[row][col] = field.get(scope, col, row).floatValue();
}
}
final double width = scope.getSimulation().getEnvelope().getWidth();
final double height = scope.getSimulation().getEnvelope().getHeight();
Envelope2D refEnvelope;
refEnvelope = new Envelope2D(crs, x, y, width, height);
// In order to fix issue #2793, it seems that (before the GAMA 1.8 release), GAMA is only able,
// to read GeoTiff files with Byte format data.
// The use of the following create from org.geotools.coverage.grid.GridCoverageFactory, will produce a
// dataset of floats.
// This is perfectly possible for the GeoTiff, but as GAMA can only read Byte format GeoTiff files, we limit
// the save to this
// specific format of data.
final GridCoverage2D coverage = new GridCoverageFactory().create("data", imagePixelData, refEnvelope);
// final GridCoverage2D coverage = createCoverageByteFromFloat("data", imagePixelData, refEnvelope);
try {
final GeoTiffFormat format = new GeoTiffFormat();
final GridCoverageWriter writer = format.getWriter(f);
writer.write(coverage, (GeneralParameterValue[]) null);
/*
* final WorldImageWriter writer = new WorldImageWriter(f); writer.write(coverage, null);
*/
} catch (final Exception e) {
e.printStackTrace();
}
}
}
// Inspired by the code of public GridCoverage2D create(final CharSequence name, final float[][] matrix, final
// Envelope envelope)
// from org.geotools.coverage.grid.GridCoverageFactory
public static GridCoverage2D createCoverageByteFromFloat(final CharSequence name, final float[][] matrix,
final Envelope envelope) {
int width = 0;
final int height = matrix.length;
for (int j = 0; j < height; j++) {
final float[] row = matrix[j];
if (row != null && row.length > width) { width = row.length; }
}
final WritableRaster raster;
raster = RasterFactory.createBandedRaster(DataBuffer.TYPE_BYTE, width, height, 1, null);
for (int j = 0; j < height; j++) {
int i = 0;
final float[] row = matrix[j];
if (row != null) {
for (; i < row.length; i++) {
raster.setSample(i, j, 0, (byte) Math.round(row[i]));
}
}
for (; i < width; i++) {
raster.setSample(i, j, 0, (byte) 255);
}
}
return new GridCoverageFactory().create(name, raster, envelope);
}
public static String getGeometryType(final List<? extends IShape> agents) {
String geomType = "";
for (final IShape be : agents) {
final IShape geom = be.getGeometry();
if (geom != null && geom.getInnerGeometry() != null) {
geomType = geom.getInnerGeometry().getClass().getSimpleName();
if (geom.getInnerGeometry().getNumGeometries() > 1) {
if (geom.getInnerGeometry().getGeometryN(0).getClass() == Point.class) {
geomType = MultiPoint.class.getSimpleName();
} else if (geom.getInnerGeometry().getGeometryN(0).getClass() == LineString.class) {
geomType = MultiLineString.class.getSimpleName();
} else if (geom.getInnerGeometry().getGeometryN(0).getClass() == Polygon.class) {
geomType = MultiPolygon.class.getSimpleName();
}
break;
}
}
}
if ("DynamicLineString".equals(geomType)) { geomType = LineString.class.getSimpleName(); }
return geomType;
}
public void saveGraph(final IGraph g, final File f, final String type, final IScope scope) {
GraphExporter exp = GraphExporters.getGraphWriter(type);
if (exp != null) { exp.exportGraph(g, f.getAbsoluteFile()); }
}
public void saveShape(final IList<? extends IShape> agents, final File f, final IScope scope, final boolean geoJson)
throws GamaRuntimeException {
final StringBuilder specs = new StringBuilder(agents.size() * 20);
final String geomType = getGeometryType(agents);
specs.append("geometry:" + geomType);
try {
final SpeciesDescription species =
agents instanceof IPopulation ? ((IPopulation) agents).getSpecies().getDescription()
: agents.getGamlType().getContentType().getSpecies();
final Map<String, IExpression> attributes = GamaMapFactory.create();
// if (species != null) {
if (withFacet != null) {
computeInitsFromWithFacet(scope, withFacet, attributes, species);
} else if (attributesFacet != null) { computeInitsFromAttributesFacet(scope, attributes, species); }
for (final String e : attributes.keySet()) {
if (e == null) { continue; }
final IExpression var = attributes.get(e);
String name = e.replace("\"", "");
name = name.replace("'", "");
name = name.replace(":", "_");
final String type = type(var);
specs.append(',').append(name).append(':').append(type);
}
// }
final IProjection proj = defineProjection(scope, f);
if (!geoJson) {
saveShapeFile(scope, f, agents, specs.toString(), attributes, proj);
} else {
saveGeoJSonFile(scope, f, agents, specs.toString(), attributes, proj);
}
} catch (final GamaRuntimeException e) {
throw e;
} catch (final Throwable e) {
throw GamaRuntimeException.create(e, scope);
}
}
public IProjection defineProjection(final IScope scope, final File f) {
String code = null;
if (crsCode != null) {
final IType type = crsCode.getGamlType();
if (type.id() == IType.INT || type.id() == IType.FLOAT) {
code = "EPSG:" + Cast.asInt(scope, crsCode.value(scope));
} else if (type.id() == IType.STRING) { code = (String) crsCode.value(scope); }
}
IProjection gis;
if (code == null) {
final boolean useNoSpecific = GamaPreferences.External.LIB_USE_DEFAULT.getValue();
if (!useNoSpecific) {
code = "EPSG:" + GamaPreferences.External.LIB_OUTPUT_CRS.getValue();
try {
gis = scope.getSimulation().getProjectionFactory().forSavingWith(scope, code);
} catch (final FactoryException e1) {
throw GamaRuntimeException.error(
"The code " + code + " does not correspond to a known EPSG code. GAMA is unable to save "
+ f.getAbsolutePath(),
scope);
}
} else {
gis = scope.getSimulation().getProjectionFactory().getWorld();
if (gis == null || gis.getInitialCRS(scope) == null) {
final boolean alreadyprojected = GamaPreferences.External.LIB_PROJECTED.getValue();
if (alreadyprojected) {
code = "EPSG:" + GamaPreferences.External.LIB_TARGET_CRS.getValue();
} else {
code = "EPSG:" + GamaPreferences.External.LIB_INITIAL_CRS.getValue();
}
try {
gis = scope.getSimulation().getProjectionFactory().forSavingWith(scope, code);
} catch (final FactoryException e1) {
throw GamaRuntimeException.error("The code " + code
+ " does not correspond to a known EPSG code. GAMA is unable to save "
+ f.getAbsolutePath(), scope);
}
}
}
} else {
if (code.startsWith("GAMA")) {
if ("GAMA".equals(code)) return null;
final String[] cs = code.split("::");
if (cs.length == 2) {
final Double val = Double.parseDouble(cs[1]);
return new SimpleScalingProjection(val);
} else
return null;
}
try {
gis = scope.getSimulation().getProjectionFactory().forSavingWith(scope, code);
} catch (final FactoryException e1) {
throw GamaRuntimeException.error("The code " + code
+ " does not correspond to a known EPSG code. GAMA is unable to save " + f.getAbsolutePath(),
scope);
}
}
return gis;
}
public void saveText(final String type, final File fileTxt, final boolean header, final IScope scope)
throws GamaRuntimeException {
try (FileWriter fw = new FileWriter(fileTxt, true)) {
if ("text".equals(type)) {
fw.write(Cast.asString(scope, item.value(scope)) + Strings.LN);
} else if ("csv".equals(type)) {
final IType itemType = item.getGamlType();
final SpeciesDescription sd;
if (itemType.isAgentType()) {
sd = itemType.getSpecies();
} else if (itemType.getContentType().isAgentType()) {
sd = itemType.getContentType().getSpecies();
} else {
sd = null;
}
final Object value = item.value(scope);
final IList values = itemType.isContainer() ? Cast.asList(scope, value)
: GamaListFactory.create(scope, itemType, value);
if (values.isEmpty()) return;
if (sd != null) {
final Collection<String> attributeNames = sd.getAttributeNames();
attributeNames.removeAll(NON_SAVEABLE_ATTRIBUTE_NAMES);
if (header) {
fw.write("cycle;name;location.x;location.y;location.z");
for (final String v : attributeNames) {
fw.write(";" + v);
}
fw.write(Strings.LN);
}
for (final Object obj : values) {
if (obj instanceof IAgent) {
final IAgent ag = Cast.asAgent(scope, obj);
fw.write(scope.getClock().getCycle() + ";" + ag.getName().replace(';', ',') + ";"
+ ag.getLocation().getX() + ";" + ag.getLocation().getY() + ";"
+ ag.getLocation().getZ());
for (final String v : attributeNames) {
String val = Cast.toGaml(ag.getDirectVarValue(scope, v)).replace(';', ',');
if (val.startsWith("'") && val.endsWith("'")
|| val.startsWith("\"") && val.endsWith("\"")) {
val = val.substring(1, val.length() - 1);
}
fw.write(";" + val);
}
fw.write(Strings.LN);
}
}
} else {
if (header) {
fw.write(item.serialize(true).replace("]", "").replace("[", ""));
fw.write(Strings.LN);
}
if (itemType.id() == IType.MATRIX) {
final String[] tmpValue = value.toString().replace("[", "").replace("]", "").split(",");
for (int i = 0; i < tmpValue.length; i++) {
if (i > 0) { fw.write(','); }
fw.write(toCleanString(tmpValue[i]));
}
} else {
final int size = values.size();
for (int i = 0; i < size; i++) {
if (i > 0) { fw.write(','); }
fw.write(toCleanString(values.get(i)));
}
}
fw.write(Strings.LN);
}
}
} catch (final GamaRuntimeException e) {
throw e;
} catch (final Throwable e) {
throw GamaRuntimeException.create(e, scope);
}
}
public String toCleanString(final Object o) {
String val = Cast.toGaml(o).replace(';', ',');
if (val.startsWith("'") && val.endsWith("'") || val.startsWith("\"") && val.endsWith("\"")) {
val = val.substring(1, val.length() - 1);
}
if (o instanceof String) {
val = val.replace("\\'", "'");
val = val.replace("\\\"", "\"");
}
return val;
}
public String type(final ITyped var) {
switch (var.getGamlType().id()) {
case IType.BOOL:
return "Boolean";
case IType.INT:
return "Integer";
case IType.FLOAT:
return "Double";
default:
return "String";
}
}
private static final Set<String> NON_SAVEABLE_ATTRIBUTE_NAMES = new HashSet<>(Arrays.asList(IKeyword.PEERS,
IKeyword.LOCATION, IKeyword.HOST, IKeyword.AGENTS, IKeyword.MEMBERS, IKeyword.SHAPE));
private void computeInitsFromWithFacet(final IScope scope, final Arguments withFacet,
final Map<String, IExpression> values, final SpeciesDescription species) throws GamaRuntimeException {
if (species == null) return;
if (withFacet.isEmpty()) {
for (final String var : species.getAttributeNames()) {
if (!NON_SAVEABLE_ATTRIBUTE_NAMES.contains(var)) { values.put(var, species.getVarExpr(var, false)); }
}
} else {
withFacet.forEachFacet((key, value) -> {
values.put(value.getExpression().literalValue(), species.getVarExpr(key, false));
return true;
});
}
}
private void computeInitsFromAttributesFacet(final IScope scope, final Map<String, IExpression> values,
final SpeciesDescription species) throws GamaRuntimeException {
if (attributesFacet instanceof MapExpression) {
final Map<IExpression, IExpression> map = ((MapExpression) attributesFacet).getElements();
map.forEach((key, value) -> {
final String name = Cast.asString(scope, key.value(scope));
values.put(name, value);
});
} else {
final List<String> names =
GamaListFactory.create(scope, Types.STRING, Cast.asList(scope, attributesFacet.value(scope)));
if (species != null) {