-
Notifications
You must be signed in to change notification settings - Fork 4
/
GamaSpatialMatrix.java
2519 lines (2229 loc) · 75.1 KB
/
GamaSpatialMatrix.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
/*******************************************************************************************************
*
* GamaSpatialMatrix.java, in msi.gama.core, 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 msi.gama.metamodel.topology.grid;
import static java.lang.Math.max;
import static java.lang.Math.min;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.stream.Stream;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.operation.distance.DistanceOp;
import org.opengis.referencing.ReferenceIdentifier;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.google.common.collect.Ordering;
import msi.gama.common.geometry.Envelope3D;
import msi.gama.common.geometry.GeometryUtils;
import msi.gama.common.interfaces.IKeyword;
import msi.gama.common.util.JavaUtils;
import msi.gama.common.util.RandomUtils;
import msi.gama.metamodel.agent.AbstractAgent;
import msi.gama.metamodel.agent.GamlAgent;
import msi.gama.metamodel.agent.IAgent;
import msi.gama.metamodel.agent.IMacroAgent;
import msi.gama.metamodel.population.GamaPopulation;
import msi.gama.metamodel.population.IPopulation;
import msi.gama.metamodel.shape.GamaPoint;
import msi.gama.metamodel.shape.GamaProxyGeometry;
import msi.gama.metamodel.shape.GamaShape;
import msi.gama.metamodel.shape.IShape;
import msi.gama.metamodel.topology.ITopology;
import msi.gama.metamodel.topology.filter.IAgentFilter;
import msi.gama.metamodel.topology.projection.IProjection;
import msi.gama.runtime.IScope;
import msi.gama.runtime.concurrent.GamaExecutorService;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.Collector;
import msi.gama.util.GamaColor;
import msi.gama.util.GamaListFactory;
import msi.gama.util.GamaMapFactory;
import msi.gama.util.ICollector;
import msi.gama.util.IContainer;
import msi.gama.util.IList;
import msi.gama.util.file.GamaGridFile;
import msi.gama.util.matrix.GamaMatrix;
import msi.gama.util.matrix.IMatrix;
import msi.gama.util.path.GamaSpatialPath;
import msi.gama.util.path.PathFactory;
import msi.gaml.expressions.IExpression;
import msi.gaml.operators.Cast;
import msi.gaml.operators.Maths;
import msi.gaml.operators.Spatial;
import msi.gaml.operators.Spatial.Projections;
import msi.gaml.skills.GridSkill.IGridAgent;
import msi.gaml.species.ISpecies;
import msi.gaml.statements.RemoteSequence;
import msi.gaml.types.GamaGeometryType;
import msi.gaml.types.GamaMatrixType;
import msi.gaml.types.IType;
import msi.gaml.types.Types;
import msi.gaml.variables.IVariable;
import one.util.streamex.StreamEx;
/**
* This matrix contains geometries and can serve to organize the agents of a population as a grid in the environment, or
* as a support for grid topologies
*/
@SuppressWarnings ({ "unchecked", "rawtypes" })
public class GamaSpatialMatrix extends GamaMatrix<IShape> implements IGrid {
/** The geometry of host. */
public final boolean useIndividualShapes;
/** The environment frame. */
public final IShape environmentFrame;
/** The use neighbors cache. */
public boolean useNeighborsCache = false;
/** The optimizer. */
public String optimizer = "A*"; // possible value: ["BF","Dijkstra", "A*"]
/** The bounds. */
final Envelope bounds;
/** The precision. */
final double precision;
/** The matrix. */
protected IShape[] matrix;
/** The cell height. */
double cellWidth, cellHeight;
/** The support image pixels. */
public int[] supportImagePixels;
/** The grid value. */
public double[] gridValue;
/** The nb bands. */
public int nbBands = 1;
/** The bands. */
public List<IList<Double>> bands = null;
/** The uses VN. */
protected Boolean usesVN = null;
/** The is torus. */
protected Boolean isTorus = null;
/** The is hexagon. */
protected Boolean isHexagon = null;
/** The is horizontal orientation. */
protected Boolean isHorizontalOrientation = null;
/** The neighborhood. */
public INeighborhood neighborhood;
/** The actual number of cells. */
int actualNumberOfCells;
/** The last cell. */
int firstCell, lastCell;
/** The cell species. */
// UnmodifiableIterator<? extends IShape> iterator = null;
private ISpecies cellSpecies;
// private IAgentFilter cellFilter;
/** The hex agent to loc. */
Map hexAgentToLoc = null;
/** The reference shape. */
final IShape referenceShape;
@Override
public void dispose() {
if (neighborhood != null) { neighborhood.clear(); }
neighborhood = null;
gridValue = null;
_clear();
matrix = null;
cellSpecies = null;
}
/**
* Instantiates a new gama spatial matrix.
*
* @param scope
* the scope
* @param environment
* the environment
* @param cols
* the cols
* @param rows
* the rows
* @param isTorus
* the is torus
* @param usesVN
* the uses VN
* @param indiv
* the indiv
* @param useNeighborsCache
* the use neighbors cache
* @param optimizer
* the optimizer
* @throws GamaRuntimeException
* the gama runtime exception
*/
public GamaSpatialMatrix(final IScope scope, final IShape environment, final Integer cols, final Integer rows,
final boolean isTorus, final boolean usesVN, final boolean indiv, final boolean useNeighborsCache,
final String optimizer) throws GamaRuntimeException {
super(cols, rows, Types.GEOMETRY);
environmentFrame = environment.getGeometry();
bounds = environmentFrame.getEnvelope();
cellWidth = bounds.getWidth() / cols;
cellHeight = bounds.getHeight() / rows;
precision = bounds.getWidth() / 1000;
final int size = numRows * numCols;
createMatrix(size);
// image = ImageUtils.createCompatibleImage(cols, rows);
supportImagePixels = new int[size];
this.isTorus = isTorus;
this.usesVN = usesVN;
actualNumberOfCells = 0;
referenceShape = GamaGeometryType.buildRectangle(cellWidth, cellHeight, new GamaPoint(0, 0));
firstCell = -1;
lastCell = -1;
this.isHexagon = false;
useIndividualShapes = indiv;
this.useNeighborsCache = useNeighborsCache;
createCells(scope, false);
this.optimizer = optimizer;
}
/**
* Instantiates a new gama spatial matrix.
*
* @param scope
* the scope
* @param gfile
* the gfile
* @param isTorus
* the is torus
* @param usesVN
* the uses VN
* @param indiv
* the indiv
* @param useNeighborsCache
* the use neighbors cache
* @param optimizer
* the optimizer
* @throws GamaRuntimeException
* the gama runtime exception
*/
public GamaSpatialMatrix(final IScope scope, final GamaGridFile gfile, final boolean isTorus, final boolean usesVN,
final boolean indiv, final boolean useNeighborsCache, final String optimizer) throws GamaRuntimeException {
super(100, 100, Types.GEOMETRY);
// DEBUG.OUT("GamaSpatialMatrix.GamaSpatialMatrix create
// new");
numRows = gfile.getRows(scope);
numCols = gfile.getCols(scope);
environmentFrame = scope.getSimulation().getGeometry();
// environmentFrame = gfile.getGeometry(scope);
bounds = environmentFrame.getEnvelope();
cellWidth = bounds.getWidth() / numCols;
cellHeight = bounds.getHeight() / numRows;
precision = bounds.getWidth() / 1000;
final int size = gfile.length(scope);
createMatrix(size);
supportImagePixels = new int[size];
referenceShape = GamaGeometryType.buildRectangle(cellWidth, cellHeight, new GamaPoint(0, 0));
this.isTorus = isTorus;
this.usesVN = usesVN;
useIndividualShapes = indiv;
this.isHexagon = false;
this.useNeighborsCache = useNeighborsCache;
this.optimizer = optimizer;
gridValue = gfile.getFieldData(scope).clone();
this.nbBands = gfile.getBandsNumber(scope);
if (nbBands > 1) {
bands = new ArrayList<>();
for (int i = 0; i < size; i++) {
IList<Double> bb = GamaListFactory.create(Types.FLOAT);
for (int b = 0; b < nbBands; b++) { bb.add(gfile.getBand(scope, b)[i]); }
bands.add(bb);
}
}
actualNumberOfCells = 0;
firstCell = -1;
lastCell = -1;
createCells(scope, false);
}
/**
* Instantiates a new gama spatial matrix.
*
* @param scope
* the scope
* @param gfiles
* the gfiles
* @param isTorus
* the is torus
* @param usesVN
* the uses VN
* @param indiv
* the indiv
* @param useNeighborsCache
* the use neighbors cache
* @param optimizer
* the optimizer
* @throws GamaRuntimeException
* the gama runtime exception
*/
public GamaSpatialMatrix(final IScope scope, final IList<GamaGridFile> gfiles, final boolean isTorus,
final boolean usesVN, final boolean indiv, final boolean useNeighborsCache, final String optimizer)
throws GamaRuntimeException {
this(scope, gfiles.firstValue(scope), isTorus, usesVN, indiv, useNeighborsCache, optimizer);
// GamaGridFile gfile = gfiles.firstValue(scope);
this.nbBands = gfiles.size();
bands = new ArrayList<>();
// See #3306 : initCRS was never used to compute the location and had an error it its computation
// String initCRS = null;
// IProjection proj = gfile.getGis(scope);
// CoordinateReferenceSystem crs = proj.getInitialCRS(scope);
// ReferenceIdentifier[] ids = crs.getIdentifiers().toArray(new ReferenceIdentifier[0]);
// if (ids.length > 0) { initCRS = ids[0].toString(); }
List<String> crsF = new ArrayList<>();
List<Envelope3D> envF = new ArrayList<>();
for (int j = 1; j < gfiles.size(); j++) {
String taCRS = null;
IProjection proj = gfiles.get(j).getGis(scope);
CoordinateReferenceSystem crs = proj.getInitialCRS(scope);
ReferenceIdentifier[] ids = crs.getIdentifiers().toArray(new ReferenceIdentifier[0]);
if (ids.length > 0) { taCRS = ids[0].toString(); }
crsF.add(taCRS);
envF.add(gfiles.get(j).computeEnvelope(scope));
}
for (int i = 0; i < matrix.length; i++) {
final IList vals = GamaListFactory.create(Types.FLOAT);
vals.add(gridValue[i]);
for (int j = 1; j < gfiles.size(); j++) {
final GamaGridFile gfile2 = gfiles.get(j);
String taCRS = crsF.get(j - 1);
GamaPoint loc = matrix[i].getLocation();
// See #3306 : initCRS was never used to compute the location
if (/* initCRS != null && */ taCRS != null) {
loc = Projections.transform_CRS(scope, loc, taCRS).getLocation();
}
final Double v = gfile2.valueOf(scope, loc);
vals.add(v);
}
bands.add(vals);
// System.out.println("vals: " + vals);
// WARNING A bit overkill as we only use the GamaGisGeometry for its
// attribute...
// matrix[i] = g;
}
actualNumberOfCells = 0;
firstCell = -1;
lastCell = -1;
createCells(scope, false);
}
/**
* Instantiates a new gama spatial matrix.
*
* @param scope
* the scope
* @param environment
* the environment
* @param cols
* the cols
* @param rows
* the rows
* @param isTorus
* the is torus
* @param usesVN
* the uses VN
* @param isHexagon
* the is hexagon
* @param horizontalOrientation
* the horizontal orientation
* @param indiv
* the indiv
* @param useNeighborsCache
* the use neighbors cache
* @param optimizer
* the optimizer
*/
// constructor used to build hexagonal grid (-> useVN = false)
public GamaSpatialMatrix(final IScope scope, final IShape environment, final Integer cols, final Integer rows,
final boolean isTorus, final boolean usesVN, final boolean isHexagon, final boolean horizontalOrientation,
final boolean indiv, final boolean useNeighborsCache, final String optimizer) {
super(cols, rows, Types.GEOMETRY);
// scope.getGui().debug("GamaSpatialMatrix.GamaSpatialMatrix create
// new");
isHorizontalOrientation = horizontalOrientation;
environmentFrame = environment.getGeometry();
bounds = environmentFrame.getEnvelope();
cellWidth = bounds.getWidth() / cols;
cellHeight = bounds.getHeight() / rows;
// TODO False
referenceShape = GamaGeometryType.buildRectangle(cellWidth, cellHeight, new GamaPoint(0, 0));
precision = bounds.getWidth() / 1000;
final int size = numRows * numCols;
createMatrix(size);
// image = ImageUtils.createCompatibleImage(cols, rows);
supportImagePixels = new int[size];
this.isTorus = isTorus;
this.usesVN = false;
this.isHexagon = isHexagon;
actualNumberOfCells = 0;
firstCell = -1;
lastCell = -1;
useIndividualShapes = indiv;
this.optimizer = optimizer;
this.useNeighborsCache = useNeighborsCache;
if (isHorizontalOrientation != null && !isHorizontalOrientation) {
createHexagonsVertical(scope, false);
} else {
createHexagonsHorizontal(scope, false);
}
}
/**
* Creates the matrix.
*
* @param size
* the size
*/
private void createMatrix(final int size) {
matrix = new IShape[size];
gridValue = new double[size];
}
/**
* Creates the hexagons horizontal.
*
* @param scope
* the scope
* @param partialCells
* the partial cells
*/
private void createHexagonsHorizontal(final IScope scope, final boolean partialCells) {
final double widthEnv = environmentFrame.getEnvelope().getWidth();
final double heightEnv = environmentFrame.getEnvelope().getHeight();
double xmin = environmentFrame.getEnvelope().getMinX();
double ymin = environmentFrame.getEnvelope().getMinY();
// final GamaShape gbg = new
// GamaShape(environmentFrame.getInnerGeometry().buffer(0.1, 2));
cellWidth = widthEnv / (numCols * 0.75 + 0.25);
cellHeight = heightEnv / (numRows + 0.5);
xmin += cellWidth / 2.0;
ymin += cellHeight / 2.0;
// numCols = (int) (width / cellWidth);
hexAgentToLoc = GamaMapFactory.create();
int i = 0;
for (int l = 0; l < numRows; l++) {
for (int c = 0; c < numCols; c = c + 2) {
i = c + numCols * l;
final GamaShape poly = (GamaShape) GamaGeometryType.buildHexagon(cellWidth, cellHeight,
new GamaPoint(xmin + c * cellWidth * 0.75, ymin + l * cellHeight));
// if (gbg.covers(poly)) {
if (firstCell == -1) { firstCell = i; }
matrix[i] = poly;
hexAgentToLoc.put(poly, new GamaPoint(c, l));
actualNumberOfCells++;
lastCell = Math.max(lastCell, i);
// }
}
}
for (int l = 0; l < numRows; l++) {
for (int c = 1; c < numCols; c = c + 2) {
i = c + numCols * l;
final GamaShape poly = (GamaShape) GamaGeometryType.buildHexagon(cellWidth, cellHeight,
new GamaPoint(xmin + c * cellWidth * 0.75, ymin + (l + 0.5) * cellHeight));
// if (gbg.covers(poly)) {
if (firstCell == -1) { firstCell = i; }
matrix[i] = poly;
hexAgentToLoc.put(poly, new GamaPoint(c, l));
actualNumberOfCells++;
lastCell = Math.max(lastCell, i);
// }
}
}
}
/**
* Creates the hexagons vertical.
*
* @param scope
* the scope
* @param partialCells
* the partial cells
*/
private void createHexagonsVertical(final IScope scope, final boolean partialCells) {
final double widthEnv = environmentFrame.getEnvelope().getWidth();
final double heightEnv = environmentFrame.getEnvelope().getHeight();
double xmin = environmentFrame.getEnvelope().getMinX();
double ymin = environmentFrame.getEnvelope().getMinY();
// final GamaShape gbg = new
// GamaShape(environmentFrame.getInnerGeometry().buffer(0.1, 2));
cellWidth = widthEnv / (numCols + 0.5);
cellHeight = heightEnv / (numRows * 0.75 + 0.25);
xmin += cellWidth / 2.0;
ymin += cellHeight / 2.0;
// numCols = (int) (width / cellWidth);
hexAgentToLoc = GamaMapFactory.create();
int i = 0;
for (int l = 0; l < numRows; l = l + 2) {
for (int c = 0; c < numCols; c++) {
i = c + numCols * l;
final IShape poly = Spatial.Transformations.rotated_by(scope, GamaGeometryType.buildHexagon(cellHeight,
cellWidth, new GamaPoint(xmin + c * cellWidth, ymin + l * cellHeight * 0.75)), 90.0);
// if (gbg.covers(poly)) {
if (firstCell == -1) { firstCell = i; }
matrix[i] = poly;
hexAgentToLoc.put(poly, new GamaPoint(c, l));
actualNumberOfCells++;
lastCell = Math.max(lastCell, i);
// }
}
}
for (int l = 1; l < numRows; l = l + 2) {
for (int c = 0; c < numCols; c++) {
i = c + numCols * l;
final IShape poly = Spatial.Transformations.rotated_by(scope, GamaGeometryType.buildHexagon(cellHeight,
cellWidth, new GamaPoint(xmin * 2 + c * cellWidth, ymin + l * cellHeight * 0.75)), 90.0);
// if (gbg.covers(poly)) {
if (firstCell == -1) { firstCell = i; }
matrix[i] = poly;
hexAgentToLoc.put(poly, new GamaPoint(c, l));
actualNumberOfCells++;
lastCell = Math.max(lastCell, i);
// }
}
}
}
/**
* Creates the cells.
*
* @param scope
* the scope
* @param partialCells
* the partial cells
* @throws GamaRuntimeException
* the gama runtime exception
*/
private void createCells(final IScope scope, final boolean partialCells) throws GamaRuntimeException {
final boolean isRectangle = environmentFrame.getInnerGeometry().isRectangle();
final GamaPoint origin =
new GamaPoint(environmentFrame.getEnvelope().getMinX(), environmentFrame.getEnvelope().getMinY());
final IShape translatedReferenceFrame = Spatial.Transformations.translated_by(scope, environmentFrame, origin);
final GamaPoint[][] xs = new GamaPoint[numCols + 1][numRows + 1];
for (int i = 0; i < numCols + 1; i++) {
for (int j = 0; j < numRows + 1; j++) {
final GamaPoint p = new GamaPoint(i * cellWidth, j * cellHeight);
xs[i][j] = p;
}
}
for (int i = 0, n = numRows * numCols; i < n; i++) {
final int yy = i / numCols;
final int xx = i - yy * numCols;
// WARNING HACK
IShape rect = null;
if (useIndividualShapes) {
// Change in the function used in building cells in order to minimize computations and mutualize points.
// See #2896
rect = new GamaShape(GeometryUtils.GEOMETRY_FACTORY.buildRectangle(new GamaPoint[] { xs[xx][yy],
xs[xx + 1][yy], xs[xx + 1][yy + 1], xs[xx][yy + 1], xs[xx][yy] }));
} else {
final double cmx = cellWidth / 2;
final double cmy = cellHeight / 2;
rect = new CellProxyGeometry(new GamaPoint(xx * cellWidth + cmx, yy * cellHeight + cmy));
}
boolean ok = isRectangle || translatedReferenceFrame.covers(rect);
if (partialCells && !ok && rect.intersects(translatedReferenceFrame)) {
rect.setGeometry(Spatial.Operators.inter(scope, rect, translatedReferenceFrame));
ok = true;
}
if (ok) {
if (firstCell == -1) { firstCell = i; }
matrix[i] = rect;
actualNumberOfCells++;
lastCell = i;
}
}
}
@Override
public INeighborhood getNeighborhood() {
if (neighborhood == null) {
if (useNeighborsCache) {
neighborhood = isHexagon ? isHorizontalOrientation != null && !isHorizontalOrientation
? new GridHexagonalNeighborhoodVertical(this) : new GridHexagonalNeighborhoodHorizontal(this)
: usesVN ? new GridVonNeumannNeighborhood(this) : new GridMooreNeighborhood(this);
} else {
neighborhood = new NoCacheNeighborhood(this);
}
}
return neighborhood;
}
@Override
public int[] getDisplayData() { return supportImagePixels; }
@Override
public double[] getGridValue() { return gridValue; }
@Override
public double[] getGridValueOf(final IScope scope, final IExpression exp) {
final double[] result = new double[matrix.length];
for (int i = 0; i < matrix.length; i++) {
final IShape s = matrix[i];
if (s != null) {
final IAgent a = s.getAgent();
if (a != null) { result[i] = Cast.asFloat(scope, scope.evaluate(exp, a).getValue()); }
}
}
return result;
}
/**
* Gets the grid value.
*
* @param col
* the col
* @param row
* the row
* @return the grid value
*/
public double getGridValue(final int col, final int row) {
final int index = getPlaceIndexAt(col, row);
if (index != -1) return gridValue[index];
return 0.0;
}
/**
* Gets the place index at.
*
* @param xx
* the xx
* @param yy
* the yy
* @return the place index at
*/
final int getPlaceIndexAt(final int xx, final int yy) {
if (isHexagon) return yy * numCols + xx;
if (isTorus) return (yy < 0 ? yy + numCols : yy) % numRows * numCols + (xx < 0 ? xx + numCols : xx) % numCols;
if (xx < 0 || xx >= numCols || yy < 0 || yy >= numRows) return -1;
return yy * numCols + xx;
}
/**
* Gets the place index at.
*
* @param p
* the p
* @return the place index at
*/
private final int getPlaceIndexAt(final GamaPoint p) {
if (isHexagon) {
int xx = 0;
int yy = 0;
if (isHorizontalOrientation) {
xx = (int) (p.getX() / (cellWidth * 0.75));
yy = xx % 2 == 0 ? (int) (p.getY() / cellHeight) : (int) ((p.getY() - cellHeight) / cellHeight);
} else {
yy = (int) (p.getY() / (cellHeight * 0.75));
xx = yy % 2 == 0 ? (int) (p.getX() / cellWidth) : (int) ((p.getX() - cellWidth) / cellWidth);
}
xx = Math.min(xx, this.numCols - 1);
yy = Math.min(yy, this.numRows - 1);
final int i = getPlaceIndexAt(xx, yy);
if (matrix[i] == null) return -1;
if (matrix[i].getLocation() == p || matrix[i].intersects(p)) return i;
final Set<Integer> toObserve =
((GridHexagonalNeighborhood) getNeighborhood()).getNeighborsAtRadius1(i, numCols, numRows, isTorus);
toObserve.add(i);
int x = 0, y = 0;
final Iterator<Integer> it = toObserve.iterator();
while (it.hasNext()) {
final int id = it.next();
final IShape sh = matrix[id];
if (sh.intersects(p)) {
final GamaPoint pt = (GamaPoint) hexAgentToLoc.get(sh.getGeometry());
x = (int) pt.x;
y = (int) pt.y;
return getPlaceIndexAt(x, y);
}
}
return -1;
}
final double px = p.getX();
final double py = p.getY();
final double xx = px == bounds.getMaxX() ? (px - precision) / cellWidth : px / cellWidth;
final double yy = py == bounds.getMaxY() ? (py - precision) / cellHeight : py / cellHeight;
final int x = (int) xx;
final int y = (int) yy;
return getPlaceIndexAt(x, y);
}
@Override
public final int getX(final IShape shape) {
return (int) ((GamaPoint) hexAgentToLoc.get(shape)).x;
}
@Override
public final int getY(final IShape shape) {
return (int) ((GamaPoint) hexAgentToLoc.get(shape)).y;
}
@Override
public IShape getPlaceAt(final GamaPoint c) {
if (c == null) return null;
final int p = getPlaceIndexAt(c);
if (p == -1) return null;
return matrix[p];
}
@Override
public void shuffleWith(final RandomUtils randomAgent) {
// TODO not allowed for the moment (fixed grid)
//
}
@Override
public IShape get(final IScope scope, final int col, final int row) {
final int index = getPlaceIndexAt(col, row);
if (index != -1) return matrix[index];
return null;
}
@Override
public void set(final IScope scope, final int col, final int row, final Object obj) throws GamaRuntimeException {
// TODO not allowed for the moment (fixed grid)
}
@Override
public IShape remove(final IScope scope, final int col, final int row) {
// TODO not allowed for the moment (fixed grid)
return null;
}
@Override
public boolean _removeFirst(final IScope scope, final IShape o) throws GamaRuntimeException {
// TODO not allowed for the moment (fixed grid)
return false;
}
@Override
public boolean _removeAll(final IScope scope, final IContainer<?, IShape> value) throws GamaRuntimeException {
// TODO not allowed for the moment (fixed grid)
return false;
}
@Override
public void _clear() {
Arrays.fill(matrix, null);
matrix = null;
}
@Override
protected IList _listValue(final IScope scope, final IType contentType, final boolean cast) {
if (actualNumberOfCells == 0) return GamaListFactory.EMPTY_LIST;
if (cellSpecies == null) return cast ? GamaListFactory.create(scope, contentType, matrix)
: GamaListFactory.wrap(contentType, matrix);
final IList result = GamaListFactory.create(contentType, actualNumberOfCells);
for (final IShape a : matrix) {
if (a != null) {
final IAgent ag = a.getAgent();
final Object toAdd = ag == null ? a : ag;
result.add(cast ? contentType.cast(scope, toAdd, null, false) : toAdd);
}
}
return result;
}
@Override
public java.lang.Iterable<IShape> iterable(final IScope scope) {
return Arrays.asList(matrix);
}
@Override
protected IMatrix _matrixValue(final IScope scope, final GamaPoint preferredSize, final IType type,
final boolean copy) {
// WARNING: copy is not taken into account here
return GamaMatrixType.from(scope, this, type, preferredSize, copy);
}
@Override
public Integer _length(final IScope scope) {
return actualNumberOfCells;
}
@Override
public IShape _first(final IScope scope) {
if (firstCell == -1) return null;
return matrix[firstCell];
}
@Override
public IShape _last(final IScope scope) {
if (lastCell == -1) return null;
return matrix[lastCell];
}
@Override
public IMatrix _reverse(final IScope scope) throws GamaRuntimeException {
// TODO Auto-generated method stub
return null;
}
@Override
public IMatrix copy(final IScope scope, final GamaPoint size, final boolean copy) throws GamaRuntimeException {
if (size == null && !copy) return this;
return new GamaSpatialMatrix(scope, environmentFrame, numCols, numRows, isTorus, usesVN, useIndividualShapes,
useNeighborsCache, optimizer);
}
@Override
public boolean _contains(final IScope scope, final Object o) {
if (cellSpecies != null) return cellSpecies.contains(scope, o);
return false;
}
@Override
public void _putAll(final IScope scope, final Object value) throws GamaRuntimeException {
// TODO Not allowed for the moment
}
@Override
public boolean _isEmpty(final IScope scope) {
return actualNumberOfCells == 0;
}
/**
* Method usesIndiviualShapes()
*
* @see msi.gama.metamodel.topology.grid.IGrid#usesIndiviualShapes()
*/
@Override
public boolean usesIndiviualShapes() {
return useIndividualShapes;
}
@Override
public int manhattanDistanceBetween(final IShape g1, final IShape g2) {
IGridAgent s1 = g1.getAgent() != null && g1.getAgent().getSpecies() == this.getCellSpecies()
? (IGridAgent) g1.getAgent() : null;
IGridAgent s2 = g2.getAgent() != null && g2.getAgent().getSpecies() == this.getCellSpecies()
? (IGridAgent) g2.getAgent() : null;
if (s1 == null || s2 == null) {
GamaPoint p1 = g1.isPoint() ? g1.getLocation() : null;
GamaPoint p2 = g2.isPoint() ? g2.getLocation() : null;
if (s1 == null) {
s1 = (IGridAgent) this.getPlaceAt(g1.getLocation());
if (!s1.covers(g1)) { s1 = null; }
}
if (s2 == null) {
s2 = (IGridAgent) this.getPlaceAt(g2.getLocation());
if (!s2.covers(g2)) { s2 = null; }
}
final Coordinate[] coord = new DistanceOp(g1.getInnerGeometry(), g2.getInnerGeometry()).nearestPoints();
if (s1 == null) {
p1 = new GamaPoint(coord[0]);
s1 = (IGridAgent) this.getPlaceAt(p1);
}
if (s2 == null) {
p2 = new GamaPoint(coord[1]);
s2 = (IGridAgent) this.getPlaceAt(p2);
}
}
final int dx = Math.abs(s1.getX() - s2.getX());
final int dy = Math.abs(s1.getY() - s2.getY());
if (usesVN) return dx + dy;
return Math.max(dx, dy);
}
/**
* Returns the cells making up the neighborhood of a geometrical shape. First, the cells covered by this shape are
* computed, then their neighbors are collated (excluding the previous ones). A special case is made for point
* geometries and for agents contained in this matrix.
*
* @param source
* @param distance
* @return
*/
@Override
public Set<IAgent> getNeighborsOf(final IScope scope, final IShape shape, final Double distance,
final IAgentFilter filter) {
// If the shape is a point or if it is a cell of this matrix, we run the
// method with an GamaPoint instead
if (shape.isPoint() || shape.getAgent() != null && shape.getAgent().getSpecies() == cellSpecies)
return getNeighborsOf(scope, shape.getLocation(), distance, filter);
// We compute all the cells covered by the shape (we know that it is not
// a cell of the matrix) -- no filter used
// here, as we must take all the cells into account
final Set<IAgent> coveredPlaces = allInEnvelope(scope, shape, shape.getEnvelope(), null, true);
// final Set<IAgent> placesToRemove = Sets.newHashSet(coveredPlaces);
// We now compute all the cells that are at "distance" away from these
// covered cells
final Set<IAgent> allPlaces = new LinkedHashSet();
for (final IAgent ag : coveredPlaces) {
allPlaces.addAll(
getNeighborhood().getNeighborsIn(scope, getPlaceIndexAt(ag.getLocation()), distance.intValue()));
}
// And we filter these cells by removing those that are in the "interior
// cells" (which are not part of the
// neighborood) and that are not accepted by the IAgentFilter. A
// special case is made if the filter is only
// accepting cells of this matrix : in that case, we simply remove the
// "interior cells" from the iterator and
// we return it;
allPlaces.removeAll(coveredPlaces);
if (filter != null && filter.getSpecies() != cellSpecies) { filter.filter(scope, shape, allPlaces); }
return allPlaces;
}
/**
* Gets the neighbors of.
*
* @param scope
* the scope
* @param shape
* the shape
* @param distance
* the distance
* @param filter
* the filter
* @return the neighbors of
*/
protected Set<IAgent> getNeighborsOf(final IScope scope, final GamaPoint shape, final Double distance,
final IAgentFilter filter) {
final Set<IAgent> allPlaces =
getNeighborhood().getNeighborsIn(scope, getPlaceIndexAt(shape), distance.intValue());
if (filter != null) {
if (filter.getSpecies() == cellSpecies) return allPlaces;
filter.filter(scope, shape, allPlaces);
}
return allPlaces;
}
/**
* Test place.
*
* @param scope
* the scope
* @param source
* the source
* @param filter
* the filter
* @param toTest
* the to test
* @return the i agent
*/
static IAgent testPlace(final IScope scope, final IShape source, final IAgentFilter filter, final IShape toTest) {
if (filter.accept(scope, source, toTest)) return toTest.getAgent();
ITopology.SpatialRelation rel = filter.getSpecies() != null && toTest.getAgent() != null
&& filter.getSpecies().equals(toTest.getAgent().getSpecies()) ? ITopology.SpatialRelation.INSIDE
: ITopology.SpatialRelation.OVERLAP;
final List<IAgent> agents = new ArrayList<>(scope.getTopology().getAgentsIn(scope, toTest, filter, rel));
agents.remove(source);
if (agents.isEmpty()) return null;
scope.getRandom().shuffleInPlace(agents);
return agents.get(0);
}
/**
* Gets the agent closest to.
*
* @param scope
* the scope
* @param source
* the source