forked from dankelley/oce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.R
3612 lines (3534 loc) · 156 KB
/
map.R
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
.axis <- local({
val <- list(longitude=NULL, latitude=NULL)
function(new) if (!missing(new)) val <<- new else val
})
.Projection <- local({
## Tave state, in a way that emulates mapproj.
## The 'type' can be 'none' or 'proj4' (previously, 'mapproj' was also allowed)
val <- list(type="none", projection="")
function(new) if (!missing(new)) val <<- new else val
})
#' Wrapper to rgdal::project()
#'
#' This function is used to isolate other oce functions from
#' changes to the [rgdal::project()] function in the \CRANpkg{rgdal}
#' package, which is used for calculations involved in both forward
#' and inverse map projections.
#'
#' Some highlights of the evolving relationship with rgdal are:
#' 1. See https://github.com/dankelley/oce/issues/653#issuecomment-107040093
#' for the reason why oce switched from using [rgdal::rawTransform()],
#' to [rgdal::project()], both functions provided by the
#' \CRANpkg{rgdal} package.
#' 2. 2016 Apr: rgdal::project started returning named quantities
#' 3. 2019 Feb: allowNAs_if_not_legacy was added in rgdal 1.3-9 to prevent
#' an error on i386/windows. However, using this argument imposes a
#' burden on users to update \CRANpkg{rgdal}, so the approach taken
#' here (by default, i.e. with `passNA=FALSE`) is to
#' temporarily switch NA data to 0, and then switch
#' back to NA after the calculation.
#'
#' @param xy,proj,inv,use_ob_tran,legacy As for the [rgdal::project()] function in the
#' \CRANpkg{rgdal} package.
#'
#' @param passNA Logical value indicating whether to pass NA values into
#' \CRANpkg{rgdal}. The default is `FALSE`, meaning that any NA
#' values are first converted to 0 before the calculation, and then
#' converted to NA afterwards. Setting this to `TRUE` produces
#' errors on the i386/windows platform, but it seems likely that a version
#' of \CRANpkg{rgdal} released after 1.3-9 may not have that error.
#'
#' @return A two-column matrix, with first column holding either
#' `longitude` or `x`, and second column holding either
#' `latitude` or `y`.
oceProject <- function(xy, proj, inv=FALSE, use_ob_tran=FALSE, legacy=TRUE, passNA=FALSE)
{
if (!requireNamespace("rgdal", quietly=TRUE))
stop('must install.packages("rgdal") to do map projections')
owarn <- options()$warn # this, and the capture.output, quieten the processing
options(warn=-1)
if (passNA) {
na <- which(is.na(xy[,1]))
xy[na, ] <- 0
capture.output(
{
XY <- unname(rgdal::project(xy, proj=proj, inv=inv))
}
)
XY[na, ] <- NA
} else {
if (.Platform$OS.type == "windows" && .Platform$r_arch == "i386") {
if (packageVersion("rgdal") < "1.3.9")
stop("rgdal must be at least version 1.3.9, on i386/windows platforms")
capture.output(
{
XY <- unname(rgdal::project(xy, proj=proj, inv=inv, legacy=legacy, allowNAs_if_not_legacy=TRUE))
}
)
} else {
capture.output(
{
XY <- unname(rgdal::project(xy=xy, proj=proj, inv=inv, legacy=legacy))
}
)
}
}
options(warn=owarn)
XY
}
#' Calculate lon-lat coordinates of plot-box trace
#'
#' Trace along the plot box, converting from xy coordinates to lonlat
#' coordinates. The results are used by [mapGrid()]
#' and [mapAxis()] to ignore out-of-frame grid
#' lines and axis labels.
#'
#' Note: this procedure does not work for projections that have trouble
#' inverting points that are "off the globe". For this reason, this function
#' examines .Projection()$projection and if it contains the string
#' `"wintri"`, then the above-stated procedure is skipped, and
#' the return value has each of the numerical quantities set to `NA`,
#' and `ok` set to `FALSE`.
#'
#' @param n number of points to check along each side of the plot box
#' @template debugTemplate
#'
#' @return a list containing `lonmin`, `lonmax`,
#' `latmin`, `latmax`, and `ok`; the last
#' of which indicates whether at least one point on the plot box
#' is invertible. Note that longitude are expressed in the
#' range from -180 to 180 degrees.
#'
#' @author Dan Kelley
#'
#' @family functions related to maps
usrLonLat <- function(n=25, debug=getOption("oceDebug"))
{
oceDebug(debug, "usrLonLat(n=", n, ", debug=", debug, "\n", unindent=1, sep="")
usr <- par("usr")
oceDebug(debug, "usr=", paste(usr, collapse=" "), "\n", sep="")
if (length(grep("wintri", .Projection()$projection)))
return(list(lonmin=NA, lonmax=NA, latmin=NA, latmax=NA, ok=FALSE))
x <- c(seq(usr[1], usr[2], length.out=n),
rep(usr[2], n),
seq(usr[2], usr[1], length.out=n),
rep(usr[1], n))
y <- c(rep(usr[3], n),
seq(usr[3], usr[4], length.out=n),
rep(usr[4], n),
seq(usr[4], usr[3], length.out=n))
g <- expand.grid(x=seq(usr[1], usr[2], length.out=n),
y=seq(usr[3], usr[4], length.out=n))
x <- g$x
y <- g$y
## if (debug > 2)
## points(x, y, pch=20, cex=3, col=2)
oceDebug(debug, "about to call map2lonlat\n")
ll <- map2lonlat(x, y)
nok <- sum(is.finite(ll$longitude))
## Convert -Inf and +Inf to NA
oceDebug(debug, "DONE with call map2lonlat\n")
bad <- !is.finite(ll$longitude) | !is.finite(ll$latitude)
ll$longitude[bad] <- NA
ll$latitude[bad] <- NA
oceDebug(debug, "sum(bad)/length(bad)=", sum(bad)/length(bad), "\n", sep="")
if (debug > 2)
mapPoints(ll$longitude, ll$latitude, pch=20, cex=2, col=3)
lonmin <- if (any(is.finite(ll$longitude))) min(ll$longitude, na.rm=TRUE) else NA
lonmax <- if (any(is.finite(ll$longitude))) max(ll$longitude, na.rm=TRUE) else NA
latmin <- if (any(is.finite(ll$latitude))) min(ll$latitude, na.rm=TRUE) else NA
latmax <- if (any(is.finite(ll$latitude))) max(ll$latitude, na.rm=TRUE) else NA
## To simplify later use, put lon in range -180 to 180, and order if needed
lonmin <- min(lonmin, 180, na.rm=TRUE)
lonmin <- max(lonmin, -180, na.rm=TRUE)
lonmax <- min(lonmax, 180, na.rm=TRUE)
lonmax <- max(lonmax, -180, na.rm=TRUE)
if (!is.na(lonmin) && !is.na(lonmax)) {
if (lonmin > lonmax) {
tmp <- lonmin
lonmin <- lonmax
lonmax <- tmp
}
## special case: if we are showing more than half the earth, assume
## it's a global view, and extend accordingly
if ((lonmax - lonmin) > 180) {
lonmin <- -180
lonmax <- 180
latmin <- -90
latmax <- 90
}
}
oceDebug(debug, sprintf("lonmin=%.3f, lonmax=%.3f, latmin=%.3f, latmax=%.3f\n",
lonmin, lonmax, latmin, latmax))
oceDebug(debug, "nok=", nok, ", n=", n, ", nok/n=", nok/n, "\n")
oceDebug(debug, "} # usrLonLat()\n", unindent=1)
rval <- list(lonmin=lonmin, lonmax=lonmax, latmin=latmin, latmax=latmax,
ok=nok/n>0.5&&is.finite(lonmin)&&is.finite(lonmax)&&is.finite(latmin)&&is.finite(latmax))
rval
}
#' Coordinate Reference System strings for some oceans
#'
#' Create a coordinate reference string (CRS), suitable for use as a
#' `projection` argument to [mapPlot()] or
#' [plot,coastline-method()].
#'
#' @section Caution: This is a preliminary version of this function,
#' with the results being very likely to change through the autumn of 2016,
#' guided by real-world usage.
#'
#' @param region character string indicating the region. This must be
#' in the following list (or a string that matches to just one entry,
#' with [pmatch()]):
#' `"North Atlantic"`, `"South Atlantic"`, `"Atlantic"`,
#' `"North Pacific"`, `"South Pacific"`, `"Pacific"`,
#' `"Arctic"`, and `"Antarctic"`.
#'
#' @return string contain a CRS, which can be used as `projection`
#' in [mapPlot()].
#'
#' @author Dan Kelley
#'
#' @family functions related to maps
#'
#' @examples
#'\donttest{
#' library(oce)
#' data(coastlineWorld)
#' par(mar=c(2, 2, 1, 1))
#' plot(coastlineWorld, proj=oceCRS("Atlantic"), span=12000)
#' plot(coastlineWorld, proj=oceCRS("North Atlantic"), span=8000)
#' plot(coastlineWorld, proj=oceCRS("South Atlantic"), span=8000)
#' plot(coastlineWorld, proj=oceCRS("Arctic"), span=4000)
#' plot(coastlineWorld, proj=oceCRS("Antarctic"), span=10000)
#' # Avoid ugly horizontal lines, an artifact of longitude shifting.
#' # Note: we cannot fill the land once we shift, either.
#' pacific <- coastlineCut(coastlineWorld, -180)
#' plot(pacific, proj=oceCRS("Pacific"), span=15000, col=NULL)
#' plot(pacific, proj=oceCRS("North Pacific"), span=12000, col=NULL)
#' plot(pacific, proj=oceCRS("South Pacific"), span=12000, col=NULL)
#'}
oceCRS <- function(region)
{
regionChoices <- c("North Atlantic", "South Atlantic", "Atlantic", "Arctic", "Antarctic",
"Pacific", "North Pacific", "South Pacific")
id <- pmatch(region, regionChoices)
if (is.na(id))
stop("region must be in \"", paste(regionChoices, collapse="\" \""), "\" but it is \"", region, "\"\n")
region <- regionChoices[id]
CRS <- if (region == "Atlantic") "+proj=laea +lon_0=-30 +lat_0=0"
else if (region == "North Atlantic") "+proj=laea +lon_0=-40 +lat_0=30"
else if (region == "South Atlantic") "+proj=laea +lon_0=-20 +lat_0=-30"
else if (region == "Arctic") "+proj=stere +lon_0=0 +lat_0=90"
else if (region == "Antarctic") "+proj=stere +lon_0=0 +lat_0=-90"
else if (region == "Pacific") "+proj=merc +lon_0=-180 +lat_0=0"
else if (region == "North Pacific") "+proj=robin +lon_0=-180 +lat_0=30"
else if (region == "South Pacific") "+proj=robin +lon_0=-180 +lat_0=-30"
else stop("unknown region")
CRS
}
#' Shift Longitude to Range -180 to 180
#'
#' This is a utility function used by [mapGrid()]. It works
#' simply by subtracting 180 from each longitude, if any longitude
#' in the vector exceeds 180.
#'
#' @param longitudes numerical vector of longitudes.
#'
#' @return vector of longitudes, shifted to the desired range.
#'
#' @seealso [matrixShiftLongitude()] and [standardizeLongitude()].
#'
#' @family functions related to maps
shiftLongitude <- function(longitudes) {
if (any(longitudes > 180)) longitudes-360 else longitudes
}
fixneg <- function(v)
{
res <- v
for (i in seq_along(v)) {
if (res[i] == "0N") {
res[i] <- "0"
} else if (res[i] == "0E") {
res[i] <- "0"
} else if ("-" == substr(v[i], 1, 1)) {
##cat("res[i]=", res[i], "\n")
res[i] <- gsub("^-", "", v[i])
res[i] <- gsub("E", "W", res[i])
res[i] <- gsub("N", "S", res[i])
##cat(" -> res[i]=", res[i], "\n")
}
}
res
}
badFillFix1 <- function(x, y, latitude, projection="")
{
##xrange <- range(x, na.rm=TRUE)
##yrange <- range(y, na.rm=TRUE)
n <- length(x)
## 1181 necessitated this use of n>100 (it was a case of 3 isolated islands)
if (n > 100) { # avoid getting confused by e.g. a view with two islands
## FIXME: below is a kludge to avoid weird horiz lines; it
## FIXME: would be better to complete the polygons, so they
## FIXME: can be filled. It might be smart to do this in C
d <- c(0, sqrt(diff(x)^2 + diff(y)^2))
d[!is.finite(d)] <- 0 # FIXME: ok?
##dc <- as.numeric(quantile(d, 1-100*(1/3/length(x)), na.rm=TRUE)) # FIXME: criterion
##bad <- d > dc
##bad <- 0.1 < (d / diff(range(x, na.rm=TRUE)))
antarctic <- latitude < -60
bad <- ( (d / diff(range(x, na.rm=TRUE))) > 0.1 ) & !antarctic
## if (length(options("oce1181")[[1]])) browser()
## FIXME: this should finish off polygons, but that is a bit tricky, e.g.
## FIXME: should we create a series of points to a trace along the edge
## FIXME: the visible earth?
x[bad] <- NA
y[bad] <- NA
}
bad2 <- !is.finite(x) | !is.finite(y)
x[bad2] <- NA
y[bad2] <- NA
list(x=x, y=y)
}
badFillFix2 <- function(x, y, xorig, yorig)
{
usr <- par("usr")
w <- which(is.na(xorig))
if (length(w) > 1) {
for (iw in seq(1, -1+length(w))) {
##message("check chunk", iw)
look <- seq.int(w[iw]+1, w[iw+1]-1)
xl <- xorig[look]
yl <- yorig[look]
offscale <- yl < usr[3] | xl < usr[1] | yl > usr[4] | xl > usr[2]
offscale <- offscale[is.finite(offscale)]
if (all(offscale)) {
## probably faster to do this than to make new vectors
##message(" TRIM")
x[look] <- NA
y[look] <- NA
}
}
}
list(x=x, y=y)
}
#' Add Axis Labels to an Existing Map
#'
#' Plot axis labels on an existing map.
#'
#' @param side the side at which labels are to be drawn. If not provided,
#' sides 1 and 2 will be used (i.e. bottom and left-hand sides).
#'
#' @param longitude either a logical value or a numeric vector of longitudes. There
#' are three possible cases:
#' (1) If `longitude=TRUE` (the default) then ticks and nearby numbers will occur at the
#' longitude grid established by the previous call to [mapPlot()];
#' (2) if `longitude=FALSE` then no longitude ticks or numbers are
#' drawn;
#' (3) if `longitude` is a vector of numerical values, then those ticks
#' are placed at those values, and numbers are written beside them.
#' Note that in cases 1 and 3, efforts are made to avoid overdrawing text,
#' so some longitude values might get ticks but not numbers. To get ticks
#' but not numbers, set `cex.axis=0`.
#'
#' @param latitude similar to `longitude` but for latitude.
#'
#' @param tick parameter passed to [axis()].
#'
#' @param line parameter passed to [axis()].
#'
#' @param pos parameter passed to [axis()].
#'
#' @param outer parameter passed to [axis()].
#'
#' @param font axis font, passed to [axis()].
#'
#' @param lty axis line type, passed to [axis()].
#'
#' @param lwd axis line width, passed to [axis()]).
#'
#' @param lwd.ticks tick line width, passed to [axis()].
#'
#' @param col axis color, passed to [axis()].
#'
#' @param col.ticks axis tick color, passed to [axis()].
#'
#' @param hadj an argument that is transmitted to [axis()].
#'
#' @param padj an argument that is transmitted to [axis()].
#'
#' @param tcl axis-tick size (see [par()]).
#'
#' @param cex.axis axis-label expansion factor (see [par()]); set to 0
#' to prevent numbers from being placed in axes.
#'
#' @param mgp three-element numerical vector describing axis-label
#' placement (see [par()]). It usually makes sense to set
#' the first and third elements to zero.
#'
#' @param debug a flag that turns on debugging. Set to 1 to get a moderate
#' amount of debugging information, or to 2 to get more.
#'
#' @details
#' This function is still in development, and the argument list as well as the
#' action taken are both subject to change, hence the brevity of this help page.
#'
#' Note that if a grid line crosses the axis twice, only one label will be drawn.
#'
#' @examples
#'\donttest{
#' library(oce)
#' data(coastlineWorld)
#' par(mar=c(2, 2, 3, 1))
#' lonlim <- c(-180, 180)
#' latlim <- c(60, 120)
#' mapPlot(coastlineWorld, projection="+proj=stere +lat_0=90",
#' longitudelim=lonlim, latitudelim=latlim,
#' grid=FALSE)
#' mapGrid(15, 15, polarCircle=1/2)
#' mapAxis()
#'}
#'
#' @author Dan Kelley
#'
#' @seealso A map must first have been created with [mapPlot()].
#'
#' @family functions related to maps
mapAxis <- function(side=1:2, longitude=TRUE, latitude=TRUE,
tick=TRUE, line=NA, pos=NA, outer=FALSE, font=NA,
lty="solid", lwd=1, lwd.ticks=lwd, col=NULL, col.ticks=NULL,
hadj=NA, padj=NA, tcl=-0.3, cex.axis=1,
mgp=c(0, 0.5, 0),
debug=getOption("oceDebug"))
{
if ("none" == .Projection()$type)
stop("must create a map first, with mapPlot()\n")
oceDebug(debug, "mapAxis(side=c(", paste(side, collapse=","), ")",
", longitude=", if (length(longitude)) c(longitude[1], "...") else "NULL",
", latitude=", if (length(latitude)) c(latitude[1], "...") else "NULL",
") { \n", unindent=1, sep="")
boxLonLat <- usrLonLat()
axis <- .axis()
#if (debug > 0) print(axis)
if (is.logical(longitude) && !longitude && is.logical(latitude) && !latitude) {
oceDebug(debug, "longitude=latitude=FALSE, so not drawing axes\n")
return()
}
if (is.logical(longitude) && longitude[1]) {
longitude <- axis$longitude
oceDebug(debug, "autosetting to", vectorShow(longitude))
}
if (is.logical(latitude) && latitude[1]) {
latitude <- axis$latitude
oceDebug(debug, "autosetting to", vectorShow(latitude))
}
oceDebug(debug, "mapAxis: initially, ", vectorShow(longitude))
if (boxLonLat$ok) {
ok <- boxLonLat$lonmin <= longitude & longitude <= boxLonLat$lonmax
longitude <- longitude[ok]
}
oceDebug(debug, "mapAxis: after box-trimming, ", vectorShow(longitude))
oceDebug(debug, "mapAxis: initially, ", vectorShow(latitude))
if (boxLonLat$ok) {
ok <- boxLonLat$latmin <= latitude & latitude <= boxLonLat$latmax
latitude <- latitude[ok]
}
oceDebug(debug, "mapAxis: after box-trimming, ", vectorShow(latitude))
## if (is.null(axis$longitude)) oceDebug(debug, "should auto generate longitude grid and then axis\n")
## if (is.null(axis$latitude)) oceDebug(debug, "should auto generate latitude grid and then axis\n")
## if (missing(longitude)) longitude <- axis$longitude
## if (missing(latitude)) latitude <- axis$latitude
if (missing(side))
side <- 1:2
usr <- par('usr')
axisSpan <- max(usr[2]-usr[1], usr[4]-usr[3])
if (1 %in% side) {
oceDebug(debug, "drawing axis on side 1\n")
AT <- NULL
LAB <- NULL
for (lon in longitude) {
if (debug > 3) oceDebug(debug, "check longitude", lon, "for axis on side=1\n")
## Seek a point at this lon that matches the lon-lat relationship on side=1
o <- optimize(function(lat) abs(lonlat2map(lon, lat)$y-usr[3]), lower=-89.9999, upper=89.9999)
if (is.na(o$objective) || o$objective > 0.01*axisSpan) {
if (debug > 3) oceDebug(debug, " longitude", lon, "is unmappable\n")
next
}
## Check that the point matches lat, as well as lon (this matters for full-globe)
P <- lonlat2map(lon, o$minimum)
## oceDebug(debug, "Investigate point at x=", P$x, ", y=", P$y, "; note usr[3]=", usr[3], "\n")
x <- P$x
if (is.finite(P$y) && (abs(P$y - usr[3]) < 0.01 * (usr[4] - usr[3]))) {
if (!is.na(x) && usr[1] < x && x < usr[2]) {
label <- fixneg(paste(lon, "E", sep=""))
##mtext(label, side=1, at=x)
AT <- c(AT, x)
LAB <- c(LAB, label)
if (debug > 3) oceDebug(debug, " ", label, "intersects side 1\n")
} else {
if (debug > 3) oceDebug(debug, " ", lon, "E does not intersect side 1\n")
}
} else {
## oceDebug(debug, "skipping off-globe point\n")
}
}
if (!is.null(AT)) {
## prevent calling axis() with cex.axis=0, by just giving empty labels then
oceDebug(debug, "calling axis(1) with cex.axis=", cex.axis, "\n")
axis(side=1, at=AT, labels=if (cex.axis>0) fixneg(LAB) else rep("", length(AT)),
mgp=mgp, tick=tick, line=line, pos=pos, outer=outer, font=font,
lty=lty, lwd=lwd, lwd.ticks=lwd.ticks, col=col, col.ticks=col.ticks,
hadj=hadj, padj=padj, tcl=tcl, cex.axis=if (cex.axis>0) cex.axis else 1)
}
if (length(latitude)) {
warning("mapAxis(side=1) cannot draw latitude labels yet; contact author if you need this")
}
}
if (2 %in% side) {
oceDebug(debug, "drawing axis on side 2\n")
AT <- NULL
LAB <- NULL
f <- function(lon) lonlat2map(lon, lat)$x-usr[1]
## FIXME: if this uniroot() method looks good for side=2, try for side=1 also.
LONLIST <- seq(-360, 360, 20) # smaller increments are slower but catch more labels
oceDebug(debug, paste("LONLIST=", paste(LONLIST, collapse=" "), "\n"))
for (lat in latitude) {
if (debug > 3)
oceDebug(debug, "check ", lat, "N for axis on side=2 (usr[1]=", usr[1], ")\n", sep="")
## Seek a point at this lon that matches the lon-lat relationship on side=1
## FIXME: I wonder why I don't use the optimize() method that I use for side=1 here
## as well. Maybe I ought to try both. I sort of think this bracket-uniroot method
## is best, but note that issue 1349 was because I had the `tol` in the `uniroot`
## set to 1deg, which was nutty.
for (iLON in 2:length(LONLIST)) {
#if (lat == 55) browser()
LONLOOK <- LONLIST[iLON+c(-1, 0)]
##cat("f(LONLOOK[1]=", LONLOOK[1], "=", LONLOOK[1]+360, ")= ", f(LONLOOK[1]), " (iLON=", iLON, ")\n")
##cat("f(LONLOOK[2]=", LONLOOK[2], "=", LONLOOK[2]+360, ")= ", f(LONLOOK[2]), " (iLON=", iLON, ")\n")
f1 <- f(LONLOOK[1])
if (!is.finite(f1))
next
f2 <- f(LONLOOK[2])
if (!is.finite(f2)) {
##cat("f2 not finite, so skipping\n")
next
}
if (f1 * f2 > 0) {
##cat("f1*f2 > 0, so skipping\n")
next
}
##cat(" looking promising LONLOOK[1]=", LONLOOK[1], ", LONLOOK[2]=", LONLOOK[2], "; r follows\n")
r <- uniroot(f, lower=LONLOOK[1], upper=LONLOOK[2], tol=0.001) # 0.001deg < 100m.
##print(r)
P <- lonlat2map(r$root, lat)
##OLD| ## using optimize. This seems slower, and can hit boundaries.
##OLD| o <- optimize(function(lon) abs(lonlat2map(lon, lat)$x-usr[1]), lower=LONLOOK[1], upper=LONLOOK[2], tol=1)
##OLD| if (is.na(o$objective) || o$objective > 0.01*axisSpan) {
##OLD| if (debug > 3) oceDebug(debug, " ", lat, "N is unmappable for iLON=", iLON, "; o$objective=", o$objective, "\n", sep="")
##OLD| next
##OLD| }
##OLD| # Check that the point matches lat, as well as lon (this matters for full-globe)
#P <- lonlat2map(o$minimum, lat)
y <- P$y
if (is.finite(P$x) && (abs(P$x - usr[1]) < 0.01 * (usr[2] - usr[1]))) {
if (!is.na(y) && usr[3] < y && y < usr[4]) {
label <- fixneg(paste(lat, "N", sep=""))
AT <- c(AT, y)
LAB <- c(LAB, label)
if (debug > 3) oceDebug(debug, " ", label, " intersects side 2\n", sep="")
} else {
if (debug > 3) oceDebug(debug, " ", lat, "N does not intersect side 2\n", sep="")
}
} else {
##oceDebug(debug, "skipping off-globe point\n")
}
}
}
#browser()
if (!is.null(AT)) {
oceDebug(debug, "calling axis(2) with cex.axis=", cex.axis, "\n")
## prevent calling axis() with cex.axis=0, by just giving empty labels then
axis(side=2, at=AT, labels=if (cex.axis>0) fixneg(LAB) else rep("", length(AT)),
mgp=mgp, tick=tick, line=line, pos=pos, outer=outer, font=font,
lty=lty, lwd=lwd, lwd.ticks=lwd.ticks, col=col, col.ticks=col.ticks,
hadj=hadj, padj=padj, tcl=tcl, cex.axis=if (cex.axis>0) cex.axis else 1)
}
if (length(longitude)) {
warning("mapAxis(side=2) cannot draw longitude labels yet; contact author if you need this")
}
}
if (3 %in% side) {
oceDebug(debug, "drawing axis on side 3 NOT CODED YET\n")
}
if (4 %in% side) {
oceDebug(debug, "drawing axis on side 4 NOT CODED YET\n")
}
oceDebug(debug, "} # mapAxis()\n", unindent=1)
}
#' Add Contours on a Existing map
#'
#' Plot contours on an existing map.
#'
#' @param longitude numeric vector of longitudes of points to be plotted, or an object of
#' class `topo` (see [topo-class]), in which case
#' `longitude`, `latitude` and `z` are inferred from that object.
#'
#' @param latitude numeric vector of latitudes of points to be plotted.
#'
#' @param z matrix to be contoured. The number of rows and columns in `z`
#' must equal the lengths of `longitude` and `latitude`, respectively.
#'
#' @param nlevels number of contour levels, if and only if `levels` is not supplied.
#'
#' @param levels vector of contour levels.
#'
#' @param labcex `cex` value used for contour labelling. As with
#' [contour()], this is an absolute size, not a multiple of
#' [`par`]`("cex")`.
#'
#' @param drawlabels logical value or vector indicating whether to draw contour
#' labels. If the length of `drawlabels` is less than the number of
#' levels specified, then [rep()] is used to increase the length,
#' providing a value for each contour line. For those levels that are thus
#' indicated, labels are added, at a spot where the contour line is
#' closest to horizontal on the page. First, though, the region underneath
#' the label is filled with the colour given by [`par`]`("bg")`.
#' See \dQuote{Limitations} for notes on the status of contour
#' labelling, and its limitations.
#'
#' @param underlay character value relating to handling labels. If
#' this equals `"erase"` (which is the default), then the contour line
#' is drawn first, then the area under the label is erased (filled with
#' white 'ink'), and then the label is drawn. This can be useful
#' in drawing coarsely-spaced labelled contours on top of finely-spaced
#' unlabelled contours. On the othr hand, if `underlay` equals
#' `"interrupt"`, then the contour line is interrupted in the
#' region of the label, which is closer to the scheme used by the
#' base [contour()] function.
#'
#' @param col colour of the contour line, as for [`par`]`("col")`,
#' except here `col` gets lengthened by calling [rep()],
#' so that individual contours can be coloured distinctly.
#'
#' @param lty type of the contour line, as for [`par`]`("lty")`,
#' except for lengthening, as described for `col`.
#'
#' @param lwd width of the contour line, as for [`par`]`("lwd")`,
#' except for lengthening, as described for `col` and `lty`.
#'
#' @template debugTemplate
#'
#' @details
#' Adds contour lines to an existing map, using [mapLines()].
#'
#' The ability to label the contours was added in February, 2019, and
#' how this works may change through the summer months of that year.
#' Note that label placement in `mapContour` is handled differently
#' than in [contour()].
#'
#' @examples
#'\donttest{
#' library(oce)
#' data(coastlineWorld)
#' if (requireNamespace("ocedata", quietly=TRUE)) {
#' data(levitus, package="ocedata")
#' par(mar=rep(1, 4))
#' mapPlot(coastlineWorld, projection="+proj=robin", col="lightgray")
#' mapContour(levitus[['longitude']], levitus[['latitude']], levitus[['SST']])
#' }
#'}
#'
#' @author Dan Kelley
#'
#' @seealso A map must first have been created with [mapPlot()].
#' @family functions related to maps
mapContour <- function(longitude, latitude, z,
nlevels=10, levels=pretty(range(z, na.rm=TRUE), nlevels),
##labels=null,
##xlim=range(longitude, finite=TRUE),
#ylim=range(latitude, finite=TRUE),
labcex=0.6,
drawlabels=TRUE,
underlay="erase",
##vfont,
## axes=TRUE, frame.plot=axes,
col=par("fg"), lty=par("lty"), lwd=par("lwd"),
debug=getOption("oceDebug"))
{
oceDebug(debug, "mapContour() {\n", sep="", unindent=1)
if ("none" == .Projection()$type)
stop("must create a map first, with mapPlot()\n")
if (missing(longitude))
stop("must supply longitude")
if ("data" %in% slotNames(longitude) && # handle e.g. 'topo' class
3 == sum(c("longitude", "latitude", "z") %in% names(longitude@data))) {
z <- longitude@data$z
latitude <- longitude@data$latitude
longitude <- longitude@data$longitude
}
if (missing(latitude))
stop("must supply latitude")
if (missing(z))
stop("must supply z")
if (!underlay %in% c("erase", "interrupt"))
stop("underlay must be \"erase\" or \"interrupt\"")
if (underlay == "interrupt" && !requireNamespace("sp", quietly=TRUE))
stop("must have \"sp\" package available for underlay=\"interupt\"")
if ("data" %in% slotNames(longitude) && # handle e.g. 'topo' class
3 == sum(c("longitude", "latitude", "z") %in% names(longitude@data))) {
z <- longitude@data$z
latitude <- longitude@data$latitude
longitude <- longitude@data$longitude
}
nlevels <- length(levels)
col <- rep(col, nlevels)
lty <- rep(lty, nlevels)
lwd <- rep(lwd, nlevels)
drawlabels <- rep(drawlabels, nlevels)
labcex <- rep(labcex, nlevels)
xx <- seq_along(longitude)
yy <- seq_along(latitude)
if (length(xx) > 1 && diff(longitude[1:2]) < 0) {
xx <- rev(xx)
z <- z[xx, ]
##cat("flipped in x\n")
}
if (length(yy) > 1 && diff(latitude[1:2]) < 0) {
yy <- rev(yy)
z <- z[, yy]
##cat("flipped in y\n")
}
colUnderLabel <- "white" # use a variable in case we want to add as an arg
for (ilevel in 1:nlevels) {
oceDebug(debug, "contouring at level ", levels[ilevel], "\n")
label <- as.character(levels[ilevel]) # ignored unless drawlabels=TRUE
w <- 1.0*strwidth(levels[ilevel], "user", cex=labcex) # ignored unless drawlabels=TRUE
h <- 1.0*strheight(label, "user", cex=labcex) # ignored unless drawlabels=TRUE
oceDebug(debug > 1, "w=", w, ", h=", h, "\n")
cl <- contourLines(x=longitude[xx],
y=latitude[yy],
z=z, levels=levels[ilevel])
if (length(cl) > 0) {
for (i in seq_along(cl)) {
oceDebug(debug > 1, "segment number=i=", i, "; level=", levels[ilevel], "\n")
xy <- lonlat2map(cl[[i]]$x, cl[[i]]$y)
xc <- xy$x
yc <- xy$y
nc <- length(xc)
if (drawlabels[ilevel]) {
slopeMin <- 9999999 # big
slopeMinj <- NULL
slopeMinj2 <- NULL
canlabel <- FALSE
for (j in 1:nc) {
j2 <- j
while (j2 < nc) {
dy <- yc[j2] - yc[j]
dx <- xc[j2] - xc[j]
dist <- sqrt(dx^2 + dy^2)
if (dist > 1.4 * w && dx != 0.0) {
oceDebug(debug > 2, "enough space at j=",j,", j2=", j2, "\n")
slope <- dy / dx
if (abs(slope) < slopeMin) {
slopeMin <- abs(slope)
slopeMinj <- j
slopeMinj2 <- j2
canlabel <- TRUE
}
break
}
j2 <- j2 + 1
}
}
if (canlabel) {
labelj <- floor(0.5 + 0.5*(slopeMinj + slopeMinj2))
angle <- atan2(yc[slopeMinj2]-yc[slopeMinj], xc[slopeMinj2]-xc[slopeMinj])
oceDebug(debug > 1,
sprintf("j=%d j2=%d slopeMin=%.3g slopeMinj=%d slopeMinj2=%d\n",
j, j2, slopeMin, slopeMinj, slopeMinj2))
if (debug > 2) {
points(xc[slopeMinj], yc[slopeMinj], col="darkgreen", pch=20)
points(xc[slopeMinj2], yc[slopeMinj2], col="red", pch=20)
points(xc[labelj], yc[labelj], col="blue", pch=20) # centre
}
if (angle > pi/2 || angle < -pi/2)
angle <- angle + pi
oceDebug(debug, sprintf("step 2: label='%s' x=%.2g y=%.2g angle=%.9g deg\n",
label, xc[labelj], yc[labelj], angle*180/pi))
S <- sin(-angle)
C <- cos(-angle)
rot <- matrix(c(C, -S, S, C), byrow=TRUE, nrow=2)
X <- c(-w/2, -w/2, w/2, w/2)
Y <- c(-h/2, h/2, h/2, -h/2)
XY <- cbind(X, Y)
XYrot <- XY %*% rot
if (underlay == "erase") {
lines(xc, yc, lwd=lwd[ilevel], lty=lty[ilevel], col=col[ilevel])
polygon(xc[labelj]+XYrot[,1], yc[labelj]+XYrot[,2],
col=colUnderLabel, border=colUnderLabel)
} else if (underlay == "interrupt") {
erase <- 1==sp::point.in.polygon(xc, yc,
xc[labelj]+XYrot[,1], yc[labelj]+XYrot[,2])
polyx <- xc[labelj] + XYrot[,1]
polyy <- yc[labelj] + XYrot[,2]
polyNew <- sf::st_polygon(list(outer=cbind(c(polyx, polyx[1]), c(polyy, polyy[1]))))
pointsNew <- sf::st_multipoint(cbind(xc, yc))
insideNew <- sf::st_intersection(pointsNew, polyNew)
tmpMatrix <- matrix(pointsNew %in% insideNew, ncol=2)
eraseNew <- tmpMatrix[,1] & tmpMatrix[,2] # could also use an apply op, but this is simple
##eraseOld <- erase
if (!isTRUE(all.equal(eraseNew, erase))) {
warning("mapContour() error: 'erase' disagreement with trial 'sf' method. Please post an issue on www.github.com/dankelley/oce/issues\n")
}
oceDebug(debug, "ignoring", sum(erase), "points under", label, "contour\n")
XC <- xc
YC <- yc
XC[erase] <- NA
YC[erase] <- NA
lines(XC, YC, lwd=lwd[ilevel], lty=lty[ilevel], col=col[ilevel])
} else {
stop("cannot have underlay=\"", underlay, "\"; please report as a bug")
}
text(xc[labelj], yc[labelj], label, col=col[ilevel],
srt=angle*180/pi, cex=labcex[ilevel])
} else {
lines(xc, yc, lwd=lwd[ilevel], lty=lty[ilevel], col=col[ilevel])
}
} else {
lines(xc, yc, lwd=lwd[ilevel], lty=lty[ilevel], col=col[ilevel])
}
}
}
}
oceDebug(debug, "} # mapContour()\n", sep="", unindent=1)
}
#' Draw a coordinate system
#'
#' Draws arrows on a map to indicate a coordinate system, e.g. for an
#' to indicate a coordinate system set up so that one axis is parallel
#' to a coastline.
#'
#' This is a preliminary version of this function. It only
#' works if the lines of constant latitude are horizontal on the plot.
#'
#' @param longitude numeric vector of longitudes in degrees.
#'
#' @param latitude numeric vector of latitudes in degrees.
#'
#' @param L axis length in km.
#'
#' @param phi angle, in degrees counterclockwise, that the "x" axis makes to a line of latitude.
#'
#' @param ... plotting arguments, passed to [mapArrows()];
#' see \dQuote{Examples} for how to control the arrow-head size.
#'
#' @examples
#'\donttest{
#' library(oce)
#' if (requireNamespace("ocedata", quietly=TRUE)) {
#' data(coastlineWorldFine, package='ocedata')
#' HfxLon <- -63.5752
#' HfxLat <- 44.6488
#' mapPlot(coastlineWorldFine, proj='+proj=merc',
#' longitudelim=HfxLon+c(-2,2), latitudelim=HfxLat+c(-2,2),
#' col='lightgrey')
#' mapCoordinateSystem(HfxLon, HfxLat, phi=45, length=0.05)
#' }
#'}
#'
#' @author Chantelle Layton
#'
#' @family functions related to maps
mapCoordinateSystem <- function(longitude, latitude, L=100, phi=0, ...)
{
if (missing(longitude))
stop('must supply longitude')
if (missing(latitude))
stop('must supply latitude')
R <- 6371
pi <- 4 * atan2(1, 1)
phirad <- phi*pi/180 + c(0, pi/2)
kmperlon <- pi*R*cos(latitude*pi/180)/180
kmperlat <- pi*R/180
dx <- L*cos(phirad)
dy <- L*sin(phirad)
dlon <- dx/kmperlon
dlat <- dy/kmperlat
lonend <- longitude + dlon
latend <- latitude + dlat
mapArrows(longitude, latitude, lonend[1], latend[1], ...)
mapArrows(longitude, latitude, lonend[2], latend[2], ...)
}
#' Add a Direction Field to an Existing Map
#'
#' Plot a direction field on a existing map.
#'
#' Adds arrows for a direction field on an existing map. There are different
#' possibilities for how `longitude`, `latitude` and `u` and
#' `v` match up. In one common case, all four of these are matrices, e.g.
#' output from a numerical model. In another, `longitude` and
#' `latitude` are the coordinates along the matrices, and are thus stored in
#' vectors with lengths that match appropriately.
#'
#' @param longitude,latitude numeric vectors of the starting points for arrows.
#'
#' @param u,v numeric vectors of the components of a vector to be shown as a direction
#' field.
#'
#' @param scale latitude degrees per unit of `u` or `v`.
#'
#' @param length length of arrow heads, passed to [arrows()].
#'
#' @param code code of arrows, passed to [arrows()].
#'
#' @param col color of arrows. This may be a single color, or a matrix
#' of colors of the same dimension as `u`.
#'
#' @param \dots optional arguments passed to [arrows()], e.g.
#' `angle` and `lwd` can be useful in differentiating different
#' fields.
#'
#' @examples
#'\donttest{
#' library(oce)
#' data(coastlineWorld)
#' par(mar=rep(2, 4))
#' mapPlot(coastlineWorld, longitudelim=c(-120,-55), latitudelim=c(35, 50),
#' proj="+proj=laea +lat0=40 +lat1=60 +lon_0=-110")
#' lon <- seq(-120, -60, 15)
#' lat <- 45 + seq(-15, 15, 5)
#' lonm <- matrix(expand.grid(lon, lat)[, 1], nrow=length(lon))
#' latm <- matrix(expand.grid(lon, lat)[, 2], nrow=length(lon))
#' ## vectors pointed 45 degrees clockwise from north
#' u <- matrix(1/sqrt(2), nrow=length(lon), ncol=length(lat))
#' v <- matrix(1/sqrt(2), nrow=length(lon), ncol=length(lat))
#' mapDirectionField(lon, lat, u, v, scale=3)
#' mapDirectionField(lonm, latm, 0, 1, scale=3, col='red')
#' # Color code by longitude, using thick lines
#' col <- colormap(lonm)$zcol
#' mapDirectionField(lonm, latm, 1, 0, scale=3, col=col, lwd=2)
#'}
#'
#' @author Dan Kelley
#'
#' @seealso A map must first have been created with [mapPlot()].
#'
#' @family functions related to maps
mapDirectionField <- function(longitude, latitude, u, v,
scale=1, length=0.05, code=2, col=par("fg"), ...)
{
if ("none" == .Projection()$type)
stop("must create a map first, with mapPlot()\n")
## handle case where lon and lat are coords on edges of grid
if (is.matrix(u)) {
if (is.vector(longitude) && is.vector(latitude)) {
nlon <- length(longitude)
nlat <- length(latitude)
longitude <- matrix(rep(longitude, nlat), nrow=nlon)
latitude <- matrix(rep(latitude, nlon), byrow=TRUE, nrow=nlon)
}
}
xy <- lonlat2map(longitude, latitude)
## Calculate spatially-dependent scale (fails for off-page points)
## Calculate lon-lat at ends of arrows
scalex <- scale / cos(pi * latitude / 180)
latEnd <- latitude + v * scale
lonEnd <- longitude + u * scalex
xy <- lonlat2map(longitude, latitude)
xyEnd <- lonlat2map(lonEnd, latEnd)
arrows(xy$x, xy$y, xyEnd$x, xyEnd$y, length=length, code=code, col=col, ...)
}
#' Convert From Longitude and Latitude to X and Y
#'
#' Find (x, y) values corresponding to (longitude, latitude) values, using the
#' present projection.
#'
#'
#' @param longitude numeric vector of the longitudes of points, or an object from which
#' both latitude and longitude can be inferred (e.g. a coastline file, or the
#' return value from [mapLocator()]), in which case the following
#' two arguments are ignored.
#'
#' @param latitude numeric vector of latitudes of points, needed only if they cannot
#' be inferred from the first argument.
#'
#' @details
#' This is mainly a wrapper around [lonlat2map()].
#'
#' @return
#' A list containing `x` and `y`.
#'
#'
#' @examples
#'\donttest{
#' library(oce)
#' data(coastlineWorld)
#' par(mfrow=c(2, 1), mar=rep(2, 4))
#' mapPlot(coastlineWorld, projection="+proj=moll") # sets a projection
#' xy <- mapLongitudeLatitudeXY(coastlineWorld)
#' plot(xy, type='l', asp=1)
#'}
#'
#' @author Dan Kelley
#'
#' @seealso A map must first have been created with [mapPlot()].
#'
#' @family functions related to maps
mapLongitudeLatitudeXY <- function(longitude, latitude)
{
if ("none" == .Projection()$type)