blib/lib/PDL/Transform/Cartography.pm

filter: Statementstmt 79.1% 682 / 862 Branchbran 39.9% 123 / 308 Conditioncond 30.1% 16 / 53 MC/DCmcdc 6.9% 2 / 29 Subroutinesub 88.1% 67 / 76 Podpod 96.0% 24 / 25 totaltotal 67.5% 914 / 1353 CC 192 SCAR 32.2
CC
192
Cov
67%
graticule
182.0
_uconv
78.5
earth_image
72.0
CRAP 25.1
« lib/PDL/Doc.pm ↑ Summary lib/PDL/ImageRGB.pd »
1 =head1 NAME
2  
3 PDL::Transform::Cartography - Useful cartographic projections
4  
5 =head1 SYNOPSIS
6  
7 # make a Mercator map of Earth
8 use PDL::Transform::Cartography;
9 use PDL::Graphics::Simple;
10 $x = earth_coast();
11 $x = graticule(10,2)->glue(1,$x);
12 $t = t_mercator;
13 $w = pgswin();
14 $w->plot(with=>'polylines', $t->apply($x)->clean_lines);
15  
16 =head1 DESCRIPTION
17  
18 PDL::Transform::Cartography includes a variety of useful cartographic
19 and observing projections (mappings of the surface of a sphere),
20 including reprojected observer coordinates. See L<PDL::Transform>
21 for more information about image transforms in general.
22  
23 Cartographic transformations are used for projecting not just
24 terrestrial maps, but also any nearly spherical surface including the
25 Sun, the Celestial sphere, various moons and planets, distant stars,
26 etc. They also are useful for interpreting scientific images, which
27 are themselves generally projections of a sphere onto a flat focal
28 plane (e.g. the L</t_gnomonic> projection).
29  
30 Unless otherwise noted, all the transformations in this file convert
31 from (theta,phi) coordinates on the unit sphere (e.g. (lon,lat) on a
32 planet or (RA,dec) on the celestial sphere) into some sort of
33 projected coordinates, and have inverse transformations that convert
34 back to (theta,phi). This is equivalent to working from the
35 equidistant cylindrical (or L<"plate carree"|/t_carree>) projection, if
36 you are a cartography wonk.
37  
38 The projected coordinates are generally in units of body radii
39 (radians), so that multiplying the output by the scale of the map
40 yields physical units that are correct wherever the scale is correct
41 for that projection. For example, areas should be correct everywhere
42 in the authalic projections; and linear scales are correct along
43 meridians in the equidistant projections and along the standard
44 parallels in all the projections.
45  
46 The transformations that are authalic (equal-area), conformal
47 (equal-angle), azimuthal (circularly symmetric), or perspective (true
48 perspective on a focal plane from some viewpoint) are marked. The
49 first two categories are mutually exclusive for all but the
50 L<"unit sphere"|/t_unit_sphere> 3-D projection.
51  
52 Extra dimensions tacked on to each point to be transformed are, in
53 general, ignored. That is so that you can add on an extra index
54 to keep track of pen color. For example, L</earth_coast>
55 returns a 3x<n> ndarray containing (lon, lat, pen) at each list location.
56 Transforming the vector list retains the pen value as the first index
57 after the dimensional directions.
58  
59 =head1 GENERAL NOTES ON CARTOGRAPHY
60  
61 Unless otherwise noted, the transformations and miscellaneous
62 information in this section are taken from Snyder & Voxland 1989: "An
63 Album of Map Projections", US Geological Survey Professional Paper
64 1453, US Printing Office (Denver); and from Snyder 1987: "Map
65 Projections - A Working Manual", US Geological Survey Professional
66 Paper 1395, US Printing Office (Denver, USA). You can obtain your own
67 copy of both by contacting the U.S. Geological Survey, Federal Center,
68 Box 25425, Denver, CO 80225 USA.
69  
70 The mathematics of cartography have a long history, and the details
71 are far trickier than the broad overview. For terrestrial (and, in
72 general, planetary) cartography, the best reference datum is not a
73 sphere but an oblate ellipsoid due to centrifugal force from the
74 planet's rotation. Furthermore, because all rocky planets, including
75 Earth, have randomly placed mass concentrations that affect the
76 gravitational field, the reference gravitational isosurface (sea level
77 on Earth) is even more complex than an ellipsoid and, in general,
78 different ellipsoids have been used for different locations at the
79 same time and for the same location at different times.
80  
81 The transformations in this package use a spherical datum and hence
82 include global distortion at about the 0.5% level for terrestrial maps
83 (Earth's oblateness is ~1/300). This is roughly equal to the
84 dimensional precision of physical maps printed on paper (due to
85 stretching and warping of the paper) but is significant at larger
86 scales (e.g. for regional maps). If you need more precision than
87 that, you will want to implement and use the ellipsoidal
88 transformations from Snyder 1987 or another reference work on geodesy.
89 A good name for that package would be C<...::Cartography::Geodetic>.
90  
91 =head1 GENERAL NOTES ON PERSPECTIVE AND SCIENTIFIC IMAGES
92  
93 Cartographic transformations are useful for interpretation of
94 scientific images, as all cameras produce projections of the celestial
95 sphere onto the focal plane of the camera. A simple (single-element)
96 optical system with a planar focal plane generates
97 L<gnomonic|/t_gnomonic> images -- that is to say, gnomonic projections
98 of a portion of the celestial sphere near the paraxial direction.
99 This is the projection that most consumer grade cameras produce.
100  
101 Magnification in an optical system changes the angle of incidence
102 of the rays on the focal plane for a given angle of incidence at the
103 aperture. For example, a 10x telescope with a 2 degree field of view
104 exhibits the same gnomonic distortion as a simple optical system with
105 a 20 degree field of view. Wide-angle optics typically have magnification
106 less than 1 ('fisheye lenses'), reducing the gnomonic distortion
107 considerably but introducing L<"equidistant azimuthal"|/t_az_eqd> distortion --
108 there's no such thing as a free lunch!
109  
110 Because many solar-system objects are spherical,
111 PDL::Transform::Cartography includes perspective projections for
112 producing maps of spherical bodies from perspective views. Those
113 projections are L<"t_vertical"|/t_vertical> and
114 L<"t_perspective"|/t_perspective>. They map between (lat,lon) on the
115 spherical body and planar projected coordinates at the viewpoint.
116 L<"t_vertical"|/t_vertical> is the vertical perspective projection
117 given by Snyder, but L<"t_perspective"|/t_perspective> is a fully
118 general perspective projection that also handles magnification correction.
119  
120 =head1 TRANSVERSE & OBLIQUE PROJECTIONS; STANDARD OPTIONS
121  
122 Oblique projections rotate the sphere (and graticule) to an arbitrary
123 angle before generating the projection; transverse projections rotate
124 the sphere exactly 90 degrees before generating the projection.
125  
126 Most of the projections accept the following standard options,
127 useful for making transverse and oblique projection maps.
128  
129 =over 3
130  
131 =item o, origin, Origin [default (0,0,0)]
132  
133 The origin of the oblique map coordinate system, in (old-theta, old-phi)
134 coordinates.
135  
136 =item r, roll, Roll [default 0.0]
137  
138 The roll angle of the sphere about the origin, measured CW from (N = up)
139 for reasonable values of phi and CW from (S = up) for unreasonable
140 values of phi. This is equivalent to observer roll angle CCW from the
141 same direction.
142  
143 =item u, unit, Unit [default 'degree']
144  
145 This is the name of the angular unit to use in the lon/lat coordinate system.
146  
147 =item b, B
148  
149 The "B" angle of the body -- used for extraterrestrial maps. Setting
150 this parameter is exactly equivalent to setting the phi component
151 of the origin, and in fact overrides it.
152  
153 =item l,L
154  
155 The longitude of the central meridian as observed -- used for extraterrestrial
156 maps. Setting this parameter is exactly equivalent to setting the theta
157 component of the origin, and in fact overrides it.
158  
159 =item p,P
160  
161 The "P" (or position) angle of the body -- used for extraterrestrial maps.
162 This parameter is a synonym for the roll angle, above.
163  
164 =item bad, Bad, missing, Missing [default nan]
165  
166 This is the value that missing points get. Mainly useful for the
167 inverse transforms. (This should work fine if set to BAD).
168  
169 =back
170  
171 =head1 EXAMPLES
172  
173 Draw a Mercator map of the world on-screen:
174  
175 $w = pgswin();
176 $w->plot(with=>'polylines', earth_coast->apply(t_mercator)->clean_lines);
177  
178 Here, C<earth_coast()> returns a 3xn ndarray containing (lon, lat, pen)
179 values for the included world coastal outline; C<t_mercator> converts
180 the values to projected Mercator coordinates, and C<clean_lines> breaks
181 lines that cross the 180th meridian.
182  
183 Draw a Mercator map of the world, with lon/lat at 10 degree intervals:
184  
185 $w = pgswin();
186 $x = earth_coast()->glue(1,graticule(10,1));
187 $w->plot(with=>'polylines', $x->apply(t_mercator)->clean_lines);
188  
189 This works just the same as the first example, except that a map graticule
190 has been applied with interline spacing of 10 degrees lon/lat and
191 inter-vertex spacing of 1 degree (so that each meridian contains 181 points,
192 and each parallel contains 361 points).
193  
194 =head1 NOTES
195  
196 Currently angular conversions are rather simpleminded. A list of
197 common conversions is present in the main constructor, which inserts a
198 conversion constant to radians into the {params} field of the new
199 transform. Something like Math::Convert::Units should be used instead
200 to generate the conversion constant.
201  
202 A cleaner higher-level interface is probably needed (see the examples);
203 for example, earth_coast could return a graticule if asked, instead of
204 needing one to be glued on.
205  
206 The class structure is somewhat messy because of the varying needs of
207 the different transformations. PDL::Transform::Cartography is a base
208 class that interprets the origin options and sets up the basic
209 machinery of the Transform. The conic projections have their
210 own subclass, PDL::Transform::Conic, that interprets the standard
211 parallels. Since the cylindrical and azimuthal projections are pretty
212 simple, they are not subclassed.
213  
214 The perl 5.6.1 compiler is quite slow at adding new classes to the
215 structure, so it does not makes sense to subclass new transformations
216 merely for the sake of pedantry.
217  
218 =head1 AUTHOR
219  
220 Copyright 2002, Craig DeForest (deforest@boulder.swri.edu). This
221 module may be modified and distributed under the same terms as PDL
222 itself. The module comes with NO WARRANTY.
223  
224 The included digital world map is derived from the 1987 CIA World Map,
225 translated to ASCII in 1988 by Joe Dellinger (geojoe@freeusp.org) and
226 simplified in 1995 by Kirk Johnson (tuna@indra.com) for the program
227 XEarth. The map comes with NO WARRANTY. An ASCII version of the map,
228 and a sample PDL function to read it, may be found in the F<examples>
229 subdirectory of the PDL source distribution.
230  
231 =head1 FUNCTIONS
232  
233 The module exports both transform constructors ('t_<foo>') and some
234 auxiliary functions (no leading 't_').
235  
236 =cut
237  
238 # Import PDL::Transform into the calling package -- the cartography
239 # stuff isn't much use without it.
240 1 ▶use PDL::Transform;
Subroutine BEGIN: called CC=1 SCAR=0.0
241  
242 package PDL::Transform::Cartography;
243 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
244 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
245 1 ▶use PDL::Core ':Internal'; # Load 'topdl' (internal routine)
Subroutine BEGIN: called CC=1 SCAR=0.0
246  
247 1 ▶use Exporter ();
Subroutine BEGIN: called CC=1 SCAR=0.0
248 1 ▶use PDL::LiteF;
Subroutine BEGIN: called CC=1 SCAR=0.0
249 1 ▶use PDL::Math;
Subroutine BEGIN: called CC=1 SCAR=0.0
250 1 ▶use PDL::Transform;
Subroutine BEGIN: called CC=1 SCAR=0.0
251 1 ▶use PDL::MatrixOps;
Subroutine BEGIN: called CC=1 SCAR=0.0
252 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
253  
254 1 our @ISA = ( 'Exporter','PDL::Transform' );
255 1 our $VERSION = "0.6";
256 1 $VERSION = eval $VERSION;
257 1 our @EXPORT_OK = qw(
258 graticule earth_image earth_coast earth_shape clean_lines t_unit_sphere
259 raster2fits
260 t_orthographic t_rot_sphere t_caree t_carree t_mercator t_utm t_sin_lat
261 t_sinusoidal t_conic t_albers t_lambert t_stereographic t_gnomonic
262 t_az_eqd t_az_eqa t_vertical t_perspective t_hammer t_aitoff
263 );
264 1 our @EXPORT = @EXPORT_OK;
265 1 our %EXPORT_TAGS = (Func=>\@EXPORT_OK);
266  
267 1 our @PLATE_CARREE = ([qw(Longitude Latitude RGB)],
268 [qw(degrees degrees index)], [[-180,180], [-90,90], [0,2]]);
269  
270 ##############################
271 # Steal _opt from PDL::Transform.
272 1 *PDL::Transform::Cartography::_opt = \&PDL::Transform::_opt;
273 1 ▶use overload '""' => \&_strval;
Subroutine BEGIN: called CC=1 SCAR=0.0
274 1 ▶use PDL::Constants qw(PI RAD2DEG DEG2RAD);
Subroutine BEGIN: called CC=1 SCAR=0.0
275  
276 28 ▶sub _strval {
Subroutine _strval: called CC=1 SCAR=0.0
277 28 my($me) = shift;
278 28 $me->stringify();
279 }
280  
281 ######################################################################
282  
283 =head2 graticule
284  
285 =for usage
286  
287 $lonlatp = graticule(<grid-spacing>,<line-segment-size>);
288 $lonlatp = graticule(<grid-spacing>,<line-segment-size>,1);
289  
290 =for ref
291  
292 (Cartography) PDL constructor - generate a lat/lon grid.
293  
294 Returns a grid of meridians and parallels as a list of vectors suitable
295 for sending to
296 L<PDL::Graphics::Simple|PDL::Graphics::Simple/polylines>
297 for plotting.
298 The grid is in degrees in (theta, phi) coordinates -- this is (E lon, N lat)
299 for terrestrial grids or (RA, dec) for celestial ones. You must then
300 transform the graticule in the same way that you transform the map.
301  
302 You can attach the graticule to a vector map using the syntax:
303  
304 $out = graticule(10,2)->glue(1,$map);
305  
306 In array context you get back a 2-element list containing an ndarray of
307 the (theta,phi) pairs and an ndarray of the pen values (1 or 0) suitable for
308 calling
309 L<PDL::Graphics::Simple|PDL::Graphics::Simple/polylines>.
310 In scalar context the two elements are combined into a single ndarray.
311  
312 The pen values associated with the graticule are negative, which will cause
313 L<PDL::Graphics::Simple|PDL::Graphics::Simple/polylines>
314 to plot them as hairlines.
315  
316 If a third argument is given, it is a hash of options, which can be:
317  
318 =over 3
319  
320 =item nan - if true, use two columns instead of three, and separate lines with a 'nan' break
321  
322 =item lonpos - if true, all reported longitudes are positive (0 to 360) instead of (-180 to 180).
323  
324 =item dup - if true, the meridian at the far boundary is duplicated.
325  
326 =back
327  
328 =cut
329  
330 0 ▶sub graticule {
Subroutine graticule: not called CC=13 SCAR=52.0
Pod documented
331 0 my $grid = shift;
332 0 my $step = shift;
333 0 ▶ my $hash = shift; $hash = {} unless defined($hash); # avoid // for ancient compatibility
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash 0 0 0
334 0 ▶ my $two_cols = $hash->{nan} || 0;
Condition0%0/2
$hash->{'nan'} || 0
l!l
00
MC/DC0%0/1
$hash->{'nan'} || 0
$hash->{'nan'}
Truth table0%0/2
A
A= $hash->{'nan'}
Aresult
11
00
335 0 ▶ my $lonpos = $hash->{lonpos} || 0;
Condition0%0/2
$hash->{'lonpos'} || 0
l!l
00
MC/DC0%0/1
$hash->{'lonpos'} || 0
$hash->{'lonpos'}
Truth table0%0/2
A
A= $hash->{'lonpos'}
Aresult
11
00
336 0 ▶ my $dup = $hash->{dup} || 0;
Condition0%0/2
$hash->{'dup'} || 0
l!l
00
MC/DC0%0/1
$hash->{'dup'} || 0
$hash->{'dup'}
Truth table0%0/2
A
A= $hash->{'dup'}
Aresult
11
00
337  
338 0 ▶ $grid = 10 unless defined($grid);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $grid 0 0 0
339 0 ▶ $grid = $grid->at(0) if(ref($grid) eq 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
if ref $grid eq "PDL" 0 0 0
340  
341 0 ▶ $step = $grid/2 unless defined($step);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $step 0 0 0
342 0 ▶ $step = $step->at(0) if(ref($step) eq 'PDL');
Branch: 1 branch
BranchTrueFalseTotal
if ref $step eq "PDL" 0 0 0
343  
344 # Figure number of parallels and meridians
345 0 my $np = 2 * int(90/$grid);
346 0 my $nm = 2 * int(180/$grid);
347  
348 # First do parallels.
349 0 my $xp = xvals(360/$step + 1 + !!$two_cols, $np + 1) * $step - 180 * (!$lonpos);
350 0 my $yp = yvals(360/$step + 1 + !!$two_cols, $np + 1) * 180/$np - 90;
351 0 ▶ $xp->slice("-1,:") .= $yp->slice("-1,:") .= nan() if($two_cols);
Branch: 1 branch
BranchTrueFalseTotal
if $two_cols 0 0 0
352  
353 # Next do meridians.
354 0 my $xm = yvals( 180/$step + 1 + !!$two_cols, $nm + !!$dup ) * 360/$nm - 180 * (!$lonpos);
355 0 my $ym = xvals( 180/$step + 1 + !!$two_cols, $nm + !!$dup ) * $step - 90;
356 0 ▶ $xm->slice("-1,:") .= $ym->slice("-1,:") .= nan() if($two_cols);
Branch: 1 branch
BranchTrueFalseTotal
if $two_cols 0 0 0
357  
358  
359 0 ▶ if($two_cols) {
Branch: 1 branch
BranchTrueFalseTotal
if ($two_cols) { } 0 0 0
360 0 return pdl( $xp->flat->append($xm->flat),
361 $yp->flat->append($ym->flat)
362 )->mv(1,0);
363 } else {
364 0 our $pp = zeroes($xp)-1; $pp->slice("(-1)") .= 0;
365 0 our $pm = zeroes($xm)-1; $pm->slice("(-1)") .= 0;
366  
367 0 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
368 0 return ( pdl( $xp->flat->append($xm->flat),
369 $yp->flat->append($ym->flat)
370 )->mv(1,0),
371  
372 $pp->flat->append($pm->flat)
373 );
374 } else {
375 0 return pdl( $xp->flat->append($xm->flat),
376 $yp->flat->append($ym->flat),
377 $pp->flat->append($pm->flat)
378 )->mv(1,0);
379 }
380 0 barf "This can't happen";
381 }
382 }
383  
384 =head2 earth_coast
385  
386 =for usage
387  
388 $x = earth_coast()
389  
390 =for ref
391  
392 (Cartography) PDL constructor - coastline map of Earth
393  
394 Returns a vector coastline map based on the 1987 CIA World Coastline
395 database (see author information). The vector coastline data are in
396 plate carree format so they can be converted to other projections via
397 the L<apply|PDL::Transform/apply> method and cartographic transforms,
398 and are suitable for plotting with the
399 L<polylines|PDL::Graphics::Simple/polylines>
400 plot type in the PDL::Graphics::Simple
401 output library: the first dimension is (X,Y,pen) with breaks having
402 a pen value of 0 and hairlines having negative pen values. The second
403 dimension broadcasts over all the points in the data set.
404  
405 The vector map includes lines that pass through the antipodean
406 meridian, so if you want to plot it without reprojecting, you should
407 run it through L</clean_lines> first:
408  
409 $w = pgswin();
410 $w->plot(with=>'polylines',
411 earth_coast->clean_lines); # plot plate carree map of world
412 $w->plot(with=>'polylines',
413 earth_coast->apply(t_gnomonic)->clean_lines)# plot gnomonic map of world
414  
415 C<earth_coast> is just a quick-and-dirty way of loading the file
416 "earth_coast.vec.fits" that is part of the normal installation tree.
417  
418 =cut
419  
420 1 ▶sub earth_coast {
Subroutine earth_coast: called CC=3 SCAR=11.0
Pod documented
421 1 my $fn = "PDL/Transform/Cartography/earth_coast.vec.fits";
422 1 local $_;
423 1 require PDL::IO::FITS;
424 1 foreach(@INC) {
425 2 my $file = "$_/$fn";
426 2 ▶ next if !-e $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $file 1 1 2
427 1 my $val = PDL::IO::FITS::rfits($file);
428 1 $val->hdrcpy(1);
429 1 return $val;
430 }
431 0 barf("earth_coast: $fn not found in \@INC.\n");
432 }
433  
434 =head2 earth_image
435  
436 =for usage
437  
438 $rgb = earth_image()
439  
440 =for ref
441  
442 (Cartography) PDL constructor - RGB pixel map of Earth
443  
444 Returns an RGB image of Earth based on data from the MODIS instrument
445 on the NASA EOS/Terra satellite. (You can get a full-resolution
446 image from L<http://earthobservatory.nasa.gov/Newsroom/BlueMarble/>).
447 The image is a plate carree map, so you can convert it to other
448 projections via the L<map|PDL::Transform/map> method and cartographic
449 transforms.
450  
451 This is just a quick-and-dirty way of loading the earth-image files that
452 are distributed along with PDL.
453  
454 =cut
455  
456 0 ▶sub earth_image {
Subroutine earth_image: not called CC=8 SCAR=42.8
Pod documented
457 0 my($nd) = shift;
458 0 my $f;
459 0 require PDL::IO::Pic;
460 0 my $dir = "PDL/Transform/Cartography/earth_";
461 0 ▶ $f = (($nd//'') =~ m/^n/i) ? "${dir}night.jpg" : "${dir}day.jpg";
Branch: 1 branch
BranchTrueFalseTotal
($nd // '') =~ /^n/i ? : 0 0 0
Condition0%0/2
$nd // ""
l!l
00
MC/DC0%0/1
$nd // ""
$nd
Truth table0%0/2
A
A= $nd
Aresult
11
00
462 0 local $_;
463 0 my $im;
464 0 my $found = 0;
465 0 foreach(@INC) {
466 0 my $file = "$_/$f";
467 0 ▶ if(-e $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $file) 0 0 0
468 0 $found = 1;
469 0 $im = PDL::IO::Pic::rpic($file);
470 }
471 0 ▶ last if defined($im);
Branch: 1 branch
BranchTrueFalseTotal
if defined $im 0 0 0
472 }
473 0 ▶ barf("earth_image: $f not found in \@INC\n") if !$found;
Branch: 1 branch
BranchTrueFalseTotal
unless $found 0 0 0
474 0 ▶ barf("earth_image: couldn't load $f; you may need to install netpbm.\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $im 0 0 0
475 unless defined($im);
476 0 raster2fits($im, @PLATE_CARREE);
477 }
478  
479 =head2 earth_shape
480  
481 =for usage
482  
483 $fits_shape = earth_shape()
484  
485 =for ref
486  
487 (Cartography) PDL constructor - height map of Earth
488  
489 Returns a height map of Earth based on data from the General
490 Bathymetric Chart of the Oceans (GEBCO) produced by the British
491 Oceanographic Data Centre. (You can get a full-resolution image from
492 L<http://visibleearth.nasa.gov/view.php?id=73934>). The image is a
493 plate carree map, so you can convert it to other projections via the
494 L<map|PDL::Transform/map> method and cartographic transforms.
495 The data is from 8-bit grayscale (so only 256 levels), but is returned
496 as float, values in Earth radii, in dimensions (2048,1024), like
497 L</earth_image>. The range represents a span of 6400m, so Everest and
498 the Marianas Trench are not accurately represented.
499  
500 Value Hex value Float From centre in km Float as radius
501 Base 00 0.0 6370.69873km 0.99995
502 Sea level 0C 0.04705 6371km 1.0
503 Highest FF 1.0 6377.09863km 1.00096
504  
505 Code:
506  
507 $shape = earth_shape();
508  
509 =cut
510  
511 0 ▶sub earth_shape {
Subroutine earth_shape: not called CC=6 SCAR=37.4
Pod documented
512 0 my($nd) = shift;
513 0 require PDL::IO::Pic;
514 0 my $f = "PDL/Transform/Cartography/earth_height-2048x1024.jpg";
515 0 local $_;
516 0 my $im;
517 0 my $found = 0;
518 0 foreach (@INC) {
519 0 my $file = "$_/$f";
520 0 ▶ if(-e $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $file) 0 0 0
521 0 $found = 1;
522 0 $im = PDL::IO::Pic::rpic($file);
523 }
524 0 ▶ last if defined($im);
Branch: 1 branch
BranchTrueFalseTotal
if defined $im 0 0 0
525 }
526 0 ▶ barf("earth_shape: $f not found in \@INC\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $found 0 0 0
527 unless defined($found);
528 0 ▶ barf("earth_shape: couldn't load $f; you may need to install netpbm.\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $im 0 0 0
529 unless defined($im);
530 0 ((raster2fits($im, @PLATE_CARREE)->float - float(0x0C)) / float(255*6400))
531 + float(1);
532 }
533  
534 =head2 raster2fits
535  
536 =for usage
537  
538 $pdl_fits = raster2fits($pdl, \@axislabels, \@axisunits, \@axisranges);
539 $pdl_fits = raster2fits($pdl, @PDL::Transform::Cartography::PLATE_CARREE);
540  
541 =for ref
542  
543 Convert a raster ([3,]x,y) to FITS (x,y[,3]), with a suitable header
544 for the given parameters.
545  
546 =cut
547  
548 3 ▶sub raster2fits {
Subroutine raster2fits: called CC=10 SCAR=23.2
Pod documented
549 3 ▶ die "Usage: raster2fits(\$d, \\\@axislabels, \\\@axisunits, \\\@axisranges)\n" if @_ != 4;
Branch: 1 branch
BranchTrueFalseTotal
if @_ != 4 0 3 3
550 3 my ($d, $axislabels, $axisunits, $axisranges) = @_;
551 3 my $is_single_plane = (my $ndims = $d->ndims) <= 2;
552 3 ▶ my $out = $is_single_plane ? $d : $d->mv(0,2);
Branch: 1 branch
BranchTrueFalseTotal
$is_single_plane ? : 3 0 3
553 3 my $h = $out->fhdr;
554 3 $h->{SIMPLE} = 'T';
555 3 $h->{NAXIS} = $ndims;
556 3 local $_;
557 3 my @dims = $out->dims;
558 3 $h->{"NAXIS".($_+1)} = $dims[$_] for 0..$ndims-1;
559 3 $h->{"CRVAL".($_+1)} = 0 for 0..$ndims-1;
560 3 ▶ $h->{"CRPIX".($_+1)} = $_<2 ? ($dims[$_]+1)/2 : 1 for 0..$ndims-1;
Branch: 1 branch
BranchTrueFalseTotal
$_ < 2 ? : 6 0 6
561 3 $h->{"CTYPE".($_+1)} = $axislabels->[$_] for 0..$ndims-1;
562 3 $h->{"CUNIT".($_+1)} = $axisunits->[$_] for 0..$ndims-1;
563 $h->{"CDELT".($_+1)} = ($axisranges->[$_][1]-$axisranges->[$_][0])/$dims[$_]
564 3 for 0..$ndims-1;
565 3 $h->{HISTORY}='PDL conversion from raster image';
566 3 $out;
567 }
568  
569 =head2 clean_lines
570  
571 =for usage
572  
573 $x = clean_lines(t_mercator->apply(scalar(earth_coast())));
574 $x = $lines->clean_lines; # same as above, both "first (scalar) form"
575 $x = clean_lines($line_pen[,threshold][,opt]); # also same but threshold given
576 $x = clean_lines($line,$pen[,threshold][,opt]); # "second (list) form"
577  
578 =for ref
579  
580 (Cartography) PDL method - remove projection irregularities
581  
582 C<clean_lines> massages vector data to remove jumps due to singularities
583 in the transform.
584  
585 In the first (scalar) form, C<$line_pen> contains both (X,Y) points and pen
586 values in the 3rd column suitable to be fed to
587 the L<polylines|PDL::Graphics::Simple/polylines>
588 plot type in the PDL::Graphics::Simple.
589  
590 In the second (list) form, C<$lines> contains the (X,Y) points and C<$pen>
591 contains the pen values, in one less dimension than the C<$lines>.
592  
593 C<clean_lines> assumes that all the outline polylines are local --
594 that is to say, there are no large jumps. Any jumps larger than a
595 threshold size are broken by setting the appropriate pen values to 0.
596  
597 The C<threshold> parameter sets the relative size of the largest jump, relative
598 to the map range (as determined by a min/max operation). The default size is
599 0.1. If C<threshold> is greater than or equal to 1, lines will not be
600 broken based on point separation.
601  
602 =for options
603  
604 The following options are interpreted:
605  
606 =over 3
607  
608 =item or, orange, output_range, Output_Range
609  
610 $lp = $lp->clean_lines(1.1,{or=>[[178.9,179.7], [62.8,64.5]]})
611  
612 This sets the window of output space, similar to that in
613 L<PDL::Transform/map>. As there, it specifies a quadrilateral in
614 output space. Any points not in that will be removed from the output,
615 and line breaks (0 pen values) will be inserted before.
616  
617 Because this returns a selection of the inputs, it will not broadcast.
618  
619 =item fn, filter_nan
620  
621 Defaults to true. Will break before any points with bad/C<NaN>/C<Inf>
622 coordinates, and remove those points from the output.
623  
624 Because this returns a selection of the inputs, it will not broadcast.
625  
626 =back
627  
628 NOTES
629  
630 This almost never catches stuff near the apex of cylindrical maps,
631 because the anomalous vectors get arbitrarily small. This could be
632 improved somewhat by looking at individual runs of the pen and using
633 a relative length scale that is calibrated to the rest of each run.
634 it is probably not worth the computational overhead.
635  
636 =cut
637  
638 1 *PDL::clean_lines = *PDL::clean_lines = \&clean_lines;
639 26 ▶sub clean_lines {
Subroutine clean_lines: called CC=20 SCAR=30.8
Pod documented
640 26 ▶ my $opt = ref($_[-1]) eq 'HASH' ? pop : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[-1] eq 'HASH' ? : 25 1 26
641 26 ▶ my $th = !UNIVERSAL::isa($_[-1],'PDL') ? pop : 0.1;
Branch: 1 branch
BranchTrueFalseTotal
!UNIVERSAL::isa($_[-1], 'PDL') ? : 14 12 26
642 26 ▶ die "Usage: clean_lines(\$line[, \$pen][, \$thresh])\n"
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 2 or not @_ 0 26 26
Condition33%1/3
@_ > 2 or not @_
l!l&&r!l&&!r
0026
MC/DC0%0/2
@_ > 2 or not @_
@_ > 2 not @_
Truth table33%1/3
A or not(B)
A= @_ > 2B= not @_
ABresult
1X1
011
000
643 if @_ > 2 || !@_;
644 26 ▶ die "clean_lines: all non-threshold args must be ndarrays\n"
Branch: 1 branch
BranchTrueFalseTotal
if grep((!UNIVERSAL::isa($_, "PDL")), @_) 0 26 26
645 if grep !UNIVERSAL::isa($_,'PDL'), @_;
646 26 ▶ die "clean_lines: need lines[3,n...] in single-arg case\n"
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 and $_[0]->dim(0) != 3 0 26 26
Condition66%2/3
@_ == 1 and $_[0]->dim(0) != 3
!ll&&!rl&&r
12140
MC/DC0%0/2
@_ == 1 and $_[0]->dim(0) != 3
@_ == 1 $_[0]->dim(0) != 3
Truth table66%2/3
A and B
A= @_ == 1B= $_[0]->dim(0) != 3
ABresult
0X0
100
111
647 if @_ == 1 and $_[0]->dim(0) != 3;
648 26 ▶ my ($l, $p) = @_ == 1
Branch: 2 branches
BranchTrueFalseTotal
@_ == 1 ? : 14 12 26
$_[0]->is_inplace ? : 0 14 14
649 ? ($_[0]->slice("0:1"), $_[0]->is_inplace ? $_[0]->slice("(2)") : $_[0]->slice("(2)")->sever)
650 : ($_[0], $_[1]->new_or_inplace);
651 26 my $break_mask = !isfinite($p); # break on NaN/Inf/BAD
652 26 $break_mask |= !isfinite($l)->orover; # break on either coord NaN/Inf/BAD
653 26 ▶ if ($th < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($th < 1) 24 2 26
654 24 my ($mins, $maxes) = $l->t->whereND(($p != 0) & isfinite($p))->minmaxover;
655 24 my $threshes = abs($maxes-$mins) * $th;
656 24 my $diff = $l->t->diff2->abs->t;
657 24 $break_mask |= ($diff > $threshes)->orover->append(pdl(0));
658 }
659 26 $p->whereND($break_mask) .= 0;
660 26 my $fn = PDL::Transform::_opt($opt, ['fn','filter_nan'], 1);
661 26 ▶ if ($fn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn) 2 24 26
662 2 ▶ die "clean_lines: no broadcasting with filter_nan\n" if $p->ndims > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $p->ndims > 1 0 2 2
663 2 my $nonfinite_mask = (!$l->isfinite)->orover;
664 2 $break_mask = $nonfinite_mask->slice('1:-1')->append(pdl(0)); # break before
665 2 $p->whereND($break_mask) .= 0;
666 2 my $keep_inds = (!$nonfinite_mask)->which;
667 2 $l = $l->dice_axis(1, $keep_inds)->sever;
668 2 $p = $p->dice_axis(0, $keep_inds)->sever;
669 }
670 26 my $orange = PDL::Transform::_opt($opt, ['or','orange','output_range','Output_Range']);
671 26 ▶ if (defined $orange) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $orange) 1 25 26
672 1 ▶ die "clean_lines: no broadcasting with orange\n" if $p->ndims > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $p->ndims > 1 0 1 1
673 1 ▶ die "clean_lines: orange must be array-ref\n" if ref($orange) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $orange ne "ARRAY" 0 1 1
674 1 ▶ die "clean_lines: orange must have two elements" if @$orange != 2;
Branch: 1 branch
BranchTrueFalseTotal
if @$orange != 2 0 1 1
675 1 ▶ die "clean_lines: orange must have two array-refs\n"
Branch: 1 branch
BranchTrueFalseTotal
if grep((ref $_ ne "ARRAY"), @$orange) 0 1 1
676 if grep ref() ne 'ARRAY', @$orange;
677 1 ▶ die "clean_lines: orange must have two array-refs each with two elements\n"
Branch: 1 branch
BranchTrueFalseTotal
if grep((@$_ != 2), @$orange) 0 1 1
678 if grep @$_ != 2, @$orange;
679 1 my ($mins, $maxes) = PDL->pdl($orange)->using(0,1);
680 1 my $outside_mask = (($l < $mins) | ($l > $maxes))->orover;
681 1 $break_mask = $outside_mask->slice('1:-1')->append(pdl(0)); # break before
682 1 $p->whereND($break_mask) .= 0;
683 1 my $keep_inds = (!$outside_mask)->which;
684 1 $l = $l->dice_axis(1, $keep_inds)->sever;
685 1 $p = $p->dice_axis(0, $keep_inds)->sever;
686 }
687 26 ▶ wantarray ? ($l,$p) : $l->append($p->dummy(0,1));
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 16 10 26
688 }
689  
690 ######################################################################
691  
692 ###
693 # Units parser
694 # Get unit, return conversion factor to radii, or undef if no match found.
695 #
696 20 ▶sub _uconv{
Subroutine _uconv: called CC=18 SCAR=43.6
697 ###
698 # Replace this with a more general units resolver call!
699 ###
700 20 local($_) = shift;
701 20 my($silent) =shift;
702  
703 20 ▶ my($x) =
Branch: 13 branches
BranchTrueFalseTotal
/^deg/i ? : 17 3 20
/^arcmin/i ? : 1 2 3
/^arcsec/i ? : 0 2 2
/^hour/i ? : 0 2 2
/^min/i ? : 0 2 2
/^microrad/i ? : 0 2 2
/^millirad/i ? : 0 2 2
/^rad(ian)?s?$/i ? : 2 0 2
/^meter/ ? : 0 0 0
/^kilometer/ ? : 0 0 0
/^km/ ? : 0 0 0
/^Mm/ ? : 0 0 0
/^mile/ ? : 0 0 0
704 ( m/^deg/i ? DEG2RAD :
705 m/^arcmin/i ? DEG2RAD / 60 :
706 m/^arcsec/i ? DEG2RAD / 3600 :
707 m/^hour/i ? DEG2RAD * 15 : # Right ascension
708 m/^min/i ? DEG2RAD * 15/60 : # Right ascension
709 m/^microrad/i ? 1e-6 :
710 m/^millirad/i ? 1e-3 :
711 m/^rad(ian)?s?$/i ? 1.0 :
712 m/^meter/ ? 1.0/6371000 : # Assuming Earth cartography!
713 m/^kilometer/ ? 1.0/6371 :
714 m/^km/ ? 1.0/6371 :
715 m/^Mm/ ? 1.0/6.371 :
716 m/^mile/ ? 1.0/(637100000/2.54/12/5280) :
717 undef
718 );
719 20 ▶ print STDERR "Cartography: unrecognized unit '$_'\n"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $x || $silent and $PDL::debug || $PDL::verbose 0 20 20
Condition22%2/9
not defined $x || $silent and $PDL::debug || $PDL::verbose
!ll&&!rl&&r
2000
defined $x || $silent
l!l&&r!l&&!r
2000
$PDL::debug or $PDL::verbose
l!l&&r!l&&!r
000
MC/DC0%0/4
not defined $x || $silent and $PDL::debug || $PDL::verbose
defined $x $silent $PDL::debug $PDL::verbose
Truth table20%1/5
not(A || B) and C or D
A= defined $xB= $silentC= $PDL::debugD= $PDL::verbose
ABCDresult
1XXX0
01XX0
00000
001X1
00011
720 if( (!defined $x) && !$silent && ($PDL::debug || $PDL::verbose));
721 20 $x;
722 }
723  
724 ###
725 #
726 # Cartography general constructor -- called by the individual map
727 # constructors. Not underscored because it's certainly OK to call from
728 # outside -- but the *last* argument is the name of the transform.
729 #
730 # The options list is put into the {options} field of the newly constructed
731 # Transform -- fastidious subclass constructors will want to delete it before
732 # returning.
733 #
734  
735  
736 15 ▶sub _new { __PACKAGE__->new(@_); } # not exported
Subroutine _new: called CC=1 SCAR=0.0
737 18 ▶sub new {
Subroutine new: called CC=7 SCAR=21.0
Pod undocumented
738 18 my($class) = shift;
739 18 my($name) = pop;
740  
741 18 my($o) = $_[0];
742 18 ▶ $o = {@_}
Branch: 1 branch
BranchTrueFalseTotal
unless ref $o eq "HASH" 18 0 18
743 unless(ref $o eq 'HASH');
744  
745 18 my($me) = __PACKAGE__->SUPER::new;
746 18 $me->{idim} = $me->{odim} = 2;
747 18 $me->{name} = $name;
748  
749 ####
750 # Parse origin and units arguments
751 #
752 18 my $or = _opt($o,['o','origin','Origin'],zeroes(2));
753 18 ▶ if($or->nelem != 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($or->nelem != 2) 0 18 18
754 0 croak("PDL::Transform::Cartography: origin must have 2 elements\n");
755 }
756  
757 18 my($l) = _opt($o,['l','L']);
758 18 my($b_angle) = _opt($o,['b','B']);
759  
760 18 ▶ $or->slice("0") .= $l if defined($l);
Branch: 1 branch
BranchTrueFalseTotal
if defined $l 0 18 18
761 18 ▶ $or->slice("1") .= $b_angle if defined($b_angle);
Branch: 1 branch
BranchTrueFalseTotal
if defined $b_angle 0 18 18
762  
763 18 my $roll = topdl(_opt($o,['r','roll','Roll','P'],0));
764 18 my $unit = _opt($o,['u','unit','Unit'],'degrees');
765  
766 18 $me->{params}->{conv} = my $conv = _uconv($unit);
767 18 $me->{params}->{u} = $unit;
768  
769 18 $me->{itype} = ['longitude','latitude'];
770 18 $me->{iunit} = [$me->{params}->{u},$me->{params}->{u}];
771  
772 18 my($ou) = _opt($o,['ou','ounit','OutputUnit'],undef);
773 18 $me->{params}->{ou} = $ou;
774 18 ▶ if(defined $ou) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ou) { } 0 18 18
775 0 ▶ if(!(ref $ou)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $ou) { } 0 0 0
776 0 $me->{params}->{oconv} = _uconv($ou);
777 } else {
778 0 my @oconv;
779 0 map {push(@oconv,_uconv($_))} @$ou;
780 0 $me->{params}->{oconv} = topdl([@oconv]);
781 }
782 } else {
783 18 $me->{params}->{oconv} = undef;
784 }
785 18 $me->{ounit} = $me->{params}->{ou};
786  
787 18 $me->{params}->{o} = $or * $conv;
788 18 $me->{params}->{roll} = $roll * $conv;
789  
790 18 $me->{params}->{bad} = _opt($o,['b','bad','Bad','missing','Missing'],
791 nan());
792  
793 # Get the standard parallel (in general there's only one; the conics
794 # have two but that's handled by _c_new)
795 $me->{params}->{std} = topdl(_opt($me->{options},
796 ['s','std','standard','Standard'],
797 18 0))->at(0) * $me->{params}->{conv};
798  
799 18 $me->{options} = $o;
800 18 $me;
801 }
802  
803 # Compose self with t_rot_sphere if necessary -- useful for
804 # finishing off the transformations that accept the origin and roll
805 # options.
806 12 ▶sub PDL::Transform::Cartography::_finish {
Subroutine _finish: called CC=4 SCAR=22.1
807 12 my($me) = shift;
808 12 ▶ if( ($me->{params}->{o}->slice("0") != 0) ||
Branch: 1 branch
BranchTrueFalseTotal
if ($me->{"params"}{"o"}->slice(0) != 0 or $me->{"params"}{"o"}->slice(1) != 0 or $me->{"params"}{"roll"} != 0) 0 12 12
Condition33%2/6
$me->{"params"}{"o"}->slice(0) != 0 or $me->{"params"}{"o"}->slice(1) != 0 or $me->{"params"}{"roll"} != 0
l!l&&r!l&&!r
0012
$me->{"params"}{"o"}->slice(0) != 0 or $me->{"params"}{"o"}->slice(1) != 0
l!l&&r!l&&!r
0012
MC/DC0%0/3
$me->{"params"}{"o"}->slice(0) != 0 or $me->{"params"}{"o"}->slice(1) != 0 or $me->{"params"}{"roll"} != 0
$me->{"params"}{"o"}->slice(0) != 0 $me->{"params"}{"o"}->slice(1) != 0 $me->{"params"}{"roll"} != 0
Truth table0%0/4
A or B or C
A= $me->{"params"}{"o"}->slice(0) != 0B= $me->{"params"}{"o"}->slice(1) != 0C= $me->{"params"}{"roll"} != 0
ABCresult
1XX1
01X1
0011
0000
809 ($me->{params}->{o}->slice("1") != 0) ||
810 ($me->{params}->{roll} != 0)
811 ) {
812 0 my $out = t_compose($me,t_rot_sphere($me->{options}));
813 0 $out->{itype} = $me->{itype};
814 0 $out->{iunit} = $me->{iunit};
815 0 $out->{otype} = $me->{otype};
816 0 $out->{ounit} = $me->{ounit};
817 0 $out->{odim} = 2;
818 0 $out->{idim} = 2;
819 0 return $out;
820 }
821 12 return $me;
822 }
823  
824 ######################################################################
825  
826 =head2 t_unit_sphere
827  
828 =for usage
829  
830 $t = t_unit_sphere(<options>);
831  
832 =for ref
833  
834 (Cartography) 3-D globe projection (conformal; authalic)
835  
836 This is similar to the inverse of
837 L<t_spherical|PDL::Transform/t_spherical>,
838 but the
839 inverse transform projects 3-D coordinates onto the unit sphere,
840 yielding only a 2-D (lon/lat) output. Similarly, the forward
841 transform deprojects 2-D (lon/lat) coordinates onto the surface of a
842 unit sphere.
843  
844 The cartesian system has its Z axis pointing through the pole of the
845 (lon,lat) system, and its X axis pointing through the equator at the
846 prime meridian.
847  
848 Unit sphere mapping is unusual in that it is both conformal and authalic.
849 That is possible because it properly embeds the sphere in 3-space, as a
850 notional globe.
851  
852 This is handy as an intermediate step in lots of transforms, as
853 Cartesian 3-space is cleaner to work with than spherical 2-space.
854  
855 Higher dimensional indices are preserved, so that "rider" indices (such as
856 pen value) are propagated.
857  
858 There is no oblique transform for t_unit_sphere, largely because
859 it's so easy to rotate the output using t_linear once it's out into
860 Cartesian space. In fact, the other projections implement oblique
861 transforms by
862 L<wrapping|PDL::Transform/t_wrap>
863 L<t_linear|PDL::Transform/t_linear> with
864 L</t_unit_sphere>.
865  
866 OPTIONS:
867  
868 =over 3
869  
870 =item radius, Radius (default 1.0)
871  
872 The radius of the sphere, for the inverse transform. (Radius is ignored
873 in the forward transform). Defaults to 1.0 so that the resulting Cartesian
874 coordinates are in units of "body radii".
875  
876 =back
877  
878 =cut
879  
880 3 ▶sub t_unit_sphere {
Subroutine t_unit_sphere: called CC=1 SCAR=0.0
Pod documented
881 3 my($me) = _new(@_,'Unit Sphere Projection');
882 3 $me->{odim} = 3;
883  
884 3 $me->{params}->{otype} = ['X','Y','Z'];
885 3 $me->{params}->{ounit} = ['body radii','body radii','body radii'];
886  
887 $me->{params}->{r} = topdl(_opt($me->{options},
888 3 ['r','radius','Radius'],
889 1.0)
890 )->at(0);
891  
892  
893 10 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
894 10 my ($d,$o) = @_;
895 10 my @dims = $d->dims;
896 10 $dims[0] ++;
897 10 my $out = zeroes(@dims);
898  
899 my($thetaphi) = ((defined $o->{conv} && $o->{conv} != 1.0) ?
900 10 ▶ $d->slice("0:1") * $o->{conv} : $d->slice("0:1")
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'conv'} && $o->{'conv'} != 1.0 ? : 1 9 10
Condition66%2/3
defined $o->{"conv"} and $o->{"conv"} != 1
!ll&&!rl&&r
091
MC/DC50%1/2
defined $o->{"conv"} and $o->{"conv"} != 1
defined $o->{"conv"} $o->{"conv"} != 1
Truth table66%2/3
A and B
A= defined $o->{"conv"}B= $o->{"conv"} != 1
ABresult
0X0
100
111
901 );
902  
903 10 my ($th, $ph) = $thetaphi->using(0,1);
904  
905 10 my ($out0, $out1, $out2) = $out->using(0..2);
906 # use x as a holding tank for the cos-phi multiplier
907 10 $out0 .= $o->{r} * cos($ph) ;
908 10 $out1 .= $out->slice("(0)") * sin($th);
909 10 $out0 *= cos($th);
910  
911 10 $out2 .= $o->{r} * sin($ph);
912  
913 10 ▶ if ($d->dim(0) > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->dim(0) > 2) 0 10 10
914 0 $out->slice("3:-1") .= $d->slice("2:-1");
915 }
916  
917 10 $out;
918 3 };
919  
920 2 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
921 2 my($d,$o) = @_;
922  
923 2 my ($d0,$d1,$d2) = $d->using(0..2);
924 2 my $r = $d->slice("0:2")->magnover;
925 2 my @dims = $d->dims;
926 2 $dims[0]--;
927 2 my $out = zeroes(@dims);
928  
929 2 $out->slice("(0)") .= atan2($d1,$d0);
930 2 $out->slice("(1)") .= asin($d2/$r);
931  
932 2 ▶ if ($d->dim(0) > 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->dim(0) > 3) 0 2 2
933 0 $out->slice("2:-1") .= $d->slice("3:-1");
934 }
935  
936 $out->slice("0:1") /= $o->{conv}
937 2 ▶ if(defined $o->{conv} && $o->{conv} != 1.0);
Branch: 1 branch
BranchTrueFalseTotal
if defined $o->{"conv"} and $o->{"conv"} != 1 1 1 2
Condition66%2/3
defined $o->{"conv"} and $o->{"conv"} != 1
!ll&&!rl&&r
011
MC/DC50%1/2
defined $o->{"conv"} and $o->{"conv"} != 1
defined $o->{"conv"} $o->{"conv"} != 1
Truth table66%2/3
A and B
A= defined $o->{"conv"}B= $o->{"conv"} != 1
ABresult
0X0
100
111
938  
939 2 $out;
940 3 };
941  
942  
943 3 $me;
944 }
945  
946 ######################################################################
947  
948 =head2 t_rot_sphere
949  
950 =for usage
951  
952 $t = t_rot_sphere({origin=>[<theta>,<phi>],roll=>[<roll>]});
953  
954 =for ref
955  
956 (Cartography) Generate oblique projections
957  
958 You feed in the origin in (theta,phi) and a roll angle, and you get back
959 out (theta', phi') coordinates. This is useful for making oblique or
960 transverse projections: just compose t_rot_sphere with your favorite
961 projection and you get an oblique one.
962  
963 Most of the projections automagically compose themselves with t_rot_sphere
964 if you feed in an origin or roll angle.
965  
966 t_rot_sphere converts the base plate carree projection (straight lon, straight
967 lat) to a Cassini projection.
968  
969 OPTIONS
970  
971 =over 3
972  
973 =item STANDARD POSITIONAL OPTIONS
974  
975 =back
976  
977 =cut
978  
979 # helper routine for making the rotation matrix
980 4 ▶sub _rotmat {
Subroutine _rotmat: called CC=1 SCAR=0.0
981 4 my($th,$ph,$r) = @_;
982  
983 4 pdl( [ cos($th) , -sin($th), 0 ], # apply theta
984 [ sin($th) , cos($th), 0 ],
985 [ 0, 0, 1 ] )
986 x
987 pdl( [ cos($ph), 0, -sin($ph) ], # apply phi
988 [ 0, 1, 0 ],
989 [ sin($ph), 0, cos($ph) ] )
990 x
991 pdl( [ 1, 0 , 0 ], # apply roll last
992 [ 0, cos($r), -sin($r) ],
993 [ 0, sin($r), cos($r) ])
994 ;
995 }
996  
997 0 ▶sub t_rot_sphere {
Subroutine t_rot_sphere: not called CC=1 SCAR=6.9
Pod documented
998 0 my($me) = _new(@_,'Spherical rotation');
999  
1000  
1001 0 my($th,$ph) = $me->{params}->{o}->list;
1002 0 my($r) = $me->{params}->{roll}->at(0);
1003  
1004 0 my($rotmat) = _rotmat($th,$ph,$r);
1005  
1006 0 my $out = t_wrap( t_linear(m=>$rotmat, d=>3), t_unit_sphere());
1007 0 $out->{itype} = $me->{itype};
1008 0 $out->{iunit} = $me->{iunit};
1009 0 $out->{otype} = ['rotated longitude','rotated latitude'];
1010 0 $out->{ounit} = $me->{iunit};
1011  
1012 0 $out;
1013 }
1014  
1015  
1016 ######################################################################
1017  
1018 =head2 t_orthographic
1019  
1020 =for usage
1021  
1022 $t = t_orthographic(<options>);
1023  
1024 =for ref
1025  
1026 (Cartography) Ortho. projection (azimuthal; perspective)
1027  
1028 This is a perspective view as seen from infinite distance. You
1029 can specify the sub-viewer point in (lon,lat) coordinates, and a rotation
1030 angle of the map CW from (north=up). This is equivalent to specify
1031 viewer roll angle CCW from (north=up).
1032  
1033 t_orthographic is a convenience interface to t_unit_sphere -- it is implemented
1034 as a composition of a t_unit_sphere call, a rotation, and a slice.
1035  
1036 [*] In the default case where the near hemisphere is mapped, the
1037 inverse exists. There is no single inverse for the whole-sphere case,
1038 so the inverse transform superimposes everything on a single
1039 hemisphere. If you want an invertible 3-D transform, you want
1040 L</t_unit_sphere>.
1041  
1042 OPTIONS
1043  
1044 =over 3
1045  
1046 =item STANDARD POSITIONAL OPTIONS
1047  
1048 =item m, mask, Mask, h, hemisphere, Hemisphere [default 'near']
1049  
1050 The hemisphere to keep in the projection (see L<PDL::Transform::Cartography>).
1051  
1052 =back
1053  
1054 NOTES
1055  
1056 Alone of the various projections, this one does not use
1057 L</t_rot_sphere> to handle the standard options, because
1058 the cartesian coordinates of the rotated sphere are already correctly
1059 projected -- t_rot_sphere would put them back into (theta', phi')
1060 coordinates.
1061  
1062 =cut
1063  
1064 1 ▶sub t_orthographic {
Subroutine t_orthographic: called CC=5 SCAR=17.3
Pod documented
1065 1 my($me) = _new(@_,'Orthographic Projection');
1066  
1067 1 $me->{otype} = ['projected X','projected Y'];
1068 1 $me->{ounit} = ['body radii','body radii'];
1069  
1070 my $m= _opt($me->{options},
1071 1 ['m','mask','Mask','h','hemi','hemisphere','Hemisphere'],
1072 1);
1073 1 ▶ if($m=~m/^b/i) {
Branch: 3 branches
BranchTrueFalseTotal
if ($m =~ /^b/i) { } 0 1 1
elsif ($m =~ /^n/i) { } 0 1 1
elsif ($m =~ /^f/i) { } 0 1 1
1074 0 $me->{params}->{m} = 0;
1075 } elsif($m=~m/^n/i) {
1076 0 $me->{params}->{m} = 1;
1077 } elsif($m=~m/^f/i) {
1078 0 $me->{params}->{m} = 2;
1079 } else {
1080 1 $me->{params}->{m} = $m;
1081 }
1082  
1083 1 my $origin= $me->{params}->{o} * RAD2DEG;
1084 1 my $roll = $me->{params}->{roll} * RAD2DEG;
1085  
1086 $me->{params}->{t_int} =
1087 t_compose(
1088 t_linear(rot=>[90 - $origin->at(1),
1089 0,
1090 90 + $origin->at(0)],
1091 d=>3),
1092 t_unit_sphere(u=>$me->{params}->{u})
1093 1 );
1094  
1095 $me->{params}->{t_int} =
1096 t_compose(
1097 t_linear(rot=>[0,0,$roll->at(0)],d=>3),
1098 $me->{params}->{t_int}
1099 )
1100 1 ▶ if($roll->at(0));
Branch: 1 branch
BranchTrueFalseTotal
if $roll->at(0) 0 1 1
1101  
1102 1 $me->{name} = "orthographic";
1103  
1104 1 $me->{idim} = 2;
1105 1 $me->{odim} = 2;
1106  
1107 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=8 SCAR=25.1
1108 1 my ($d,$o) = @_ ;
1109 1 my ($out) = $o->{t_int}->apply($d);
1110 1 ▶ if($o->{m}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{"m"}) 1 0 1
1111 1 my $idx;
1112 $idx = whichND($out->slice("(2)") < 0)
1113 1 ▶ if($o->{m} == 1);
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"m"} == 1 1 0 1
1114 $idx = whichND($out->slice("(2)") > 0)
1115 1 ▶ if($o->{m} == 2);
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"m"} == 2 0 1 1
1116 1 ▶ if(defined $idx && ref $idx eq 'PDL' && $idx->nelem){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx and ref $idx eq "PDL" and $idx->nelem) 0 1 1
Condition33%2/6
defined $idx and ref $idx eq "PDL" and $idx->nelem
!ll&&!rl&&r
010
defined $idx and ref $idx eq "PDL"
!ll&&!rl&&r
001
MC/DC0%0/3
defined $idx and ref $idx eq "PDL" and $idx->nelem
defined $idx ref $idx eq "PDL" $idx->nelem
Truth table25%1/4
A and B and C
A= defined $idxB= ref $idx eq "PDL"C= $idx->nelem
ABCresult
0XX0
10X0
1100
1111
1117 0 $out->slice("(0)")->range($idx) .= $o->{bad};
1118 0 $out->slice("(1)")->range($idx) .= $o->{bad};
1119 }
1120 }
1121  
1122 1 my($d0) = $out->dim(0);
1123  
1124 # Remove the Z direction
1125 1 ▶ ($d0 > 3) ? $out->slice(pdl(0,1,3..$d0-1)) : $out->slice("0:1");
Branch: 1 branch
BranchTrueFalseTotal
$d0 > 3 ? : 0 1 1
1126  
1127 1 };
1128  
1129 # This is slow to run, quick to code -- could be made better by
1130 # having its own 2-d inverse instead of calling the internal one.
1131 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
1132 1 my($d,$o) = @_;
1133 1 my($d1) = $d->slice("0:1");
1134 1 my(@dims) = $d->dims;
1135 1 $dims[0]++;
1136 1 my($out) = zeroes(@dims);
1137 1 $out->slice("0:1") .= $d1;
1138 1 ▶ $out->slice("3:-1") .= $d->slice("2:-1")
Branch: 1 branch
BranchTrueFalseTotal
if $dims[0] > 3 0 1 1
1139 if($dims[0] > 3);
1140  
1141 1 $out->slice("(2)") .= sqrt(1 - ($d1*$d1)->sumover);
1142 1 ▶ $out->slice("(2)") *= -1 if($o->{m} == 2);
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"m"} == 2 0 1 1
1143  
1144 1 $o->{t_int}->invert($out);
1145 1 };
1146  
1147 1 $me;
1148 }
1149  
1150 ######################################################################
1151  
1152 =head2 t_carree
1153  
1154 =for usage
1155  
1156 $t = t_carree(<options>);
1157  
1158 =for ref
1159  
1160 (Cartography) Plate Carree projection (cylindrical; equidistant)
1161  
1162 This is the simple Plate Carree projection -- also called a "lat/lon plot".
1163 The horizontal axis is theta; the vertical axis is phi. This is a no-op
1164 if the angular unit is radians; it is a simple scale otherwise.
1165  
1166 OPTIONS
1167  
1168 =over 3
1169  
1170 =item STANDARD POSITIONAL OPTIONS
1171  
1172 =item s, std, standard, Standard (default 0)
1173  
1174 The standard parallel where the transformation is conformal. Conformality
1175 is achieved by shrinking of the horizontal scale to match the
1176 vertical scale (which is correct everywhere).
1177  
1178 =back
1179  
1180 =cut
1181  
1182 1 @PDL::Transform::Cartography::Carree::ISA = ('PDL::Transform::Cartography');
1183  
1184 1 *t_caree = *t_carree; # compat alias for poor spellers
1185 0 ▶sub t_carree {
Subroutine t_carree: not called CC=1 SCAR=6.9
Pod documented
1186 0 my($me) = _new(@_,'Plate Carree Projection');
1187 0 my $p = $me->{params};
1188  
1189 0 $me->{otype} = ['projected longitude','latitude'];
1190 0 $me->{ounit} = ['proj. body radii','body radii'];
1191  
1192 0 $p->{stretch} = cos($p->{std});
1193  
1194 0 ▶ $me->{func} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1195 0 my($d,$o) = @_;
1196 0 my($out) = $d->new_or_inplace;
1197 0 $out->slice("0:1") *= $o->{conv};
1198 0 $out->slice("0") *= $p->{stretch};
1199 0 $out;
1200 0 };
1201  
1202 0 ▶ $me->{inv} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1203 0 my($d,$o)= @_;
1204 0 my($out) = $d->new_or_inplace;
1205 0 $out->slice("0:1") /= $o->{conv};
1206 0 $out->slice("0") /= $p->{stretch};
1207 0 $out;
1208 0 };
1209  
1210 0 $me->_finish;
1211 }
1212  
1213 ######################################################################
1214  
1215 =head2 t_mercator
1216  
1217 =for usage
1218  
1219 $t = t_mercator(<options>);
1220  
1221 =for ref
1222  
1223 (Cartography) Mercator projection (cylindrical; conformal)
1224  
1225 This is perhaps the most famous of all map projections: meridians are mapped
1226 to parallel vertical lines and parallels are unevenly spaced horizontal lines.
1227 The poles are shifted to +/- infinity. The output values are in units of
1228 globe-radii for easy conversion to kilometers; hence the horizontal extent
1229 is -pi to pi.
1230  
1231 You can get oblique Mercator projections by specifying the C<origin> or
1232 C<roll> options; this is implemented via L</t_rot_sphere>.
1233  
1234 OPTIONS
1235  
1236 =over 3
1237  
1238 =item STANDARD POSITIONAL OPTIONS
1239  
1240 =item c, clip, Clip (default 75 [degrees])
1241  
1242 The north/south clipping boundary of the transformation. Because the poles are
1243 displaced to infinity, many applications require a clipping boundary. The
1244 value is in whatever angular unit you set with the standard 'units' option.
1245 The default roughly matches interesting landforms on Earth.
1246 For no clipping at all, set b=>0. For asymmetric clipping, use a 2-element
1247 list ref or ndarray.
1248  
1249 =item s, std, Standard (default 0)
1250  
1251 This is the parallel at which the map has correct scale. The scale
1252 is also correct at the parallel of opposite sign.
1253  
1254 =back
1255  
1256 =cut
1257  
1258  
1259 1 @PDL::Transform::Cartography::Mercator::ISA = ('PDL::Transform::Cartography');
1260  
1261 1 ▶sub t_mercator {
Subroutine t_mercator: called CC=6 SCAR=18.8
Pod documented
1262 1 my($me) = _new(@_,'Mercator Projection');
1263 1 my $p = $me->{params};
1264  
1265 # This is a lot of shenanigans just to get the clip parallels, but what the
1266 # heck -- it's not a hot spot and it saves copying the input data (for
1267 # nondestructive clipping).
1268 $p->{c} = _opt($me->{options},
1269 1 ['c','clip','Clip'],
1270 undef);
1271 1 ▶ if(defined($p->{c})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p->{'c'}) { } 0 1 1
1272 0 $p->{c} = topdl($p->{c});
1273 0 $p->{c} *= $p->{conv};
1274 } else {
1275 1 $p->{c} = pdl(DEG2RAD * 75);
1276 }
1277 1 ▶ $p->{c} = abs($p->{c}) * pdl(-1,1) if($p->{c}->nelem == 1);
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"c"}->nelem == 1 1 0 1
1278  
1279 1 $p->{c} = log(tan(($p->{c}/2) + PI/4));
1280 1 $p->{c} = [$p->{c}->list];
1281  
1282 $p->{std} = topdl(_opt($me->{options},
1283 ['s','std','standard','Standard'],
1284 1 0))->at(0) * $p->{conv};
1285  
1286 1 ▶ if($p->{std} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{'std'} == 0) { } 1 0 1
1287 1 $me->{otype} = ['longitude','tan latitude'];
1288 1 ▶ $me->{ounit} = ['radians',' '] unless(defined $me->{ounit});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"ounit"} 1 0 1
1289 } else {
1290 0 $me->{otype} = ['proj. longitude','proj. tan latitude'];
1291 0 ▶ $me->{ounit} = ['radians',' '] unless(defined $me->{ounit});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"ounit"} 0 0 0
1292 }
1293  
1294 1 $p->{stretch} = cos($p->{std});
1295  
1296 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
1297 1 my($d,$o) = @_;
1298  
1299 1 my($out) = $d->new_or_inplace;
1300  
1301 1 $out->slice("0:1") *= $o->{conv};
1302  
1303 1 $out->slice("(1)") .= log(tan($out->slice("(1)")/2 + PI/4));
1304 1 $out->slice("(1)") .= $out->slice("(1)")->clip(@{$o->{c}})
1305 1 ▶ unless($o->{c}->[0] == $o->{c}->[1]);
Branch: 1 branch
BranchTrueFalseTotal
unless $o->{"c"}[0] == $o->{"c"}[1] 1 0 1
1306  
1307 1 $out->slice("0:1") *= $o->{stretch};
1308 1 ▶ $out->slice("0:1") /= $o->{oconv} if(defined $o->{oconv});
Branch: 1 branch
BranchTrueFalseTotal
if defined $o->{"oconv"} 0 1 1
1309  
1310 1 $out;
1311 1 };
1312  
1313 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1314 1 my($d,$o) = @_;
1315 1 my($out) = $d->new_or_inplace;
1316  
1317 1 ▶ $out->slice("0:1") *= $o->{oconv} if defined($o->{oconv});
Branch: 1 branch
BranchTrueFalseTotal
if defined $o->{"oconv"} 0 1 1
1318 1 $out->slice("0:1") /= $o->{stretch};
1319 1 $out->slice("(1)") .= (atan(exp($out->slice("(1)"))) - PI/4)*2;
1320 1 $out->slice("0:1") /= $o->{conv};
1321  
1322 1 $out;
1323 1 };
1324  
1325 1 $me->_finish;
1326 }
1327  
1328 ######################################################################
1329  
1330 =head2 t_utm
1331  
1332 =for usage
1333  
1334 $t = t_utm(<zone>,<options>);
1335  
1336 =for ref
1337  
1338 (Cartography) Universal Transverse Mercator projection (cylindrical)
1339  
1340 This is the internationally used UTM projection, with 2 subzones
1341 (North/South). The UTM zones are parametrized individually, so if you
1342 want a Zone 30 map you should use C<t_utm(30)>. By default you get
1343 the northern subzone, so that locations in the southern hemisphere get
1344 negative Y coordinates. If you select the southern subzone (with the
1345 "subzone=>-1" option), you get offset southern UTM coordinates.
1346  
1347 The 20-subzone military system is not yet supported. If/when it is
1348 implemented, you will be able to enter "subzone=>[a-t]" to select a N/S
1349 subzone.
1350  
1351 Note that UTM is really a family of transverse Mercator projections
1352 with different central meridia. Each zone properly extends for six
1353 degrees of longitude on either side of its appropriate central meridian,
1354 with Zone 1 being centered at -177 degrees longitude (177 west).
1355 Properly speaking, the zones only extend from 80 degrees south to 84 degrees
1356 north; but this implementation lets you go all the way to 90 degrees.
1357 The default UTM coordinates are meters. The origin for each zone is
1358 on the equator, at an easting of -500,000 meters.
1359  
1360 The default output units are meters, assuming that you are wanting a
1361 map of the Earth. This will break for bodies other than Earth (which
1362 have different radii and hence different conversions between lat/lon
1363 angle and meters).
1364  
1365 The standard UTM projection has a slight reduction in scale at the
1366 prime meridian of each zone: the transverse Mercator projection's
1367 standard "parallels" are 180km e/w of the central meridian. However,
1368 many Europeans prefer the "Gauss-Kruger" system, which is virtually
1369 identical to UTM but with a normal tangent Mercator (standard parallel
1370 on the prime meridian). To get this behavior, set "gk=>1".
1371  
1372 Like the rest of the PDL::Transform::Cartography package, t_utm uses a
1373 spherical datum rather than the "official" ellipsoidal datums for the
1374 UTM system.
1375  
1376 This implementation was derived from the rather nice description by
1377 Denis J. Dean, located on the web at:
1378 http://www.cnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/utm.html
1379  
1380 OPTIONS
1381  
1382 =over 3
1383  
1384 =item STANDARD OPTIONS
1385  
1386 (No positional options -- Origin and Roll are ignored)
1387  
1388 =item ou, ounit, OutputUnit (default 'meters')
1389  
1390 (This is likely to become a standard option in a future release) The
1391 unit of the output map. By default, this is 'meters' for UTM, but you
1392 may specify 'deg' or 'km' or even (heaven help us) 'miles' if you
1393 prefer.
1394  
1395 =item sz, subzone, SubZone (default 1)
1396  
1397 Set this to -1 for the southern hemisphere subzone. Ultimately you
1398 should be able to set it to a letter to get the corresponding military
1399 subzone, but that's too much effort for now.
1400  
1401 =item gk, gausskruger (default 0)
1402  
1403 Set this to 1 to get the (European-style) tangent-plane Mercator with
1404 standard parallel on the prime meridian. The default of 0 places the
1405 standard parallels 180km east/west of the prime meridian, yielding better
1406 average scale across the zone. Setting gk=>1 makes the scale exactly 1.0
1407 at the central meridian, and >1.0 everywhere else on the projection.
1408 The difference in scale is about 0.3%.
1409  
1410 =back
1411  
1412 =cut
1413  
1414 0 ▶sub t_utm {
Subroutine t_utm: not called CC=6 SCAR=37.4
Pod documented
1415 0 my $zone = (int(shift)-1) % 60 + 1;
1416 0 my($x) = _new(@_,"UTM-$zone");
1417 0 my $opt = $x->{options};
1418  
1419 ## Make sure that there is a conversion (default is 'meters')
1420 0 ▶ $x->{ounit} = ['meter','meter'] unless defined($x->{ounit});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x->{"ounit"} 0 0 0
1421 0 ▶ $x->{ounit} = [$x->{ounit},$x->{ounit}] unless ref($x->{ounit});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $x->{"ounit"} 0 0 0
1422 0 $x->{params}->{oconv} = _uconv($x->{ounit}->[0]);
1423  
1424 ## Define our zone and NS offset
1425 0 my $subzone = _opt($opt,['sz', 'subzone', 'SubZone'],1);
1426 0 my $offset = zeroes(2);
1427 0 $offset->slice("0") .= 5e5*(2*PI/40e6)/$x->{params}->{oconv};
1428 0 ▶ $offset->slice("1") .= ($subzone < 0) ? PI/2/$x->{params}->{oconv} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$subzone < 0 ? : 0 0 0
1429  
1430 0 my $merid = ($zone * 6) - 183;
1431  
1432 0 my $gk = _opt($opt,['gk','gausskruger'],0);
1433  
1434 my($me) = t_compose(t_linear(post=>$offset,
1435 rot=>-90
1436 ),
1437  
1438 t_mercator(o=>[$merid,0],
1439 r=>90,
1440 ou=>$x->{ounit},
1441 0 ▶ s=>$gk ? 0 : (RAD2DEG * (180/6371))
Branch: 1 branch
BranchTrueFalseTotal
$gk ? : 0 0 0
1442 )
1443 );
1444  
1445  
1446 0 ▶ my $s = ($zone < 0) ? "S Hemisphere " : "";
Branch: 1 branch
BranchTrueFalseTotal
$zone < 0 ? : 0 0 0
1447 0 $me->{otype} = ["UTM-$zone Easting","${s}Northing"];
1448 0 $me->{ounit} = $x->{ounit};
1449  
1450 0 return $me;
1451 }
1452  
1453 ######################################################################
1454  
1455 =head2 t_sin_lat
1456  
1457 =for usage
1458  
1459 $t = t_sin_lat(<options>);
1460  
1461 =for ref
1462  
1463 (Cartography) Cyl. equal-area projection (cyl.; authalic)
1464  
1465 This projection is commonly used in solar Carrington plots; but not much
1466 for terrestrial mapping.
1467  
1468 OPTIONS
1469  
1470 =over 3
1471  
1472 =item STANDARD POSITIONAL OPTIONS
1473  
1474 =item s,std, Standard (default 0)
1475  
1476 This is the parallel at which the map is conformal. It is also conformal
1477 at the parallel of opposite sign. The conformality is achieved by matched
1478 vertical stretching and horizontal squishing (to achieve constant area).
1479  
1480 =back
1481  
1482 =cut
1483  
1484 1 @PDL::Transform::Cartography::SinLat::ISA = ('PDL::Transform::Cartography');
1485 1 ▶sub t_sin_lat {
Subroutine t_sin_lat: called CC=2 SCAR=7.0
Pod documented
1486 1 my($me) = _new(@_,"Sine-Latitude Projection");
1487  
1488 $me->{params}->{std} = topdl(_opt($me->{options},
1489 ['s','std','standard','Standard'],
1490 1 0))->at(0) * $me->{params}->{conv};
1491  
1492 1 ▶ if($me->{params}->{std} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($me->{'params'}{'std'} == 0) { } 1 0 1
1493 1 $me->{otype} = ['longitude','sin latitude'];
1494 1 $me->{ounit} = ['radians',' ']; # nonzero but blank!
1495 } else {
1496 0 $me->{otype} = ['proj. longitude','proj. sin latitude'];
1497 0 $me->{ounit} = ['radians',' '];
1498 }
1499  
1500 1 $me->{params}->{stretch} = sqrt(cos($me->{params}->{std}));
1501  
1502 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1503 1 my($d,$o) = @_;
1504 1 my($out) = $d->new_or_inplace;
1505  
1506 1 $out->slice("0:1") *= $me->{params}->{conv};
1507 1 $out->slice("(1)") .= sin($out->slice("(1)")) / $o->{stretch};
1508 1 $out->slice("(0)") *= $o->{stretch};
1509 1 $out;
1510 1 };
1511  
1512 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1513 1 my($d,$o) = @_;
1514 1 my($out) = $d->new_or_inplace;
1515 1 $out->slice("(1)") .= asin($out->slice("(1)") * $o->{stretch});
1516 1 $out->slice("(0)") /= $o->{stretch};
1517 1 $out->slice("0:1") /= $me->{params}->{conv};
1518 1 $out;
1519 1 };
1520  
1521 1 $me->_finish;
1522 }
1523  
1524 ######################################################################
1525  
1526 =head2 t_sinusoidal
1527  
1528 =for usage
1529  
1530 $t = t_sinusoidal(<options>);
1531  
1532 =for ref
1533  
1534 (Cartography) Sinusoidal projection (authalic)
1535  
1536 Sinusoidal projection preserves the latitude scale but scales
1537 longitude according to sin(lat); in this respect it is the companion to
1538 L</t_sin_lat>, which is also authalic but preserves the
1539 longitude scale instead.
1540  
1541 OPTIONS
1542  
1543 =over 3
1544  
1545 =item STANDARD POSITIONAL OPTIONS
1546  
1547 =back
1548  
1549 =cut
1550  
1551 1 ▶sub t_sinusoidal {
Subroutine t_sinusoidal: called CC=1 SCAR=0.0
Pod documented
1552 1 my($me) = _new(@_,"Sinusoidal Projection");
1553 1 $me->{otype} = ['longitude','latitude'];
1554 1 $me->{ounit} = [' ','radians'];
1555  
1556 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1557 1 my ($d,$o) = @_;
1558 1 my $out = $d->new_or_inplace;
1559 1 $out->slice("0:1") *= $o->{conv};
1560 1 $out->slice("(0)") *= cos($out->slice("(1)"));
1561 1 $out;
1562 1 };
1563  
1564 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1565 1 my ($d,$o) = @_;
1566 1 my $out = $d->new_or_inplace;
1567 1 my ($x, $y) = $out->using(0,1);
1568 1 $x /= cos($y);
1569 1 my $rej = ( (abs($x)>PI) | (abs($y)>(PI/2)) )->flat;
1570 1 $_->flat->where($rej) .= $o->{bad} for $x, $y;
1571 1 $out->slice("0:1") /= $o->{conv};
1572 1 $out;
1573 1 };
1574  
1575 1 $me->_finish;
1576 }
1577  
1578  
1579 ######################################################################
1580 #
1581 # Conic projections are subclassed for easier stringification and
1582 # parsing of the standard parallels. The constructor gets copied
1583 # into the current package for ease of hackage.
1584 #
1585 # This is a little kludgy -- it's intended for direct calling
1586 # rather than method calling, and it puts its own class name on the
1587 # front of the argument list. But, hey, it works...
1588 #
1589 1 @PDL::Transform::Cartography::Conic::ISA = ('PDL::Transform::Cartography');
1590 3 ▶sub _c_new {
Subroutine _c_new: called CC=4 SCAR=14.8
1591 3 my($def_std) = pop;
1592 3 my $me = PDL::Transform::Cartography::Conic->new(@_);
1593  
1594 3 my($p) = $me->{params};
1595 3 $p->{std} = _opt($me->{options},['s','std','standard','Standard'],
1596 $def_std);
1597 3 $p->{std} = topdl($p->{std}) * $me->{params}->{conv};
1598 $p->{std} = topdl([PI/2 * ($p->{std}<0 ? -1 : 1), $p->{std}->at(0)])
1599 3 ▶ if($p->{std}->nelem == 1);
Branch: 2 branches
BranchTrueFalseTotal
if $p->{"std"}->nelem == 1 0 3 3
$p->{'std'} < 0 ? : 0 0 0
1600  
1601 $me->{params}->{cylindrical} = 1
1602 3 ▶ if approx($p->{std}->slice("0"),-$p->{std}->slice("1"));
Branch: 1 branch
BranchTrueFalseTotal
if approx($p->{"std"}->slice(0), -$p->{"std"}->slice(1)) 0 3 3
1603  
1604 3 $me;
1605 }
1606  
1607 0 ▶sub PDL::Transform::Cartography::Conic::stringify {
Subroutine stringify: not called CC=1 SCAR=6.9
1608 0 my($me) = shift;
1609 0 my($out) = $me->SUPER::stringify;
1610  
1611 $out .= sprintf("\tStd parallels: %6.2f,%6.2f %s\n",
1612 $me->{params}->{std}->at(0) / $me->{params}->{conv},
1613 $me->{params}->{std}->at(1) / $me->{params}->{conv},
1614 0 $me->{params}->{u});
1615 0 $out;
1616 }
1617  
1618 ######################################################################
1619  
1620 =head2 t_conic
1621  
1622 =for usage
1623  
1624 $t = t_conic(<options>)
1625  
1626 =for ref
1627  
1628 (Cartography) Simple conic projection (conic; equidistant)
1629  
1630 This is the simplest conic projection, with parallels mapped to
1631 equidistant concentric circles. It is neither authalic nor conformal.
1632 This transformation is also referred to as the "Modified Transverse
1633 Mercator" projection in several maps of Alaska published by the USGS;
1634 and the American State of New Mexico re-invented the projection in
1635 1936 for an official map of that State.
1636  
1637 OPTIONS
1638  
1639 =over 3
1640  
1641 =item STANDARD POSITIONAL OPTIONS
1642  
1643 =item s, std, Standard (default 29.5, 45.5)
1644  
1645 The locations of the standard parallel(s) (where the cone intersects
1646 the surface of the sphere). If you specify only one then the other is
1647 taken to be the nearest pole. If you specify both of them to be one
1648 pole then you get an equidistant azimuthal map. If you specify both
1649 of them to be opposite and equidistant from the equator you get a
1650 Plate Carree projection.
1651  
1652 =back
1653  
1654 =cut
1655  
1656 1 ▶sub t_conic {
Subroutine t_conic: called CC=3 SCAR=11.1
Pod documented
1657 1 my($me) = _c_new(@_,"Simple Conic Projection",[29.5,45.5]);
1658  
1659 1 my($p) = $me->{params};
1660  
1661 1 ▶ if($p->{cylindrical}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"cylindrical"}) 0 1 1
1662 0 ▶ print STDERR "Simple conic: degenerate case; using Plate Carree\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
1663 if($PDL::verbose);
1664 0 return t_carree($me->{options});
1665 }
1666  
1667 1 my ($p0, $p1) = $p->{std}->using(0,1);
1668 1 $p->{n} = ((cos($p0) - cos($p1))
1669 /
1670 ($p1 - $p0));
1671  
1672 1 $p->{G} = cos($p0)/$p->{n} + $p0;
1673  
1674 1 $me->{otype} = ['Conic X','Conic Y'];
1675 1 $me->{ounit} = ['Proj. radians','Proj. radians'];
1676  
1677 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1678 1 my($d,$o) = @_;
1679 1 my($out) = $d->new_or_inplace;
1680  
1681 1 my($rho) = $o->{G} - $d->slice("(1)") * $o->{conv};
1682 1 my($theta) = $o->{n} * $d->slice("(0)") * $o->{conv};
1683  
1684 1 $out->slice("(0)") .= $rho * sin($theta);
1685 1 $out->slice("(1)") .= $o->{G} - $rho * cos($theta);
1686  
1687 1 $out;
1688 1 };
1689  
1690 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1691 1 my($d,$o) = @_;
1692 1 my($out) = $d->new_or_inplace;
1693  
1694 1 my($x) = $d->slice("(0)");
1695 1 my($y) = $o->{G} - $d->slice("(1)");
1696 1 my($rho) = sqrt($x*$x + $y*$y);
1697 1 ▶ $rho *= -1 if($o->{n}<0);
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"n"} < 0 0 1 1
1698  
1699 1 ▶ my $theta = ($o->{n} < 0) ? atan2(-$x,-$y) : atan2($x,$y);
Branch: 1 branch
BranchTrueFalseTotal
$o->{'n'} < 0 ? : 0 1 1
1700  
1701 1 my ($out0, $out1) = $out->using(0,1);
1702 1 $out1 .= $o->{G} - $rho;
1703 $out1->where(($out1 < -PI()/2) | ($out1 > PI/2))
1704 1 .= $o->{bad};
1705  
1706 1 $out0 .= $theta / $o->{n};
1707 $out0->where(($out0 < -PI()) | ($out0 > PI))
1708 1 .= $o->{bad};
1709  
1710 1 $out->slice("0:1") /= $o->{conv};
1711  
1712 1 $out;
1713 1 };
1714  
1715 1 $me->_finish;
1716 }
1717  
1718  
1719  
1720  
1721 ######################################################################
1722  
1723 =head2 t_albers
1724  
1725 =for usage
1726  
1727 $t = t_albers(<options>)
1728  
1729 =for ref
1730  
1731 (Cartography) Albers conic projection (conic; authalic)
1732  
1733 This is the standard projection used by the US Geological Survey for
1734 sectionals of the 50 contiguous United States of America.
1735  
1736 The projection reduces to the Lambert equal-area conic (infrequently
1737 used and not to be confused with the Lambert conformal conic,
1738 L</t_lambert>!) if the pole is used as one of the two
1739 standard parallels.
1740  
1741 Notionally, this is a conic projection onto a cone that intersects the
1742 sphere at the two standard parallels; it works best when the two parallels
1743 straddle the region of interest.
1744  
1745 OPTIONS
1746  
1747 =over 3
1748  
1749 =item STANDARD POSITIONAL OPTIONS
1750  
1751 =item s, std, standard, Standard (default (29.5,45.5))
1752  
1753 The locations of the standard parallel(s). If you specify only one then
1754 the other is taken to be the nearest pole and a Lambert Equal-Area Conic
1755 map results. If you specify both standard parallels to be the same pole,
1756 then the projection reduces to the Lambert Azimuthal Equal-Area map as
1757 aq special case. (Note that L</t_lambert> is Lambert's
1758 Conformal Conic, the most commonly used of Lambert's projections.)
1759  
1760 The default values for the standard parallels are those chosen by Adams
1761 for maps of the lower 48 US states: (29.5,45.5). The USGS recommends
1762 (55,65) for maps of Alaska and (8,18) for maps of Hawaii -- these latter
1763 are chosen to also include the Canal Zone and Philippine Islands farther
1764 south, which is why both of those parallels are south of the Hawaiian islands.
1765  
1766 The transformation reduces to the cylindrical equal-area (sin-lat)
1767 transformation in the case where the standard parallels are opposite and
1768 equidistant from the equator, and in fact this is implemented by a call to
1769 t_sin_lat.
1770  
1771 =back
1772  
1773 =cut
1774  
1775 1 ▶sub t_albers {
Subroutine t_albers: called CC=3 SCAR=11.1
Pod documented
1776 1 my($me) = _c_new(@_,"Albers Equal-Area Conic Projection",[29.5,45.5]);
1777  
1778 1 my($p) = $me->{params};
1779  
1780 1 ▶ if($p->{cylindrical}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"cylindrical"}) 0 1 1
1781 0 ▶ print STDERR "Albers equal-area conic: degenerate case; using equal-area cylindrical\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
1782 if($PDL::verbose);
1783 0 return t_sin_lat($me->{options});
1784 }
1785  
1786 1 my ($p1) = $p->{std}->using(0,1);
1787 1 $p->{n} = sin($p->{std})->sumover / 2;
1788 $p->{C} = (cos($p1)*cos($p1) +
1789 1 2 * $p->{n} * sin($p1) );
1790 1 $p->{rho0} = sqrt($p->{C}) / $p->{n};
1791  
1792 1 $me->{otype} = ['Conic X','Conic Y'];
1793 1 $me->{ounit} = ['Proj. radians','Proj. radians'];
1794  
1795 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1796 1 my($d,$o) = @_;
1797 1 my($out) = $d->new_or_inplace;
1798  
1799 1 my($rho) = sqrt( $o->{C} - 2 * $o->{n} * sin($d->slice("(1)") * $o->{conv}) ) / $o->{n};
1800 1 my($theta) = $o->{n} * $d->slice("(0)") * $o->{conv};
1801  
1802 1 $out->slice("(0)") .= $rho * sin($theta);
1803 1 $out->slice("(1)") .= $p->{rho0} - $rho * cos($theta);
1804 1 $out;
1805 1 };
1806  
1807 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1808 1 my($d,$o) = @_;
1809  
1810 1 my($out) = $d->new_or_inplace;
1811  
1812 1 my($x) = $d->slice("(0)");
1813 1 my($y) = $o->{rho0} - $d->slice("(1)");
1814  
1815 1 ▶ my($theta) = ($o->{n} < 0) ? atan2 -$x,-$y : atan2 $x, $y;
Branch: 1 branch
BranchTrueFalseTotal
$o->{'n'} < 0 ? : 0 1 1
1816 1 my($rho) = sqrt( $x*$x + $y*$y ) * $o->{n};
1817  
1818 1 $out->slice("(1)") .= asin( ( $o->{C} - ( $rho * $rho ) ) / (2 * $o->{n}) );
1819  
1820 1 $out->slice("(0)") .= $theta / $o->{n};
1821 1 $out->slice("(0)")->where(($out->slice("(0)")>PI) | ($out->slice("(0)")<-PI())) .= $o->{bad};
1822  
1823 1 $out->slice("0:1") /= $o->{conv};
1824  
1825 1 $out;
1826 1 };
1827  
1828 1 $me->_finish;
1829 }
1830  
1831 ######################################################################
1832  
1833 =head2 t_lambert
1834  
1835 =for usage
1836  
1837 $t = t_lambert(<options>);
1838  
1839 =for ref
1840  
1841 (Cartography) Lambert conic projection (conic; conformal)
1842  
1843 Lambert conformal conic projection is widely used in aeronautical
1844 charts and state base maps published by the USA's FAA and USGS. It's
1845 especially useful for mid-latitude charts. In particular, straight lines
1846 approximate (but are not exactly) great circle routes of up to ~2 radians.
1847  
1848 The default standard parallels are 33 and 45 to match the USGS state
1849 1:500,000 base maps of the United States. At scales of 1:500,000 and
1850 larger, discrepancies between the spherical and ellipsoidal projections
1851 become important; use care with this projection on spheres.
1852  
1853 OPTIONS
1854  
1855 =over 3
1856  
1857 =item STANDARD POSITIONAL OPTIONS
1858  
1859 =item s, std, standard, Standard (default (33,45))
1860  
1861 The locations of the standard parallel(s) for the conic projection.
1862 The transform reduces to the Mercator projection in the case where the
1863 standard parallels are opposite and equidistant from the equator, and
1864 in fact this is implemented by a call to t_mercator.
1865  
1866 =item c, clip, Clip (default [-75,75])
1867  
1868 Because the transform is conformal, the distant pole is displaced to
1869 infinity. Many applications require a clipping boundary. The value
1870 is in whatever angular unit you set with the standard 'unit' option.
1871 For consistency with L</t_mercator>, clipping works the same
1872 way even though in most cases only one pole needs it. Set this to 0
1873 for no clipping at all.
1874  
1875 =back
1876  
1877 =cut
1878  
1879 1 ▶sub t_lambert {
Subroutine t_lambert: called CC=6 SCAR=18.5
Pod documented
1880 1 my($me)= _c_new(@_,"Lambert Conformal Conic Projection",[33,45]);
1881 1 my($p) = $me->{params};
1882  
1883 1 ▶ if($p->{cylindrical}){
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"cylindrical"}) 0 1 1
1884 0 ▶ print STDERR "Lambert conformal conic: std parallels are opposite & equal; using Mercator\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
1885 if($PDL::verbose);
1886 0 return t_mercator($me->{options});
1887 }
1888  
1889 # Find clipping parallels
1890 1 $p->{c} = _opt($me->{options},['c','clip','Clip'],undef);
1891 1 ▶ if(defined($p->{c})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p->{'c'}) { } 0 1 1
1892 0 $p->{c} = topdl($p->{c});
1893 } else {
1894 1 $p->{c} = topdl([-75,75]);
1895 }
1896 1 ▶ $p->{c} = abs($p->{c}) * topdl([-1,1]) if($p->{c}->nelem == 1);
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"c"}->nelem == 1 0 1 1
1897 1 $p->{c} = [$p->{c}->list];
1898  
1899 1 my ($p0, $p1) = $p->{std}->using(0,1);
1900 # Prefrobnicate
1901 1 ▶ if (approx($p0,$p1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (approx($p0, $p1)) { } 0 1 1
1902 0 $p->{n} = sin($p0);
1903 } else {
1904 1 $p->{n} = log(cos($p0)/cos($p1))
1905 /
1906 log( tan( PI/4 + $p1/2 )
1907 /
1908 tan( PI/4 + $p0/2 )
1909 )
1910 ;
1911 }
1912  
1913 $p->{F} = ( cos($p0)
1914 *
1915 ( tan( PI/4 + $p0/2 ) ** $p->{n} ) / $p->{n}
1916 1 );
1917  
1918 1 $p->{rho0} = $p->{F};
1919  
1920 1 $me->{otype} = ['Conic X','Conic Y'];
1921 1 $me->{ounit} = ['Proj. radians','Proj. radians'];
1922  
1923 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1924 1 my($d,$o) = @_;
1925 1 my($out) = $d->new_or_inplace;
1926  
1927 my($cl) = ( ($o->{c}->[0] == $o->{c}->[1]) ?
1928 $d->slice("(1)")*$o->{conv} :
1929 1 ($d->slice("(1)")->clip(@{$o->{c}}) * $o->{conv})
1930 1 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$o->{'c'}[0] == $o->{'c'}[1] ? : 0 1 1
1931  
1932 1 my($rho) = $o->{F} / ( tan(PI/4 + ($cl)/2 ) ** $o->{n} );
1933 1 my($theta) = $o->{n} * $d->slice("(0)") * $o->{conv};
1934  
1935 1 $out->slice("(0)") .= $rho * sin($theta);
1936 1 $out->slice("(1)") .= $o->{rho0} - $rho * cos($theta);
1937 1 $out;
1938 1 };
1939  
1940 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1941 1 my($d,$o) = @_;
1942 1 my($out) = $d->new_or_inplace;
1943  
1944 1 my($x) = $d->slice("(0)");
1945 1 my($y) = $o->{rho0} - $d->slice("(1)");
1946  
1947 1 my($rho) = sqrt($x * $x + $y * $y);
1948 1 ▶ $rho *= -1 if($o->{n} < 0);
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"n"} < 0 0 1 1
1949 1 ▶ my($theta) = ($o->{n} < 0) ? atan2(-$x,-$y):(atan2 $x,$y);
Branch: 1 branch
BranchTrueFalseTotal
$o->{'n'} < 0 ? : 0 1 1
1950  
1951  
1952 1 $out->slice("(0)") .= $theta / $o->{n};
1953 1 $out->slice("(0)")->where(($out->slice("(0)") > PI) | ($out->slice("(0)") < -PI())) .= $o->{bad};
1954  
1955  
1956 1 $out->slice("(1)") .= 2 * atan(($o->{F}/$rho)**(1.0/$o->{n})) - PI/2;
1957 1 $out->slice("(1)")->where(($out->slice("(1)") > PI/2) | ($out->slice("(1)") < -PI()/2)) .= $o->{bad};
1958  
1959 1 $out->slice("0:1") /= $o->{conv};
1960  
1961 1 $out;
1962 1 };
1963  
1964  
1965 1 $me->_finish;
1966 }
1967  
1968 ######################################################################
1969  
1970 =head2 t_stereographic
1971  
1972 =for usage
1973  
1974 $t = t_stereographic(<options>);
1975  
1976 =for ref
1977  
1978 (Cartography) Stereographic projection (az.; conf.; persp.)
1979  
1980 The stereographic projection is a true perspective (planar) projection
1981 from a point on the spherical surface opposite the origin of the map.
1982  
1983 OPTIONS
1984  
1985 =over 3
1986  
1987 =item STANDARD POSITIONAL OPTIONS
1988  
1989 =item c, clip, Clip (default 120)
1990  
1991 This is the angular distance from the center to the edge of the
1992 projected map. The default 120 degrees gives you most of the opposite
1993 hemisphere but avoids the hugely distorted part near the antipodes.
1994  
1995 =back
1996  
1997 =cut
1998  
1999 1 ▶sub t_stereographic {
Subroutine t_stereographic: called CC=1 SCAR=0.0
Pod documented
2000 1 my($me) = _new(@_,"Stereographic Projection");
2001  
2002 1 $me->{params}->{k0} = 1.0;
2003 $me->{params}->{c} = _opt($me->{options},
2004 ['c','clip','Clip'],
2005 1 120) * $me->{params}->{conv};
2006  
2007 1 $me->{otype} = ['Stereo X','Stereo Y'];
2008 1 $me->{ounit} = ['Proj. body radii','Proj. radians'];
2009  
2010 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2011 1 my($d,$o) = @_;
2012 1 my($out) = $d->new_or_inplace;
2013  
2014 1 my ($out0, $out1) = $out->using(0,1);
2015 1 my ($th,$ph) = map $_ * $o->{conv}, $out0, $out1;
2016  
2017 1 my $cph = cos($ph); # gets re-used
2018 1 my($k) = 2 * $o->{k0} / (1 + cos($th) * $cph);
2019 1 $out0 .= $k * $cph * sin($th);
2020 1 $out1 .= $k * sin($ph);
2021  
2022 1 my $cl0 = 2*$o->{k0} / (1 + cos($o->{c}));
2023 1 $out0->where($k>$cl0) .= $o->{bad};
2024 1 $out1->where($k>$cl0) .= $o->{bad};
2025 1 $out;
2026 1 };
2027  
2028 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2029 1 my($d,$o) = @_;
2030 1 my($out) = $d->new_or_inplace;
2031  
2032 1 my ($x, $y) = $d->using(0,1);
2033 1 my($rho) = sqrt($x*$x + $y*$y);
2034 1 my($c) = 2 * atan2($rho,2*$o->{k0});
2035  
2036 1 $out->slice("(0)") .= atan2($x * sin($c), $rho * cos($c));
2037 1 $out->slice("(1)") .= asin($y * sin($c) / $rho);
2038  
2039 1 $out ->slice("0:1") /= $o->{conv};
2040 1 $out;
2041 1 };
2042  
2043 1 $me->_finish;
2044 }
2045  
2046 ######################################################################
2047  
2048 =head2 t_gnomonic
2049  
2050 =for usage
2051  
2052 $t = t_gnomonic(<options>);
2053  
2054 =for ref
2055  
2056 (Cartography) Gnomonic (focal-plane) projection (az.; persp.)
2057  
2058 The gnomonic projection projects a hemisphere onto a tangent plane.
2059 It is useful in cartography for the property that straight lines are
2060 great circles; and it is useful in scientific imaging because
2061 it is the projection generated by a simple optical system with a flat
2062 focal plane.
2063  
2064 OPTIONS
2065  
2066 =over 3
2067  
2068 =item STANDARD POSITIONAL OPTIONS
2069  
2070 =item c, clip, Clip (default 75)
2071  
2072 This is the angular distance from the center to the edge of the
2073 projected map. The default 75 degrees gives you most of the
2074 hemisphere but avoids the hugely distorted part near the horizon.
2075  
2076 =back
2077  
2078 =cut
2079  
2080 1 ▶sub t_gnomonic {
Subroutine t_gnomonic: called CC=1 SCAR=0.0
Pod documented
2081 1 my($me) = _new(@_,"Gnomonic Projection");
2082  
2083 1 $me->{params}->{k0} = 1.0; # Useful for standard parallel (TBD: add one)
2084  
2085 $me->{params}->{c} = topdl(_opt($me->{options},
2086 ['c','clip','Clip'],
2087 1 75) * $me->{params}->{conv});
2088  
2089 1 $me->{params}->{c} .= $me->{params}->{c}->clip(undef,(90-1e-6)*$me->{params}->{conv});
2090  
2091 1 $me->{otype} = ['Tangent-plane X','Tangent-plane Y'];
2092 1 $me->{ounit} = ['Proj. radians','Proj. radians'];
2093  
2094 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2095 1 my($d,$o) = @_;
2096 1 my($out) = $d->new_or_inplace;
2097  
2098 my ($th, $ph) = map $_ * $o->{conv},
2099 1 my ($out0, $out1) = $out->using(0,1);
2100  
2101 1 my $cph = cos($ph); # gets re-used
2102  
2103 1 my $k = $o->{k0} / (cos($th) * $cph);
2104 1 my $cl0 = $o->{k0} / (cos($o->{c}));
2105  
2106 1 $out0 .= $k * $cph * sin($th);
2107 1 $out1 .= $k * sin($ph);
2108  
2109 1 my $idx = whichND(($k > $cl0) | ($k < 0) | (!isfinite($k)));
2110 1 ▶ if ($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 0 1 1
2111 0 $_->range($idx) .= $o->{bad} for $out0, $out1;
2112 }
2113  
2114 1 $out;
2115 1 };
2116  
2117 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2118 1 my ($d,$o) = @_;
2119 1 my $out = $d->new_or_inplace;
2120  
2121 1 my ($x, $y) = $d->using(0,1);
2122  
2123 1 my $rho = sqrt($x*$x + $y*$y);
2124 1 my $c = atan($rho/$o->{k0});
2125  
2126 1 my ($out0, $out1) = $out->using(0,1);
2127 1 $out0 .= atan2($x * sin($c), $rho * cos($c));
2128 1 $out1 .= asin($y * sin($c) / $rho);
2129  
2130 1 my $idx = whichND($rho==0);
2131  
2132 1 ▶ if ($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 1 0 1
2133 1 $_->range($idx) .= 0 for $out0, $out1;
2134 }
2135 1 $out->slice("0:1") /= $o->{conv};
2136 1 $out;
2137 1 };
2138  
2139 1 $me->_finish;
2140 }
2141  
2142 ######################################################################
2143  
2144 =head2 t_az_eqd
2145  
2146 =for usage
2147  
2148 $t = t_az_eqd(<options>);
2149  
2150 =for ref
2151  
2152 (Cartography) Azimuthal equidistant projection (az.; equi.)
2153  
2154 Basic azimuthal projection preserving length along radial lines from
2155 the origin (meridians, in the original polar aspect). Hence, both
2156 azimuth and distance are correct for journeys beginning at the origin.
2157  
2158 Applied to the celestial sphere, this is the projection made by
2159 fisheye lenses; it is also the projection into which C<t_vertical>
2160 puts perspective views.
2161  
2162 The projected plane scale is normally taken to be planetary radii;
2163 this is useful for cartographers but not so useful for scientific
2164 observers. Setting the 't=>1' option causes the output scale to shift
2165 to camera angular coordinates (the angular unit is determined by the
2166 standard 'Units' option; default is degrees).
2167  
2168 OPTIONS
2169  
2170 =over 3
2171  
2172 =item STANDARD POSITIONAL OPTIONS
2173  
2174 =item c, clip, Clip (default 180 degrees)
2175  
2176 The largest angle relative to the origin. Default is the whole sphere.
2177  
2178 =back
2179  
2180 =cut
2181  
2182 1 ▶sub t_az_eqd {
Subroutine t_az_eqd: called CC=1 SCAR=0.0
Pod documented
2183 1 my($me) = _new(@_,"Equidistant Azimuthal Projection");
2184  
2185 $me->{params}->{c} = topdl(_opt($me->{options},
2186 ['c','clip','Clip'],
2187 1 180) * $me->{params}->{conv});
2188  
2189 1 $me->{otype} = ['X distance','Y distance'];
2190 1 $me->{ounit} = ['radians','radians'];
2191  
2192 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2193 1 my($d,$o) = @_;
2194 1 my($out) = $d->new_or_inplace;
2195  
2196 1 my($ph) = $d->slice("(1)") * $o->{conv};
2197 1 my($th) = $d->slice("(0)") * $o->{conv};
2198  
2199 1 my $cos_c = cos($ph) * cos($th);
2200 1 my $c = acos($cos_c);
2201 1 my $k = $c / sin($c);
2202 1 $k->where($c==0) .= 1;
2203  
2204 1 my ($x, $y) = $out->using(0,1);
2205  
2206 1 $x .= $k * cos($ph) * sin($th);
2207 1 $y .= $k * sin($ph);
2208  
2209 1 my $idx = whichND($c > $o->{c});
2210 1 ▶ if ($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 0 1 1
2211 0 $_->range($idx) .= $o->{bad} for $x, $y;
2212 }
2213  
2214 1 $out;
2215 1 };
2216  
2217 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2218 1 my($d,$o) = @_;
2219 1 my $out = $d->new_or_inplace;
2220 1 my ($x, $y) = $d->using(0,1);
2221  
2222 1 my $rho = $d->slice("0:1")->magnover;
2223 1 my ($out0, $out1) = $out->using(0,1);
2224 1 $out0 .= atan2( $x * sin($rho), $rho * cos $rho );
2225 1 $out1 .= asin( $y * sin($rho) / $rho );
2226  
2227 1 my $idx = whichND(($rho == 0) | ($rho > PI));
2228 1 ▶ if ($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 1 0 1
2229 1 $_->range($idx) .= $o->{bad} for $out0, $out1;
2230 }
2231  
2232 1 $out->slice("0:1") /= $o->{conv};
2233  
2234 1 $out;
2235 1 };
2236  
2237 1 $me->_finish;
2238 }
2239  
2240  
2241 ######################################################################
2242  
2243 =head2 t_az_eqa
2244  
2245 =for usage
2246  
2247 $t = t_az_eqa(<options>);
2248  
2249 =for ref
2250  
2251 (Cartography) Azimuthal equal-area projection (az.; auth.)
2252  
2253 OPTIONS
2254  
2255 =over 3
2256  
2257 =item STANDARD POSITIONAL OPTIONS
2258  
2259 =item c, clip, Clip (default 180 degrees)
2260  
2261 The largest angle relative to the origin. Default is the whole sphere.
2262  
2263 =back
2264  
2265 =cut
2266  
2267 1 ▶sub t_az_eqa {
Subroutine t_az_eqa: called CC=1 SCAR=0.0
Pod documented
2268 1 my($me) = _new(@_,"Equal-Area Azimuthal Projection");
2269  
2270 $me->{params}->{c} = topdl(_opt($me->{options},
2271 ['c','clip','Clip'],
2272 1 180) * $me->{params}->{conv});
2273  
2274 1 $me->{otype} = ['Azimuthal X','Azimuthal Y'];
2275 1 $me->{ounit} = ['Proj. radians','Proj. radians'];
2276  
2277 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2278 1 my ($d,$o) = @_;
2279 1 my $out = $d->new_or_inplace;
2280  
2281 my ($th, $ph) = map $_ * $o->{conv},
2282 1 my ($x, $y) = $out->using(0,1);
2283  
2284 1 my $cos_ph = cos($ph);
2285 1 my $c = acos($cos_ph * cos($th));
2286 1 my $k = 1.0/cos($c/2);
2287  
2288 1 $x .= $k * $cos_ph * sin($th);
2289 1 $y .= $k * sin($ph);
2290  
2291 1 my $idx = whichND($c > $o->{c});
2292 1 ▶ if ($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 0 1 1
2293 0 $_->range($idx) .= $o->{bad} for $x, $y;
2294 }
2295  
2296 1 $out;
2297 1 };
2298  
2299 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2300 1 my ($d,$o) = @_;
2301 1 my $out = $d->new_or_inplace;
2302  
2303 1 my ($x, $y) = $d->using(0,1);
2304 1 my ($th, $ph) = $out->using(0,1);
2305 1 my $rho = sqrt($x*$x + $y*$y);
2306 1 my $c = 2 * asin($rho/2);
2307 1 my $sin_c = sin($c);
2308  
2309 1 my $rho_no0 = $rho + ($rho == 0);
2310 1 $ph .= asin($y * $sin_c / $rho_no0);
2311 1 $th .= atan2($x * $sin_c,$rho * cos($c));
2312  
2313 1 $ph /= $o->{conv};
2314 1 $th /= $o->{conv};
2315  
2316 1 $out;
2317 1 };
2318  
2319 1 $me->_finish;
2320 }
2321  
2322  
2323 ######################################################################
2324  
2325 =head2 t_hammer, t_aitoff
2326  
2327 =for ref
2328  
2329 (Cartography) Hammer/Aitoff elliptical projection (az.; auth.)
2330  
2331 The Hammer/Aitoff projection is often used to display the Celestial
2332 sphere. It is mathematically related to the Lambert Azimuthal Equal-Area
2333 projection (L</t_az_eqa>), and maps the sphere to an ellipse of unit
2334 eccentricity, with vertical radius sqrt(2) and horizontal radius of
2335 2 sqrt(2).
2336  
2337 OPTIONS
2338  
2339 =over 3
2340  
2341 =item STANDARD POSITIONAL OPTIONS
2342  
2343 =back
2344  
2345 =cut
2346  
2347 1 *t_aitoff = *t_aitoff = \&t_hammer;
2348  
2349 1 ▶sub t_hammer {
Subroutine t_hammer: called CC=1 SCAR=0.0
Pod documented
2350 1 my($me) = _new(@_,"Hammer/Aitoff Projection");
2351  
2352 1 $me->{otype} = ['Longitude','Latitude'];
2353 1 $me->{ounit} = [' ',' '];
2354 1 $me->{odim} = 2;
2355 1 $me->{idim} = 2;
2356  
2357 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2358 1 my ($d,$o) = @_;
2359 1 my $out = $d->new_or_inplace;
2360 1 $out->slice("0:1") *= $o->{conv};
2361 1 my ($th, $ph) = $out->using(0,1);
2362 1 my $t = sqrt( 2 / (1 + cos($ph) * cos($th/2)));
2363 1 $th .= 2 * $t * cos($ph) * sin($th/2);
2364 1 $ph .= $t * sin($ph);
2365 1 $out;
2366 }
2367 1 ;
2368  
2369 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
2370 1 my ($d,$o) = @_;
2371 1 my $out = $d->new_or_inplace;
2372 1 my ($x, $y) = $out->using(0,1);
2373  
2374 1 my $rej = which(($x*$x/8 + $y*$y/2)->flat > 1);
2375  
2376 1 my $z = sqrt( my $zz = (1 - $x*$x/16 - $y*$y/4) );
2377 1 $x .= 2 * atan( ($z * $x) / (4 * $zz - 2) );
2378 1 $y .= asin($y * $z);
2379  
2380 1 $out->slice("0:1") /= $o->{conv};
2381  
2382 1 ▶ if (!$rej->isempty) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rej->isempty) 0 1 1
2383 0 $_->flat->slice($rej) .= $o->{bad} for $x, $y;
2384 }
2385  
2386 1 $out;
2387 1 };
2388  
2389 1 $me->_finish;
2390 }
2391  
2392  
2393 ######################################################################
2394  
2395 =head2 t_vertical, t_zenithal
2396  
2397 =for usage
2398  
2399 $t = t_vertical(<options>);
2400  
2401 =for ref
2402  
2403 (Cartography) Vertical perspective projection (az.; persp.)
2404  
2405 Vertical (also called "zenithal") perspective projection is a
2406 generalization of L<gnomonic|/t_gnomonic>
2407 and L<stereographic|/t_stereographic> projection, and a special case of
2408 L<perspective|/t_perspective> projection. It is a projection from the
2409 sphere onto a tangent plane from a point at the camera location.
2410  
2411 OPTIONS
2412  
2413 =over 3
2414  
2415 =item STANDARD POSITIONAL OPTIONS
2416  
2417 =item m, mask, Mask, h, hemisphere, Hemisphere [default 'near']
2418  
2419 The hemisphere to keep in the projection (see L<PDL::Transform::Cartography>).
2420  
2421 =item r0, R0, radius, d, dist, distance [default 2.0]
2422  
2423 The altitude of the focal plane above the center of the sphere. The default
2424 places the point of view one radius above the surface.
2425  
2426 =item t, telescope, Telescope, cam, Camera (default '')
2427  
2428 If this is set, then the central scale is in telescope or camera
2429 angular units rather than in planetary radii. The angular units are
2430 parsed as with the normal 'u' option for the lon/lat specification.
2431 If you specify a non-string value (such as 1) then you get telescope-frame
2432 radians, suitable for working on with other transformations.
2433  
2434 =item f, fish, fisheye (default '')
2435  
2436 If this is set then the output is in azimuthal equidistant coordinates
2437 instead of in tangent-plane coordinates. This is a convenience function
2438 for '(t_az_eqd) x !(t_gnomonic) x (t_vertical)'.
2439  
2440 =back
2441  
2442 =cut
2443  
2444 1 ▶sub t_vertical {
Subroutine t_vertical: called CC=13 SCAR=31.8
Pod documented
2445 1 my($me) = _new(@_,'Vertical Perspective');
2446 1 my $p = $me->{params};
2447  
2448 my $m= _opt($me->{options},
2449 1 ['m','mask','Mask','h','hemi','hemisphere','Hemisphere'],
2450 1);
2451  
2452 1 $me->{otype} = ['Perspective X','Perspective Y'];
2453 1 $me->{ounit} = ['Body radii','Body radii'];
2454  
2455 1 ▶ if($m=~m/^b/i) {
Branch: 3 branches
BranchTrueFalseTotal
if ($m =~ /^b/i) { } 0 1 1
elsif ($m =~ /^n/i) { } 0 1 1
elsif ($m =~ /^f/i) { } 0 1 1
2456 0 $p->{m} = 0;
2457 } elsif($m=~m/^n/i) {
2458 0 $p->{m} = 1;
2459 } elsif($m=~m/^f/i) {
2460 0 $p->{m} = 2;
2461 } else {
2462 1 $p->{m} = $m;
2463 }
2464  
2465 $p->{r0} = _opt($me->{options},
2466 1 ['r0','R0','radius','Radius',
2467 'd','dist','distance','Distance'],
2468 2.0
2469 );
2470  
2471 1 ▶ if($p->{r0} == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"r0"} == 0) 0 1 1
2472 0 ▶ print "t_vertical: r0 = 0; using t_gnomonic instead\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
2473 if($PDL::verbose);
2474 0 return t_gnomonic($me->{options});
2475 }
2476  
2477 1 ▶ if($p->{r0} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"r0"} == 1) 0 1 1
2478 0 ▶ print "t_vertical: r0 = 1; using t_stereographic instead\n"
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
2479 if($PDL::verbose);
2480 0 return t_stereographic($me->{options});
2481 }
2482  
2483  
2484 $p->{t} = _opt($me->{options},
2485 1 ['t','tele','telescope','Telescope',
2486 'cam','camera','Camera'],
2487 undef);
2488  
2489 $p->{f} = _opt($me->{options},
2490 1 ['f','fish','fisheye','Fisheye'],
2491 undef);
2492  
2493 $p->{t} = 'rad'
2494 1 ▶ if($p->{f} && !defined($p->{t}));
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"f"} and not defined $p->{"t"} 0 1 1
Condition33%1/3
$p->{"f"} and not defined $p->{"t"}
!ll&&!rl&&r
100
MC/DC0%0/2
$p->{"f"} and not defined $p->{"t"}
$p->{"f"} not defined $p->{"t"}
Truth table33%1/3
A and not(B)
A= $p->{"f"}B= not defined $p->{"t"}
ABresult
0X0
100
111
2495  
2496 $p->{tconv} = _uconv($p->{t},1) || _uconv('rad')
2497 1 ▶ if(defined $p->{t});
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"t"} 0 1 1
Condition0%0/3
_uconv($p->{'t'}, 1) || _uconv('rad')
l!l&&r!l&&!r
000
MC/DC0%0/2
_uconv($p->{'t'}, 1) || _uconv('rad')
_uconv($p->{'t'}, 1) _uconv('rad')
Truth table0%0/3
A || B
A= _uconv($p->{'t'}, 1)B= _uconv('rad')
ABresult
1X1
011
000
2498  
2499 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=10 SCAR=26.0
2500 1 my ($d,$o) = @_;
2501 1 my $out = $d->new_or_inplace;
2502 1 my ($th, $ph) = map $_*$o->{conv}, $d->using(0,1);
2503  
2504 1 my $cph = cos($ph);
2505 1 my $cos_c = $cph * cos($th);
2506  
2507 my $k = (($o->{r0} - 1) /
2508 1 ($o->{r0} - $cos_c));
2509  
2510 $out->slice("0:1") /= ($o->{r0} - 1.0) * ($o->{f} ? 1.0 : $o->{tconv})
2511 1 ▶ if($o->{t});
Branch: 2 branches
BranchTrueFalseTotal
if $o->{"t"} 0 1 1
$o->{'f'} ? : 0 0 0
2512  
2513 1 my ($out0, $out1) = $out->using(0,1);
2514 1 $out0 .= $cph * sin($th);
2515 1 $out1 .= sin($ph);
2516  
2517 # Handle singularity at the origin
2518 1 $k->where(($out->slice("(0)") == 0) & ($out->slice("(1)") == 0)) .= 0;
2519 1 $out->slice("0:1") *= $k->dummy(0,2);
2520  
2521 1 ▶ if ($o->{m}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{"m"}) 1 0 1
2522 1 my $idx;
2523 $idx = whichND($cos_c < 1.0/$o->{r0})
2524 1 ▶ if $o->{m} == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"m"} == 1 1 0 1
2525 $idx = whichND($cos_c > 1.0/$o->{r0})
2526 1 ▶ if $o->{m} == 2;
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"m"} == 2 0 1 1
2527 1 ▶ if (defined $idx && ref $idx eq 'PDL' && $idx->nelem){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx and ref $idx eq "PDL" and $idx->nelem) 0 1 1
Condition33%2/6
defined $idx and ref $idx eq "PDL" and $idx->nelem
!ll&&!rl&&r
010
defined $idx and ref $idx eq "PDL"
!ll&&!rl&&r
001
MC/DC0%0/3
defined $idx and ref $idx eq "PDL" and $idx->nelem
defined $idx ref $idx eq "PDL" $idx->nelem
Truth table25%1/4
A and B and C
A= defined $idxB= ref $idx eq "PDL"C= $idx->nelem
ABCresult
0XX0
10X0
1100
1111
2528 0 $_->range($idx) .= $o->{bad} for $out0, $out1;
2529 }
2530 }
2531  
2532 1 $out;
2533 1 };
2534  
2535 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=6 SCAR=20.7
2536 1 my ($d,$o) = @_;
2537 1 my $out = $d->new_or_inplace;
2538  
2539 # Reverse the hemisphere if the mask is set to 'far'
2540 1 ▶ my $P = ($o->{m} == 2) ? -$o->{r0} : $o->{r0};
Branch: 1 branch
BranchTrueFalseTotal
$o->{'m'} == 2 ? : 0 1 1
2541  
2542 $out->slice("0:1") *= ($P - 1.0) * ($o->{f} ? 1.0 : $o->{tconv})
2543 1 ▶ if($o->{t});
Branch: 2 branches
BranchTrueFalseTotal
if $o->{"t"} 0 1 1
$o->{'f'} ? : 0 0 0
2544  
2545 1 my $rho = $d->slice("0:1")->magnover;
2546 1 my $sin_c = ( $P - sqrt( 1 - ($rho*$rho * ($P+1)/($P-1)) ) ) /
2547 ( ($P-1)/$rho + $rho/($P-1) );
2548  
2549 1 my $cos_c = sqrt(1 - $sin_c*$sin_c);
2550  
2551 # Switch c's quadrant where necessary, by inverting cos(c).
2552 1 ▶ if ($P<0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($P < 0) 0 1 1
2553 0 my $idx = whichND($rho > ($P-1/$P));
2554 0 ▶ $cos_c->range($idx) *= -1
Branch: 1 branch
BranchTrueFalseTotal
if $idx->nelem > 0 0 0 0
2555 if $idx->nelem > 0;
2556 }
2557  
2558 1 $out->slice("(0)") .= atan( $d->slice("(0)") * $sin_c / ($rho * $cos_c) );
2559 1 $out->slice("(1)") .= asin( $d->slice("(1)") * $sin_c / $rho );
2560  
2561 1 $out->slice("0:1") /= $o->{conv};
2562  
2563 1 $out;
2564 1 };
2565  
2566  
2567 # Compose on both front and back as necessary.
2568 return t_compose( t_scale(1.0/$p->{tconv}),
2569 t_az_eqd,
2570 t_gnomonic->inverse,
2571 $me->_finish )
2572 1 ▶ if($p->{f});
Branch: 1 branch
BranchTrueFalseTotal
if $p->{"f"} 0 1 1
2573  
2574 1 $me->_finish;
2575 }
2576  
2577 1 *t_zenithal = *t_zenithal = \&t_vertical;
2578  
2579 ######################################################################
2580  
2581 =head2 t_perspective
2582  
2583 =for usage
2584  
2585 $t = t_perspective(<options>);
2586  
2587 =for ref
2588  
2589 (Cartography) Arbitrary perspective projection
2590  
2591 Perspective projection onto a focal plane from an arbitrary location
2592 within or without the sphere, with an arbitrary central look direction,
2593 and with correction for magnification within the optical system.
2594  
2595 In the forward direction, t_perspective generates perspective views of
2596 a sphere given (lon/lat) mapping or vector information. In the reverse
2597 direction, t_perspective produces (lon/lat) maps from aerial or distant
2598 photographs of spherical objects.
2599  
2600 Viewpoints outside the sphere treat the sphere as opaque by default,
2601 though you can use the 'm' option to specify either the near or far
2602 surface (relative to the origin). Viewpoints below the surface treat
2603 the sphere as transparent and undergo a mirror reversal for
2604 consistency with projections that are special cases of the perspective
2605 projection (e.g. t_gnomonic for r0=0 or t_stereographic for r0=-1).
2606  
2607 Magnification correction handles the extra edge distortion due to
2608 higher angles between the focal plane and focused rays within the
2609 optical system of your camera. If you do not happen to know the
2610 magnification of your camera, a simple rule of thumb is that the
2611 magnification of a reflective telescope is roughly its focal length
2612 (plate scale) divided by its physical length; and the magnification of
2613 a compound refractive telescope is roughly twice its physical length divided
2614 by its focal length. Simple optical systems with a single optic have
2615 magnification = 1. Fisheye lenses have magnification < 1.
2616  
2617 This transformation was derived by direct geometrical calculation
2618 rather than being translated from Voxland & Snyder.
2619  
2620 OPTIONS
2621  
2622 =over 3
2623  
2624 =item STANDARD POSITIONAL OPTIONS
2625  
2626 As always, the 'origin' field specifies the sub-camera point on the
2627 sphere.
2628  
2629 The 'roll' option is the roll angle about the sub-camera point, for
2630 consistency with the other projectons.
2631  
2632 =item p, ptg, pointing, Pointing (default (0,0,0))
2633  
2634 The pointing direction, in (horiz. offset, vert. offset, roll) of the
2635 camera relative to the center of the sphere. This is a spherical
2636 coordinate system with the origin pointing directly at the sphere and
2637 the pole pointing north in the pre-rolled coordinate system set by the
2638 standard origin. It's most useful for space-based images taken some distance
2639 from the body in question (e.g. images of other planets or the Sun).
2640  
2641 Be careful not to confuse 'p' (pointing) with 'P' (P angle, a standard
2642 synonym for roll).
2643  
2644 =item c, cam, camera, Camera (default undef)
2645  
2646 Alternate way of specifying the camera pointing, using a spherical
2647 coordinate system with poles at the zenith (positive) and nadir
2648 (negative) -- this is useful for aerial photographs and such, where
2649 the point of view is near the surface of the sphere. You specify
2650 (azimuth from N, altitude from horizontal, roll from vertical=up). If
2651 you specify pointing by this method, it overrides the 'pointing'
2652 option, above. This coordinate system is most useful for aerial photography
2653 or low-orbit work, where the nadir is not necessarily the most interesting
2654 part of the scene.
2655  
2656 =item r0, R0, radius, d, dist, distance [default 2.0]
2657  
2658 The altitude of the point of view above the center of the sphere.
2659 The default places the point of view 1 radius aboove the surface.
2660 Do not confuse this with 'r', the standard origin roll angle! Setting
2661 r0 < 1 gives a viewpoint inside the sphere. In that case, the images are
2662 mirror-reversed to preserve the chiralty of the perspective. Setting
2663 r0=0 gives gnomonic projections; setting r0=-1 gives stereographic projections.
2664 Setting r0 < -1 gives strange results.
2665  
2666 =item iu, im_unit, image_unit, Image_Unit (default 'degrees')
2667  
2668 This is the angular units in which the viewing camera is calibrated
2669 at the center of the image.
2670  
2671 =item mag, magnification, Magnification (default 1.0)
2672  
2673 This is the magnification factor applied to the optics -- it affects the
2674 amount of tangent-plane distortion within the telescope.
2675 1.0 yields the view from a simple optical system; higher values are
2676 telescopic, while lower values are wide-angle (fisheye). Higher
2677 magnification leads to higher angles within the optical system, and more
2678 tangent-plane distortion at the edges of the image.
2679 The magnification is applied to the incident angles themselves, rather than
2680 to their tangents (simple two-element telescopes magnify tan(theta) rather
2681 than theta itself); this is appropriate because wide-field optics more
2682 often conform to the equidistant azimuthal approximation than to the
2683 tangent plane approximation. If you need more detailed control of
2684 the relationship between incident angle and focal-plane position,
2685 use mag=1.0 and compose the transform with something else to tweak the
2686 angles.
2687  
2688 =item m, mask, Mask, h, hemisphere, Hemisphere [default 'near']
2689  
2690 'hemisphere' is by analogy to other cartography methods although the two
2691 regions to be selected are not really hemispheres.
2692  
2693 =item f, fov, field_of_view, Field_Of_View [default 60 degrees]
2694  
2695 The field of view of the telescope -- sets the crop radius on the
2696 focal plane. If you pass in a scalar, you get a circular crop. If you
2697 pass in a 2-element list ref, you get a rectilinear crop, with the
2698 horizontal 'radius' and vertical 'radius' set separately.
2699  
2700 =back
2701  
2702 EXAMPLES
2703  
2704 Model a camera looking at the Sun through a 10x telescope from Earth
2705 (~230 solar radii from the Sun), with an 0.5 degree field of view and
2706 a solar P (roll) angle of 30 degrees, in February (sub-Earth solar
2707 latitude is 7 degrees south). Convert a solar FITS image taken with
2708 that camera to a FITS lon/lat map of the Sun with 20 pixels/degree
2709 latitude:
2710  
2711 # Define map output header (no need if you don't want a FITS output map)
2712 $maphdr = {NAXIS1=>7200,NAXIS2=>3600, # Size of image
2713 CTYPE1=>longitude,CTYPE2=>latitude, # Type of axes
2714 CUNIT1=>deg,CUNIT2=>deg, # Unit of axes
2715 CDELT1=>0.05,CDELT2=>0.05, # Scale of axes
2716 CRPIX1=>3601,CRPIX2=>1801, # Center of map
2717 CRVAL1=>0,CRVAL2=>0 # (lon,lat) of center
2718 };
2719  
2720 # Set up the perspective transformation, and apply it.
2721 $t = t_perspective(r0=>229,fov=>0.5,mag=>10,P=>30,B=>-7);
2722 $map = $im->map( $t , $maphdr );
2723  
2724 Draw an aerial-view map of the Chesapeake Bay, as seen from a sounding
2725 rocket at an altitude of 100km, looking NNE from ~200km south of
2726 Washington (the radius of Earth is 6378 km; Washington D.C. is at
2727 roughly 77W,38N). Superimpose a linear coastline map on a photographic map.
2728  
2729 $x = graticule(1,0.1)->glue(1,earth_coast());
2730 $t = t_perspective(r0=>6478/6378.0,fov=>60,cam=>[22.5,-20],o=>[-77,36])
2731 $w = pgswin(size=>[10,6],J=>1);
2732 $w->plot(with=>'fits', earth_image()->map($t,[800,500],{m=>linear}),
2733 with=>'polylines', $x->apply($t)->clean_lines);
2734  
2735 Model a 5x telescope looking at Betelgeuse with a 10 degree field of view
2736 (since the telescope is looking at the Celestial sphere, r is 0 and this
2737 is just an expensive modified-gnomonic projection).
2738  
2739 $t = t_perspective(r0=>0,fov=>10,mag=>5,o=>[88.79,7.41])
2740  
2741 =cut
2742  
2743 2 ▶sub t_perspective {
Subroutine t_perspective: called CC=6 SCAR=19.8
Pod documented
2744 2 my $me = _new(@_,'Focal-Plane Perspective');
2745 2 my $p = $me->{params};
2746  
2747 my $m= _opt($me->{options},
2748 2 ['m','mask','Mask','h','hemi','hemisphere','Hemisphere'],
2749 1);
2750 2 $p->{m} = $m;
2751 2 ▶ $p->{m} = 0 if($m=~m/^b/i);
Branch: 1 branch
BranchTrueFalseTotal
if $m =~ /^b/i 0 2 2
2752 2 ▶ $p->{m} = 1 if($m=~m/^n/i);
Branch: 1 branch
BranchTrueFalseTotal
if $m =~ /^n/i 0 2 2
2753 2 ▶ $p->{m} = 2 if($m=~m/^f/i);
Branch: 1 branch
BranchTrueFalseTotal
if $m =~ /^f/i 0 2 2
2754  
2755 $p->{r0} = _opt($me->{options},
2756 2 ['r0','R0','radius','Radius',
2757 'd','dist','distance','Distance'],
2758 2.0
2759 );
2760  
2761 $p->{iu} = _opt($me->{options},
2762 2 ['i','iu','image_unit','Image_Unit'],
2763 'degrees');
2764  
2765 2 $p->{tconv} = _uconv($p->{iu});
2766  
2767 $p->{mag} = _opt($me->{options},
2768 2 ['mag','magnification','Magnification'],
2769 1.0);
2770  
2771 # Regular pointing pseudovector -- make sure there are exactly 3 elements
2772 $p->{p} = (topdl(_opt($me->{options},
2773 ['p','ptg','pointing','Pointing'],
2774 [0,0,0])
2775 )
2776 * $p->{tconv}
2777 2 )->append(zeroes(3))->slice("0:2");
2778  
2779 2 $p->{pmat} = _rotmat( (- $p->{p})->list );
2780  
2781 # Funky camera pointing pseudovector overrides normal pointing option
2782 $p->{c} = _opt($me->{options},
2783 2 ['c','cam','camera','Camera'],
2784 undef
2785 );
2786  
2787 2 ▶ if(defined($p->{c})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p->{"c"}) 0 2 2
2788 0 $p->{c} = (topdl($p->{c}) * $p->{tconv})->append(zeroes(3))->slice("0:2");
2789  
2790 $p->{pmat} = ( _rotmat( 0,-PI()/2,0 ) x
2791 0 _rotmat( (-$p->{c})->list )
2792 );
2793 }
2794  
2795 # Reflect X axis if we're inside the sphere.
2796 2 ▶ if($p->{r0}<1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p->{"r0"} < 1) 0 2 2
2797 0 $p->{pmat} = topdl([[-1,0,0],[0,1,0],[0,0,1]]) x $p->{pmat};
2798 }
2799  
2800 $p->{f} = ( _opt($me->{options},
2801 ['f','fov','field_of_view','Field_of_View'],
2802 topdl(PI*2/3) / $p->{tconv} / $p->{mag} )
2803 * $p->{tconv}
2804 2 );
2805  
2806 2 $me->{otype} = ['Tan X','Tan Y'];
2807 2 $me->{ounit} = [$p->{iu},$p->{iu}];
2808  
2809 # "Prefilter" -- subsidiary transform to convert the
2810 # spherical coordinates to 3-D coords in the viewer's
2811 # reference frame (Y,Z are more-or-less tangent-plane X and Y,
2812 # and -X is the direction toward the planet, before rotation
2813 # to account for pointing).
2814  
2815 $me->{params}->{prefilt} =
2816 t_compose(
2817 # Offset for the camera pointing.
2818 t_linear(m=>$p->{pmat},
2819 d=>3),
2820  
2821 # Rotate the sphere so the correct origin is at the
2822 # maximum-X point, then move the whole thing in the
2823 # -X direction by r0.
2824 t_linear(m=>(_rotmat($p->{o}->at(0),
2825 $p->{o}->at(1),
2826 $p->{roll}->at(0))
2827 ),
2828 d=>3,
2829 2 post=> topdl( [- $me->{params}->{r0},0,0] )
2830 ),
2831  
2832 # Put initial sci. coords into Cartesian space
2833 t_unit_sphere(u=>'radian')
2834 );
2835  
2836 # Store the origin of the sphere -- useful for the inverse function
2837 $me->{params}->{sph_origin} = (
2838 topdl([-$me->{params}->{r0},0,0]) x
2839 $p->{pmat}
2840 2 )->slice(":,(0)");
2841  
2842 #
2843 # Finally, the meat -- the forward function!
2844 #
2845 9 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=10 SCAR=28.0
2846 9 my ($d,$o) = @_;
2847  
2848 9 my $out = $d->new_or_inplace;
2849 9 $out->slice("0:1") *= $o->{conv};
2850  
2851 # If we're outside the sphere, do hemisphere filtering
2852 9 my $idx;
2853 9 ▶ if(abs($o->{r0}) < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (abs $o->{'r0'} < 1) { } 0 9 9
2854 0 $idx = null;
2855 } else {
2856 # Great-circle distance to origin
2857 my $cos_c = (sin($o->{o}->slice("(1)")) * sin($out->slice("(1)"))
2858 +
2859 cos($o->{o}->slice("(1)")) * cos($out->slice("(1)")) *
2860 9 cos($out->slice("(0)") - $o->{o}->slice("(0)"))
2861 );
2862  
2863 9 my $thresh = (1.0/$o->{r0});
2864  
2865 9 ▶ if ($o->{m}==1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($o->{'m'} == 1) { } 9 0 9
elsif ($o->{'m'} == 2) { } 0 0 0
2866 9 $idx = whichND($cos_c < $thresh);
2867 } elsif ($o->{m}==2) {
2868 0 $idx = whichND($cos_c > $thresh);
2869 } else {
2870 0 $idx = null;
2871 }
2872 }
2873  
2874 ### Transform everything -- just chuck out the bad points at the end.
2875  
2876 ## convert to 3-D viewer coordinates (there's a dimension change!)
2877 9 my $dc = $out->apply($o->{prefilt});
2878  
2879 ## Apply the tangent-plane transform, and scale by the magnification.
2880 9 my $dcyz = $dc->slice("1:2");
2881  
2882 9 my $r = $dcyz->magnover;
2883 9 my $rscale;
2884 9 ▶ if( $o->{mag} == 1.0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{'mag'} == 1.0) { } 9 0 9
2885 9 $rscale = - 1.0 / $dc->slice("(0)");
2886 } else {
2887 0 ▶ print "(using magnification...)\n" if $PDL::verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose 0 0 0
2888 0 $rscale = - tan( $o->{mag} * atan( $r / $dc->slice("(0)") ) ) / $r;
2889 }
2890 9 $r *= $rscale;
2891 9 $out->slice("0:1") .= $dcyz * $rscale->dummy(0,1);
2892  
2893 # Chuck points that are outside the FOV: glue those points
2894 # onto the removal list. The conditional works around a bug
2895 # in 2.3.4cvs and earlier: null ndarrays make append() crash.
2896 9 my $w;
2897 9 ▶ if(ref $o->{f} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o->{'f'} eq 'ARRAY') { } 0 9 9
2898 $w = whichND( ( abs($dcyz->slice("(0)")) > $o->{f}->[0] ) |
2899 0 ( abs($dcyz->slice("(1)")) > $o->{f}->[1] ) |
2900 ($r < 0)
2901 );
2902 } else {
2903 9 $w = whichND( ($r > $o->{f}) | ($r < 0) );
2904 }
2905  
2906 9 ▶ $idx = ($idx->nelem) ? $idx->glue(1,$w) : $w
Branch: 2 branches
BranchTrueFalseTotal
if $w->nelem 0 9 9
$idx->nelem ? : 0 0 0
2907 if($w->nelem);
2908  
2909 9 ▶ if($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 0 9 9
2910 0 $out->slice("(0)")->range($idx) .= $o->{bad};
2911 0 $out->slice("(1)")->range($idx) .= $o->{bad};
2912 }
2913  
2914 ## Scale by the output conversion factor
2915 9 $out->slice("0:1") /= $o->{tconv};
2916  
2917 9 $out;
2918 2 };
2919  
2920  
2921 #
2922 # Inverse function
2923 #
2924 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=8 SCAR=23.4
2925 1 my($d,$o) = @_;
2926  
2927 1 my $out = $d->new_or_inplace;
2928 1 $out->slice("0:1") *= $o->{tconv};
2929  
2930 1 my $oyz = $out->slice("0:1") ;
2931  
2932 ## Inverse-magnify if required
2933 1 ▶ if($o->{mag} != 1.0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{"mag"} != 1) 0 1 1
2934 0 my $r = $oyz->magnover;
2935 0 my $scale = tan( atan( $r ) / $o->{mag} ) / $r;
2936 0 $oyz *= $scale->dummy(0,1);
2937 }
2938  
2939 ## Solve for the X coordinate of the surface.
2940 ## This is a quadratic in the tangent-plane coordinates;
2941 ## so here we just figure out the coefficients and plug into
2942 ## the quadratic formula. $y here is actually -B/2.
2943 1 my $a1 = ($oyz * $oyz)->sumover + 1;
2944 my $y = ( $o->{sph_origin}->slice("(0)")
2945 1 - ($o->{sph_origin}->slice("1:2") * $oyz)->sumover
2946 );
2947 1 my $c = topdl($o->{r0}*$o->{r0} - 1);
2948  
2949 1 my $x;
2950 1 ▶ if ($o->{m} == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{'m'} == 2) { } 0 1 1
2951 # Exceptional case: mask asks for the far hemisphere
2952 0 $x = - ( $y - sqrt($y*$y - $a1 * $c) ) / $a1;
2953 } else {
2954 # normal case: mask asks for the near hemisphere
2955 1 $x = - ( $y + sqrt($y*$y - $a1 * $c) ) / $a1;
2956 }
2957  
2958 1 my ($out0, $out1) = $out->using(0,1);
2959 ## Assemble the 3-space coordinates of the points
2960 1 my $int = $out->slice("0")->append($out);
2961 1 $int->slice("(0)") .= -1.0;
2962 1 $int->slice("0:2") *= $x->dummy(0,3);
2963  
2964 ## convert back to (lon,lat) coordinates...
2965 1 $out .= $int->invert($o->{prefilt});
2966  
2967 # If we're outside the sphere, do hemisphere filtering
2968 1 my $idx;
2969 1 ▶ if (abs($o->{r0}) < 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (abs $o->{'r0'} < 1) { } 0 1 1
2970 0 $idx = null;
2971 } else {
2972 # Great-circle distance to origin
2973 my $cos_c = ( sin($o->{o}->slice("(1)")) * sin($out->slice("(1)"))
2974 +
2975 cos($o->{o}->slice("(1)")) * cos($out->slice("(1)")) *
2976 1 cos($out->slice("(0)") - $o->{o}->slice("(0)"))
2977 );
2978 1 my $thresh = 1.0/$o->{r0};
2979 1 ▶ if ($o->{m}==1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($o->{'m'} == 1) { } 1 0 1
elsif ($o->{'m'} == 2) { } 0 0 0
2980 1 $idx = whichND($cos_c < $thresh);
2981 } elsif ($o->{m}==2) {
2982 0 $idx = whichND($cos_c > $thresh);
2983 } else {
2984 0 $idx = null;
2985 }
2986 }
2987  
2988 ## Convert to the units the user requested
2989 1 $out->slice("0:1") /= $o->{conv};
2990  
2991 ## Mark bad values
2992 1 ▶ if($idx->nelem) {
Branch: 1 branch
BranchTrueFalseTotal
if ($idx->nelem) 0 1 1
2993 0 $_->range($idx) .= $o->{bad} for $out0, $out1;
2994 }
2995  
2996 1 $out;
2997  
2998 2 };
2999  
3000 2 $me;
3001 }
3002  
3003 1 1;
« lib/PDL/Doc.pm ↑ Summary lib/PDL/ImageRGB.pd »