forked from JamesSaxon/C4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc4.cpp
3671 lines (2735 loc) · 112 KB
/
c4.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
// [MIT License]
//
// Copyright (c) 2017 James Saxon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software. Academic papers or commercial
// products using this software must clearly cite this work.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "c4.h"
namespace c4 {
static std::map<ObjectiveMethod, RadiusType> obj_radius = {{DISTANCE_A, EQUAL_AREA}, {DISTANCE_P, EQUAL_AREA_POP},
{INERTIA_A, EQUAL_AREA}, {INERTIA_P, EQUAL_AREA_POP},
{HULL_A, HULL}, {HULL_P, HULL},
{POLSBY, EQUAL_CIRCUMFERENCE}, {POLSBY_W, EQUAL_CIRCUMFERENCE},
{REOCK, SCC},
{EHRENBURG, LIC}, {POLSBY_W, EQUAL_CIRCUMFERENCE},
{PATH_FRAC, EQUAL_AREA}, {AXIS_RATIO, EQUAL_AREA}};
Cell::Cell()
: region(-1), id(0), pop(0), x(0), y(0), area(0) {}
Cell::Cell(const Cell &c)
: region(-1), id(c.id), pop(c.pop), x(c.x), y(c.y), area(c.area), wm(c.wm),
edge_perim(c.edge_perim), is_univ_edge(c.is_univ_edge), is_split(c.is_split), split_neighbor(c.split_neighbor),
pt(c.pt) {}
Cell::Cell(int i, int p, double x, double y, double a, weight_map wm, float ep, bool split = false)
: region(-1), id(i), pop(p), x(x), y(y), area(a), wm(wm), edge_perim(ep),
is_univ_edge(ep > 1e-3), is_split(split), split_neighbor(false), pt(x, y) {
if (!p) pop = 1; // N.B. that we're setting the minimum population per cell to 1!!
}
// Adjacency map to pointers.
void Cell::adjacency_to_pointers(std::vector<Cell*>& univ_cells) {
weight_map::iterator wit;
weight_map::iterator wmend = wm.end();
// iterate over the full universe
for (auto c : univ_cells) {
// if this cell's id is in our weight map,
// add the cell and its weight to the
// neighbor map.
wit = wm.find(c->id);
if (wit != wmend) nm.push_back(std::make_pair(c, wit->second));
}
}
// Add an edge -- a perimeter component --
// only used for some algos.
void Cell::add_edge(int edge_id, int nodea, int nodeb) {
edges.push_back(Edge(edge_id, nodea, nodeb));
}
// Nodes -- corners between cells -- IDs converted to pointers.
void Cell::node_ids_to_pointers(std::vector<Node*>& univ_nodes) {
for (auto& n : univ_nodes) {
for (auto& e : edges) {
if (e.na_id == n->id) { e.set_na(n); nodes.insert(n); }
if (e.nb_id == n->id) { e.set_nb(n); nodes.insert(n); }
}
}
// Need to know if neighbor is split,
// for get_node_ring.
if (is_split) {
for (auto& n : nm) {
n.first->split_neighbor = true;
}
}
}
// Index from id
int Cell::get_edge_idx(int id) {
int eidx = -1;
for (auto& e : edges) { eidx++;
if (e.id == id) return eidx;
}
return eidx; // shit got fucked.
}
int Cell::get_ext_edge_idx() {
int eidx = -1;
// If this cell is not on the border of the universe,
// we're looking for an edge shared with a foreign neighbor.
if (!is_univ_edge) {
for (auto e : edges) { eidx++; // For each edge,
for (auto nei : nm) { // loop over the
if (nei.first->region == region) continue; // foreign neighbors'
for (auto nei_e : nei.first->edges) { // edges;
if (nei_e.id == e.id) { // if the edge is in both,
return eidx; // return the edge index.
}
}
}
}
} else { // otherwise, looking for an edge shared with no one.
for (auto e : edges) { eidx++; // For each edge,
bool found_edge = false;
for (auto nei : nm) { // loop over the neighbors'
for (auto nei_e : nei.first->edges) { // edges;
if (nei_e.id == e.id) { // if it's shared,
found_edge = true; // it's not what we're looking for.
break;
}
}
if (found_edge) break;
}
if (found_edge) continue;
return eidx;
}
}
return -1; // otherwise -1, to signify failure.
}
/// std::pair<Node*, Node*> Cell::get_cw_node(int reg) {
/// std::pair<Node*, Node*> rval(0, 0);
/// cout << "On get_cw_node for cell " << id << " (x,y)=(" << x << "," << y << ") in region=" << reg << ")" << endl;
/// // Do the last one first, to deal with
/// // the first transition.
/// bool na_dom_nei, nb_dom_nei;
/// for (auto& e : edges) {
/// na_dom_nei = nb_dom_nei = false;
/// for (auto na_e : e.na->edges) {
/// for (auto n : nm) {
/// if (n.first->region == reg &&
/// n.first->has_edge(na_e)) {
/// na_dom_nei = true;
/// break;
/// }
/// }
/// if (na_dom_nei) break;
/// }
/// for (auto nb_e : e.nb->edges) {
/// for (auto n : nm) {
/// if (n.first->region == reg &&
/// n.first->has_edge(nb_e)) {
/// nb_dom_nei = true;
/// break;
/// }
/// }
/// if (nb_dom_nei) break;
/// }
/// // Is THIS edge in the region?
/// // Must do false -> true, because univ. edges are not in the region
/// // but won't give any contradiction -- there is no cell OUT of region on the edge.
/// bool edge_in_region = false;
/// for (auto n : nm) {
/// if (n.first->region == reg &&
/// n.first->has_edge(e.id)) {
/// edge_in_region = true;
/// }
/// }
/// cout << " Edge id=" << e.id << " inreg=" << edge_in_region << " na_dom_nei=" << na_dom_nei << " nb_dom_nei=" << nb_dom_nei << endl;
/// if ( na_dom_nei && !nb_dom_nei) rval.first = e.na;
/// if (!na_dom_nei && nb_dom_nei) rval.second = e.nb;
/// if (!edge_in_region && na_dom_nei && nb_dom_nei)
/// rval.first = e.na; rval.second = e.nb;
/// // if (rval.first && rval.second) break;
/// }
/// // if (!rval.first || !rval.second)
/// // throw std::runtime_error(std::string("get_cw_node() got an empty start or end!"));
/// return rval;
/// }
// If cell has edge, by ID.
bool Cell::has_edge(int edge_id) {
for (auto e : edges) {
if (edge_id == e.id) return true;
}
return false;
}
// Edge pointer from ID (if exists)
Edge* Cell::get_edge(int edge_id) {
for (auto e = edges.begin(); e != edges.end(); e++) {
if (edge_id == e->id) return &(*e);
}
return 0;
}
// Circulate around a node corner, to next edge on the perim.
bool Cell::next_edge_in_region(Node* node, int start_edge_id,
Cell*& next_cell, Edge*& next_edge,
bool CW = true, int region_id = -1) {
if (region_id < 0) region_id = region;
int edge_id;
if (!node->set_edge(start_edge_id)) cout << "Cell " << id << " doesn't even have " << start_edge_id << "!!" << endl;
for (int ni = 0; ni < node->size(); ni++) {
if (CW) edge_id = node->next();
else edge_id = node->prev();
int border = (region == region_id) && has_edge(edge_id);
if (border) {
next_cell = this;
next_edge = get_edge(edge_id);
}
for (auto& nei : nm) {
if (nei.first->region == region_id &&
nei.first->has_edge(edge_id)) {
next_cell = nei.first;
next_edge = nei.first->get_edge(edge_id);
border++;
}
}
if (border == 1) return true;
}
// Should never arrive here.
cout << "Cell=" << id << " region=" << region << ", edge=" << start_edge_id << endl;
assert(0 && "Never found the next border -- made a full loop!!\nIs the cell's region set correctly?");
return false;
}
// Get a set of the foreign regions.
std::unordered_set<int> Cell::neighbor_regions(bool QUEEN) {
std::unordered_set<int> rval;
for (auto& n : nm)
if (n.first->region != region &&
n.first->region >= 0 &&
(QUEEN || n.second > 0))
rval.insert(n.first->region);
return rval;
}
// Overloading.... if the neighbor cells belong to more than one
// connected component, then this is a cut vertex.
bool Cell::neighbors_connected(bool QUEEN = false, bool FAST = false) {
std::vector<std::unordered_set<Cell*> > graphs;
int nsets = neighbor_sets(graphs, false, QUEEN, FAST);
return nsets == 1;
}
// Get neighboring strands -- cut-able components,
// if there's one with size less than max_merge.
int Cell::neighbor_strands(std::unordered_set<Cell*>& strand, // int dest_reg,
unsigned int max_merge = 0, bool QUEEN = false) {
std::vector<std::unordered_set<Cell*> > graphs;
int nsets = neighbor_sets(graphs, max_merge, false);
if (nsets == 1) return 1;
if (nsets > 2) return nsets;
for (auto& g : graphs) {
if (g.size() < max_merge) {
strand = g;
return 2;
}
}
return nsets;
}
// This is quite similar to "connect graph."
// Count the connected components among the neighbors.
// It is possibly the most important function in this code,
// since it's what makes it run fast.
int Cell::neighbor_sets(std::vector<std::unordered_set<Cell*> >& graphs,
unsigned int max_merge, bool QUEEN, bool FAST) {
for (auto& n : nm) {
if (n.first->region != region) continue;
// First make the local star graph,
// for now, just with cells connected to the original,
// and _in the same region._
std::unordered_set<Cell*> lone_star;
lone_star.insert(n.first);
for (auto& nn : n.first->nm) {
if (nn.first->region == region &&
// best this way? removing this would allow corners...
nn.first->wm.find(id) != nn.first->wm.end() &&
(QUEEN || nn.second > 0)) // ROOK
lone_star.insert(nn.first);
}
// Then get a vector of all the existing
// graphs that it's connected to:
// if any element in lone star is in an
// existing graph, just mark it.
std::vector<int> gidx;
for (size_t gi = 0; gi < graphs.size(); gi++) {
for (auto& c : lone_star) {
if (graphs[gi].find(c) != graphs[gi].end()) {
gidx.push_back(gi);
break;
}
}
} // gid should now hold a list of overlapping graphs
// If it has (yet) no neighbors, add it on its own.
if (!gidx.size()) {
graphs.push_back(lone_star);
// Otherwise, add it to the first,
// and add _others_ on to that one.
} else {
graphs[gidx[0]].insert(lone_star.begin(), lone_star.end());
// backwards, to keep removals consistent.
for (auto gi : boost::adaptors::reverse(gidx)) {
if (gi == gidx[0]) continue;
graphs[gidx[0]].insert(graphs[gi].begin(), graphs[gi].end());
graphs.erase(graphs.begin() + gi);
}
}
}
// If the cell's neighbors are connected, we're done.
if (graphs.size() <= 1) return 1;
else if (FAST) return 2; // Ignores QUEEN etc.
// Otherwise, expand search.
// We will have to expand out each of the disjoint star graphs,
// in the "hopes" that these expanding graphs will eventually overlap.
// Create a set of cells "to add", for each set.
std::vector<std::unordered_set<Cell*> > to_add;
// Add the neighbors of the current sets to each list.
for (auto g : graphs) {
to_add.push_back(std::unordered_set<Cell*>()); // start with an empty set...
// Consider the neighbors of all does in the graph. If it is ...
for (auto c : g) for (auto n : c->nm) if (QUEEN || n.second > 0) { // ROOK
if (n.first->region == region && // in the region
g.find(n.first) == g.end() && // not yet in graph, and
n.first != this) { // not the cell in question.
to_add.back().insert(n.first); // then we will have to add work out from this node.
}
}
}
std::unordered_set<Cell*> next;
// Now go about building these sets up.
// If they are merged or we can't go further, we're done.
while (graphs.size() > 1 &&
// may not be empty, but can still flesh out the sets.
(( max_merge && (std::none_of(to_add.begin(), to_add.end(), uo_set_empty) ||
!maxed_or_empty(max_merge, graphs, to_add))) ||
// (( max_merge && std::any_of(to_add.begin(), to_add.end(), uo_set_nempty)) ||
// all of them have neighbors, so we've gotta keep searching.
(!max_merge && std::all_of(to_add.begin(), to_add.end(), uo_set_nempty)))) {
// For each graph, check if a cell to_add in another graph
// is already in this graph or its list to add.
// If there are, and there are only two graphs, then we're done.
// If there are, and there are more than two graphs,
// then merge the two graphs (graphs list and to_add list), and continue.
for (int gidx = 0; gidx < int(graphs.size()); gidx++) {
for (int giidx = int(graphs.size())-1; giidx > gidx; giidx--) {
for (auto c : to_add[giidx]) {
// Cell from gii is in gi. Merge or return.
if (to_add[gidx].find(c) != to_add[gidx].end() ||
graphs[gidx].find(c) != graphs[gidx].end()) {
// Only two graphs, and they merge. We're done.
if (graphs.size() == 2) {
return 1;
}
// Merge lists...
to_add[gidx].insert(to_add[giidx].begin(), to_add[giidx].end());
graphs[gidx].insert(graphs[giidx].begin(), to_add[giidx].end());
to_add.erase(to_add.begin() + giidx);
graphs.erase(graphs.begin() + giidx);
giidx--;
break;
}
}
}
}
// Add to_add to the graph itself, and make neighbors of to_add the next round's to_add.
for (int gidx = 0; gidx < int(graphs.size()); gidx++) {
graphs[gidx].insert(to_add[gidx].begin(), to_add[gidx].end());
next.clear();
for (auto c : to_add[gidx]) {
// If it's a neighbor of to_add...
for (auto n : c->nm) if (QUEEN || n.second > 0) { // ROOK
// in this region and not already in the graph, then add it to the next round.
if (n.first->region == region && c != this &&
graphs[gidx].find(n.first) == graphs[gidx].end()) {
next.insert(n.first);
}
}
}
to_add[gidx].clear();
to_add[gidx].insert(next.begin(), next.end());
}
}
return graphs.size();
}
void Cell::disconnect() { // Dissociate the cell from neighbors.
for (auto nei : nm) {
// Remove this cell from all neighbors' weight map.
nei.first->wm.erase(id);
// Now cycle over the neighbor's _neighor_map_ to remove the pointer as well.
int nm_idx = 0;
for (auto nnei : nei.first->nm) {
if (nnei.first == this) {
// cout << "Disconnecting " << id << " from " << nei.first->id << endl;
nei.first->nm.erase(nei.first->nm.begin()+nm_idx);
break;
}
nm_idx++;
}
}
}
void Cell::merge(Cell* m) { // Subsume a cell in another.
// Do we want to move the coords? I think not.
// x = (x * area + m->x * m->area)/(area + m->area);
// y = (y * area + m->y * m->area)/(area + m->area);
m->disconnect();
// Including the area screws up some
// of the calculations with area normalizations.
// area += m->area;
// Merged cell population "given" to host.
pop += m->pop;
// If this cell had any enclaves or islands already,
// these are forwarded to the "host."
for (auto ei : m->enclaves_and_islands)
enclaves_and_islands.push_back(ei);
// And this cell in it's turn, is a "ward" of the host.
enclaves_and_islands.push_back(m->id);
}
float Cell::regime_match_weight(Cell* c) {
float rweight(1);
for (auto w : rm) {
if (w.second != c->rm[w.first])
rweight *= Universe::urwm[w.first];
}
return rweight;
}
Region::Region()
: id(0), pop(0), ncells(0), area(1e-6), xctr(0), yctr(0), xpctr(0), ypctr(0), sumw_border(0), sumww_border(0),
Ip(0), Ia(0), has_topo(false), eps_scc(1e7), x_scc(0), y_scc(0), r2_scc(0),
eps_lic(2), x_lic(0), y_lic(0), r2_lic(0), x_pow(0), y_pow(0), r2_pow(0)
{}
Region::Region(int rid)
: id(rid), pop(0), ncells(0), area(1e-6), xctr(0), yctr(0), xpctr(0), ypctr(0), sumw_border(0), sumww_border(0),
Ip(0), Ia(0), has_topo(false), eps_scc(1e7), x_scc(0), y_scc(0), r2_scc(0),
eps_lic(2), x_lic(0), y_lic(0), r2_lic(0), x_pow(0), y_pow(0), r2_pow(0)
{}
Region::Region(int rid, Cell* c)
: id(rid), pop(0), ncells(0), area(1e-6), xctr(c->x), yctr(c->y), xpctr(c->x), ypctr(c->y), sumw_border(0), sumww_border(0),
Ip(0), Ia(0), has_topo(false), eps_scc(1e7), x_scc(0), y_scc(0), r2_scc(0),
eps_lic(2), x_lic(0), y_lic(0), r2_lic(0), x_pow(0), y_pow(0), r2_pow(0)
{ add_cell(c, true); }
void Region::reindex(int rid) {
id = rid;
for (auto c : cells) {
c->region = rid;
}
}
// This updates all of the internal values -- all of the objective functions --
// for the addition of one cell.
void Region::add_cell(Cell* c, bool UPDATE_CTR = true) {
ncells++;
c->region = id;
cells.insert(c);
// Maintain the list of internal and external neighbors.
add_cell_int_ext_neighbors(c);
// If the topology is loaded, make the ring.
if (has_topo && node_ring.size() && ncells > 2) make_ring();
// Update the moments of inertia.
Ia = inertia_parallel_axis(Ia, xctr, yctr, area, c->x, c->y, c->area);
Ip = inertia_parallel_axis(Ip, xpctr, ypctr, pop, c->x, c->y, c->pop);
// Update the area and population centers.
if (UPDATE_CTR) {
xctr = (xctr * area + c->x * c->area)/(area + c->area);
yctr = (yctr * area + c->y * c->area)/(area + c->area);
xpctr = (xpctr * pop + c->x * c->pop )/(pop + c->pop );
ypctr = (ypctr * pop + c->y * c->pop )/(pop + c->pop );
// as well as the centers for the Smallest Circumscribing
// and largest inscribed circles.
update_scc(c, 0, true); // add cell, do update.
if (has_topo && node_ring.size()) update_lic(c, 0, true);
// not adding, since it's already since it's already in "cells". don't care about return value; do update axes.
update_pca(0, 0, false, true);
}
area += c->area;
pop += c->pop;
// bgeo::union_(poly, c->poly, poly);
bgeo::append(mpt, c->pt);
// Convex Hull
if (!bgeo::within(c->pt, ch_poly)) {
bgeo::clear(ch_poly);
bgeo::convex_hull(mpt, ch_poly);
ch_area = bgeo::area(ch_poly);
}
}
// Parallel axis theorem for fast moment of inertia update.
double Region::inertia_parallel_axis(double I0, double x0, double y0, double w0, double xc, double yc, double wc) {
if (wc == 0) return I0; // avoid case of w0 = wc = 0...
if (ncells == 1) return 0; // the area is initialized to 1e-6, and won't perfectly cancel...
// Find the new center
double xp = (w0 * x0 + wc * xc) / (w0 + wc);
double yp = (w0 * y0 + wc * yc) / (w0 + wc);
// Calculate distances squares from the center
// to the initial objects and new cells.
double d0p2 = (xp - x0) * (xp - x0) + (yp - y0) * (yp - y0);
double dcp2 = (xp - xc) * (xp - xc) + (yp - yc) * (yp - yc);
// Use the theorem -- look it up.
return I0 + w0 * d0p2 + wc * dcp2;
}
// A bit finnicky, but critical to do this right...
void Region::add_cell_int_ext_neighbors(Cell *c) {
ext_borders.erase(c);
// require check, because otherwise cells can
// get assigned after all ext. neighbors are,
// and then never re-visited.
if (c->is_univ_edge) {
int_borders.insert(c);
sumw_border += c->edge_perim;
sumww_border += c->edge_perim; // * Universe::regime_product;
}
for (auto n : c->nm) {
if (n.first->region != id) {
int_borders.insert(c); break;
}
}
// Iterate over the MOVING cell's neighbors.
for (auto const& n : c->nm) {
// If the neighbor is not a member of the
// destination region, then this is a new border.
// We try to add it to the list of border cells
// (it may already be there), but at any rate
// add its newly-exposed border to sumw_border.
if (n.first->region != id) {
if (n.second > 0) ext_borders.insert(n.first); // ROOK
sumw_border += n.second;
sumww_border += n.second * c->regime_match_weight(n.first);
// If the cell's neighbor IS a member of
// the destination region, then this border was
// previously exposed. Remove its contribution
// to sumw_border.
} else {
sumw_border -= n.second;
sumww_border -= n.second * c->regime_match_weight(n.first);
// if, further, that neighbor has no other connections
// to the outside world, then remove it from int_borders.
bool indep_connections = false;
for (auto nn : n.first->nm) {
if (nn.first->region != id) {
indep_connections = true;
break;
}
}
if (!indep_connections && !n.first->is_univ_edge) {
int_borders.erase(n.first);
}
}
}
// Sanity check.
unsigned int count_ib = 0;
for (auto c : cells) {
bool border = false;
for (auto n : c->nm)
if (n.first->region != id) border = true;
if (border || c->is_univ_edge) {
if (int_borders.find(c) == int_borders.end())
cout << c->id << " should be an internal border of " << id << " but is not!!" << endl;
count_ib++;
}
}
if (count_ib != int_borders.size()) {
cout << "Did not find all of the cells in the internal border -- " << count_ib << " v. " << int_borders.size() << endl;
for (auto ib : int_borders) cout << ib->id << " ";
cout << endl;
}
}
// Very similar to add_cell, but everything in reverse.
void Region::remove_cell(Cell *c, bool UPDATE_CTR = true) {
if (ncells == 1) return; // FIXME how to treat this.
if (c->region == id) c->region = -1;
ncells--;
cells.erase(c);
remove_cell_int_ext_neighbors(c);
if (has_topo && node_ring.size() && ncells > 2) make_ring();
Ia = inertia_parallel_axis(Ia, xctr, yctr, area, c->x, c->y, -c->area);
Ip = inertia_parallel_axis(Ip, xpctr, ypctr, pop, c->x, c->y, -c->pop);
if (UPDATE_CTR) {
xctr = (xctr * area - c->x * c->area)/(area - c->area);
yctr = (yctr * area - c->y * c->area)/(area - c->area);
xpctr = (xpctr * pop - c->x * c->pop )/(pop - c->pop );
ypctr = (ypctr * pop - c->y * c->pop )/(pop - c->pop );
update_pca(0, 0, false, true); // Not subtracting; already removed from "cells."
update_scc(0, c, true); // sub cell, do update.
if (has_topo && node_ring.size()) update_lic(0, c, true);
}
area -= c->area;
pop -= c->pop;
mpt.clear(); // faster to just re-copy.
for (auto c : cells) bgeo::append(mpt, c->pt);
// check "within" because corners count as outside.
if (!bgeo::within(c->pt, ch_poly)) {
bgeo::clear(ch_poly);
bgeo::convex_hull(mpt, ch_poly);
ch_area = bgeo::area(ch_poly);
bgeo::centroid(ch_poly, ch_pt);
ch_x = bgeo::get<0>(ch_pt);
ch_y = bgeo::get<1>(ch_pt);
}
}
void Region::remove_cell_int_ext_neighbors(Cell* c) {
int_borders.erase(c);
// This would be unnecessary if I ALWAYS worked one cell at a time:
// a cell removed would necessarily be in the external border.
// But in the case of e.g. splits, there can be "temporarily non-contiguous"
// graphs. In that case, if the cell is not connected to the main subgraph,
// it is not in the ext border!! Careful!!
for (auto n : c->nm) {
if (n.first->region == id) {
ext_borders.insert(c); break;
}
}
if (c->is_univ_edge) {
sumw_border -= c->edge_perim;
sumww_border -= c->edge_perim; // * Universe::regime_product;
}
// Iterate over the MOVING cell's neighbors.
for (auto const& n : c->nm) {
// If the neighbor cell is not a member of the
// source (= id, this) region, remove this boundary's
// contribution to sumw_border. If, furthermore,
// that cell does not have any *other* connections
// to the source, erase it from the border.
if (n.first->region != id) {
sumw_border -= n.second;
sumww_border -= n.second * c->regime_match_weight(n.first);
bool indep_connections = false;
for (auto nn : n.first->nm) {
if (nn.first->region == id &&
nn.second > 0) { // ROOK
indep_connections = true;
break;
}
}
if (!indep_connections) {
ext_borders.erase(n.first);
}
// If the moving cell's neighbor IS a member of
// source region, add its contribution to
// the sumw_border. (It is an internal border.)
} else {
int_borders.insert(n.first);
sumw_border += n.second;
sumww_border += n.second * c->regime_match_weight(n.first);
}
}
// Sanity check.
// for (auto b : ext_borders) {
// float total_border = 0;
// float region_border = 0;
// int nonzero_borders = 0;
// for (auto bn : b->nm) {
// total_border += bn.second;
// if (bn.second > 0) nonzero_borders++;
// if (bn.first->region == id)
// region_border += bn.second;
// }
// // if (region_border == 0 && nonzero_borders > 1) {
// // cout << __FUNCTION__ << "::" << __LINE__
// // << " :: cell " << b->id << " is in the external border of Region " << id << " but has no non-zero connection to it." << endl;
// // }
// }
// if (c->is_univ_edge) {
// float sum_border_check = 0;
// for (auto b : int_borders) {
// sum_border_check += b->edge_perim;
// for (auto n : b->nm) if (n.first->region != id) {
// sum_border_check += n.second;
// }
// }
// cout << "sum_border_check=" << sum_border_check << " v. sumw_border=" << sumw_border << endl;
// }
// Sanity check.
// uint count_ib = 0;
// for (auto c : cells) {
// bool border = false;
// for (auto n : c->nm)
// if (n.first->region != id) border = true;
// if (border || c->is_univ_edge) {
// if (int_borders.find(c) == int_borders.end())
// cout << c->id << " should be an internal border of " << id << " but is not!!" << endl;
// count_ib++;
// }
// }
// for (auto ib : int_borders) {
// if (cells.find(ib) == cells.end())
// cout << "Did not find all of the cells in the internal border -- missing : " << ib->id << endl;
// }
}
bool Region::make_ring() {
// node_ring.clear();
get_node_ring(node_ring);
return node_ring.size();
}
std::pair<std::pair<float, float>, float> Region::get_circle_coords(RadiusType rt) {
switch (rt) {
case RadiusType::EQUAL_AREA_POP: return std::make_pair(std::make_pair(xpctr, ypctr), sqrt(area/M_PI));
case RadiusType::EQUAL_CIRCUMFERENCE: return std::make_pair(std::make_pair(xctr, yctr), sumw_border/2/M_PI );
case RadiusType::SCC: return std::make_pair(std::make_pair(x_scc, y_scc), sqrt(r2_scc));
case RadiusType::LIC: return std::make_pair(std::make_pair(x_lic, y_lic), sqrt(r2_lic));
case RadiusType::HULL: return std::make_pair(std::make_pair(ch_x, ch_y) , sqrt(ch_area/M_PI));
case RadiusType::POWER: return std::make_pair(std::make_pair(x_pow, y_pow), sqrt(r2_pow));
case RadiusType::EQUAL_AREA:
default: return std::make_pair(std::make_pair(xctr, yctr), sqrt(area/M_PI));
}
}
// The convex hull is made by taking the convex hull
// of all the points on the internal border.
// This is just for plotting in python.
std::vector<std::pair<float, float> > Region::hull(bool IB) {
std::vector<std::pair<float, float> > hull_ring;
bg_mpt multipt;
bg_poly poly_hull;
// if (IB) for (auto c : cells) bgeo::append(multipt, c->pt);
if (IB) for (auto c : int_borders)
if (cells.find(c) != cells.end())
bgeo::append(multipt, c->pt);
else cout << "ib id=" << c->id << " not in cells!!" << endl;
else for (auto c : cells) bgeo::append(multipt, c->pt);
bgeo::convex_hull(multipt, poly_hull);
auto it = boost::begin(boost::geometry::exterior_ring(poly_hull));
auto eit = boost::end (boost::geometry::exterior_ring(poly_hull));
for (; it != eit; ++it)
hull_ring.push_back(std::make_pair<float, float>(bgeo::get<0>(*it), bgeo::get<1>(*it)));
return hull_ring;
}
// The coordinates of the node ring are just returned for python plotting.
std::vector<std::pair<float, float> > Region::get_point_ring() {
std::vector<std::pair<float, float> > point_ring;
if (ncells < 2) {
point_ring.push_back(std::make_pair(xctr, yctr));
point_ring.push_back(std::make_pair(xctr, yctr));
return point_ring;
}
// Make the ring from the edge topology.
make_ring();
for (auto n : node_ring) {
point_ring.push_back(std::make_pair(n->x, n->y));
}
if (node_ring.size()) point_ring.push_back(point_ring.front()); // close the loop.
else {
cerr << "Found a ring with size 0 in region " << id << ", which has "
<< cells.size() << " cells and "
<< int_borders.size() << " internal border cells." << endl;
throw std::runtime_error(std::string("Found a ring with size 0"));
}
return point_ring;
}
// This is the actual perimeter border, rather than just
// the nodes along the edge.
// Not directly returning the float pairs makes it easier
// to add in the queen/corner loops.
void Region::get_node_ring(std::vector<Node*> &ring,
Cell* curr_cell, int this_edge_idx) {
ring.clear();
bool recursed = curr_cell; // safety -- one layer deep.
if (ncells == 1) {
for (auto e : (*cells.begin())->edges) {
ring.push_back(e.na);
}
return;
}
// If a starting cell/edge is not provided, find a random one.
// if we happen to choose a cell with only a corner connection
// to the outside, the external edge will fail; hence we loop.
for (auto ib = int_borders.begin();
ib != int_borders.end() && this_edge_idx < 0; ++ib) {
curr_cell = *ib;
if (curr_cell->region != id) continue; // region can be -1 if removing...
if (curr_cell->is_split) continue; // just not worth starting here.
if (curr_cell->split_neighbor) continue;
this_edge_idx = curr_cell->get_ext_edge_idx();
}
if (this_edge_idx < 0) {
if (ncells > 10)
cout << "WARNING :: Region " << id << " found no good start on get_node_ring(), "
<< " with ncells=" << ncells << ". Using a random cell." << endl;
for (auto e : (*cells.begin())->edges) ring.push_back(e.na);
return;
}
int start_cell_id = curr_cell->id;
// cout << "Starting cell for node ring " << start_cell_id << ", edge=" << this_edge_idx << endl;
Edge* this_edge = &curr_cell->edges[this_edge_idx];
Node* node = this_edge->nb;
// cout << "Region " << id << ", cell " << curr_cell->id << " at node " << node->id << endl;
Node* start_node = this_edge->na;
if (start_node->size() > 2) ring.push_back(start_node);