-
Notifications
You must be signed in to change notification settings - Fork 134
/
Shapefile_Geoprocessing.cpp
3940 lines (3405 loc) · 136 KB
/
Shapefile_Geoprocessing.cpp
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
//********************************************************************************************************
//File name: Shapefile_Geoprocessing.cpp
//Description: Implementation of the CShapefile (see other cpp files as well)
//********************************************************************************************************
//The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
//you may not use this file except in compliance with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/
//Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
//ANY KIND, either express or implied. See the License for the specific language governing rights and
//limitations under the License.
//
//The Original Code is MapWindow Open Source.
//
//The Initial Developer of this version of the Original Code is Daniel P. Ames using portions created by
//Utah State University and the Idaho National Engineering and Environmental Lab that were released as
//public domain in March 2004.
//
//Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// lsu 3-02-2011: split the initial Shapefile.cpp file to make entities of the reasonable size
#include "StdAfx.h"
#include "Shapefile.h"
#include "OgrConverter.h"
#include "Templates.h"
#include "Extents.h"
#include "clipper.h"
#include <GeosHelper.h>
#include "FieldStatOperations.h"
#include "Shape.h"
#include "ColoringGraph.h"
#include "GeometryHelper.h"
#ifdef SERIALIZE_POLYGONS
#include <fstream>
#include <iostream>
using namespace std;
#endif
#include "GeosConverter.h"
#include "ShapefileHelper.h"
#include "FieldHelper.h"
#include "ShapeHelper.h"
#include "GeoProcessing.h"
// ReSharper disable CppUseAuto
#pragma region Utilities
// ********************************************************************
// CloneField()
// ********************************************************************
int CloneField(IShapefile* source, IShapefile* target, int fieldIndex, long newFieldIndex)
{
IField* fld = nullptr;
source->get_Field(fieldIndex, &fld);
if (fld)
{
IField* newField = nullptr;
fld->Clone(&newField);
fld->Release();
VARIANT_BOOL vb;
if (newFieldIndex == -1)
{
long numShapes;
target->get_NumShapes(&numShapes);
newFieldIndex = numShapes;
}
target->EditInsertField(newField, &newFieldIndex, nullptr, &vb);
newField->Release();
}
return newFieldIndex;
}
// ******************************************************************
// InsertShapesVector()
// ******************************************************************
// Inserts shapes, resulting from intersection of one shape of subject shapefile,
// and one shape of clip shapefile, attributes a copied from both shapefiles
void CShapefile::InsertShapesVector(IShapefile* sf, vector<IShape*>& vShapes,
IShapefile* sfSubject, long subjectId, std::map<long, long>* fieldMapSubject,
IShapefile* sfClip, long clipId, std::map<long, long>* fieldMapClip)
{
long numFieldSubject, numFieldsClip;
sfSubject->get_NumFields(&numFieldSubject);
if (sfClip)
sfClip->get_NumFields(&numFieldsClip);
VARIANT_BOOL vbretval;
ShpfileType fileType;
sf->get_ShapefileType(&fileType);
CComVariant var;
VARIANT_BOOL isGeographic = VARIANT_FALSE;
sf->get_IsGeographicProjection(&isGeographic);
for (vector<IShape*>::value_type shp : vShapes)
{
ShpfileType shpType;
shp->get_ShapeType(&shpType);
if (shpType == fileType)
{
// area checking
shpType = ShapeUtility::Convert2D(shpType);
if (shpType == SHP_POLYGON)
{
double area;
shp->get_Area(&area);
if (area < m_globalSettings.GetMinPolygonArea(isGeographic))
{
shp->Release();
continue;
}
double perimeter;
shp->get_Perimeter(&perimeter);
if (isGeographic)
area *= METERS_PER_DEGREE;
// comparison is performed in meters, area will grow as square of linear size
// we multilpy area only; in reality:((area * c^2)/ (perimeter * c))
if (area / perimeter < m_globalSettings.minAreaToPerimeterRatio)
{
shp->Release();
continue;
}
}
long newId;
sf->get_NumShapes(&newId);
sf->EditInsertShape(shp, &newId, &vbretval);
// passing the values from subject shapefile
// can be optimized for not extracting the same values many times
if (fieldMapSubject)
{
std::map<long, long>::iterator p = fieldMapSubject->begin();
while (p != fieldMapSubject->end())
{
sfSubject->get_CellValue(p->first, subjectId, &var);
sf->EditCellValue(p->second, newId, var, &vbretval);
++p;
}
}
else
{
for (int iFld = 0; iFld < numFieldSubject; iFld++)
{
sfSubject->get_CellValue(iFld, subjectId, &var);
sf->EditCellValue(iFld, newId, var, &vbretval);
}
}
// passing the values from clip shapefile
if (sfClip && fieldMapClip)
{
std::map<long, long>::iterator p = fieldMapClip->begin();
while (p != fieldMapClip->end())
{
sfClip->get_CellValue(p->first, clipId, &var);
sf->EditCellValue(p->second, newId, var, &vbretval);
++p;
}
}
}
shp->Release();
}
}
// **********************************************************************
// InsertGeosGeometry()
// **********************************************************************
// A utility function to add geometry produced by simplification routine to the sfTarget shapefile,
// with copying of attributes from source shapefile.
// initShapeIndex - the index of shape to copy the attribute from
bool InsertGeosGeometry(IShapefile* sfTarget, GEOSGeometry* gsNew, IShapefile* sfSouce, int initShapeIndex)
{
if (gsNew)
{
ShpfileType shpType;
sfTarget->get_ShapefileType(&shpType);
const bool isM = ShapeUtility::IsM(shpType);
std::vector<IShape*> shapes;
if (GeosConverter::GeomToShapes(gsNew, &shapes, isM))
{
long index, numFields;
VARIANT_BOOL vbretval;
sfTarget->get_NumFields(&numFields);
for (auto& shape : shapes)
{
sfTarget->get_NumShapes(&index);
sfTarget->EditInsertShape(shape, &index, &vbretval);
if (vbretval)
{
CComVariant val;
for (int f = 0; f < numFields; f++)
{
sfSouce->get_CellValue(f, initShapeIndex, &val);
sfTarget->EditCellValue(f, index, val, &vbretval);
}
}
shape->Release();
}
return true;
}
}
return false;
}
// ********************************************************************
// CopyShape()
// ********************************************************************
// For the sort function
// The row index of attribute table are taken from the key property of the shape
void CopyShape(IShapefile* sfSource, IShape* shp, IShapefile* sfResult)
{
if (shp)
{
USES_CONVERSION;
CComBSTR key;
shp->get_Key(&key);
const CString str = OLE2CA(key);
const int initIndex = atoi(str);
VARIANT_BOOL isEditingShapes, vbretval;
sfSource->get_EditingShapes(&isEditingShapes);
LONG numShapes;
sfResult->get_NumShapes(&numShapes);
if (isEditingShapes)
{
// in the editing mode we share a shape with the parent shapefile
// a copy is needed to avoid conflicts
IShape* shpCopy = nullptr;
shp->Clone(&shpCopy);
sfResult->EditInsertShape(shpCopy, &numShapes, &vbretval);
shpCopy->Release();
}
else
{
sfResult->EditInsertShape(shp, &numShapes, &vbretval);
}
if (vbretval)
{
LONG numFields;
sfSource->get_NumFields(&numFields);
// copy attributes
CComVariant val;
for (int iFld = 0; iFld < numFields; iFld++)
{
sfSource->get_CellValue(iFld, initIndex, &val);
sfResult->EditCellValue(iFld, numShapes, val, &vbretval);
}
}
shp->Release();
}
}
#pragma endregion
#pragma region SelectByShapefile
// ******************************************************************
// SelectByShapefile()
// ******************************************************************
// Returns numbers(ids) of shapes of this shapefile which are situated
// in certain spatial relation to the shapes of the input shapefile.
STDMETHODIMP CShapefile::SelectByShapefile(IShapefile* sf, tkSpatialRelation relation,
VARIANT_BOOL selectedOnly, VARIANT* arr, ICallback* cBack,
VARIANT_BOOL* retval)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
USES_CONVERSION;
*retval = VARIANT_FALSE;
if (_globalCallback == nullptr && cBack != nullptr)
{
_globalCallback = cBack;
_globalCallback->AddRef();
}
if (sf == nullptr)
{
ErrorMessage(tkUNEXPECTED_NULL_PARAMETER);
return S_OK;
}
long _numShapes2;
const long _numShapes1 = _shapeData.size();
sf->get_NumShapes(&_numShapes2);
if (_numShapes1 == 0)return NULL;
if (_numShapes2 == 0) return NULL;
QTree* qTree = this->GenerateQTreeCore(false);
if (!qTree)
{
ErrorMessage(tkFAILED_TO_BUILD_SPATIAL_INDEX);
return NULL;
}
// ids of selected shapes
set<long> result;
// to avoid converting same shapes to ogr geometry multiple times
vector<OGRGeometry *> vGeometries;
vGeometries.assign(_numShapes1, nullptr);
vector<ShapeRecord*>* data = ((CShapefile*)sf)->get_ShapeVector();
long percent = 0;
for (long shapeid2 = 0; shapeid2 < _numShapes2; shapeid2++)
{
CallbackHelper::Progress(_globalCallback, shapeid2, _numShapes2, "Calculating...", _key, percent);
if (selectedOnly && !(*data)[shapeid2]->selected())
continue;
double xMin, xMax, yMin, yMax;
((CShapefile*)sf)->QuickExtentsCore(shapeid2, &xMin, &yMin, &xMax, &yMax);
vector<int> shapeIds = qTree->GetNodes(QTreeExtent(xMin, xMax, yMax, yMin));
if (!shapeIds.empty())
{
IShape* shp2 = nullptr;
sf->get_Shape(shapeid2, &shp2);
OGRGeometry* oGeom2 = OgrConverter::ShapeToGeometry(shp2);
shp2->Release();
if (oGeom2 != nullptr)
{
for (long shapeId1 : shapeIds)
{
// shape wasn't selected so far
if (result.find(shapeId1) == result.end())
{
OGRGeometry* oGeom1;
if (vGeometries[shapeId1] == nullptr)
{
IShape* shp1 = nullptr;
this->get_Shape(shapeId1, &shp1);
oGeom1 = OgrConverter::ShapeToGeometry(shp1);
shp1->Release();
vGeometries[shapeId1] = oGeom1;
}
else
{
oGeom1 = vGeometries[shapeId1];
}
OGRBoolean res = 0;
if (relation == srContains) res = oGeom1->Contains(oGeom2);
else if (relation == srCrosses) res = oGeom1->Crosses(oGeom2);
else if (relation == srEquals) res = oGeom1->Equals(oGeom2);
else if (relation == srIntersects) res = oGeom1->Intersects(oGeom2);
else if (relation == srDisjoint) res = oGeom1->Intersects(oGeom2);
else if (relation == srOverlaps) res = oGeom1->Overlaps(oGeom2);
else if (relation == srTouches) res = oGeom1->Touches(oGeom2);
else if (relation == srWithin) res = oGeom1->Within(oGeom2);
if (res)
{
result.insert(shapeId1);
}
}
}
OGRGeometryFactory::destroyGeometry(oGeom2);
}
}
}
// disjoint is opposite to intersects; so to get it we need to find shapes that do intersect with input
// and then invert the selection
if (relation == srDisjoint)
{
vector<long> v;
set<long>::iterator p = result.begin();
for (int i = 0; i < _numShapes1; i++)
{
bool include = true;
while (p != result.end())
{
if (*p == i)
include = false; // this shape actually intersects, so it can't be disjointed
if (*p > i)
break;
++p;
}
if (include)
{
v.push_back(i);
}
}
*retval = Templates::Vector2SafeArray(&v, VT_I4, arr) ? VARIANT_TRUE : VARIANT_FALSE;
}
else
{
*retval = Templates::Set2SafeArray(&result, VT_I4, arr) ? VARIANT_TRUE : VARIANT_FALSE;
}
// cleaning
CallbackHelper::ProgressCompleted(_globalCallback, _key);
for (auto& vGeometrie : vGeometries)
{
if (vGeometrie != nullptr)
OGRGeometryFactory::destroyGeometry(vGeometrie);
}
delete qTree;
return S_OK;
}
// ***********************************************************
// SelectShapesAlt()
// ***********************************************************
// Alternative function for selection of shapes which fall in the given
// rectangular. Uses quad tree on permanent basis. May become
// a substitute for SelectShapes function after some improvements.
// returns VARIANT_TRUE when shapes were selected, and VARIANT_FALSE if
// no shapes fell into selection
VARIANT_BOOL CShapefile::SelectShapesAlt(IExtents* boundBox, double tolerance, SelectMode selectMode, VARIANT* arr)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
double xMin, xMax, yMin, yMax, zMin, zMax;
boundBox->GetBounds(&xMin, &yMin, &zMin, &xMax, &yMax, &zMax);
if (xMin == xMax && yMin == yMax)
{
xMax += 1;
yMax += 1;
}
QTree* qTree = this->GenerateQTreeCore(false);
if (!qTree)
{
ErrorMessage(tkFAILED_TO_BUILD_SPATIAL_INDEX);
return NULL;
}
if (tolerance > 0.0)
{
xMin = xMin - tolerance / 2;
yMin = yMin - tolerance / 2;
xMax = xMax + tolerance / 2;
yMax = yMax + tolerance / 2;
}
boundBox->SetBounds(xMin, yMin, zMin, xMax, yMax, zMax);
set<long> results;
vector<int> shapeIds = qTree->GetNodes(QTreeExtent(xMin, xMax, yMax, yMin));
IShape* temp = nullptr;
((CExtents*)boundBox)->ToShape(&temp);
OGRGeometry* oBox = OgrConverter::ShapeToGeometry(temp);
temp->Release();
for (int shapeId : shapeIds)
{
IShape* shp = nullptr;
this->get_Shape((long)shapeId, &shp);
OGRGeometry* oGeom = OgrConverter::ShapeToGeometry(shp);
shp->Release();
OGRBoolean res = oBox->Contains(oGeom);
if (!res)
res = oGeom->Contains(oBox);
if (selectMode == INTERSECTION && !res)
res = oGeom->Intersects(oBox);
if (res) results.insert(shapeId);
OGRGeometryFactory::destroyGeometry(oGeom);
}
delete qTree;
if (oBox != nullptr) OGRGeometryFactory::destroyGeometry(oBox);
const VARIANT_BOOL retval = Templates::Set2SafeArray(&results, VT_I4, arr);
return retval;
}
#pragma endregion
#pragma region Dissolve
// *************************************************************
// Dissolve()
// *************************************************************
// Merges shapes of the shapefile based on the attribute of the given
// field. Shapes with the same attribute are merged into one.
STDMETHODIMP CShapefile::Dissolve(long fieldIndex, VARIANT_BOOL selectedOnly, IShapefile** sf)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
DissolveCore(fieldIndex, selectedOnly, nullptr, sf);
return S_OK;
}
// *************************************************************
// DissolveWithStats()
// *************************************************************
STDMETHODIMP CShapefile::DissolveWithStats(long fieldIndex, VARIANT_BOOL selectedOnly,
IFieldStatOperations* statOperations, IShapefile** sf)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
DissolveCore(fieldIndex, selectedOnly, statOperations, sf);
return S_OK;
}
// *************************************************************
// Dissolve()
// *************************************************************
// Merges shapes of the shapefile based on the attribute of the given
// field. Shapes with the same attribute are merged into one.
void CShapefile::DissolveCore(long fieldIndex, VARIANT_BOOL selectedOnly, IFieldStatOperations* operations,
IShapefile** sf)
{
// ----------------------------------------------
// Validation
// ----------------------------------------------
long numFields;
this->get_NumFields(&numFields);
if (fieldIndex < 0 || fieldIndex >= numFields)
{
ErrorMessage(tkINDEX_OUT_OF_BOUNDS);
return;
}
if (!ValidateInput(this, "Dissolve", "this", selectedOnly))
return;
// ----------------------------------------------
// Creating output
// ----------------------------------------------
ShpfileType type = _shpfiletype;
// for points change to multi-point type, as there is no other way to group them
if (type == SHP_POINT) type = SHP_MULTIPOINT;
if (type == SHP_POINTZ) type = SHP_MULTIPOINTZ;
if (type == SHP_POINTM) type = SHP_MULTIPOINTM;
// ShapefileHelper::CloneNoFields(this, sf, type);
// -----------------------------------------------
// Creating output
// -----------------------------------------------
if (!ShapefileHelper::CloneNoFields(this, sf, type))
{
// Get errorcode and pass the source:
long errorCode;
(*sf)->get_LastErrorCode(&errorCode);
*sf = nullptr;
ErrorMessage(errorCode);
return;
}
CloneField(this, *sf, fieldIndex, -1);
// -------------------------------------------
// processing
// -------------------------------------------
if (_geometryEngine == engineGeos)
{
this->DissolveGEOS(fieldIndex, selectedOnly, operations, *sf);
}
else
{
this->DissolveClipper(fieldIndex, selectedOnly, operations, *sf);
}
// -------------------------------------------
// output validation
// -------------------------------------------
CallbackHelper::ProgressCompleted(_globalCallback, _key);
ValidateOutput(sf, "Dissolve");
return;
}
// *************************************************************
// GetStatOperationName()
// *************************************************************
char* GetStatOperationName(tkFieldStatOperation op)
{
switch (op)
{
case fsoSum:
return "SUM";
case fsoAvg:
return "AVG";
case fsoMin:
return "MIN";
case fsoMax:
return "MAX";
case fsoMode:
return "MOD";
case fsoWeightedAvg:
return "WAVG";
default:
return "";
}
}
// *************************************************************
// CalculateFieldStats()
// *************************************************************
void CShapefile::CalculateFieldStats(map<int, vector<int>*>& fieldMap, IFieldStatOperations* ioperations,
IShapefile* sf)
{
// --------------------------------------------
// validating operations
// --------------------------------------------
USES_CONVERSION;
long numFields;
this->get_NumFields(&numFields);
std::vector<FieldOperation*>* operations = &((CFieldStatOperations*)ioperations)->_operations;
VARIANT_BOOL vb;
ioperations->Validate(this, &vb);
for (vector<FieldOperation*>::value_type op : *operations)
{
// creating output field for operation
if (op->valid)
{
IField* field = nullptr;
this->get_Field(op->fieldIndex, &field);
if (field)
{
CComBSTR bstr;
field->get_Name(&bstr);
CStringW name = OLE2W(bstr);
name = name + "_" + A2W(GetStatOperationName(op->operation));
FieldType type;
field->get_Type(&type);
if (type == INTEGER_FIELD && op->operation == fsoAvg)
type = DOUBLE_FIELD;
long precision;
field->get_Precision(&precision);
long width;
field->get_Width(&width);
long fieldIndex;
const CComBSTR bstrName(name);
sf->EditAddField(bstrName, type, precision, width, &fieldIndex);
op->targetIndex = fieldIndex;
op->targetFieldType = type;
field->Release();
}
}
}
// make sure that output field names are unique
FieldHelper::UniqueFieldNames(sf);
// --------------------------------------------
// calculating
// --------------------------------------------
double areaSum = 0;
double area;
double val;
double sum = 0.0;
CString sSum;
CComVariant var;
int index = 0;
const int size = fieldMap.size();
long percent = 0;
map<CString, int> frequencies;
ShpfileType type;
sf->get_ShapefileType(&type);
type = ShapeUtility::Convert2D(type);
map<int, vector<int>*>::iterator p = fieldMap.begin(); // row in the output, rows in the input
while (p != fieldMap.end())
{
CallbackHelper::Progress(_globalCallback, index, size, "Calculating stats", _key, percent);
for (vector<FieldOperation*>::value_type op : *operations)
{
if (!op->valid) continue;
if (op->targetFieldType == STRING_FIELD)
{
CString sVal = "";
frequencies.clear();
for (int j : *p->second)
{
this->get_CellValue(op->fieldIndex, j, &var);
stringVal(var, sVal);
if (op->operation == fsoMode)
{
frequencies[sVal] = frequencies.find(sVal) == frequencies.end() ? 1 : frequencies[sVal] + 1;
}
else
{
// take the first one, as output despite the operation
if (sSum.GetLength() == 0)
{
sSum = sVal;
}
else
{
const int res = sSum.CompareNoCase(sVal);
if (res < 0 && op->operation == fsoMax ||
res > 0 && op->operation == fsoMin)
{
sSum = sVal;
}
}
}
}
if (op->operation == fsoMode)
{
int max = INT_MIN;
map<CString, int>::iterator frequency = frequencies.begin();
while (frequency != frequencies.end())
{
if (max < frequency->second)
{
max = frequency->second;
sSum = frequency->first;
}
++frequency;
}
}
const CComVariant result(sSum);
sf->EditCellValue(op->targetIndex, p->first, result, &vb);
}
else
{
switch (op->operation)
{
case fsoSum:
case fsoAvg:
case fsoWeightedAvg:
sum = 0.0;
areaSum = 0.0;
break;
case fsoMin:
sum = DBL_MAX;
break;
case fsoMax:
sum = DBL_MIN;
break;
case fsoMode: break;
default: ;
}
// going through rows of original shapefile, which fell into the same group
for (int j : *p->second)
{
this->get_CellValue(op->fieldIndex, j, &var);
dVal(var, val);
switch (op->operation)
{
case fsoSum:
case fsoAvg:
sum += val;
break;
case fsoMin:
if (val < sum) sum = val;
case fsoMax:
if (val > sum) sum = val;
break;
case fsoWeightedAvg:
{
if (type == SHP_POLYGON || type == SHP_POLYLINE)
{
IShape* shp = nullptr;
this->GetValidatedShape(j, &shp);
if (shp)
{
if (type == SHP_POLYGON) shp->get_Area(&area);
else shp->get_Length(&area); // weighting by length of polylines
shp->Release();
areaSum += area;
sum += val * area;
}
}
else
{
sum += val; // regular sum for points
}
}
break;
case fsoMode: break;
default: ;
}
}
if (op->operation == fsoAvg)
{
sum /= p->second->size();
}
if (op->operation == fsoWeightedAvg)
{
sum /= areaSum;
}
if (op->targetFieldType == INTEGER_FIELD)
{
const CComVariant result(Utility::Rint(sum));
sf->EditCellValue(op->targetIndex, p->first, result, &vb);
}
else
{
const CComVariant result(sum);
sf->EditCellValue(op->targetIndex, p->first, result, &vb);
}
}
}
index++;
++p;
}
CallbackHelper::ProgressCompleted(_globalCallback, _key);
}
// *************************************************************
// DissolveGEOS()
// *************************************************************
void CShapefile::DissolveGEOS(long fieldIndex, VARIANT_BOOL selectedOnly, IFieldStatOperations* operations,
IShapefile* sf)
{
map<int, vector<int>*> fieldMap; // index in output, indices in input
map<CComVariant, vector<int>*> indicesMap; // value in input, indices in input
map<CComVariant, vector<GEOSGeometry*>*> shapeMap;
CComVariant val; // VARIANT hasn't got comparison operators and therefore
// can't be used with associative containers
bool calcStats = false;
if (operations)
{
int count;
operations->get_Count(&count);
calcStats = count > 0;
}
ReadGeosGeometries(selectedOnly);
long percent = 0;
int size = (int)_shapeData.size();
for (long i = 0; i < size; i++)
{
CallbackHelper::Progress(_globalCallback, i, size, "Grouping shapes...", _key, percent);
if (!ShapeAvailable(i, selectedOnly))
continue;
GEOSGeometry* gsGeom = this->GetGeosGeometry(i);
if (gsGeom != nullptr)
{
this->get_CellValue(fieldIndex, i, &val);
if (shapeMap.find(val) != shapeMap.end())
{
shapeMap[val]->push_back(gsGeom);
if (calcStats)
{
indicesMap[val]->push_back(i);
}
}
else
{
auto* v = new vector<GEOSGeometry*>;
v->push_back(gsGeom);
shapeMap[val] = v;
if (calcStats)
{
auto* v2 = new vector<int>;
v2->push_back(i);
indicesMap[val] = v2;
}
}
}
}
const bool isM = ShapeUtility::IsM(_shpfiletype);
// saving results
long count = 0; // number of shapes inserted
int shapeProcessed = 0; // for progress bar
percent = 0;
size = shapeMap.size();
VARIANT_BOOL vbretval;
map<CComVariant, vector<GEOSGeometry*>*>::iterator p = shapeMap.begin();
ShpfileType targetType;
sf->get_ShapefileType(&targetType);
while (p != shapeMap.end())
{
CallbackHelper::Progress(_globalCallback, shapeProcessed, size, "Merging shapes...", _key, percent);
GEOSGeometry* gsGeom = GeosConverter::MergeGeometries(*p->second, nullptr, false, false);
delete p->second; // deleting the vector
if (gsGeom != nullptr)
{
std::vector<IShape*> vShapes;
if (GeosConverter::GeomToShapes(gsGeom, &vShapes, isM))
{
for (std::vector<IShape*>::value_type shp : vShapes)
{
if (shp != nullptr)
{
ShapeHelper::ForceProperShapeType(shp, targetType);
sf->EditInsertShape(shp, &count, &vbretval);
if (vbretval)
sf->EditCellValue(0, count, (VARIANT)p->first, &vbretval);
shp->Release();
if (calcStats)
{
std::vector<int>* indices = indicesMap[p->first];
fieldMap[count] = indices;
}
count++;
}
}
}
GeosHelper::DestroyGeometry(gsGeom);
}
++p;
shapeProcessed++;
}
if (calcStats)
{
CalculateFieldStats(fieldMap, operations, sf);
// delete indices map
map<CComVariant, vector<int>*>::iterator p2 = indicesMap.begin();
while (p2 != indicesMap.end())
{
delete p2->second;
++p2;
}
}
this->ClearCachedGeometries();
CallbackHelper::ProgressCompleted(_globalCallback, _key);
}
// *************************************************************
// DissolveClipper()
// *************************************************************
void CShapefile::DissolveClipper(long fieldIndex, VARIANT_BOOL selectedOnly, IFieldStatOperations* operations,
IShapefile* sf)
{
map<int, vector<int>*> fieldMap; // index in output, indices in input
map<CComVariant, vector<int>*> indicesMap; // value in input, indices in input
map<CComVariant, ClipperLib::Clipper*> shapeMap;
CComVariant val; // VARIANT hasn't got comparison operators and therefore
// can't be used with associative containers
long percent = 0;
const int size = (int)_shapeData.size();
// std::vector<ClipperLib::Polygons*> polygons;
std::vector<ClipperLib::Paths*> polygons;
polygons.resize(size, nullptr);
ClipperConverter ogr(this);
bool calcStats = false;
if (operations)
{
int count;
operations->get_Count(&count);
calcStats = count > 0;
}
for (long i = 0; i < size; i++)
{