forked from gringer/bioinfscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
perlshaper.pl
executable file
·2059 lines (1815 loc) · 71.2 KB
/
perlshaper.pl
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
#!/usr/bin/perl
use warnings;
use strict;
use Pod::Usage; ## uses pod documentation in usage code
use Getopt::Long qw(:config auto_version auto_help pass_through); # for option parsing
use Math::Trig qw(asin_real acos_real pi);
# http://search.cpan.org/~jasonk/Geo-ShapeFile-2.52/lib/Geo/ShapeFile.pm
use Geo::ShapeFile;
use SVG;
use POSIX qw(fmod);
## more verbose traceback on errors
use Carp 'verbose';
$SIG{ __DIE__ } = \&Carp::confess;
our $VERSION = "2.09";
## Write out version name to standard error
printf(STDERR "Perlshaper version %s\n", ${VERSION});
=head1 NAME
perlshaper.pl - convert shapefile data to SVG format, for use in
wikimedia maps.
=head1 SYNOPSIS
./perlshaper.pl <shapefile(s)> -type <mapType> [options] > output.svg
=head2 Basic Options
=over 2
=item B<-help>
Only display this help message
=item B<-type> I<string>
Type of map (location|locator|area|world|orthographic)
=item B<-res> I<float>
Resolution of map in SVG file (in pixels)
=item B<-centre> I<long>,I<lat>
Identify centre of map (by longitude/latitude)
=item B<-centre> I<ISO 3A-code>
Identify centre of map (by target country). The target can be specified as 'I<sovCode>/I<countryCode>' for a stricter match.
=item B<-data> I<file>
Colour countries based on numerical data in file
=back
=head1 ARGUMENTS
Most of the map-based variables used in the code can be customised to
fit particular needs using command-line arguments.
=head2 Advanced Options
=over 2
=item B<-psize> I<float>
Radius of small points
=item B<-colour> I<string>
Change colour theme to a different map type
=item B<-proj> I<string>
Change target projection
=item B<-landcol> I<string>
Land colour
=item B<-seacol> I<string>
Sea colour
=item B<-bordcol> I<string>
Border colour
=item B<-sub> I<ISO 3A-code>
Identify subject region
=item B<-pol> I<ISO 3A-code>
Identify related political region
=item B<-only> I<ISO 3A-code>
Only display specified shape(s)
=item B<-zoom> I<ISO 3A-code>
Zoom to projected extents of shape(s)
=item B<-zoom> I<minX,Y,maxX,Y>
Zoom to projected extents, typically with I<X> = longitude, I<Y> = latitude
=item B<-nokey>
Don't display heatmap key (if heatmap is used)
=item B<-annotate> I<Text>;I<long>,I<lat>
Add text annotation to a point on the image
=item B<-nohighlights>
Don't display circular highlights for small areas
=item B<-[no]lines>
[don't] print lines of latitude and longitude
=item B<-v>
Verbose output (also '-v -v')
=back
=head1 DESCRIPTION
This code is designed with wikimedia in mind, so the default options
should produce SVG images that follow the general map conventions (see
http://en.wikipedia.org/wiki/Wikipedia:WikiProject_Maps/Conventions). In
particular, the expected input format is that of Natural Earth files
(http://www.naturalearthdata.com).
Just as a head's up, latitude lines are horizontal in the typical
projection of the world, while longitude lines are
vertical. Latitude is usually represented by a number (in degrees)
in the range -90..90, while longitude is usually represented by a
number (in degrees) in the range -180..180.
/---------\ --- latitude (Y)
| | | | | | |
|-|-|-|-|-|-|
| | | | | | |
\---------/
|
\-- longitude (X)
=head1 METHODS
=cut
=head2 transform(optionRef, point)
Transform a point from {[-180,180],[-90,90]} to
{[-0.5,0.5],[-0.5,0.5]} relative to the desired projection. This
replaces the proj4 transform function with something that will
always return a valid point. Orthographic transformations that
appear on the opposite side of the globe will be converted to a
point with the same angle, but sitting at the circle
edge. Adjustments need to be made post-transform (e.g. multiply by
SVG width, add to fit in 0..max range) to convert to SVG
coordinates.
=cut
sub transform {
my ($options, $inPoint) = @_;
my $pi180 = pi / 180;
my $oldLong = $inPoint->[0];
my $oldLat = $inPoint->[1];
my $projection = $options->{"projection"};
my $lambda = fmod(($oldLong - $options->{"centreLn"} + 540), 360) - 180;
my $include = 1;
my $phi = $oldLat;
my $phi1 = $options->{"centreLt"};
my ($x, $y);
if ($projection eq "equirectangular") {
# see http://en.wikipedia.org/wiki/Equirectangular_projection
$x = ($lambda * cos($phi1 * $pi180)) / 360;
$y = ($phi / 180);
} elsif ($projection eq "orthographic") {
# see http://en.wikipedia.org/wiki/Orthographic_projection_(cartography)
$phi = $phi * $pi180;
$phi1 = $phi1 * $pi180;
$lambda = $lambda * $pi180;
$x = cos($phi) * sin($lambda);
$y = sin($phi) * cos($phi1) - sin($phi1) * cos($phi) * cos($lambda);
my $theta = atan2($y,$x);
my $cosc = sin($phi1) * sin($phi) +
cos($phi1) * cos($phi) * cos($lambda);
if (($cosc) < 0) {
$include = 0;
$x = cos($theta); # put on edge of map (i.e. r = 1)
$y = sin($theta);
}
if ($options->{"rotation"}) {
# there may be a quicker way to do this above...
my $r = sqrt($x*$x + $y*$y);
$theta += $options->{"rotation"} * $pi180;
$x = $r * cos($theta);
$y = $r * sin($theta);
}
# adjust by a factor of 0.5 to fit in -0.5..0.5 that other projections use
$x *= 0.5;
$y *= 0.5;
} elsif ($projection eq "wintri") {
$phi = $phi * $pi180;
my $cphi1 = (2 / pi);
$lambda = $lambda * $pi180;
# see http://en.wikipedia.org/wiki/Winkel_Tripel
my $alpha = acos_real(cos($phi) * cos($lambda / 2));
my $sincalpha = ($alpha == 0) ? 1 : (sin($alpha) / $alpha);
$x = (($lambda * $cphi1) +
(2 * cos($phi) * sin($lambda / 2) / $sincalpha)) / (4 + 2 * pi);
$y = ($phi + sin($phi) / $sincalpha) / (2 * pi);
} else {
die("Error: projection must be one of the following: ".
"equirectangular, wintri, orthographic");
}
return([$x, $y, $include]);
}
=head2 project(optionRef, pointRef)
Convert a set of points from standard equirectangular projection
("+proj=latlong +datum=WGS84" in proj4-speak) to another
projection. Natural Earth Data uses this equirectangular format, where
coordinates are specified based on their latitude and longitude
locations in degrees.
This method attempts to fit the map into a rectangle (or square)
that fits in a 1100x550 box.
=cut
sub project {
my ($options, $pointRef) = @_;
my @input = @{$pointRef};
my $newProj = $options->{"projection"};
my $projWidth = $options->{"svgWidth"};
my $projHeight = $options->{"svgHeight"};
my $padding = $options->{"padding"};
my $xAdj = $options->{"xAdj"};
my $yAdj = $options->{"yAdj"};
my ($minX, $minY) = (1.5 - $xAdj, 1.5 - $yAdj);
my ($maxX, $maxY) = ($minX + $projWidth + $padding * 2,
$minY + $projHeight + $padding * 2);
if(defined($options->{"minX"})){
($minX, $maxX) = ($options->{"minX"}, $options->{"maxX"});
($minY, $maxY) = ($options->{"minY"}, $options->{"maxY"});
}
my $xScale = $options->{"xScale"};
my $yScale = $options->{"yScale"};
my @output = ();
my ($oldX, $oldY);
my $oldLat;
my $maxDist2 = ($projWidth / 4) ** 2; # maximum distance between points
foreach my $inPoint (@input) {
my $newLong = 0;
my $newLat = 0;
if ((ref($inPoint) eq "Geo::ShapeFile::Point") ||
(ref($inPoint) eq "HASH")) {
$newLong = $inPoint->X;
$newLat = $inPoint->Y;
} elsif (ref($inPoint) eq "ARRAY") {
$newLong = $inPoint->[0];
$newLat = $inPoint->[1];
} else {
my $ptRefType = ref($inPoint);
die("Error: expecting a reference to an array or a hash [actual reference type: $ptRefType]");
}
# convert point to fit into -0.5..0.5,-0.5..0.5
# Note that this happens before scaling and centering
my $pt = transform($options, [$newLong, $newLat]);
my $px = ($pt -> [0]) * $xScale * $projWidth;
# Y inverted because SVG file is inverted
my $py = -($pt -> [1]) * $yScale * $projHeight;
$oldX = $px if !defined($oldX);
$oldY = $py if !defined($oldY);
$oldLat = $newLat if !defined($oldLat);
my $xd = $px - $oldX;
if (($xd * $xd) > $maxDist2) {
# don't connect lines that have wrapped around the map (over half the image width)
if(($options->{"zoomed"}) ||
($options->{"projection"} eq "orthographic")){
# zoomed and orthographic projections don't get additional points added
### removed to fix latitude/longitide lines not printing
# push(@output, 0);
} else {
# add additional points on the border edge
my ($minLong, $maxLong) = ($options->{"minLong"}, $options->{"maxLong"});
my $oldEdgePoint =
transform($options, [($px > $oldX) ? $minLong : $maxLong, $oldLat]);
my $newEdgePoint =
transform($options, [($px > $oldX) ? $maxLong : $minLong, $newLat]);
$oldEdgePoint->[0] = $oldEdgePoint->[0] * $xScale * $projWidth;
$newEdgePoint->[0] = $newEdgePoint->[0] * $xScale * $projWidth;
$oldEdgePoint->[1] = $oldEdgePoint->[1] * $yScale * -$projHeight;
$newEdgePoint->[1] = $newEdgePoint->[1] * $yScale * -$projHeight;
push(@output, $oldEdgePoint);
push(@output, 0);
push(@output, $newEdgePoint);
}
}
$oldX = $px;
$oldLat = $newLat;
$px = $px;
$py = $py;
push(@output, [$px, $py, $pt->[2]]);
}
if (scalar(grep($_ && $_->[2],@output)) > 0) {
return(@output);
} else { # if everything is clipped, output 'undefined' for everything
return((0) x scalar(@input));
}
}
=head2 orthDist2(point1, pointP, point2)
calculates the square of the minimum distance between the point (xP,yP) and the line [(x1,y1) - (x2,y2)]
The distance formula is from
L<wolfram|http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html>
with modifications for division by zero, and for points outside the line
=cut
sub orthDist2 {
my ($point1, $pointP, $point2) = @_;
my $x1 = $point1 -> [0];
my $y1 = $point1 -> [1];
my $xP = $pointP -> [0];
my $yP = $pointP -> [1];
my $x2 = $point2 -> [0];
my $y2 = $point2 -> [1];
if (($x2 == $x1) && ($y2 == $y1)) {
# exclude case where denominator is zero
my $dist2 = ($x1-$xP)**2 + ($y1 - $yP)**2;
return($dist2);
}
my $dist2 = (($x2 - $x1)*($y1 - $yP) - ($x1 - $xP)*($y2 - $y1))**2 /
(($x2 - $x1)**2 + ($y2 - $y1)**2);
if ($dist2 == 0) {
# on the line, but need to consider points outside the line
# this fixes a problem where the equator line is clipped
my $p1Dist = (($x1-$xP)**2 + ($y1 - $yP)**2);
my $p2Dist = (($x2-$xP)**2 + ($y2 - $yP)**2);
my $p12Dist = (($x1-$x2)**2 + ($y1 - $y2)**2);
my $sigma = 0.0001;
if (($p1Dist + $p2Dist) > ($p12Dist + $sigma)) {
# point is outside the line, use smallest distance from line end points
$dist2 = ($p1Dist < $p2Dist) ? $p1Dist : $p2Dist;
}
}
return($dist2);
}
=head2 distGr2(point1, point2, res2)
Determines if the distance between the point (x1,y1) and the point
(x2,y2) is greater than the square root of res2.
=cut
sub distGr2 {
my ($point1, $point2, $res2) = @_;
my $dx = $point2 -> [0] - $point1 -> [0];
my $dy = $point2 -> [1] - $point1 -> [1];
return(($dx * $dx + $dy * $dy) > ($res2));
}
=head2 simplify(optionRef, pointHash, pointRef)
Simplify curves to reduce number of points in SVG file. This method
should keep points if they have already been included as part of the
simplifcation of another curve, so that shapes that overlap won't
have any gaps. This requires a global hash of already added points.
This is a quick process based around resolving distance -- if points
are closer than the resolution distance to another included point,
then they are removed.
=cut
sub simplify {
my ($options, $pointHash, $pointRef) = @_;
if($options->{"resolution"} == -1){
return @{$pointRef};
}
my $res = $options->{"resolution"};
my $last = undef;
my ($lastXRounded, $lastYRounded, $xRounded, $yRounded);
my @input = map {
if($_){
$xRounded = int($_->[0] / $res);
$yRounded = int($_->[1] / $res);
if(!defined($last) || $pointHash->{($xRounded, $yRounded)}){
$pointHash->{($xRounded,$yRounded)} = 1;
$last = $_;
$lastXRounded = $xRounded;
$lastYRounded = $yRounded;
} elsif((($xRounded != $lastXRounded) && ($yRounded != $lastYRounded)) ||
(($xRounded - $lastXRounded) + ($yRounded - $lastYRounded) > 1.4)){
$pointHash->{($xRounded,$yRounded)} = 1;
$last = $_;
$lastXRounded = $xRounded;
$lastYRounded = $yRounded;
}
} else {
$last = undef;
}
$_;
} @{$pointRef};
return(@input);
}
=head2 clip(optionRef, pointRef)
clip the shape to the limits of the zoom box (if any). The
algorithm used here is the Sutherland-Hodgman algorithm:
http://en.wikipedia.org/wiki/Sutherland-Hodgman
Note that this algorithm can leave some zero-width polygon
sections in the resultant clip region.
=cut
sub clip {
my ($options, $pointRef) = @_;
my $xAdj = $options->{"xAdj"};
my $yAdj = $options->{"yAdj"};
my @oldPoints = @{$pointRef};
# if all points have been previously excluded, clip them out
if(!grep($_ && $_->[2], @oldPoints)){
return((0) x scalar(@oldPoints));
}
if(!$options->{"zoomed"}){
return(@oldPoints);
}
# map edge name to the array location it refers to, and the
# direction of checking
my %edges = ("minX" => 0, "maxX" => 1, "minY" => 2, "maxY" => 3);
for my $edge (keys(%edges)){
my $edgeLoc = int($edges{$edge} / 2);
my $checkLt = $edges{$edge} % 2;
my @processedPoints = ();
my $lastPt = 0;
while(@oldPoints && !$oldPoints[$#oldPoints]){
push(@processedPoints, pop(@oldPoints));
}
if(@oldPoints){
$lastPt = $oldPoints[$#oldPoints];
}
while(@oldPoints){
my $pt = shift(@oldPoints);
if (!$pt) {
push(@processedPoints, $pt);
} else {
if ($checkLt xor ($pt->[$edgeLoc] >= $options->{$edge})) {
if (!$checkLt xor ($lastPt->[$edgeLoc] >= $options->{$edge})) {
# calculates the intersection of the line between pt and
# lastPt and the boundary line
my $ptA = $pt->[$edgeLoc];
my $lptA = $lastPt->[$edgeLoc];
my $ptB = $pt->[1 - $edgeLoc];
my $lptB = $lastPt->[1 - $edgeLoc];
my $edgeCoord = $options->{$edge};
my $locProp = ($ptA - $edgeCoord) / ($ptA - $lptA);
my $locCoord = $locProp * ($ptB - $lptB) + $ptB;
push(@processedPoints,
[($edgeLoc == 0) ? $edgeCoord : $locCoord,
($edgeLoc == 1) ? $edgeCoord : $locCoord, 1]);
}
push(@processedPoints, $pt);
} elsif ($checkLt xor ($lastPt->[$edgeLoc] >= $options->{$edge})) {
# same as above, not wrapped into a function
my $ptA = $pt->[$edgeLoc];
my $lptA = $lastPt->[$edgeLoc];
my $ptB = $pt->[1 - $edgeLoc];
my $lptB = $lastPt->[1 - $edgeLoc];
my $edgeCoord = $options->{$edge};
my $locProp = ($ptA - $edgeCoord) / ($ptA - $lptA);
my $locCoord = $locProp * ($ptB - $lptB) + $ptB;
push(@processedPoints,
[($edgeLoc == 0) ? $edgeCoord : $locCoord,
($edgeLoc == 1) ? $edgeCoord : $locCoord, 1]);
}
$lastPt = $pt;
}
} # ends while
push(@oldPoints, @processedPoints);
} # ends for
return(@oldPoints);
}
=head2 boundBox(pointList)
Determines post-projection rectangular bounding box for a polygon
(e.g. for determining if borders are useful, or zooming in to a
particular region)
=cut
sub boundBox {
my @input = @_;
@input = grep($_, @input);
my $minX = 0;
my $minY = 0;
my $maxX = 0;
my $maxY = 0;
if (@input) {
my $minPoint = $input[0];
$minX = $minPoint -> [0];
$minY = $minPoint -> [1];
$maxX = $minPoint -> [0];
$maxY = $minPoint -> [1];
foreach my $point (@input) {
my $px = $point -> [0];
my $py = $point -> [1];
$minX = $px if ($px < $minX);
$minY = $py if ($py < $minY);
$maxX = $px if ($px > $maxX);
$maxY = $py if ($py > $maxY);
}
}
return(($minX, $minY, $maxX, $maxY));
}
=head2 boundBoxPre(pointList)
Determines pre-projection rectangular bounding box for a polygon
(e.g. for identifying shape boundaries for zoom, etc)
=cut
sub boundBoxPre {
my @input = @_;
@input = grep($_, @input);
my $minX = 0;
my $minY = 0;
my $maxX = 0;
my $maxY = 0;
if (@input) {
my $minPoint = $input[0];
$minX = $minPoint -> X;
$minY = $minPoint -> Y;
$maxX = $minPoint -> X;
$maxY = $minPoint -> Y;
foreach my $point (@input) {
my $px = $point -> X;
my $py = $point -> Y;
$minX = $px if ($px < $minX);
$minY = $py if ($py < $minY);
$maxX = $px if ($px > $maxX);
$maxY = $py if ($py > $maxY);
}
}
return(($minX, $minY, $maxX, $maxY));
}
=head2 shapeNames(shapeData)
retrieve shape name data from a shape database. For countries, three-letter ISO codes are preferred
=cut
sub shapeNames {
my ($shapeData) = @_;
my $outCountry = "";
my $outSov = ""; # 'sovereignty' is easy to mis-spell, and 'sov' is shorter
my $outRegion = "";
if (exists($shapeData->{"Name2"})) {
# Name2 seems to be 3-letter code for Point data
$outSov = $shapeData->{"Name2"};
$outCountry = $shapeData->{"Name2"};
} elsif (exists($shapeData->{"sov_a3"}) && exists($shapeData->{"adm0_a3"})) {
# 3-letter code for polygon data
$outSov = $shapeData->{"sov_a3"};
$outCountry = $shapeData->{"adm0_a3"};
} elsif (exists($shapeData->{"SOV_A3"}) && exists($shapeData->{"ADM0_A3"})) {
# 3-letter code for polygon data
$outSov = $shapeData->{"SOV_A3"};
$outCountry = $shapeData->{"ADM0_A3"};
} elsif (exists($shapeData->{"SOV"}) && exists($shapeData->{"COUNTRY"})) {
# 10m data uses full name, rather than 3-letter code
# should a lookup table be used for conversion?
$outSov = $shapeData->{"SOV"};
$outCountry = $shapeData->{"COUNTRY"};
} elsif (exists($shapeData->{"ISO"})) {
$outSov = $shapeData->{"ISO"}; # no 10m Sov data in state/province file
$outCountry = $shapeData->{"ISO"};
} elsif (exists($shapeData->{"NAME_0"})) {
$outSov = $shapeData->{"NAME_0"}; # this is used in GADM data
$outCountry = $shapeData->{"NAME_0"};
} elsif (exists($shapeData->{"featurecla"})) {
if (($shapeData->{"featurecla"} eq "River") && exists($shapeData->{"name"})) {
$outRegion = $shapeData->{"name"};
}
} elsif (exists($shapeData->{"FEATURECLA"})) {
if (($shapeData->{"FEATURECLA"} eq "River") && exists($shapeData->{"NAME"})) {
$outRegion = $shapeData->{"NAME"};
}
}
if (exists($shapeData->{"name_1"})) {
$outRegion = $shapeData->{"name_1"};
} elsif (exists($shapeData->{"NAME_1"})) {
$outRegion = $shapeData->{"NAME_1"};
}
utf8::encode($outRegion);
utf8::encode($outSov);
utf8::encode($outCountry);
return($outSov, $outCountry, $outRegion);
}
=head2 makeRelative(optionRef, pointRef)
Creates relative point definitions (excluding the first point). This
is used to reduce the SVG output file size.
=cut
sub makeRelative {
my ($options, $pointRef) = @_;
my $round = ($options->{"resolution"} != -1);
my $res = $options->{"resolution"};
my $xAdj = $round ? int($options->{"xAdj"} / $res + 0.5) : $options->{"xAdj"};
my $yAdj = $round ? int($options->{"yAdj"} / $res + 0.5) : $options->{"yAdj"};
my @points = map{$_->[0] /= $res; $_->[1] /= $res; $_} @{$pointRef};
my $lastX = 0;
my $lastY = 0;
foreach my $point (@points) {
my $nextX = $round ? int($point->[0] + $xAdj) : ($point->[0] + $xAdj);
my $nextY = $round ? int($point->[1] + $yAdj) : ($point->[1] + $yAdj);
$point->[0] = $nextX - $lastX;
$point->[1] = $nextY - $lastY;
$lastX = $nextX;
$lastY = $nextY;
}
map{$_->[0] *= $res; $_->[1] *= $res} @points;
}
=head2 chopPoly(optionRef, pointRef, joinEnds)
Closes up lines in a polygon that contain discontinuous points -- this
usually happens when part of a polygon goes outside the projection
area. If I<joinEnds> is true, then the ends of the polygon are joined
together.
The input is a sequence of Geo::Points, and the output is a string
that can be used as a path description in an SVG file
=cut
sub chopPoly {
my ($options, $pointRef, $joinEnds) = @_;
my @oldPoints = @{$pointRef};
if (!@oldPoints) {
return (""); # nothing to process
}
my $xAdj = $options->{"xAdj"};
my $yAdj = $options->{"yAdj"};
# trim off start and end undefined / missing points
while(@oldPoints && !$oldPoints[0]){
shift(@oldPoints);
}
while(@oldPoints && !$oldPoints[$#oldPoints]){
pop(@oldPoints);
}
# create list of contiguous sequences
my @contigLists = ();
my $currentList = [];
push(@contigLists, $currentList);
foreach(@oldPoints){
if($_){
push(@{$currentList}, $_);
} else {
if(@{$currentList}){
$currentList = [];
push(@contigLists, $currentList);
}
}
}
# If a discontinuity exists, check if start/end point are the
# same. If so, rotate the array to start/end on the first
# discontinuity. This fixes an issue where polygons that cross the
# boundaries of a full-sized location / world projection are
# inappropriately joined
if(scalar(@contigLists) > 1){
my $distX = $oldPoints[0]->[0] - $oldPoints[$#oldPoints]->[0];
my $distY = $oldPoints[0]->[1] - $oldPoints[$#oldPoints]->[1];
my $distFL = sqrt($distX*$distX + $distY*$distY);
my $minDist = 0.01;
if($distFL < $minDist){
# tack start list on the end of the end list, remove start list
push(@{$contigLists[$#contigLists]}, @{shift @contigLists});
}
}
if (!(@oldPoints) || !(@{$contigLists[0]})) {
return ("");
}
# note: %f rounds to decimal places, %g rounds to significant figures
#my $printfString = ($dp > -1) ? ("%.".$dp."f,%.".$dp."f") : ("%f,%f");
my $printfString = ("%s,%s");
if($options->{"resolution"} != -1){
my $dp = int(-log($options->{"resolution"})/log(10))+2;
$printfString = ("%0.".$dp."f,%0.".$dp."f");
}
my @subPaths = ();
foreach (@contigLists) {
my @currentList = @{$_};
if(scalar(@currentList) > 1){ # ignore single-point subpaths
makeRelative($options, \@currentList);
my @pointStrs = map {
sprintf($printfString, ($_->[0]), ($_->[1]));
} @currentList;
my $subPath = "M".join("l",@pointStrs).($joinEnds?"Z":"");
$subPath =~ s/l0(\.0+)?,0(\.0+)?(?=[^\.])//g; # remove 'no change' relative movements
push(@subPaths, $subPath);
}
}
my $pointPath = join(" ", @subPaths);
return($pointPath);
}
my $mapType = "";
my $colourTheme = "";
my $centreCountry = "";
my $landColour = ""; # outside area (or default land colour)
my $seaColour = ""; # ocean / sea / lake
my $borderColour = "";
# Extra colours (only used if land/sea/border not specified)
my $subLandColour = ""; # subject colour
my $othLandColour = ""; # other lands of the same political unity
my $coastColour = ""; # coast along lake, rivers, sea coasts
my $polBordColour = ""; # Other minor political borders
my $intBordColour = ""; # border colour for areas of interest
my $printKey = 1; # true
my $latSep = 30; # separation (degrees) for lines of latitude
my $longSep = 30; # separation (degrees) for lines of longitude
my $latLimit = ""; # maximum latitude to display
my @dataFiles = (); # files containing numerical data
my %subjectNames = ();
my %politicalNames = ();
my %annotations = ();
my %onlyNames = ();
my %zoomNames = ();
my %zoomExtents = ();
my $debugLevel = 0;
my @shpFileBases = ();
my @commandLine = @ARGV;
# set default options
my $projOpts =
{
"roundDP" => -1,
"res" => -1,
"projection" => "", # map projection (equirectangular / orthographic)
"centreLn" => "", # projection centre X / longitude
"centreLt" => "", # projection centre Y / latitude
"svgWidth" => "", # width of SVG file, excluding padding
"svgHeight" => "", # height of SVG file, excluding padding
"xAdj" => 0, # X adjustment to fit in SVG bounds
"yAdj" => 0, # Y adjustment to fit in SVG bounds
"xScale" => "", # Scale factor of points (for zoom box)
"yScale" => "", # Scale factor of points (for zoom box)
"padding" => "", # amount of padding to add (for zoom box)
"highlights" => 1, # highlight small enclosed subject areas
"lines" => 1, # draw lines of latitude / longitude
"key" => 1, # print a key for the heatmap
};
GetOptions($projOpts, 'lines!', 'key!', 'highlights!', 'pointSize|psize=f', 'roundDP|round=i', 'resolution|res=f',
'centre|center=s',
'projection=s',
'zoomed|zoom=s@',
'colourTheme|color|colour=s', => \$colourTheme,
'v|verbose+', => \$debugLevel,
'mapType|type=s' => \$mapType,
'landcol=s' => \$landColour,
'seacol=s' => \$seaColour,
'bordcol=s' => \$borderColour,
'subjects|sub=s' => sub { my ($opt,$val) = @_;
grep {$subjectNames{$_} = 1} split(/,/, $val)},
'politicals|pol=s' => sub { my ($opt,$val) = @_;
grep {$politicalNames{$_} = 1} split(/,/, $val)},
'annotate=s' => sub { my ($opt,$val) = @_; my @F = split(/[;,]/, $val);
$annotations{$F[0]} = $F[1].",".$F[2]; },
'only=s' => sub { my ($opt,$val) = @_;
$onlyNames{$val} = 1},
'data=s@' => \@dataFiles,
'man' => sub { pod2usage({-verbose => 3}) }
);
# process remaining command line arguments (hopefully only shapefiles)
while (@ARGV) {
my $argument = shift @ARGV;
if (((-f $argument) && ($argument =~ /\.shp$/)) ||
(-f ($argument.".shp"))) { # file existence check
$argument =~ s/\.shp$//;
printf(STDERR "Adding '%s.shp' to list of input files\n", $argument)
if ($debugLevel > 0);
push (@shpFileBases, $argument);
} elsif (-f $argument) {
pod2usage({-exitVal => 2, -message => "Error: Invalid file extension for '$argument'. ".
"Please use files with '.shp' extension\n"});
} else {
pod2usage({-exitVal => 3, -message => "Error: Unknown command-line option or non-existent file, ".
"'$argument'\n", -verbose => 0});
}
}
if(($projOpts->{"resolution"} == -1) && ($projOpts->{"roundDP"} != -1)){
$projOpts->{"resolution"} = 10**(-$projOpts->{"roundDP"});
}
if($debugLevel > 0){
print(STDERR "Command-line options:\n");
foreach my $key (keys(%{$projOpts})){
if(ref($projOpts->{$key}) eq 'ARRAY'){
printf(STDERR " %s: %s\n", $key, join("; ", @{$projOpts->{$key}}));
} elsif($projOpts->{$key} ne "") {
printf(STDERR " %s: %s\n", $key, $projOpts->{$key});
}
}
}
if($projOpts->{"lines"}){
$projOpts->{"lines"} = 3;
}
if(scalar(@shpFileBases) == 0){
print(STDERR "Error: No input files specified\n");
pod2usage(2);
}
if(keys(%onlyNames)){
print(STDERR "Will only display the following features on the map:\n");
print(STDERR " ".join("\n ",keys(%onlyNames))."\n");
}
if(!$projOpts->{"highlights"}){
warn("Small points and areas will NOT be highlighted\n");
}
if(@dataFiles){
warn("Will extract numerical data (assuming <ISO 3A-code>,<float>) from the following files:\n");
foreach my $fName (@dataFiles){
warn(" $fName\n");
}
}
if($projOpts->{"zoomed"}){
my @zoomArgs = @{$projOpts->{"zoomed"}};
foreach my $newArg (@zoomArgs){
if ($newArg =~ /([0-9\.\-]+),([0-9\.\-]+),([0-9\.\-]+),([0-9\.\-]+)/) {
$projOpts->{"manualZoom"} = 1;
$projOpts->{"minX"} = $1;
$projOpts->{"minY"} = $2;
$projOpts->{"maxX"} = $3;
$projOpts->{"maxY"} = $4;
printf(STDERR "Setting initial zoom box to (%s,%s)-(%s,%s)\n",
$projOpts->{"minX"},$projOpts->{"minY"},
$projOpts->{"maxX"},$projOpts->{"maxY"});
} else {
print(STDERR "Zooming map to include '$newArg'\n");
grep {$zoomNames{$_} = 1} split(/,/, $newArg);
}
}
}
if($mapType !~ /^(location|locator|area|world|orthographic)$/){
pod2usage({ -exitval => 1, -message => "Error: '".$projOpts->{"mapType"}.
"' is not a valid map type. ".
"Only accepts '(location|locator|area|world|orthographic)'",
-verbose => 0});
}
if($projOpts->{"centre"}){
my $newArg = $projOpts->{"centre"};
if ($newArg =~ /^[0-9\.\-,]+$/) {
my @centre = split(/,/,$newArg,2);
$projOpts->{"centreLn"} = $centre[0];
$projOpts->{"centreLt"} = $centre[1];
printf(STDERR "Map centre changed to '%s,%s'\n",
$projOpts->{"centreLn"},
$projOpts->{"centreLt"});
} else {
$centreCountry = $newArg;
print(STDERR "Map centre changed to centre of country ".
"'$newArg' (if found)\n");
}
}
if ($mapType =~ /^(location|locator|area)/) {
$projOpts->{"projection"} = "equirectangular"
unless $projOpts->{"projection"};
$projOpts->{"svgWidth"} = 1100 unless $projOpts->{"svgWidth"};
$projOpts->{"svgHeight"} = 550 unless $projOpts->{"svgHeight"};
} elsif ($mapType =~ /^world/) {
# Winkel Tripel projection for world maps
$projOpts->{"projection"} = "wintri"
unless $projOpts->{"projection"};
$projOpts->{"svgWidth"} =
((4 + 2 * pi) / (2 * pi) * 550) unless $projOpts->{"svgWidth"};
$projOpts->{"svgHeight"} = 550 unless $projOpts->{"svgHeight"};
} elsif ($mapType =~ /^ortho(graphic)?/) {
# Orthographic projection for locator maps
$projOpts->{"projection"} = "orthographic"
unless $projOpts->{"projection"};
$projOpts->{"xScale"} = 1 unless $projOpts->{"xScale"};
$projOpts->{"yScale"} = 1 unless $projOpts->{"yScale"};
$projOpts->{"svgWidth"} = 550 unless $projOpts->{"svgWidth"};
$projOpts->{"svgHeight"} = 550 unless $projOpts->{"svgHeight"};
$projOpts->{"lines"} = 3 if ($projOpts->{"lines"});
}
# specify width / height if not modified by type definitions
$projOpts->{"pointSize"} = 0.5 unless $projOpts->{"pointSize"};
$projOpts->{"svgWidth"} = 1100 unless $projOpts->{"svgWidth"};
$projOpts->{"svgHeight"} = 1100 unless $projOpts->{"svgHeight"};
$projOpts->{"xScale"} = 1 unless $projOpts->{"xScale"};
$projOpts->{"yScale"} = 1 unless $projOpts->{"yScale"};
# adjustment allows for 1.5px border around SVG image
$projOpts->{"xAdj"} = $projOpts->{"svgWidth"} / 2 + 1.5;
$projOpts->{"yAdj"} = $projOpts->{"svgHeight"} / 2 + 1.5;
$projOpts->{"padding"} = 0 unless $projOpts->{"padding"};
$colourTheme = $mapType unless $colourTheme;
# protect user-specified land/sea/border colours
my $landColTemp = $landColour;
my $seaColTemp = $seaColour;
my $bordColTemp = $borderColour;
# default colours (a consensus of consensus colours, if you like)
$landColour = "#FEFEE9";
$borderColour = "#646464";
$seaColour = "#C6ECFF";
# set up colours for particular map types.
# location: used as backgrounds for automatic geo-localisation
# locator: display an article's subject area of occupation
# area: focus on group their respective area of control
# world: grey world map
# orthographic: grey/green orthographic map\n");
if ($colourTheme eq "location") {
$subLandColour = "#FEFEE9";
$othLandColour = "#F6E1B9";
$landColour = "#E0E0E0";
$borderColour = "#646464";
$seaColour = "#C6ECFF";
$coastColour = "#0978AB";
} elsif (($colourTheme eq "locator") || ($colourTheme eq "area")) {
$subLandColour = "#F07568";
$othLandColour = "#FFFFD0";
$landColour = "#F7D3AA";
$polBordColour = "#D0C0A0";
$intBordColour = "#E0584E";
$borderColour = "#A08070";
# assumed from locator map definition
$seaColour = "#9EC7F3";
$coastColour = "#1821DE";