File: Proj4.pd

package info (click to toggle)
libpdl-transform-proj4-perl 2.098-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 372 kB
  • sloc: perl: 2,823; makefile: 9
file content (538 lines) | stat: -rw-r--r-- 16,062 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# PDL::PP Definition file for the PDL::Transform::Proj4 module
#
# Judd Taylor, USF IMaRS
# 4 Apr 2006

use strict;
use warnings;
use File::Spec;
use IPC::Run qw(run);

our $VERSION = "2.098";
pp_setversion($VERSION);

pp_add_isa( 'PDL::Transform' );

# This array holds the list of functions we want to export (everything here is explicit!)
my @export_funcs = ();

pp_addhdr(<<'EOHDR');
#include "proj.h"
#include <string.h>
/* from proj_api.h */
#define RAD_TO_DEG      57.295779513082321
#define DEG_TO_RAD      .017453292519943296
EOHDR

sub wrap_code {
  my ($name, $in, $out, $is_fwd) = @_;
  pp_def($name,
    Code => <<EOF,
PJ_CONTEXT *pj_context = proj_context_create();
if (!pj_context)
  \$CROAK("Projection context creation failed: %s\\n", proj_errno_string(proj_errno(NULL)));
PJ *proj = proj_create( pj_context, \$COMP(params) );
if (!proj)
  \$CROAK("Projection initialization failed: %s\\n", proj_errno_string(proj_errno(NULL)));
char rad_in = @{[$is_fwd ? 'proj_angular_input(proj, PJ_FWD)' : '0']},
  deg_out = @{[$is_fwd ? '0' : 'proj_angular_output(proj, PJ_INV)']};
loop (n) %{
  PJ_COORD in, out;
  PDL_IF_BAD(
  if ( @{[ join '||', map "\$ISBAD($in(ncoord=>$_))", 0,1 ]} ) {
    loop (ncoord) %{ \$SETBAD($out()); %}
    continue;
  },)
  loop (ncoord) %{ in.v[ncoord] = rad_in ? DEG_TO_RAD*\$$in() : \$$in(); %}
  out = proj_trans(proj, PJ_@{[$is_fwd ? 'FWD' : 'INV']}, in);
  if (out.v[0] == HUGE_VAL) {
    PDL_IF_BAD(
    loop (ncoord) %{ \$SETBAD($out()); %}
    continue;
    ,
    \$CROAK("Projection conversion failed at (%f, %f): %s\\n",
      \$$in(ncoord=>0), \$$in(ncoord=>1), proj_errno_string(proj_errno(proj)));
    )
  }
  loop (ncoord) %{ \$$out() = deg_out ? RAD_TO_DEG*out.v[ncoord] : out.v[ncoord]; %}
%}
proj_destroy(proj);
proj_context_destroy(pj_context);
EOF
    Pars => "$in(ncoord=2,n); [o] $out(ncoord,n);",
    GenericTypes => ['D'],
    OtherPars => 'char* params;',
    HandleBad => 1,
    Inplace => 1,
    Doc => undef,
  );
}

wrap_code('fwd_transform', 'lonlat', 'xy', 1);
wrap_code('inv_transform', 'xy', 'lonlat', 0);

# Utility functions for getting projection description information (in a general case).
pp_addxs('', <<'ENDXS' );
void
proj_version(...)
  PPCODE:
    EXTEND(sp, 3);
    mPUSHu(PROJ_VERSION_MAJOR);
    mPUSHu(PROJ_VERSION_MINOR);
    mPUSHu(PROJ_VERSION_PATCH);

# returns input_units, output_units
void
units(proj_str)
  char *proj_str
PPCODE:
  PJ *proj = proj_create( NULL, proj_str ); /* Init the projection */
  if (!proj)
    croak("Failed to create PJ from '%s': %s", proj_str, proj_errno_string(proj_errno(proj)));
  EXTEND(sp, 2);
  char *input_u = proj_angular_input(proj, PJ_FWD) ||
    proj_degree_input(proj, PJ_FWD) ? "degrees" : "metres";
  char *output_u = proj_angular_output(proj, PJ_FWD) ||
    proj_degree_output(proj, PJ_FWD) ? "degrees" : "metres";
  mPUSHs(newSVpv(input_u, 0));
  mPUSHs(newSVpv(output_u, 0));
  proj_destroy(proj);
ENDXS

my %SKIP = map +($_=>1), qw(
  and or Special for Madagascar
  fixed Earth For CH1903
);
sub load_projection_information {
    my @cmd = ("proj", "-lP");
    my ($text, $stderr, $exit_code, $in);
    run \@cmd, \$in, \$text, \$stderr;
    $exit_code = $?;
    warn $stderr if $stderr;
    die "proj -lP error $exit_code. See above for error text." if $exit_code;
    my @chunks = $text =~ /(.+?)(?=(?:^\S|\z))/gms;
    chomp for @chunks;
    my %descriptions = map {
      my ($id, $rest) = split /\s*:\s*/, $_, 2;
    } @chunks;
    my %info;
    foreach my $projection ( sort keys %descriptions ) {
        my $description = $descriptions{$projection};
        my %hash = (CODE => $projection);
        my @lines = split( /\n/, $description );
        chomp @lines;
        # Can this projection do inverse?
        $hash{INVERSE} = 1;
        # Full name of this projection:
        ($hash{NAME}, my $temp) = splice @lines, 0, 2;
        if ($temp) {
          # The second line is usually a list of projection types this one is:
          $hash{INVERSE} = 0 if $temp =~ s/no inv\.*,*//i;
          $temp =~ s/or//;
          my @temp_types = split(/[,&\s]/, $temp );
          my @types = grep( /.+/, @temp_types );
          $hash{CATEGORIES} = \@types;
        }
        # If there's more than 2 lines, then it usually is a listing of parameters:
        # Projection Specific Parameters:
        $hash{PARAMS}{PROJ} = [
          grep !$SKIP{$_}, map {s/=//; s/[,\[\]]//sg; $_}
            grep length, map split(/\s+/), @lines
        ];
        $info{$projection} = \%hash;
    }
    # A couple of overrides:
    #
    $info{ob_tran}{PARAMS}{PROJ} =
        [ 'o_proj', 'o_lat_p', 'o_lon_p', 'o_alpha', 'o_lon_c',
          'o_lat_c', 'o_lon_1', 'o_lat_1', 'o_lon_2', 'o_lat_2' ];
    $info{nzmg}{CATEGORIES} = [ 'fixed Earth' ];
    return \%info;
}

pp_addpm(<<'ENDPM');
=head2 proj_version

Returns a 3-element list with PROJ major, minor, patch version-numbers.
Not exported.

=cut

ENDPM
pp_addpm("sub load_projection_information {+" . do {
  use Data::Dumper;
  local $Data::Dumper::Sortkeys = 1;
  local $Data::Dumper::Terse = 1;
  local $Data::Dumper::Indent = 1;
  join '', Dumper load_projection_information();
}."}\n\n");
pp_export_nothing();

pp_addpm( { At => 'Top' }, <<'ENDPM' );
# PDL::Transform::Proj4
#
# Judd Taylor, USF IMaRS
# 4 Apr 2006

use strict;
use warnings;
use PDL::LiteF;
use PDL::Transform;

=head1 NAME

PDL::Transform::Proj4 - PDL::Transform interface to the Proj4 projection library

=head1 SYNOPSIS

 # Using the generalized proj interface:
 # Make an orthographic map of Earth
 use PDL::Transform::Cartography;
 use PDL::Transform::Proj4;
 use PDL::Graphics::Simple;
 $e = earth_image('day');
 ($c, $pen) = graticule(10,2)->glue(1,earth_coast())->clean_lines;
 $t = t_proj(proj_params => "+proj=ortho +ellps=WGS84 +lon_0=0 +lat_0=40");
 $w = pgswin();
 $w->plot(with=>'fits', $e->map($t),
   with=>'polylines', clean_lines($c->apply($t), $pen), {j=>1});

 # Using the aliased functions:
 # Make an orthographic map of Earth
 use PDL::Transform::Cartography;
 use PDL::Transform::Proj4;
 use PDL::Graphics::Simple;
 $e = earth_image('day');
 ($c, $pen) = graticule(10,2)->glue(1,earth_coast())->clean_lines;
 $t = t_proj_ortho( ellps => 'WGS84', lon_0=>0, lat_0=>40 );
 $w = pgswin();
 $w->plot(with=>'fits', $e->map($t),
   with=>'polylines', clean_lines($c->apply($t), $pen), {j=>1});

=head1 DESCRIPTION

Works like PDL::Transform::Cartography, but using the proj library in the background.

Please see the proj library docs at L<http://www.remotesensing.org/proj> for more information
on proj, and how to use the library.

=head1 GENERALIZED INTERFACE

The main object here is the PDL::Transform::Proj4 object, aliased to the t_proj() function.

This object accepts all of the standard options described below, but mainly is there to be called
with just the B<proj_params> option defined.

When options are used, they must be used with a '+' before them when placed in the proj_params string,
but that is not required otherwise. See the SYNOPSIS above.

Please note that unlike PROJ, all angles in these operations are
in degrees. This is correctly (as of PDL 2.094) reflected in the
PDL::Transform subclass objects.

=head2 ALIASED INTERFACE

Other than t_proj(), all of the other transforms below have been autogenerated, and may not work
properly. The main problem is determining the parameters a projection requires from the proj
library itself.

Due to the difficulties in doing this, there may be times when the proj docs specify a parameter
for a projection that won't work using the anon-hash type specification. In that case, just throw
that parameter in the proj_params string, and everything should work fine.

=head1 PARAMETERS AVAILABLE IN ALL PROJECTIONS

=head2 General Parameters

=head3 proj_params

This is a string containing the proj "plus style" parameters. This would be similar to what you
would put on the command line for the 'proj' tool. Like "+proj=ortho +ellps=WGS84 +lon_0=-90 +lat_0=40".

This parameter overrides the others below when it contains parameters that are also specified
explicitly.

=head3 proj

The proj projection code to use (like ortho...)

=head3 x_0

Cartesian X offset for the output of the transformation

=head3 y_0

Cartesian Y offset for the output of the transformation

=head3 lat_0

Central latitude for the projection.
NOTE: This may mean other things depending on the projection selected, read the proj docs!

=head3 lon_0

Central longitude for the projection.
NOTE: This may mean other things depending on the projection selected, read the proj docs!

=head3 units

Cartesian units used for the output of the projection.
NOTE: Like most of the options here, this is likely useless in the current implementation
of this library.

=head3 init

Specify a file:unit for proj to use for its runtime defaults. See the proj docs.

=head3 no_defs

Don't load any defaults. See the proj docs.

=head3 over

Normally, the transformation limits the output to between -180 and 180 degrees (or the
cartesian equivalent), but with this option that behavior is turned off.

=head3 geoc

Input values are geocentric coordinates.

=head2 Earth Figure Parameters

=head3 ellps

Ellipsoid datum to use. Ex: WGS72, WGS74.
See the proj docs and command line tool for list of possibilities ('proj -le').

=head3 R

Radius of the Earth.

=head3 R_A

Radius of a sphere with equivalent surface area of specified ellipse.

=head3 R_V

Radius of a sphere with equivalent volume of specified ellipse.

=head3 R_a

Arithmetic mean of the major and minor axis, Ra = (a + b)/2.

=head3 R_g

Geometric mean of the major and minor axis, Rg = (ab)/2.

=head3 R_h

Harmonic mean of the major and minor axis, Rh = 2ab/(a + b).

=head3 R_lat_a=phi

Arithmetic mean of the principle radii at latitude phi.

=head3 R_lat_g=phi

Geometric mean of the principle radii at latitude phi.

=head3 b

Semiminor axis or polar radius

=head3 f

Flattening

=head3 rf

Reciprocal flattening, +rf=1/f

=head3 e

Eccentricity +e=e

=head3 es

Eccentricity squared +es=e2

=cut

# Projection options available to all projections:
our @GENERAL_PARAMS = qw(proj x_0 y_0 lat_0 lon_0 units init);
# Options for the Earth figure: (ellipsoid, etc):
our @EARTH_PARAMS = qw(ellps R R_A R_V R_a R_g R_h R_lat_a R_lat_g b f rf e es);
# Options that have no value (like "+over"):
our @BOOL_PARAMS = qw( no_defs over geoc );

# The meat -- just copy and paste from Transform.pm :)
#    (and do some proj stuff here as well)
sub _proj4_fwd {
  my ($in, $opt) = @_;
  my $out = $in->new_or_inplace();
  # Always set the badflag to 1 here, to handle possible bad projection values:
  $out->badflag(1);
  $out->inplace(1);
  fwd_transform( $out, $opt->{proj_params} );
}
sub _proj4_inv {
  my ($in, $opt) = @_;
  my $out = $in->new_or_inplace();
  # Always set the badflag to 1 here, to handle possible bad projection values:
  $out->badflag(1);
  $out->inplace(1);
  inv_transform( $out, $opt->{proj_params} );
}

sub new {
    my $self  = shift->SUPER::new( @_ );
    my $o = $_[0];
    $o = {@_} if !ref $o;
    $self->{name} = "Proj4";
    $self->{params}{proj_params} = PDL::Transform::_opt( $o, ['proj_params','params'] );
    foreach my $param ( @BOOL_PARAMS ) {
        my $val = PDL::Transform::_opt( $o, [ $param ] );
        $self->{params}{$param} = 'ON' if $val;
    }
    foreach my $param (@GENERAL_PARAMS, @EARTH_PARAMS) {
        my $val = PDL::Transform::_opt( $o, [ $param ] );
        $self->{params}{$param} = $val if defined $val;
    }
    # First process the old params that may already be in the string:
    # These override the specific params set above:
    if (defined( $self->{params}{proj_params} )) {
        $self->{orig_proj_params} = $self->{params}{proj_params};
        my @params = split( /\s+/, $self->{orig_proj_params} );
        foreach my $param ( @params ) {
            if ($param =~ /^\+(\S+)=(\S+)/) {
                my ($name, $val) = ($1, $2);
                $self->{params}{$name} = $val;
            } elsif ($param =~ /^\+(\S+)/) {   # Boolean option
                $self->{params}{$1} = 'ON';
            }
        }
    }
    @$self{qw(idim odim)} = (2, 2);
    # Update proj_string to current options:
    $self->update_proj_string if $self->{params}{proj};
    $self->{func} = \&_proj4_fwd; # Forward transformation
    $self->{inv} = \&_proj4_inv; # Inverse transformation
    return $self;
} # End of new()...

sub update_proj_string {
    my $self = shift;
    # (Re)Generate the proj_params string from the options passed:
    my @params = map "+$_".($self->{params}{$_} eq 'ON' ? '' : "=$self->{params}{$_}"),
      sort grep $_ ne 'proj_params' && defined $self->{params}{$_}, keys %{$self->{params}};
    $self->{params}{proj_params} = "@params";
  my ($iunit, $ounit) = PDL::Transform::Proj4::units($self->{params}{proj_params});
  @$self{qw(iunit ounit)} = ([($iunit)x2], [($ounit)x2]);
} # End of update_proj_string()...

sub proj_params {
    my $self = shift;
    $self->update_proj_string;
    return $self->{params}{proj_params};
} # End of proj_params()...

sub t_proj {
    PDL::Transform::Proj4->new( @_ );
} # End of t_proj()...

sub _make_class {
  my ($name, $full_name, $can_inv, $param_list) = @_;
  eval <<"EOF";
package PDL::Transform::Proj4::${name};
our \@ISA = 'PDL::Transform::Proj4';
our \@PARAM_LIST = $param_list;
sub new {
  my \$self  = shift->SUPER::new( \@_ );
  my \$o = \$_[0];
  \$o = {\@_} if !ref \$o;
  \$self->{name} = \$self->{params}{proj} = q{$name};
  foreach my \$param (\@PARAM_LIST) {
      my \$val = PDL::Transform::_opt( \$o, [ \$param ] );
      \$self->{params}{\$param} = \$val if defined \$val;
  }
  delete \$self->{inv} if !$can_inv;
  \$self->update_proj_string;
  return \$self;
}
EOF
}
ENDPM

#
# Add the docs for t_proj:
#
pp_addpm( { At => 'Middle' }, <<'ENDPM' );

=head1 FUNCTIONS

=head2 t_proj

This is the main entry point for the generalized interface. See above on its usage.

=cut

ENDPM
push( @export_funcs, 't_proj' );

# Add in the auto-generated projection classes:
my $projections = eval { load_projection_information() } || {};

my $ALIAS_TEMPLATE = pp_line_numbers __LINE__, <<'ENDTEMPLATE';
=head2 INSERT_ALIAS_NAME_HERE

Proj4 projection code C<INSERT_NAME_HERE>, full name "INSERT_FULL_NAME_HERE".
INSERT_CATEGORIES_LIST_HERE
INSERT_PARAM_LIST_HERE

=cut

sub INSERT_ALIAS_NAME_HERE {'PDL::Transform::Proj4::INSERT_NAME_HERE'->new(@_)}
ENDTEMPLATE

foreach my $name ( sort keys %$projections )
{
    my $projection = $projections->{$name};
    my $param_list = 'qw('.join(' ', @{ $projection->{PARAMS}{PROJ} }).')';
    pp_addpm( {At => 'Bot'}, "_make_class(q{$name}, q{$projection->{NAME}}, $projection->{INVERSE}, q{$param_list});\n" );
    # Generate the alias sub:
    my $alias_name = "t_proj_$name";
    push( @export_funcs, $alias_name );
    $_ = "" for my ($doc_param_list, $cat_list);
    if( scalar( @{ $projection->{PARAMS}{PROJ} } ) ) {
        $doc_param_list .= "\nProjection Parameters\n\n=for options\n\n=over 4\n\n";
        $doc_param_list .= join '', map "=item $_\n\n", sort @{ $projection->{PARAMS}{PROJ} };
        $doc_param_list .= "=back\n\n";
    }
    unshift @{$projection->{CATEGORIES}}, "B<no inverse>"
      if !$projection->{INVERSE};
    $cat_list = "\nCategories: @{$projection->{CATEGORIES}}.\n\n"
      if @{$projection->{CATEGORIES} || []};
    my $alias_template = $ALIAS_TEMPLATE;
    $alias_template =~ s/INSERT_ALIAS_NAME_HERE/$alias_name/sg;
    $alias_template =~ s/INSERT_NAME_HERE/$name/sg;
    $alias_template =~ s/INSERT_FULL_NAME_HERE/$projection->{NAME}/sg;
    $alias_template =~ s/INSERT_PARAM_LIST_HERE/$doc_param_list/sg;
    $alias_template =~ s/INSERT_CATEGORIES_LIST_HERE/$cat_list/sg;
    pp_addpm( {At => 'Middle'},  $alias_template );
} # for each projection...

pp_add_exported(join(' ', @export_funcs));

# Add the end docs:
#
pp_addpm( {At => 'Bot'}, <<'ENDDOC');

=head1 AUTHOR

Judd Taylor, Orbital Systems, Ltd.
judd dot t at orbitalsystems dot com

=cut
ENDDOC

pp_done();