lib/PDL/Transform.pd

filter: Statementstmt 86.1% 717 / 832 Branchbran 52.7% 215 / 408 Conditioncond 42.7% 97 / 227 MC/DCmcdc 15.5% 19 / 122 Subroutinesub 91.7% 67 / 73 Podpod 60.7% 17 / 28 totaltotal 66.9% 1132 / 1690 CC 306 SCAR 47.3
CC
306
Cov
70%
map
357.0
apply
170.7
stringify
110.0
CRAP 113.7
« blib/lib/PDL/IO/FITS.pm ↑ Summary lib/PDL/MatrixOps.pd »
1 use PDL::Types qw(ppdefs_all);
2 my $ALL = [ppdefs_all()];
3  
4 pp_addhdr("#include <sys/time.h>\n") unless $^O =~ /MSWin32/i;
5 pp_addpm({At=>'Top'},<<'+======EOD======');
6  
7 =head1 NAME
8  
9 PDL::Transform - Coordinate transforms, image warping, and N-D functions
10  
11 =head1 SYNOPSIS
12  
13 use PDL::Transform;
14  
15 my $t = PDL::Transform::<type>->new(<opt>)
16  
17 $out = $t->apply($in) # Apply transform to some N-vectors (Transform method)
18 $out = $in->apply($t) # Apply transform to some N-vectors (PDL method)
19  
20 $im1 = $t->map($im); # Transform image coordinates (Transform method)
21 $im1 = $im->map($t); # Transform image coordinates (PDL method)
22  
23 $t2 = $t->compose($t1); # compose two transforms
24 $t2 = $t x $t1; # compose two transforms (by analogy to matrix mult.)
25  
26 $t3 = $t2->inverse(); # invert a transform
27 $t3 = !$t2; # invert a transform (by analogy to logical "not")
28  
29 =head1 DESCRIPTION
30  
31 PDL::Transform is a convenient way to represent coordinate
32 transformations and resample images. It embodies functions mapping
33 R^N -> R^M, both with and without inverses. Provision exists for
34 parametrizing functions, and for composing them. You can use this
35 part of the Transform object to keep track of arbitrary functions
36 mapping R^N -> R^M with or without inverses.
37  
38 The simplest way to use a Transform object is to transform vector
39 data between coordinate systems. The L</apply> method
40 accepts a PDL whose 0th dimension is coordinate index (all other
41 dimensions are broadcasted over) and transforms the vectors into the new
42 coordinate system.
43  
44 Transform also includes image resampling, via the L</map> method.
45 You define a coordinate transform using a Transform object, then use
46 it to remap an image PDL. The output is a remapped, resampled image.
47  
48 You can define and compose several transformations, then apply them
49 all at once to an image. The image is interpolated only once, when
50 all the composed transformations are applied.
51  
52 In keeping with standard practice, but somewhat counterintuitively,
53 the L</map> engine uses the inverse transform to map coordinates
54 FROM the destination dataspace (or image plane) TO the source dataspace;
55 hence PDL::Transform keeps track of both the forward and inverse transform.
56  
57 For terseness and convenience, most of the constructors are exported
58 into the current package with the name C<< t_<transform> >>, so the following
59 (for example) are synonyms:
60  
61 $t = PDL::Transform::Radial->new; # Long way
62  
63 $t = t_radial(); # Short way
64  
65 Several math operators are overloaded, so that you can compose and
66 invert functions with expression syntax instead of method syntax (see below).
67  
68 =head1 EXAMPLE
69  
70 Coordinate transformations and mappings are a little counterintuitive
71 at first. Here are some examples of transforms in action:
72  
73 use PDL::Transform;
74 use PDL::Graphics::Simple;
75 $x = rfits('m51.fits'); # Substitute path if necessary!
76 $ts = t_linear(Scale=>3); # Scaling transform
77  
78 $w = pgswin(xs);
79 $w->plot(with=>'image', $x);
80  
81 ## Grow m51 by a factor of 3; origin is at lower left.
82 $y = $ts->map($x,{pix=>1}); # pix option uses direct pixel coord system
83 $w->plot(with=>'image', $y);
84  
85 ## Shrink m51 by a factor of 3; origin still at lower left.
86 $c = $ts->unmap($x, {pix=>1});
87 $w->plot(with=>'image', $c);
88  
89 ## Grow m51 by a factor of 3; origin is at scientific origin.
90 $d = $ts->map($x,$x->hdr); # FITS hdr template prevents autoscaling
91 $w->plot(with=>'image', $d);
92  
93 ## Shrink m51 by a factor of 3; origin is still at sci. origin.
94 $e = $ts->unmap($x,$x->hdr);
95 $w->plot(with=>'image', $e);
96  
97 ## A no-op: shrink m51 by a factor of 3, then autoscale back to size
98 $f = $ts->map($x); # No template causes autoscaling of output
99  
100 =head1 OPERATOR OVERLOADS
101  
102 =over 3
103  
104 =item '!'
105  
106 The bang is a unary inversion operator. It binds exactly as
107 tightly as the normal bang operator.
108  
109 =item 'x'
110  
111 By analogy to matrix multiplication, 'x' is the compose operator, so these
112 two expressions are equivalent:
113  
114 $f->inverse()->compose($g)->compose($f) # long way
115 !$f x $g x $f # short way
116  
117 Both of those expressions are equivalent to the mathematical expression
118 f^-1 o g o f, or f^-1(g(f(x))).
119  
120 =item '**'
121  
122 By analogy to numeric powers, you can apply an operator a positive
123 integer number of times with the ** operator:
124  
125 $f->compose($f)->compose($f) # long way
126 $f**3 # short way
127  
128 =back
129  
130 =head1 INTERNALS
131  
132 Transforms are perl hashes. Here's a list of the meaning of each key:
133  
134 =over 3
135  
136 =item func
137  
138 Ref to a subroutine that evaluates the transformed coordinates. It's
139 called with the input coordinate, and the "params" hash. This
140 springboarding is done via explicit ref rather than by subclassing,
141 for convenience both in coding new transforms (just add the
142 appropriate sub to the module) and in adding custom transforms at
143 run-time. Note that, if possible, new C<func>s should support
144 L<inplace|PDL::Core/inplace> operation to save memory when the data are flagged
145 inplace. But C<func> should always return its result even when
146 flagged to compute in-place.
147  
148 C<func> should treat the 0th dimension of its input as a dimensional
149 index (running 0..N-1 for R^N operation) and broadcast over all other input
150 dimensions.
151  
152 =item inv
153  
154 Ref to an inverse method that reverses the transformation. It must
155 accept the same "params" hash that the forward method accepts. This
156 key can be left undefined in cases where there is no inverse.
157  
158 =item idim, odim
159  
160 Number of useful dimensions for indexing on the input and output sides
161 (ie the order of the 0th dimension of the coordinates to be fed in or
162 that come out). If this is set to 0, then as many are allocated as needed.
163  
164 =item name
165  
166 A shorthand name for the transformation (convenient for debugging).
167 You should plan on using UNIVERAL::isa to identify classes of
168 transformation, e.g. all linear transformations should be subclasses
169 of PDL::Transform::Linear. That makes it easier to add smarts to,
170 e.g., the compose() method.
171  
172 =item itype
173  
174 An array containing the name of the quantity that is expected from the
175 input ndarray for the transform, for each dimension. This field is advisory,
176 and can be left blank if there's no obvious quantity associated with
177 the transform. This is analogous to the CTYPEn field used in FITS headers.
178  
179 =item oname
180  
181 Same as itype, but reporting what quantity is delivered for each
182 dimension.
183  
184 =item iunit
185  
186 The units expected on input, if a specific unit (e.g. degrees) is expected.
187 This field is advisory, and can be left blank if there's no obvious
188 unit associated with the transform.
189  
190 =item ounit
191  
192 Same as iunit, but reporting what quantity is delivered for each dimension.
193  
194 =item params
195  
196 Hash ref containing relevant parameters or anything else the func needs to
197 work right.
198  
199 =item is_inverse
200  
201 Bit indicating whether the transform has been inverted. That is useful
202 for some stringifications (see the PDL::Transform::Linear
203 stringifier), and may be useful for other things.
204  
205 =back
206  
207 Transforms should be inplace-aware where possible, to prevent excessive
208 memory usage.
209  
210 If you define a new type of transform, consider generating a new stringify
211 method for it. Just define the sub "stringify" in the subclass package.
212 It should call SUPER::stringify to generate the first line (though
213 the PDL::Transform::Composition bends this rule by tweaking the
214 top-level line), then output (indented) additional lines as necessary to
215 fully describe the transformation.
216  
217 =head1 NOTES
218  
219 Transforms have a mechanism for labeling the units and type of each
220 coordinate, but it is just advisory. A routine to identify and, if
221 necessary, modify units by scaling would be a good idea. Currently,
222 it just assumes that the coordinates are correct for (e.g.) FITS
223 scientific-to-pixel transformations.
224  
225 Composition works OK but should probably be done in a more
226 sophisticated way so that, for example, linear transformations are
227 combined at the matrix level instead of just strung together
228 pixel-to-pixel.
229  
230 =head1 MODULE INTERFACE
231  
232 There are both operators and constructors. The constructors are all
233 exported, all begin with "t_", and all return objects that are subclasses
234 of PDL::Transform.
235  
236 The L</apply>, L</invert>, L</map>,
237 and L</unmap> methods are also exported to the C<PDL> package: they
238 are both Transform methods and PDL methods.
239  
240 =cut
241 1 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
242 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
243 use warnings;
244  
245 +======EOD======
246  
247  
248 pp_addpm({At=>'Bot'},<<'+======EOD======');
249  
250 =head1 AUTHOR
251  
252 Copyright 2002, 2003 Craig DeForest. There is no warranty. You are allowed
253 to redistribute this software under certain conditions. For details,
254 see the file COPYING in the PDL distribution. If this file is
255 separated from the PDL distribution, the copyright notice should be
256 included in the file.
257  
258 =cut
259  
260 2 ▶package PDL::Transform;
Subroutine BEGIN: called CC=1 SCAR=0.0
261 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
262 2 ▶use overload '""' => \&_strval;
Subroutine BEGIN: called CC=1 SCAR=0.0
263 2 ▶use overload 'x' => \&_compose_op;
Subroutine BEGIN: called CC=1 SCAR=0.0
264 2 ▶use overload '**' => \&_pow_op;
Subroutine BEGIN: called CC=1 SCAR=0.0
265 use overload '!' => \&t_inverse;
266 1 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
267 1 ▶use PDL::LiteF;
Subroutine BEGIN: called CC=1 SCAR=0.0
268 1 ▶use PDL::MatrixOps;
Subroutine BEGIN: called CC=1 SCAR=0.0
269 use PDL::Constants qw(PI DEG2RAD);
270  
271 #### little helper kludge parses a list of synonyms
272 881 ▶sub _opt {
Subroutine _opt: called CC=3 SCAR=11.0
273 881 ▶ my ($hash, $synonyms, $alt) = @_; # default $alt is undef -- ok.
Branch: 1 branch
BranchTrueFalseTotal
unless my($s) = grep(defined($hash->{$_}), @$synonyms) 682 199 881
274 199 ▶ return $alt if !(my ($s) = grep defined $hash->{$_}, @$synonyms);
Branch: 1 branch
BranchTrueFalseTotal
UNIVERSAL::isa($alt, 'PDL') ? : 7 192 199
275 UNIVERSAL::isa($alt,'PDL') ? PDL->pdl($hash->{$s}) : $hash->{$s};
276 }
277  
278 ######################################################################
279 #
280 # Stringification hack. _strval just does a method search on stringify
281 # for the object itself. This gets around the fact that stringification
282 # overload is a subroutine call, not a method search.
283 #
284  
285 2 ▶sub _strval {
Subroutine _strval: called CC=1 SCAR=0.0
286 2 my($me) = shift;
287 $me->stringify();
288 }
289  
290 ######################################################################
291 #
292 # PDL::Transform overall stringifier. Subclassed stringifiers should
293 # call this routine first then append auxiliary information.
294 #
295 30 ▶sub stringify {
Subroutine stringify: called CC=5 SCAR=17.2
Pod undocumented
296 30 my($me) = shift;
297 30 my($mestr) = (ref $me);
298 30 $mestr =~ s/PDL::Transform:://;
299 30 ▶ my $out = $mestr . " (" . $me->{name} . "): ";
Branch: 2 branches
BranchTrueFalseTotal
defined $me->{'func'} ? : 30 0 30
ref $me->{'func'} eq 'CODE' ? : 30 0 30
300 30 ▶ $out .= "fwd ". ((defined ($me->{func})) ? ( (ref($me->{func}) eq 'CODE') ? "ok" : "non-CODE(!!)" ): "missing")."; ";
Branch: 2 branches
BranchTrueFalseTotal
defined $me->{'inv'} ? : 30 0 30
ref $me->{'inv'} eq 'CODE' ? : 30 0 30
301 $out .= "inv ". ((defined ($me->{inv})) ? ( (ref($me->{inv}) eq 'CODE') ? "ok" : "non-CODE(!!)" ):"missing").".\n";
302 }
303  
304 +======EOD======
305  
306 pp_add_exported('apply');
307 pp_addpm(<<'+======EOD_apply======');
308  
309 =head2 apply
310  
311 =for sig
312  
313 Signature: (data(); PDL::Transform t)
314  
315 =for usage
316  
317 $out = $data->apply($t);
318 $out = $t->apply($data);
319  
320 =for ref
321  
322 Apply a transformation to some input coordinates.
323  
324 In the example, C<$t> is a PDL::Transform and C<$data> is a PDL to
325 be interpreted as a collection of N-vectors (with index in the 0th
326 dimension). The output is a similar but transformed PDL.
327  
328 For convenience, this is both a PDL method and a Transform method.
329  
330 =cut
331 1 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
332 use Carp;
333  
334 *PDL::apply = \&apply;
335 57 ▶sub apply {
Subroutine apply: called CC=20 SCAR=51.4
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
UNIVERSAL::isa($_[0], 'PDL') ? : 29 28 57
336 57 ▶ my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL") 0 57 57
Condition33%1/3
UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL")
!ll&&!rl&&r
0057
MC/DC0%0/2
UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL")
UNIVERSAL::isa($me, "PDL::Transform") UNIVERSAL::isa($from, "PDL")
Truth table33%1/3
A and B
A= UNIVERSAL::isa($me, "PDL::Transform")B= UNIVERSAL::isa($from, "PDL")
ABresult
0X0
100
111
337 croak "apply requires both a PDL and a PDL::Transform.\n"
338 unless UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL');
339 57 ▶ croak "Applying a PDL::Transform with no func! Oops.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"func"} and ref $me->{"func"} eq "CODE" 0 57 57
Condition33%1/3
defined $me->{"func"} and ref $me->{"func"} eq "CODE"
!ll&&!rl&&r
0057
MC/DC0%0/2
defined $me->{"func"} and ref $me->{"func"} eq "CODE"
defined $me->{"func"} ref $me->{"func"} eq "CODE"
Truth table33%1/3
A and B
A= defined $me->{"func"}B= ref $me->{"func"} eq "CODE"
ABresult
0X0
100
111
340 57 unless(defined($me->{func}) and ref($me->{func}) eq 'CODE');
341 57 my $result = $me->{func}->($from,$me->{params});
342 57 ▶ $result->is_inplace(0); # clear inplace flag, just in case.
Branch: 1 branch
BranchTrueFalseTotal
if (defined $from->gethdr and $from->hdr->{"NAXIS"}) 0 57 57
Condition33%1/3
defined $from->gethdr and $from->hdr->{"NAXIS"}
!ll&&!rl&&r
5700
MC/DC0%0/2
defined $from->gethdr and $from->hdr->{"NAXIS"}
defined $from->gethdr $from->hdr->{"NAXIS"}
Truth table33%1/3
A and B
A= defined $from->gethdrB= $from->hdr->{"NAXIS"}
ABresult
0X0
100
111
343 0 ▶ if (defined $from->gethdr && $from->hdr->{NAXIS}) {
Condition0%0/5
$me->{'odim'} || $me->{'idim'} || 2
l!l
00
$me->{"odim"} or $me->{"idim"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$me->{'odim'} || $me->{'idim'} || 2
$me->{"odim"} $me->{"idim"}
Truth table0%0/3
A or B
A= $me->{"odim"}B= $me->{"idim"}
ABresult
1X1
011
000
344 0 my $nd = $me->{odim} || $me->{idim} || 2;
345 for my $d (1..$nd) {
346 $result->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
347 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
348 0 ▶ $me->{otype}[$d-1])
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'otype'}) ? : 0 0 0
ref $me->{'otype'} ne 'ARRAY' ? : 0 0 0
Condition0%0/5
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $from->hdr->{"CTYPE$d"} || ''
l!l
00
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) or $from->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
000
MC/DC0%0/2
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $from->hdr->{"CTYPE$d"} || ''
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) $from->hdr->{"CTYPE$d"}
Truth table0%0/3
not(A) or B
A= !defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1])B= $from->hdr->{"CTYPE$d"}
ABresult
1X1
011
000
349 || $from->hdr->{"CTYPE$d"}
350 || "");
351 $result->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
352 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
353 $me->{ounit}[$d-1])
354 0 ▶ || $from->hdr->{"CUNIT$d"}
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'ounit'}) ? : 0 0 0
ref $me->{'ounit'} ne 'ARRAY' ? : 0 0 0
Condition0%0/8
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $from->hdr->{"CUNIT$d"} || $from->hdr->{"CTYPE$d"} || ''
l!l
00
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $from->hdr->{"CUNIT$d"} or $from->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
000
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $from->hdr->{"CUNIT$d"}
l!l&&r!l&&!r
000
MC/DC0%0/3
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $from->hdr->{"CUNIT$d"} || $from->hdr->{"CTYPE$d"} || ''
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) $from->hdr->{"CUNIT$d"} $from->hdr->{"CTYPE$d"}
Truth table0%0/4
not(A) or B or C
A= !defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1])B= $from->hdr->{"CUNIT$d"}C= $from->hdr->{"CTYPE$d"}
ABCresult
1XX1
01X1
0011
0000
355 || $from->hdr->{"CTYPE$d"}
356 || "");
357 }
358 57 }
359 return $result;
360 }
361  
362 +======EOD_apply======
363  
364 pp_add_exported('invert');
365 pp_addpm(<<'+======EOD_invert======');
366  
367 =head2 invert
368  
369 =for sig
370  
371 Signature: (data(); PDL::Transform t)
372  
373 =for usage
374  
375 $out = $t->invert($data);
376 $out = $data->invert($t);
377  
378 =for ref
379  
380 Apply an inverse transformation to some input coordinates.
381  
382 In the example, C<$t> is a PDL::Transform and C<$data> is an ndarray to
383 be interpreted as a collection of N-vectors (with index in the 0th
384 dimension). The output is a similar ndarray.
385  
386 For convenience this is both a PDL method and a PDL::Transform method.
387  
388 =cut
389  
390 *PDL::invert = \&invert;
391 55 ▶sub invert {
Subroutine invert: called CC=6 SCAR=19.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
UNIVERSAL::isa($_[0], 'PDL') ? : 10 45 55
392 55 ▶ my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL") 0 55 55
Condition33%1/3
UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL")
!ll&&!rl&&r
0055
MC/DC0%0/2
UNIVERSAL::isa($me, "PDL::Transform") and UNIVERSAL::isa($from, "PDL")
UNIVERSAL::isa($me, "PDL::Transform") UNIVERSAL::isa($from, "PDL")
Truth table33%1/3
A and B
A= UNIVERSAL::isa($me, "PDL::Transform")B= UNIVERSAL::isa($from, "PDL")
ABresult
0X0
100
111
393 croak "invert requires a PDL and a PDL::Transform (did you want 'inverse' instead?)\n"
394 unless UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL');
395 55 ▶ croak "Inverting a PDL::Transform with no inverse! Oops.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"inv"} and ref $me->{"inv"} eq "CODE" 0 55 55
Condition33%1/3
defined $me->{"inv"} and ref $me->{"inv"} eq "CODE"
!ll&&!rl&&r
0055
MC/DC0%0/2
defined $me->{"inv"} and ref $me->{"inv"} eq "CODE"
defined $me->{"inv"} ref $me->{"inv"} eq "CODE"
Truth table33%1/3
A and B
A= defined $me->{"inv"}B= ref $me->{"inv"} eq "CODE"
ABresult
0X0
100
111
396 55 unless(defined($me->{inv}) and ref($me->{inv}) eq 'CODE');
397 55 my $result = $me->{inv}->($from, $me->{params});
398 55 $result->is_inplace(0); # make sure inplace flag is clear.
399 return $result;
400 }
401  
402 +======EOD_invert======
403  
404 pp_add_exported('map');
405 pp_def('map',
406 Pars=>'k0()', # Dummy to set type (should match the type of "in").
407 OtherPars=>'pdl *in; pdl *out; pdl *map; SV *boundary; SV *method;
408 long big; double blur; double sv_min; char flux; SV *bv',
409 CHeader => pp_line_numbers(__LINE__, <<'+==EOD_map_auxiliary=='),
410 /*
411 * Singular-value decomposition code is borrowed from
412 * MatrixOps -- cut-and-pasted here because of linker trouble.
413 * It's used by the auxiliary matrix manipulation code, below.
414 */
415 static inline void pdl_xform_svd(PDL_Double *W, PDL_Double *Z, PDL_Indx nRow, PDL_Indx nCol)
416 {
417 int i, j, k, EstColRank, RotCount, SweepCount, slimit;
418 PDL_Double eps, e2, tol, vt, p, x0, y0, q, r, c0, s0, d1, d2;
419 eps = 1e-6;
420 slimit = nCol/4;
421 if (slimit < 6.0)
422 slimit = 6;
423 SweepCount = 0;
424 e2 = 10.0*nRow*eps*eps;
425 tol = eps*.1;
426 EstColRank = nCol;
427 for (i=0; i<nCol; i++) {
428 for (j=0; j<nCol; j++) {
429 W[nCol*(nRow+i)+j] = 0.0;
430 }
431 W[nCol*(nRow+i)+i] = 1.0; /* rjrw 7/7/99: moved this line out of j loop */
432 }
433 RotCount = EstColRank*(EstColRank-1)/2;
434 while (RotCount != 0 && SweepCount <= slimit)
435 {
436 RotCount = EstColRank*(EstColRank-1)/2;
437 SweepCount++;
438 for (j=0; j<EstColRank-1; j++)
439 {
440 for (k=j+1; k<EstColRank; k++)
441 {
442 p = q = r = 0.0;
443 for (i=0; i<nRow; i++)
444 {
445 x0 = W[nCol*i+j]; y0 = W[nCol*i+k];
446 p += x0*y0; q += x0*x0; r += y0*y0;
447 }
448 Z[j] = q; Z[k] = r;
449 if (q >= r)
450 {
451 if (q<=e2*Z[0] || fabs(p)<=tol*q) RotCount--;
452 else
453 {
454 p /= q; r = 1 - r/q; vt = sqrt(4*p*p+r*r);
455 c0 = sqrt(fabs(.5*(1+r/vt))); s0 = p/(vt*c0);
456 for (i=0; i<nRow+nCol; i++)
457 {
458 d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
459 W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
460 }
461 }
462 }
463 else
464 {
465 p /= r; q = q/r-1; vt = sqrt(4*p*p+q*q);
466 s0 = sqrt(fabs(.5*(1-q/vt)));
467 if (p<0) s0 = -s0;
468 c0 = p/(vt*s0);
469 for (i=0; i<nRow+nCol; i++)
470 {
471 d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
472 W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
473 }
474 }
475 }
476 }
477 while (EstColRank>=3 && Z[(EstColRank-1)]<=Z[0]*tol+tol*tol)
478 EstColRank--;
479 }
480 }
481  
482 /*
483 * PDL_xform_aux:
484 * This handles the matrix manipulation part of the Jacobian filtered
485 * mapping code. It's separate from the main code because it's
486 * independent of the data type of the original arrays.
487 *
488 *Given a pre-allocated workspace and
489 * an integer set of coordinates, generate the discrete Jacobian
490 * from the map, pad the singular values, and return the inverse
491 * Jacobian, the largest singular value of the Jacobian itself, and
492 * the determinant of the original Jacobian. Boundary values use the
493 * asymmetric discrete Jacobian; others use the symmetric discrete Jacobian.
494 *
495 * The map and workspace must be of type PDL_D. If the dimensionality is
496 * d, then the workspace must have at least 3*n^2+n elements. The
497 * inverse of the padded Jacobian is returned in the first n^2 elements.
498 * The determinant of the original Jacobian gets stuffed into the n^2
499 * element of the workspace. The largest padded singular value is returned.
500 *
501 */
502  
503 static inline PDL_Double PDL_xform_aux ( pdl *map, PDL_Indx *coords, PDL_Double *tmp, PDL_Double sv_min) {
504 PDL_Indx ndims;
505 PDL_Indx i, j, k;
506 PDL_Indx offset;
507 PDL_Double det;
508 PDL_Double *jptr;
509 PDL_Double *svptr;
510 PDL_Double *aptr,*bptr;
511 PDL_Double max_sv = 0.0;
512  
513 ndims = map->ndims-1;
514  
515 /****** Accumulate the Jacobian */
516 /* Accumulate the offset into the map array */
517 for (i=offset=0; i<ndims; i++)
518 offset += coords[i] * map->dimincs[i+1];
519  
520 jptr = tmp + ndims*ndims;
521  
522 for (i=0; i<ndims; i++) { /* Loop over offset direction */
523 char bot = (coords[i] <=0);
524 char top = (coords[i] >= map->dims[i+1]-1);
525 char symmetric = !(bot || top);
526 PDL_Double *ohi,*olo;
527 PDL_Indx diff = map->dimincs[i+1];
528 ohi = ((PDL_Double *)map->data) + ( offset + ( top ? 0 : diff ));
529 olo = ((PDL_Double *)map->data) + ( offset - ( bot ? 0 : diff ));
530  
531 for (j=0; j<ndims; j++) { /* Loop over dimension */
532 PDL_Double jel = *ohi - *olo;
533  
534 ohi += map->dimincs[0];
535 olo += map->dimincs[0];
536  
537 if (symmetric)
538 jel /= 2;
539 *(jptr++) = jel;
540 }
541 }
542  
543  
544 /****** Singular-value decompose the Jacobian
545 * The svd routine produces the squares of the singular values,
546 * and requires normalization for one of the rotation matrices.
547 */
548  
549 jptr = tmp + ndims*ndims;
550 svptr = tmp + 3*ndims*ndims;
551 pdl_xform_svd(jptr,svptr,ndims,ndims);
552  
553 aptr = svptr;
554 for (i=0;i<ndims;i++,aptr++)
555 *aptr = sqrt(*aptr);
556  
557  
558 /* fix-up matrices here */
559 bptr = jptr;
560 for (i=0; i<ndims;i++) {
561 aptr = svptr;
562 for (j=0;j<ndims;j++)
563 *(bptr++) /= *(aptr++);
564 }
565  
566 /****** Store the determinant, and pad the singular values as necessary.*/
567 aptr = svptr;
568 det = 1.0;
569 for (i=0;i<ndims;i++) {
570 det *= *aptr;
571 if (*aptr < sv_min)
572 *aptr = sv_min;
573 if (*aptr > max_sv )
574 max_sv = *aptr;
575 aptr++;
576 }
577  
578 /****** Generate the inverse matrix */
579 /* Multiply B-transpose times 1/S times A-transpose. */
580 /* since S is diagonal we just divide by the appropriate element. */
581 /* */
582 aptr = tmp + ndims*ndims;
583 bptr = aptr + ndims*ndims;
584 jptr= tmp;
585  
586 for (i=0;i<ndims;i++) {
587 for (j=0;j<ndims;j++) {
588 *jptr = 0;
589  
590 for (k=0;k<ndims;k++)
591 *jptr += aptr[j*ndims + k] * bptr[k*ndims + i] / *svptr;
592  
593 jptr++;
594 }
595 svptr++;
596 }
597  
598 *jptr = det;
599 return max_sv;
600 }
601 +==EOD_map_auxiliary==
602 Code => pp_line_numbers(__LINE__, <<'+==EOD_map_c_code=='),
603  
604 /*
605 * Pixel interpolation & averaging code
606 *
607 * Calls a common coordinate-transformation block (see following hdr)
608 * that isn't dependent on the type of the input variable.
609 *
610 * The inputs are SVs to avoid hassling with broadcastloops; broadcasting
611 * is handled internally. To simplify the broadcasting business, any
612 * broadcast dimensions should all be collapsed to a single one by the
613 * perl front-end.
614 *
615 */
616  
617 pdl *in = $COMP(in);
618 pdl *out = $COMP(out);
619 pdl *map = $COMP(map);
620  
621 PDL_Indx ndims = map->ndims -1; /* Number of dimensions we're working in */
622 PDL_Double tmp[3*ndims*ndims+ndims]; /* Workspace for prefrobnication */
623 PDL_Indx ovec[ndims]; /* output pixel loop vector */
624 PDL_Indx ivec[ndims]; /* input pixel loop vector */
625 PDL_Indx ibvec[ndims]; /* input pixel base offset vector */
626 PDL_Double dvec[ndims]; /* Residual vector for linearization */
627 PDL_Double tvec[ndims]; /* Temporary floating-point vector */
628 PDL_Double acc[in->dims[ndims]]; /* Broadcasted accumulator */
629 PDL_Double wgt[in->dims[ndims]]; /* Broadcasted weight accumulator */
630 PDL_Double wgt2[in->dims[ndims]]; /* Broadcasted weight accumulator for badval finding */
631 char bounds[ndims]; /* Boundary condition packed string */
632 PDL_Indx index_stash[ndims]; /* Stash to store the opening index of dim sample scans */
633 char method; /* Method identifier (gets one of 'h','g') */
634 PDL_Long big; /* Max size of input footprint for each pix */
635 PDL_Double blur; /* Scaling of filter */
636 PDL_Double sv_min; /* minimum singular value */
637 char flux; /* Flag to indicate flux conservation */
638 PDL_Indx i;
639 $GENERIC() badval = SvNV($COMP(bv));
640 #define HANNING_LOOKUP_SIZE 2500
641 static PDL_Double hanning_lookup[HANNING_LOOKUP_SIZE + 2];
642 static int needs_hanning_calc = 1;
643 PDL_Double zeta = 0;
644 PDL_Double hanning_offset;
645  
646 #define GAUSSIAN_LOOKUP_SIZE 4000
647 #define GAUSSIAN_MAXVAL 6.25 /* 2.5 HWHMs (square it) */
648 static PDL_Double gaussian_lookup[GAUSSIAN_LOOKUP_SIZE + 2];
649 static int needs_gaussian_calc = 1;
650  
651 PDL_RETERROR(PDL_err, PDL->make_physical(in));
652 PDL_RETERROR(PDL_err, PDL->make_physical(out));
653 PDL_RETERROR(PDL_err, PDL->make_physical(map));
654  
655 /***
656 * Fill in the boundary condition array
657 */
658 {
659 char *bstr;
660 STRLEN blen;
661 bstr = SvPV($COMP(boundary),blen);
662  
663 if (blen == 0) {
664 /* If no boundary is specified then every dim gets truncated */
665 PDL_Indx i;
666 for (i=0;i<ndims;i++)
667 bounds[i] = 1;
668 } else {
669 PDL_Indx i;
670 for (i=0;i<ndims;i++) {
671 switch(bstr[i < blen ? i : blen-1 ]) {
672 case '0': case 'f': case 'F': /* forbid */
673 bounds[i] = 0;
674 break;
675 case '1': case 't': case 'T': /* truncate */
676 bounds[i] = 1;
677 break;
678 case '2': case 'e': case 'E': /* extend */
679 bounds[i] = 2;
680 break;
681 case '3': case 'p': case 'P': /* periodic */
682 bounds[i] = 3;
683 break;
684 case '4': case 'm': case 'M': /* mirror */
685 bounds[i] = 4;
686 break;
687 default:
688 $CROAK("Error in map: Unknown boundary condition '%c'",bstr[i]);
689 break;
690 }
691 }
692 }
693 }
694  
695 /***
696 * Parse out the 'method', 'big', 'blur', and 'sv_min' arguments
697 */
698 big = labs($COMP(big));
699 if (big <= 0)
700 $CROAK("map: 'big' parameter must be >0");
701  
702 blur = fabs($COMP(blur));
703 if (blur < 0)
704 $CROAK("map: 'blur' parameter must be >= 0");
705  
706 sv_min = fabs($COMP(sv_min));
707 if (sv_min < 0)
708 $CROAK("map: 'sv_min' parameter must be >= 0");
709  
710 flux = $COMP(flux) != 0;
711  
712 {
713 char *mstr;
714 STRLEN mlen;
715 mstr = SvPV($COMP(method),mlen);
716  
717 if (mlen==0)
718 method = 'h';
719 switch(*mstr) {
720 case 'h': // h - lookup-table hanning window
721 if ( needs_hanning_calc ) {
722 int i;
723 for (i=0;i<HANNING_LOOKUP_SIZE;i++) {
724 hanning_lookup[i] = 0.5 + 0.5 * cos(3.1415926536 / HANNING_LOOKUP_SIZE * i);
725 }
726 hanning_lookup[HANNING_LOOKUP_SIZE] = 0;
727 hanning_lookup[HANNING_LOOKUP_SIZE+1] = 0;
728 needs_hanning_calc = 0;
729 }
730 zeta = HANNING_LOOKUP_SIZE / blur; /* fall-through deliberate */
731 case 'H': // H - rigorous hanning window
732 method = *mstr;
733 hanning_offset = (blur >= 1) ? 0 : 0.5 * (1.0 - blur);
734 break;
735  
736 case 'g': case 'j': // Gaussian and/or Jacobian, using lookup table
737 method = 'g';
738 zeta = GAUSSIAN_LOOKUP_SIZE / GAUSSIAN_MAXVAL;
739  
740 if ( needs_gaussian_calc ) {
741 int i;
742 for (i=0;i<GAUSSIAN_LOOKUP_SIZE;i++) {
743 gaussian_lookup[i] = exp( - i * 1.386294 / zeta );
744 }
745 gaussian_lookup[GAUSSIAN_LOOKUP_SIZE] = 0;
746 gaussian_lookup[GAUSSIAN_LOOKUP_SIZE+1] = 0;
747 needs_gaussian_calc = 0;
748 }
749 break;
750  
751 case 'G': case 'J': // Jacobian -- same thing, with direct calculation
752 method = 'G'; break;
753 default:
754 $CROAK("Bug in map: unknown method '%c'",*mstr);
755 break;
756 }
757 }
758  
759  
760  
761 /* End of initialization */
762 /*************************************************************/
763 /* Start of Real Work */
764  
765 /* Initialize coordinate vector and map offset
766 */
767 for (i=0;i<ndims;i++)
768 ovec[i] = 0;
769  
770 PDL_Double *map_ptr = (PDL_Double *)(map->data);
771 PDL_Indx npdls = 1, incs[npdls*ndims], offs[npdls];
772 for (i=0; i < npdls; i++) offs[i] = 0;
773 for (i=0; i < ndims; i++) {
774 incs[i*npdls + 0] = map->dimincs[i+1];
775 }
776  
777 /* Main pixel loop (iterates over pixels in the output plane) */
778 do {
779 PDL_Indx psize; // Size of the region to accumulate over for this pixel
780 PDL_Indx i_off; // Offset into the data array of the source PDL
781 PDL_Indx j; // Generic loop index
782 char t_vio; // counter used for truncation boundary violations
783 char carry; // flag used for multidimensional loop iteration
784  
785 /* Prefrobnicate the transformation matrix */
786 psize = (PDL_Long)(blur * PDL_xform_aux(map, ovec, tmp, sv_min) + 0.5)+1; /* assignment */
787  
788 #ifdef DEBUG_MAP
789 {
790 PDL_Indx k; PDL_Indx foo = 0;
791 printf("ovec: [");
792 for (k=0;k<ndims;k++) {
793 foo += ovec[k] * map->dimincs[k+1];
794 printf(" %2td ",(PDL_Indx)(ovec[k]));
795 }
796 printf("]; psize is %ld; big is %d; blur is %8.2f; map is [",psize,big, blur);
797 for (k=0;k<ndims;k++) {
798 printf("%8.2f",(double)((($GENERIC() *)(map->data))[foo + k*map->dimincs[0]]));
799 }
800 printf("]\n");
801 }
802 #endif
803  
804 /* Don't bother accumulating output if psize is too large */
805 if (psize <= big) {
806 /* Use the prefrobnicated matrix to generate a local linearization.
807 * dvec gets the delta; ibvec gets the base.
808 */
809 {
810 PDL_Double *mp = map_ptr + offs[0];
811 for (i=0;i<ndims;i++) {
812 dvec[i] = *mp - ( ibvec[i] = (PDL_Long)(*mp + 0.5)); /* assignment */
813 mp += map->dimincs[0];
814 }
815 }
816  
817 /* Initialize input delta vector */
818 for (i=0;i<ndims;i++)
819 ivec[i] = -psize;
820  
821 /* Initialize accumulators */
822 {
823 PDL_Double *ac = acc;
824 for (i=0; i < in->dims[ndims]; i++)
825 *(ac++) = 0.0;
826  
827 }
828 {
829 PDL_Double *wg = wgt;
830 for (i=0;i < in->dims[ndims]; i++)
831 *(wg++) = 0.0;
832 }
833 {
834 PDL_Double *wg = wgt2;
835 for (i=0;i < in->dims[ndims]; i++)
836 *(wg++) = 0.0;
837 }
838  
839  
840 /*
841 * Calculate the original offset into the data array, to enable
842 * delta calculations in the pixel loop
843 *
844 * i runs over dims; j holds the working integer index in the
845 * current dim.
846 *
847 * This code matches the incrementation code at the bottom of the accumulation loop
848 */
849  
850 t_vio = 0; /* truncation-boundary violation count - don't bother if it is nonzero */
851 i_off = 0;
852 for (i=0;i<ndims; i++) {
853 j = ivec[i] + ibvec[i];
854 if (j<0 || j >= in->dims[i]) {
855 switch(bounds[i]) {
856 case 0: /* no breakage allowed */
857 $CROAK("index out-of-bounds in map");
858 break;
859 case 1: /* truncation */
860 t_vio++;
861 /* fall through */
862 case 2: /* extension -- crop */
863 if (j<0)
864 j=0;
865 else //if (j>=in->dims[i])
866 j = in->dims[i] - 1;
867 break;
868 case 3: /* periodic -- mod it */
869 j %= in->dims[i];
870 if (j<0)
871 j += in->dims[i];
872 break;
873 case 4: /* mirror -- reflect off the edges */
874 j += in->dims[i];
875 j %= (in->dims[i]*2);
876 if (j<0)
877 j += in->dims[i]*2;
878 j -= in->dims[i];
879 if (j<0) {
880 j *= -1;
881 j -= 1;
882 }
883 break;
884 default:
885 $CROAK("Unknown boundary condition %td in map -- bug alert!", (PDL_Indx)bounds[i]);
886 break;
887 }
888 }
889 i_off += in->dimincs[i] * j;
890 }
891  
892 /* Initialize index stashes for later reference as we scan the footprint */
893 /* It's a pain in the ass to deal with boundaries, and doubly so at the */
894 /* end of a dimensional scan. So we stash the index location at the */
895 /* start of each dimensional scan here. When we finish incrementing */
896 /* through a particular dim, we pull its value back out of the stash. */
897 for (i=0;i<ndims;i++) {
898 index_stash[i] = i_off;
899 }
900  
901 /* The input accumulation loop is the hotspot for the entire operation. */
902 /* We loop over pixels in the region of interest (+/- psize in each dimension) */
903 /* in the input array, use the linearized transform to bring each pixel center */
904 /* forward to the output plane, and calculate a weighting based on the chosen */
905 /* filter function. 'h' is a fast Hanning window rolloff using a lookup */
906 /* table that is initialized the first time through the code. 'H' is the */
907 /* same process, but explicitly calculated for each interation (~2x slower). */
908 /* 'g' uses a radial Gaussian filter. Rather than calculate the array offset */
909 /* into the input array fresh from the current input array vector each time, */
910 /* we walk through the array using dimincs and the old offset. This saves */
911 /* about half of the time spent on index calculation. */
912  
913 do { /* Input accumulation loop */
914 PDL_Double *cp;
915 PDL_Double alpha; // weighting coefficient for the current point
916  
917 /* Calculate the weight of the current input point. Don't bother if we're
918 * violating any truncation boundaries (in that case our value is zero, but
919 * for the interpolation we also set the weight to zero).
920 */
921 if ( !t_vio ) {
922  
923 PDL_Double *ap = tvec;
924 PDL_Double *bp = dvec;
925 PDL_Indx *ip = ivec;
926 for (i=0; i<ndims; i++)
927 *(ap++) = *(ip++) - *(bp++);
928  
929 switch(method) {
930 PDL_Double dd; // tmp space for calculations in filters
931  
932 case 'h':
933 /* This is the Hanning window rolloff. It is a product of a simple */
934 /* cos^2(theta) rolloff in each dimension. Using a lookup table */
935 /* is about 2x faster than using cos(theta) directly in each */
936 /* weighting calculation, so we do. Using 2500 entries and linear */
937 /* interpolation is accurate to about 10^-7, and should preserve */
938 /* the contents of cache pretty well. */
939 alpha = 1;
940 cp = tmp;
941 for (i=0; i<ndims; i++) {
942 PDL_Indx lodex;
943 PDL_Indx hidex;
944 PDL_Double beta;
945 dd = 0;
946 ap = tvec;
947 /* Get the matrix-multiply element for this dimension */
948 for (j=0;j<ndims; j++)
949 dd += *(ap++) * *(cp++);
950  
951 /* Do linear interpolation from the table */
952 /* The table captures a hanning window centered 0.5 pixel from center. */
953 /* We scale the filter by the blur parameter -- but if blur is less */
954 /* than unity, we shrink the hanning blur window while keeping the 0.5 */
955 /* value on the pixel edge at 0.5. For blur greater than unity, we */
956 /* scale simply. */
957 beta = fabs(dd) - hanning_offset;
958 if (beta > 0) {
959 if (beta >= blur) {
960 alpha = 0;
961 i = ndims;
962 } else {
963 beta *= zeta;
964 lodex = beta;
965 beta -= lodex; //lodex now has the integer part, beta has the fractional part
966 if (lodex > HANNING_LOOKUP_SIZE)
967 lodex = HANNING_LOOKUP_SIZE;
968 hidex = lodex+1;
969 //do a linear interpolation between the two nearest values
970 alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta);
971 } /* end of interpolation branch */
972 } /* end of beta > 0 branch */
973 } /* end of dimension loop */
974 break;
975  
976 case 'H':
977 /* This is the Hanning window rolloff with explicit calculation, preserved */
978 /* in case someone actually wants the slower longer method. */
979 alpha = 1;
980 cp = tmp;
981 for (i=0; i<ndims; i++) {
982 dd = 0;
983 ap = tvec;
984 for (j=0;j<ndims; j++)
985 dd += *(ap++) * *(cp++);
986 dd = (fabs(dd) - hanning_offset) / blur;
987 if ( dd > 1 ) {
988 alpha = 0;
989 i = ndims;
990 } else
991 alpha *= (0.5 + 0.5 * cos( dd * 3.1415926536 ));
992 }
993 break;
994  
995 case 'g':
996 /* This is the Gaussian rolloff. It does lookup into a precalculated exponential. */
997 {
998 PDL_Double sum = 0;
999 cp = tmp;
1000 for (i=0; i<ndims;i++) {
1001 dd = 0;
1002 ap = tvec;
1003 for (j=0;j<ndims;j++)
1004 dd += *(ap++) * *(cp++);
1005 dd /= blur;
1006 sum += dd * dd;
1007 if (sum > GAUSSIAN_MAXVAL) {
1008 i = ndims; /* exit early if we're too far out */
1009 alpha = 0;
1010 }
1011 }
1012 if ( sum > GAUSSIAN_MAXVAL || !isfinite(sum) || isnan(sum) ) {
1013 alpha = 0;
1014 } else {
1015 PDL_Indx lodex,hidex;
1016 PDL_Double beta = fabs(zeta * sum);
1017  
1018 lodex = beta;
1019 beta -= lodex; // lodex now has the integer part, beta has the fractional part
1020 hidex = lodex+1;
1021 //do a linear interpolation between the two nearest values
1022 alpha = gaussian_lookup[hidex]*beta + gaussian_lookup[lodex]*(1 - beta);
1023  
1024 }
1025 }
1026 break;
1027  
1028 case 'G':
1029 /* This is the Gaussian rolloff with explicit calculation, preserved */
1030 /* in case someone actually wants the slower longer method. */
1031 {
1032 PDL_Double sum = 0;
1033 cp = tmp;
1034 for (i=0; i<ndims; i++) {
1035 dd = 0;
1036 ap = tvec;
1037 for (j=0;j<ndims; j++)
1038 dd += *(ap++) * *(cp++);
1039 dd /= blur;
1040 sum += dd * dd;
1041 if (sum > 4) /* 2 pixels -- four half-widths */
1042 i = ndims; /* exit early if this pixel is too far outside the footprint of the ideal point */
1043 }
1044  
1045 if (sum > GAUSSIAN_MAXVAL)
1046 alpha = 0;
1047 else
1048 alpha = exp(-sum * 1.386294); /* Gaussian, rt(2)-pix HWHM */
1049 }
1050 break;
1051 default:
1052 $CROAK("This can't happen: method='%c'",method);
1053 }
1054  
1055 { /* convenience block -- accumulate the current point into the weighted sum. */
1056 /* This is more than simple assignment because we have our own explicit poor */
1057 /* man's broadcastloop here, so we accumulate each broadcasted element separately. */
1058 $GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off;
1059 PDL_Indx max = out->dims[ndims];
1060 for ( i=0; i < max; i++ ) {
1061 if ( (badval==0) || (*dat != badval) ) {
1062 acc[i] += *dat * alpha;
1063 dat += in->dimincs[ndims];
1064 wgt[i] += alpha;
1065 }
1066 wgt2[i] += alpha; // Accumulate what weight we would have with no bad values
1067 }
1068 }
1069 } /* end of t_vio check (i.e. of input accumulation) */
1070  
1071  
1072 /* Advance input accumulation loop. */
1073 /* We both increment the total vector and also advance the index. */
1074 carry = 1;
1075 for (i=0; i<ndims && carry; i++) {
1076 /* Advance the current element of the offset vector */
1077 ivec[i]++;
1078 j = ivec[i] + ibvec[i];
1079  
1080 /* Advance the offset into the data array */
1081 if ( j > 0 && j <= in->dims[i]-1 ) {
1082 /* Normal case -- just advance the input vector */
1083 i_off += in->dimincs[i];
1084 } else {
1085 /* Busted a boundary - either before or after. */
1086 switch(bounds[i]){
1087 case 0: /* no breakage allowed -- treat as truncation for interpolation */
1088 case 1: /* truncation -- if we crossed the boundary mark ourselves out-of-bounds */
1089 if ( j == 0 )
1090 t_vio--;
1091 else if ( j == in->dims[i] )
1092 t_vio++;
1093 break;
1094 case 2: /* extension -- do nothing (so the same input point is re-used) */
1095 break;
1096 case 3: /* periodic -- advance and mod into the allowed range */
1097 if ((j % in->dims[i]) == 0) {
1098 i_off -= in->dimincs[i] * (in->dims[i]-1);
1099 } else {
1100 i_off += in->dimincs[i];
1101 }
1102 break;
1103 case 4: /* mirror -- advance or retreat depending on phase */
1104 j += in->dims[i];
1105 j %= (in->dims[i]*2);
1106 j -= in->dims[i];
1107 if ( j!=0 && j!= -in->dims[i] ) {
1108 if (j<0)
1109 i_off -= in->dimincs[i];
1110 else
1111 i_off += in->dimincs[i];
1112 }
1113 break;
1114 }
1115 }
1116  
1117 /* Now check for carry */
1118 if (ivec[i] <= psize) {
1119 /* Normal case -- copy the current offset to the faster-running dim stashes */
1120 PDL_Indx k;
1121 for (k=0;k<i;k++) {
1122 index_stash[k] = i_off;
1123 }
1124 carry = 0;
1125  
1126 } else { /* End of this scan -- recover the last position, and mark carry */
1127 i_off = index_stash[i];
1128 if (bounds[i]==1) {
1129 j = ivec[i] + ibvec[i];
1130 if ( j < 0 || j >= in->dims[i] )
1131 t_vio--;
1132 ivec[i] = -psize;
1133 j = ivec[i] + ibvec[i];
1134 if ( j < 0 || j >= in->dims[i] )
1135 t_vio++;
1136 carry = 1;
1137 } else {
1138 ivec[i] = -psize;
1139 }
1140 }
1141 } /* End of counter-advance loop */
1142 } while (carry==0); /* end of total data accumulation loop (termination condition has carry on last dim) */
1143  
1144 {
1145 PDL_Double *ac = acc;
1146 PDL_Double *wg = wgt;
1147 PDL_Double *wg2 = wgt2;
1148 $GENERIC() *dat = out->data;
1149  
1150 /* Calculate output vector offset */
1151 for (i=0;i<ndims;i++)
1152 dat += out->dimincs[i] * ovec[i];
1153  
1154 if (!flux) {
1155 /* Flux flag is NOT set -- normal case. Copy the weighted accumulated data. */
1156 for (i=0; i < out->dims[ndims]; i++) {
1157 *dat = (*wg && (*wg2 / *wg) < 1.5) ? *ac / *wg : badval;
1158 ac++; wg++; wg2++;
1159 dat += out->dimincs[ndims];
1160 }
1161 } else {
1162 /* Flux flag is set - scale by the (unpadded) determinant of the Jacobian */
1163 PDL_Double det = tmp[ndims*ndims];
1164 for (i=0; i < out->dims[ndims]; i++) {
1165 if (*wg && (*wg2 / *wg) < 1.5 ) {
1166 *dat = *(ac++) / *(wg++) * det;
1167 wg2++;
1168 } else {
1169 *dat = badval;
1170 ac++; wg++; wg2++;
1171 }
1172 dat += out->dimincs[ndims];
1173 } /* end of for loop */
1174 } /* end of flux flag set conditional */
1175 } /* end of convenience block */
1176  
1177 /* End of code for normal pixels */
1178 } else {
1179 /* The pixel was ludicrously huge -- just set this pixel to nan */
1180 $GENERIC() *dat = out->data;
1181 for (i=0;i<ndims;i++)
1182 dat += out->dimincs[i] * ovec[i];
1183 for (i=0;i<out->dims[ndims];i++) {
1184 *dat = badval; /* Should handle bad values too -- not yet */
1185 dat += out->dimincs[ndims];
1186 }
1187 }
1188  
1189 /* Increment the pixel counter */
1190 if (!pdl_broadcast_nd_step(npdls, offs, 0, ndims, incs, out->dims, ovec)) break;
1191 } while (1);
1192 PDL->changed(out, PDL_PARENTDATACHANGED, 0);
1193 +==EOD_map_c_code==
1194  
1195 Doc=><<'+==EOD_map_doc==',
1196 =for sig
1197  
1198 Signature: (data(); PDL::Transform t)
1199  
1200 =for usage
1201  
1202 $y = $x->map($xform,[<template>],[\%opt]); # Distort $x with transform $xform
1203 $y = $x->map(t_identity,[$pdl],[\%opt]); # rescale $x to match $pdl's dims.
1204  
1205 =for ref
1206  
1207 Resample an image or N-D dataset using a coordinate transform.
1208  
1209 The data are resampled so that the new pixel indices are proportional
1210 to the transformed coordinates rather than the original ones.
1211  
1212 The operation uses the inverse transform: each output pixel location
1213 is inverse-transformed back to a location in the original dataset, and
1214 the value is interpolated or sampled appropriately and copied into the
1215 output domain. A variety of sampling options are available, trading
1216 off speed and mathematical correctness.
1217  
1218 For convenience, this is both a PDL method and a PDL::Transform method.
1219  
1220 C<map> is FITS-aware: if there is a FITS header in the input data,
1221 then the coordinate transform acts on the scientific coordinate system
1222 rather than the pixel coordinate system.
1223  
1224 By default, the output coordinates are separated from pixel coordinates
1225 by a single layer of indirection. You can specify the mapping between
1226 output transform (scientific) coordinates to pixel coordinates using
1227 the C<orange> and C<irange> options (see below), or by supplying a
1228 FITS header in the template.
1229  
1230 If you don't specify an output transform, then the output is
1231 autoscaled: C<map> transforms a few vectors in the forward direction
1232 to generate a mapping that will put most of the data on the image
1233 plane, for most transformations. The calculated mapping gets stuck in the
1234 output's FITS header.
1235  
1236 Autoscaling is especially useful for rescaling images -- if you specify
1237 the identity transform and allow autoscaling, you duplicate the
1238 functionality of L<rescale2d|PDL::Image2D/rescale2d>, but with more
1239 options for interpolation.
1240  
1241 You can operate in pixel space, and avoid autoscaling of the output,
1242 by setting the C<nofits> option (see below).
1243  
1244 The output has the same data type as the input. This is a feature,
1245 but it can lead to strange-looking banding behaviors if you use
1246 interpolation on an integer input variable.
1247  
1248 The C<template> can be one of:
1249  
1250 =over 3
1251  
1252 =item * a PDL
1253  
1254 The PDL and its header are copied to the output array, which is then
1255 populated with data. If the PDL has a FITS header, then the FITS
1256 transform is automatically applied so that $t applies to the output
1257 scientific coordinates and not to the output pixel coordinates. In
1258 this case the NAXIS fields of the FITS header are ignored.
1259  
1260 =item * a FITS header stored as a hash ref
1261  
1262 The FITS NAXIS fields are used to define the output array, and the
1263 FITS transformation is applied to the coordinates so that $t applies to the
1264 output scientific coordinates.
1265  
1266 =item * a list ref
1267  
1268 This is a list of dimensions for the output array. The code estimates
1269 appropriate pixel scaling factors to fill the available space. The
1270 scaling factors are placed in the output FITS header.
1271  
1272 =item * nothing
1273  
1274 In this case, the input image size is used as a template, and scaling
1275 is done as with the list ref case (above).
1276  
1277 =back
1278  
1279 OPTIONS:
1280  
1281 The following options are interpreted:
1282  
1283 =over 3
1284  
1285 =item b, bound, boundary, Boundary (default = 'truncate')
1286  
1287 This is the boundary condition to be applied to the input image; it is
1288 passed verbatim to L<range|PDL::Slices/range> or
1289 L<interpND|PDL::Primitive/interpND> in the sampling or interpolating
1290 stage. Other values are 'forbid','extend', and 'periodic'. You can
1291 abbreviate this to a single letter. The default 'truncate' causes the
1292 entire notional space outside the original image to be filled with 0.
1293  
1294 =item pix, Pixel, nf, nofits, NoFITS (default = 0)
1295  
1296 If you set this to a true value, then FITS headers and interpretation
1297 are ignored; the transformation is treated as being in raw pixel coordinates.
1298  
1299 =item j, J, just, justify, Justify (default = 0)
1300  
1301 If you set this to 1, then output pixels are autoscaled to have unit
1302 aspect ratio in the output coordinates. If you set it to a non-1
1303 value, then it is the aspect ratio between the first dimension and all
1304 subsequent dimensions -- or, for a 2-D transformation, the scientific
1305 pixel aspect ratio. Values less than 1 shrink the scale in the first
1306 dimension compared to the other dimensions; values greater than 1
1307 enlarge it compared to the other dimensions.
1308  
1309 =item ir, irange, input_range, Input_Range
1310  
1311 This is a way to modify the autoscaling. It specifies the range of
1312 input scientific (not necessarily pixel) coordinates that you want to be
1313 mapped to the output image. It can be either a nested array ref or
1314 an ndarray. The 0th dim (outside coordinate in the array ref) is
1315 dimension index in the data; the 1st dim should have order 2.
1316 For example, passing in either [[-1,2],[3,4]] or pdl([[-1,2],[3,4]])
1317 limites the map to the quadrilateral in input space defined by the
1318 four points (-1,3), (-1,4), (2,4), and (2,3).
1319  
1320 As with plain autoscaling, the quadrilateral gets sparsely sampled by
1321 the autoranger, so pathological transformations can give you strange
1322 results.
1323  
1324 This parameter is overridden by C<orange>, below.
1325  
1326 =item or, orange, output_range, Output_Range
1327  
1328 This sets the window of output space that is to be sampled onto the
1329 output array. It works exactly like C<irange>, except that it specifies
1330 a quadrilateral in output space. Since the output pixel array is itself
1331 a quadrilateral, you get pretty much exactly what you asked for.
1332  
1333 This parameter overrides C<irange>, if both are specified. It forces
1334 rectification of the output (so that scientific axes align with the pixel
1335 grid).
1336  
1337 =item r, rect, rectify
1338  
1339 This option defaults TRUE and controls how autoscaling is performed. If
1340 it is true or undefined, then autoscaling adjusts so that pixel coordinates
1341 in the output image are proportional to individual scientific coordinates.
1342 If it is false, then autoscaling automatically applies the inverse of any
1343 input FITS transformation *before* autoscaling the pixels. In the special
1344 case of linear transformations, this preserves the rectangular shape of the
1345 original pixel grid and makes output pixel coordinate proportional to input
1346 coordinate.
1347  
1348 =item m, method, Method
1349  
1350 This option controls the interpolation method to be used.
1351 Interpolation greatly affects both speed and quality of output. For
1352 most cases the option is directly passed to
1353 L<interpND|PDL::Primitive/interpND> for interpolation. Possible
1354 options, in order from fastest to slowest, are:
1355  
1356 =over 3
1357  
1358  
1359 =item * s, sample (default for ints)
1360  
1361 Pixel values in the output plane are sampled from the closest data value
1362 in the input plane. This is very fast but not very accurate for either
1363 magnification or decimation (shrinking). It is the default for templates
1364 of integer type.
1365  
1366 =item * l, linear (default for floats)
1367  
1368 Pixel values are linearly interpolated from the closest data value in the
1369 input plane. This is reasonably fast but only accurate for magnification.
1370 Decimation (shrinking) of the image causes aliasing and loss of photometry
1371 as features fall between the samples. It is the default for floating-point
1372 templates.
1373  
1374 =item * c, cubic
1375  
1376 Pixel values are interpolated using an N-cubic scheme from a 4-pixel
1377 N-cube around each coordinate value. As with linear interpolation,
1378 this is only accurate for magnification.
1379  
1380 =item * f, fft
1381  
1382 Pixel values are interpolated using the term coefficients of the
1383 Fourier transform of the original data. This is the most appropriate
1384 technique for some kinds of data, but can yield undesired "ringing" for
1385 expansion of normal images. Best suited to studying images with
1386 repetitive or wavelike features.
1387  
1388 =item * h, hanning
1389  
1390 Pixel values are filtered through a spatially-variable filter tuned to
1391 the computed Jacobian of the transformation, with hanning-window
1392 (cosine) pixel rolloff in each dimension. This prevents aliasing in the
1393 case where the image is distorted or shrunk, but allows small amounts
1394 of aliasing at pixel edges wherever the image is enlarged.
1395  
1396 =item * g, gaussian, j, jacobian
1397  
1398 Pixel values are filtered through a spatially-variable filter tuned to
1399 the computed Jacobian of the transformation, with radial Gaussian
1400 rolloff. This is the most accurate resampling method, in the sense of
1401 introducing the fewest artifacts into a properly sampled data set.
1402 This method uses a lookup table to speed up calculation of the Gaussian
1403 weighting.
1404  
1405 =item * G
1406  
1407 This method works exactly like 'g' (above), except that the Gaussian
1408 values are computed explicitly for every sample -- which is considerably
1409 slower.
1410  
1411 =back
1412  
1413 =item blur, Blur (default = 1.0)
1414  
1415 This value scales the input-space footprint of each output pixel in
1416 the gaussian and hanning methods. It's retained for historical
1417 reasons. Larger values yield blurrier images; values significantly
1418 smaller than unity cause aliasing. The parameter has slightly
1419 different meanings for Gaussian and Hanning interpolation. For
1420 Hanning interpolation, numbers smaller than unity control the
1421 sharpness of the border at the edge of each pixel (so that blur=>0 is
1422 equivalent to sampling for non-decimating transforms). For
1423 Gaussian interpolation, the blur factor parameter controls the
1424 width parameter of the Gaussian around the center of each pixel.
1425  
1426 =item sv, SV (default = 1.0)
1427  
1428 This value lets you set the lower limit of the transformation's
1429 singular values in the hanning and gaussian methods, limiting the
1430 minimum radius of influence associated with each output pixel. Large
1431 numbers yield smoother interpolation in magnified parts of the image
1432 but don't affect reduced parts of the image.
1433  
1434 =item big, Big (default = 0.5)
1435  
1436 This is the largest allowable input spot size which may be mapped to a
1437 single output pixel by the hanning and gaussian methods, in units of
1438 the largest non-broadcast input dimension. (i.e. the default won't let
1439 you reduce the original image to less than 5 pixels across). This places
1440 a limit on how long the processing can take for pathological transformations.
1441 Smaller numbers keep the code from hanging for a long time; larger numbers
1442 provide for photometric accuracy in more pathological cases. Numbers larger
1443 than 1.0 are silly, because they allow the entire input array to be compressed
1444 into a region smaller than a single pixel.
1445  
1446 Wherever an output pixel would require averaging over an area that is too
1447 big in input space, it instead gets NaN or the bad value.
1448  
1449 =item phot, photometry, Photometry
1450  
1451 This lets you set the style of photometric conversion to be used in the
1452 hanning or gaussian methods. You may choose:
1453  
1454 =over 3
1455  
1456 =item * 0, s, surf, surface, Surface (default)
1457  
1458 (this is the default): surface brightness is preserved over the transformation,
1459 so features maintain their original intensity. This is what the sampling
1460 and interpolation methods do.
1461  
1462 =item * 1, f, flux, Flux
1463  
1464 Total flux is preserved over the transformation, so that the brightness
1465 integral over image regions is preserved. Parts of the image that are
1466 shrunk wind up brighter; parts that are enlarged end up fainter.
1467  
1468 =back
1469  
1470 =back
1471  
1472 VARIABLE FILTERING:
1473  
1474 The 'hanning' and 'gaussian' methods of interpolation give
1475 photometrically accurate resampling of the input data for arbitrary
1476 transformations. At each pixel, the code generates a linear
1477 approximation to the input transformation, and uses that linearization
1478 to estimate the "footprint" of the output pixel in the input space.
1479 The output value is a weighted average of the appropriate input spaces.
1480  
1481 A caveat about these methods is that they assume the transformation is
1482 continuous. Transformations that contain discontinuities will give
1483 incorrect results near the discontinuity. In particular, the 180th
1484 meridian isn't handled well in lat/lon mapping transformations (see
1485 L<PDL::Transform::Cartography>) -- pixels along the 180th meridian get
1486 the average value of everything along the parallel occupied by the
1487 pixel. This flaw is inherent in the assumptions that underly creating
1488 a Jacobian matrix. Maybe someone will write code to work around it.
1489 Maybe that someone is you.
1490  
1491 BAD VALUES:
1492  
1493 C<map()> supports bad values in the data array. Bad values in the input
1494 array are propagated to the output array. The 'g' and 'h' methods will
1495 do some smoothing over bad values: if more than 1/3 of the weighted
1496 input-array footprint of a given output pixel is bad, then the output
1497 pixel gets marked bad.
1498  
1499 =head2 match
1500  
1501 =for usage
1502  
1503 $y = $x->match($c); # Match $c's header and size
1504 $y = $x->match([100,200]); # Rescale to 100x200 pixels
1505 $y = $x->match([100,200],{rect=>1}); # Rescale and remove rotation/skew.
1506  
1507 =for ref
1508  
1509 Resample a scientific image to the same coordinate system as another.
1510  
1511 The example above is syntactic sugar for
1512  
1513 $y = $x->map(t_identity, $c, ...);
1514  
1515 it resamples the input PDL with the identity transformation in
1516 scientific coordinates, and matches the pixel coordinate system to
1517 $c's FITS header.
1518  
1519 There is one difference between match and map: match makes the
1520 C<rectify> option to C<map> default to 0, not 1. This only affects
1521 matching where autoscaling is required (i.e. the array ref example
1522 above). By default, that example simply scales $x to the new size and
1523 maintains any rotation or skew in its scientific-to-pixel coordinate
1524 transform.
1525  
1526 =cut
1527  
1528 +==EOD_map_doc==
1529 PMCode => pp_line_numbers(__LINE__, <<'+==EOD_map_perlcode=='),
1530  
1531 sub PDL::match {
1532 # Set default for rectification to 0 for simple matching...
1533 10 ▶ push @_, {} if ref($_[-1]) ne 'HASH';
Subroutine match: called CC=3 SCAR=11.0
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[-1] ne "HASH" 1 9 10
1534 10 my @k = grep(m/^r(e(c(t)?)?)?/,sort keys %{$_[-1]});
1535 10 ▶ unless(@k) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@k) 10 0 10
1536 10 $_[-1]->{rectify} = 0;
1537 }
1538 10 t_identity()->map(@_);
1539 }
1540  
1541  
1542 *PDL::map = \&map;
1543 29 ▶sub map {
Subroutine map: called CC=92 SCAR=58.8
Pod documented
1544 29 ▶ my ($me, $in, $tmp, $opt) = @_;
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($me, "PDL") and UNIVERSAL::isa($in, "PDL::Transform") 19 10 29
Condition66%2/3
UNIVERSAL::isa($me, "PDL") and UNIVERSAL::isa($in, "PDL::Transform")
!ll&&!rl&&r
10019
MC/DC50%1/2
UNIVERSAL::isa($me, "PDL") and UNIVERSAL::isa($in, "PDL::Transform")
UNIVERSAL::isa($me, "PDL") UNIVERSAL::isa($in, "PDL::Transform")
Truth table66%2/3
A and B
A= UNIVERSAL::isa($me, "PDL")B= UNIVERSAL::isa($in, "PDL::Transform")
ABresult
0X0
100
111
1545 ($in, $me) = ($me, $in)
1546 29 ▶ if UNIVERSAL::isa($me,'PDL') && UNIVERSAL::isa($in,'PDL::Transform');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $in and UNIVERSAL::isa($in, "PDL") 0 29 29
Condition33%1/3
defined $in and UNIVERSAL::isa($in, "PDL")
!ll&&!rl&&r
0029
MC/DC0%0/2
defined $in and UNIVERSAL::isa($in, "PDL")
defined $in UNIVERSAL::isa($in, "PDL")
Truth table33%1/3
A and B
A= defined $inB= UNIVERSAL::isa($in, "PDL")
ABresult
0X0
100
111
1547 barf ("PDL::Transform::map: source is not defined or is not a PDL\n")
1548 29 ▶ unless(defined $in and UNIVERSAL::isa($in,'PDL'));
Branch: 1 branch
BranchTrueFalseTotal
unless $in->nelem 0 29 29
1549 barf ("PDL::Transform::map: source is empty\n")
1550 unless($in->nelem);
1551 # Check for options-but-no-template case
1552 ($opt, $tmp) = ($tmp, undef)
1553 29 ▶ if ref $tmp eq 'HASH' && !defined($opt)
Branch: 1 branch
BranchTrueFalseTotal
if ref $tmp eq "HASH" and not defined $opt and not defined $tmp->{"NAXIS"} 16 13 29
Condition83%5/6
ref $tmp eq "HASH" and not defined $opt and not defined $tmp->{"NAXIS"}
!ll&&!rl&&r
13016
ref $tmp eq "HASH" and not defined $opt
!ll&&!rl&&r
12116
MC/DC66%2/3
ref $tmp eq "HASH" and not defined $opt and not defined $tmp->{"NAXIS"}
ref $tmp eq "HASH" not defined $opt not defined $tmp->{"NAXIS"}
Truth table75%3/4
A and not(B) and not(C)
A= ref $tmp eq "HASH"B= not defined $optC= not defined $tmp->{"NAXIS"}
ABCresult
0XX0
10X0
1100
1111
1554 29 ▶ && !defined($tmp->{NAXIS}); # FITS headers all have NAXIS.
Branch: 1 branch
BranchTrueFalseTotal
if exists $opt->{"p"} 0 29 29
1555 29 ▶ croak("PDL::Transform::map: Option 'p' was ambiguous and has been removed. You probably want 'pix' or 'phot'.") if exists($opt->{'p'});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tmp 18 11 29
1556 $tmp = [$in->dims] unless defined $tmp; # no //= because of Devel::Cover bug
1557  
1558 29 # Generate an appropriate output ndarray for values to go in
1559 29 ▶ my ($out, @odims, $ohdr);
Branch: 3 branches
BranchTrueFalseTotal
if (UNIVERSAL::isa($tmp, 'PDL')) { } 5 24 29
elsif (ref $tmp eq 'HASH') { } 1 23 24
elsif (ref $tmp eq 'ARRAY') { } 23 0 23
1560 5 if (UNIVERSAL::isa($tmp,'PDL')) {
1561 5 ▶ @odims = $tmp->dims;
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $x = $tmp->gethdr)) 4 1 5
1562 if (defined(my $x = $tmp->gethdr)) { $ohdr = {%$x} }
1563 } elsif (ref $tmp eq 'HASH') {
1564 1 # (must be a fits header -- or would be filtered above)
1565 1 @odims = map $tmp->{"NAXIS$_"}, 1..$tmp->{NAXIS};
1566 $ohdr = {%$tmp}; # copy FITS header into output
1567 23 } elsif (ref $tmp eq 'ARRAY') {
1568 @odims = @$tmp;
1569 0 } else {
1570 barf("map: confused about dimensions of the output array...\n");
1571 }
1572 29 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @odims < scalar $in->dims) 0 29 29
1573 0 if (scalar(@odims) < scalar($in->dims)) {
1574 0 my @idims = $in->dims;
1575 push(@odims, splice(@idims,scalar(@odims)));
1576 }
1577 29  
1578 29 ▶ $out = PDL->new_from_specification($in->type,@odims);
Branch: 1 branch
BranchTrueFalseTotal
if defined $ohdr 5 24 29
1579 $out->sethdr($ohdr) if defined($ohdr);
1580  
1581 29 # set badflag on output all the time if possible, to account for boundary violations
1582 $out->badflag(1);
1583  
1584 ##############################
1585 ## Figure out the dimensionality of the
1586 29 ▶ ## transform itself (extra dimensions come along for the ride)
Condition80%4/5
$me->{'odim'} || $me->{'idim'} || 2
l!l
1514
$me->{"odim"} or $me->{"idim"}
l!l&&r!l&&!r
15014
MC/DC50%1/2
$me->{'odim'} || $me->{'idim'} || 2
$me->{"odim"} $me->{"idim"}
Truth table66%2/3
A or B
A= $me->{"odim"}B= $me->{"idim"}
ABresult
1X1
011
000
1587 29 my $nd = $me->{odim} || $me->{idim} || 2;
1588 29 my @dd = my @sizes = $out->dims;
1589 splice @dd,$nd; # Cut out dimensions after the end
1590  
1591 29 ▶ # Check that there are elements in the output fields...
Branch: 1 branch
BranchTrueFalseTotal
unless @dd 0 29 29
1592 barf "map: output has no dims!\n"
1593 29 unless(@dd);
1594 29 my $ddtotal = 1;
1595 29 ▶ $ddtotal *= $_ for @dd;
Branch: 1 branch
BranchTrueFalseTotal
unless $ddtotal 0 29 29
1596 barf "map: output has no elements (at least one dim is 0)!\n"
1597 unless($ddtotal);
1598  
1599 ##############################
1600 # If necessary, generate an appropriate FITS header for the output.
1601 29  
1602 my $nofits = _opt($opt, ['nf','nofits','NoFITS','pix','pixel','Pixel']);
1603  
1604 ##############################
1605 # Autoscale by transforming a subset of the input points' coordinates
1606 # to the output range, and pick a FITS header that fits the output
1607 # coordinates into the given template.
1608 #
1609 # Autoscaling always produces a simple, linear mapping in the FITS header.
1610 # We support more complex mappings (via t_fits) but only to match a pre-existing
1611 # FITS header (which doesn't use autoscaling).
1612 #
1613 # If the rectify option is set (the default) then the image is rectified
1614 # in scientific coordinates; if it is clear, then the existing matrix
1615 # is used, preserving any shear or rotation in the coordinate system.
1616 29 ▶ # Since we eschew CROTA whenever possible, the CDi_j formalism is used instead.
Branch: 1 branch
BranchTrueFalseTotal
defined $in->hdr->{'NAXIS'} ? : 11 18 29
1617 my $f_in = (defined($in->hdr->{NAXIS}) ? t_fits($in,{ignore_rgb=>1}) : t_identity());
1618 29 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $out->gethdr and $out->hdr->{"NAXIS"} or $nofits) 9 20 29
Condition100%6/6
defined $out->gethdr and $out->hdr->{"NAXIS"} or $nofits
l!l&&r!l&&!r
1199
defined $out->gethdr and $out->hdr->{"NAXIS"}
!ll&&!rl&&r
2441
MC/DC100%3/3
defined $out->gethdr and $out->hdr->{"NAXIS"} or $nofits
defined $out->gethdr $out->hdr->{"NAXIS"} $nofits
Truth table80%4/5
A and B or C
A= defined $out->gethdrB= $out->hdr->{"NAXIS"}C= $nofits
ABCresult
11X1
0X11
1011
0X00
1000
1619 9 ▶ unless((defined $out->gethdr && $out->hdr->{NAXIS}) or $nofits) {
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 9 9
1620 print "generating output FITS header..." if $PDL::Transform::debug;
1621 9 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if defined $in->hdr 9 0 9
1622 $out->sethdr($in->hdr_copy) # Copy extraneous fields...
1623 if defined $in->hdr;
1624 9  
1625 my $samp_ratio = 300;
1626 9  
1627 my $orange = _opt($opt, ['or','orange','output_range','Output_Range'],
1628 undef);
1629 9  
1630 my $omin;
1631 9 my $omax;
1632 my $osize;
1633 9  
1634  
1635 9 ▶ my $rectify = _opt($opt,['r','rect','rectify','Rectify'],1);
Branch: 1 branch
BranchTrueFalseTotal
if (defined $orange) { } 0 9 9
1636  
1637  
1638 if (defined $orange) {
1639 0 ▶ # orange always rectifies the coordinates -- the output scientific
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 0 0
1640 0 ▶ # coordinates *must* align with the axes, or orange wouldn't make
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($orange, "PDL") 0 0 0
1641 0 ▶ # sense.
Branch: 1 branch
BranchTrueFalseTotal
unless $orange->dim(1) == $nd and $orange->ndims == 2 0 0 0
Condition0%0/3
$orange->dim(1) == $nd and $orange->ndims == 2
!ll&&!rl&&r
000
MC/DC0%0/2
$orange->dim(1) == $nd and $orange->ndims == 2
$orange->dim(1) == $nd $orange->ndims == 2
Truth table0%0/3
A and B
A= $orange->dim(1) == $ndB= $orange->ndims == 2
ABresult
0X0
100
111
1642 print "using user's orange..." if $PDL::Transform::debug;
1643 $orange = pdl($orange) unless(UNIVERSAL::isa($orange,'PDL'));
1644 barf "map: orange must be 2xN for an N-D transform"
1645 0 unless ( (($orange->dim(1)) == $nd )
1646 0 && $orange->ndims == 2);
1647 0  
1648 $omin = $orange->slice("(0)");
1649 0 $omax = $orange->slice("(1)");
1650 $osize = $omax - $omin;
1651  
1652 $rectify = 1;
1653  
1654 } else {
1655  
1656 9 ▶ ##############################
Branch: 1 branch
BranchTrueFalseTotal
unless ($rectify or ref($f_in) =~ /Linear/i) 5 4 9
Condition100%3/3
$rectify or ref($f_in) =~ /Linear/i
l!l&&r!l&&!r
315
MC/DC100%2/2
$rectify or ref($f_in) =~ /Linear/i
$rectify ref($f_in) =~ /Linear/i
Truth table100%3/3
A or B
A= $rectifyB= ref($f_in) =~ /Linear/i
ABresult
1X1
011
000
1657 5 ▶ # Real autoscaling happens here.
Branch: 1 branch
BranchTrueFalseTotal
if ($f_in->{"name"} ne "identity") 0 5 5
1658 0  
1659 if (!$rectify and ref( $f_in ) !~ /Linear/i) {
1660 5 if ( $f_in->{name} ne 'identity' ) {
1661 print STDERR "Warning: map can't preserve nonlinear FITS distortions while autoscaling.\n";
1662 }
1663 $rectify=1;
1664 }
1665 9 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
$rectify ? : 8 1 9
$me->{'name'} eq 'identity' ? : 1 0 1
1666 my $f_tr = ( $rectify ?
1667 $me x $f_in :
1668 ( ($me->{name} eq 'identity') ? # Simple optimization for match()
1669 $me : # identity -- just matching
1670 !$f_in x $me x $f_in # common case
1671 9 )
1672 );
1673 9  
1674 my $samps = (pdl(($in->dims)[0..$nd-1]))->clip(0,$samp_ratio);
1675 9  
1676 9 my $coords = ndcoords(($samps + 1)->list);
1677  
1678 my $t;
1679 my $irange = _opt($opt, ['ir','irange','input_range','Input_Range'],
1680 undef);
1681 9 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (defined $irange) { } 0 9 9
1682 0 ▶ # If input range is defined, sample that quadrilateral -- else
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 0 0
1683 0 ▶ # sample the quad defined by the boundaries of the input image.
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($irange, "PDL") 0 0 0
1684 0 ▶ if (defined $irange) {
Branch: 1 branch
BranchTrueFalseTotal
unless $irange->dim(1) == $nd and $irange->ndims == 2 0 0 0
Condition0%0/3
$irange->dim(1) == $nd and $irange->ndims == 2
!ll&&!rl&&r
000
MC/DC0%0/2
$irange->dim(1) == $nd and $irange->ndims == 2
$irange->dim(1) == $nd $irange->ndims == 2
Truth table0%0/3
A and B
A= $irange->dim(1) == $ndB= $irange->ndims == 2
ABresult
0X0
100
111
1685 print "using user's irange..." if $PDL::Transform::debug;
1686 $irange = pdl($irange) unless(UNIVERSAL::isa($irange,'PDL'));
1687 barf "map: irange must be 2xN for an N-D transform"
1688 0 unless ( (($irange->dim(1)) == $nd )
1689 0 && $irange->ndims == 2);
1690 0  
1691 0 $coords *= ($irange->slice("(1)") - $irange->slice("(0)")) / $samps;
1692 $coords += $irange->slice("(0)");
1693 9 $coords -= 0.5; # offset to pixel corners...
1694 9 $t = $me;
1695 9 } else {
1696 $coords *= pdl(($in->dims)[0..$nd-1]) / $samps;
1697 9 $coords -= 0.5; # offset to pixel corners...
1698 $t = $f_tr;
1699 }
1700 9 my $ocoords = $t->apply($coords)->mv(0,-1)->clump($nd);
1701  
1702 # discard non-finite entries
1703 my $oc2 = $ocoords->range(
1704 which(
1705 $ocoords->
1706 transpose->
1707 sumover->
1708 isfinite
1709 )
1710 9 ->dummy(0,1)
1711 9 );
1712  
1713 9 $omin = $oc2->minimum;
1714 9 $omax = $oc2->maximum;
1715 9  
1716 $osize = $omax - $omin;
1717 my $tosize;
1718 9 ($tosize = $osize->where($osize == 0)) .= 1.0;
1719 }
1720 9  
1721 9 ▶ my ($scale) = $osize / pdl(($out->dims)[0..$nd-1]);
Branch: 1 branch
BranchTrueFalseTotal
if ($justify) 0 9 9
1722 0  
1723 0 my $justify = _opt($opt,['j','J','just','justify','Justify'],0);
1724 0 if ($justify) {
1725 $scale->slice("0") *= $justify;
1726 $scale .= $scale->max;
1727 9 ▶ $scale->slice("0") /= $justify;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 9 9
1728 9 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if ($rectify) { } 8 1 9
1729  
1730 print "done with autoscale. Making fits header....\n" if $PDL::Transform::debug;
1731 8 ▶ if ( $rectify ) {
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 8 8
1732 8 # Rectified header generation -- make a simple coordinate header with no
1733 16 # rotation or skew.
1734 16 print "rectify\n" if $PDL::Transform::debug;
1735 16 for my $d(1..$nd) {
1736 16 $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2 ;
1737 $out->hdr->{"CDELT$d"} = $scale->at($d-1);
1738 $out->hdr->{"CRVAL$d"} = ( $omin->at($d-1) + $omax->at($d-1) ) /2 ;
1739 $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
1740 16 ▶ $out->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'otype'}) ? : 16 0 16
ref $me->{'otype'} ne 'ARRAY' ? : 0 0 0
Condition80%4/5
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $in->hdr->{"CTYPE$d"} || ''
l!l
214
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) or $in->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
0214
MC/DC50%1/2
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $in->hdr->{"CTYPE$d"} || ''
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) $in->hdr->{"CTYPE$d"}
Truth table66%2/3
not(A) or B
A= !defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1])B= $in->hdr->{"CTYPE$d"}
ABresult
1X1
011
000
1741 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
1742 $me->{otype}[$d-1])
1743 || $in->hdr->{"CTYPE$d"}
1744 || "");
1745 $out->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
1746 16 ▶ ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'ounit'}) ? : 16 0 16
ref $me->{'ounit'} ne 'ARRAY' ? : 0 0 0
Condition75%6/8
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $in->hdr->{"CUNIT$d"} || $in->hdr->{"CTYPE$d"} || ''
l!l
214
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $in->hdr->{"CUNIT$d"} or $in->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
2014
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $in->hdr->{"CUNIT$d"}
l!l&&r!l&&!r
0214
MC/DC33%1/3
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $in->hdr->{"CUNIT$d"} || $in->hdr->{"CTYPE$d"} || ''
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) $in->hdr->{"CUNIT$d"} $in->hdr->{"CTYPE$d"}
Truth table50%2/4
not(A) or B or C
A= !defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1])B= $in->hdr->{"CUNIT$d"}C= $in->hdr->{"CTYPE$d"}
ABCresult
1XX1
01X1
0011
0000
1747 $me->{ounit}[$d-1])
1748 || $in->hdr->{"CUNIT$d"}
1749 8 || $in->hdr->{"CTYPE$d"}
1750 || "");
1751 8 }
1752 8 $out->hdr->{"NAXIS"} = $nd;
1753  
1754 $out->hdr->{"SIMPLE"} = 'T';
1755 $out->hdr->{"HISTORY"} .= "Header written by PDL::Transform::Cartography::map";
1756 8  
1757 8 ### Eliminate fancy newfangled output header pointing tags if they exist
1758 ### These are the CROTA<n>, PCi_j, and CDi_j.
1759 delete @{$out->hdr}{
1760 grep /(^CROTA\d*$)|(^(CD|PC)\d+_\d+[A-Z]?$)/, keys %{$out->hdr}
1761 };
1762 } else {
1763 # Non-rectified output -- generate a CDi_j matrix instead of the simple formalism.
1764 # We have to deal with a linear transformation: we've got: (scaling) x !input x (t x input),
1765 # where input is a linear transformation with offset and scaling is a simple scaling. We have
1766 # the scaling parameters and the matrix for !input -- we have only to merge them and then we
1767 # can write out the FITS header in CDi_j form.
1768 1 ▶ print "non-rectify\n" if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 1 1
1769 1 my $midpoint_val = (pdl(($out->dims)[0..$nd-1])/2 * $scale)->apply( $f_in );
1770 1 ▶ print "midpoint_val is $midpoint_val\n" if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 1 1
1771 # linear transformation
1772 1 ▶ unless(ref($f_in) =~ m/Linear/) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref($f_in) =~ /Linear/) 0 1 1
1773 0 croak("Whups -- got a nonlinear t_fits transformation. Can't deal with it.");
1774 }
1775  
1776 1 my $inv_sc_mat = PDL::MatrixOps::stretcher($scale);
1777 1 my $mat = $f_in->{params}->{matrix} x $inv_sc_mat;
1778 1 ▶ print "scale is $scale; mat is $mat\n" if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 1 1
1779  
1780 1 ▶ print "looping dims 1..$nd: " if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 1 1
1781 1 for my $d(1..$nd) {
1782 2 ▶ print "$d..." if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 2 2
1783 2 $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2;
1784 2 $out->hdr->{"CRVAL$d"} = $midpoint_val->at($d-1);
1785 2 $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
1786 $out->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
1787 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
1788 $me->{otype}[$d-1])
1789 2 ▶ || $in->hdr->{"CTYPE$d"}
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'otype'}) ? : 2 0 2
ref $me->{'otype'} ne 'ARRAY' ? : 0 0 0
Condition40%2/5
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $in->hdr->{"CTYPE$d"} || ''
l!l
20
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) or $in->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
020
MC/DC0%0/2
(!defined($me->{'otype'}) ? '' : (ref $me->{'otype'} ne 'ARRAY' ? $me->{'otype'} : $me->{'otype'}[$d - 1])) || $in->hdr->{"CTYPE$d"} || ''
!defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1]) $in->hdr->{"CTYPE$d"}
Truth table33%1/3
not(A) or B
A= !defined($me->{"otype"}) ? "" : (ref $me->{"otype"} ne "ARRAY" ? $me->{"otype"} : $me->{"otype"}[$d - 1])B= $in->hdr->{"CTYPE$d"}
ABresult
1X1
011
000
1790 || "");
1791 $out->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
1792 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
1793 $me->{ounit}[$d-1])
1794 || $in->hdr->{"CUNIT$d"}
1795 2 ▶ || $in->hdr->{"CTYPE$d"}
Branch: 2 branches
BranchTrueFalseTotal
!defined($me->{'ounit'}) ? : 2 0 2
ref $me->{'ounit'} ne 'ARRAY' ? : 0 0 0
Condition37%3/8
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $in->hdr->{"CUNIT$d"} || $in->hdr->{"CTYPE$d"} || ''
l!l
20
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $in->hdr->{"CUNIT$d"} or $in->hdr->{"CTYPE$d"}
l!l&&r!l&&!r
200
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) or $in->hdr->{"CUNIT$d"}
l!l&&r!l&&!r
020
MC/DC0%0/3
(!defined($me->{'ounit'}) ? '' : (ref $me->{'ounit'} ne 'ARRAY' ? $me->{'ounit'} : $me->{'ounit'}[$d - 1])) || $in->hdr->{"CUNIT$d"} || $in->hdr->{"CTYPE$d"} || ''
!defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1]) $in->hdr->{"CUNIT$d"} $in->hdr->{"CTYPE$d"}
Truth table25%1/4
not(A) or B or C
A= !defined($me->{"ounit"}) ? "" : (ref $me->{"ounit"} ne "ARRAY" ? $me->{"ounit"} : $me->{"ounit"}[$d - 1])B= $in->hdr->{"CUNIT$d"}C= $in->hdr->{"CTYPE$d"}
ABCresult
1XX1
01X1
0011
0000
1796 || "");
1797 2 for my $e(1..$nd) {
1798 4 $out->hdr->{"CD${d}_${e}"} = $mat->at($d-1,$e-1);
1799 4 ▶ print "setting CD${d}_${e} to ".$mat->at($d-1,$e-1)."\n" if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 4 4
1800 }
1801 }
1802  
1803 ## Eliminate competing header pointing tags if they exist
1804 1 delete @{$out->hdr}{
1805 1 grep /(^CROTA\d*$)|(^(PC)\d+_\d+[A-Z]?$)|(CDELT\d*$)/, keys %{$out->hdr}
1806 };
1807 }
1808 }
1809  
1810 29 $out->hdrcpy(1);
1811  
1812 ##############################
1813 # Sandwich the transform between the input and output plane FITS headers.
1814 29 ▶ unless($nofits) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($nofits) 10 19 29
1815 10 $me = !t_fits($out,{ignore_rgb=>1}) x $me x $f_in;
1816 }
1817  
1818 ##############################
1819 ## Figure out the interpND options
1820 29 my $method = _opt($opt,['m','method','Method'],undef);
1821 29 my $bound = _opt($opt,['b','bound','boundary','Boundary'],'t');
1822  
1823 ##############################
1824 ## Rubber meets the road: calculate the inverse transformed points.
1825 29 my $ndc = PDL::Basic::ndcoords(@dd);
1826 29 my $idx = $me->invert($ndc->double);
1827  
1828 29 ▶ barf "map: Transformation had no inverse\n" unless defined($idx);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $idx 0 29 29
1829  
1830 ##############################
1831 ## Integrate ? (Jacobian, Gaussian, Hanning)
1832 29 ▶ my $integrate = ($method =~ m/^[jghJGH]/) if defined($method);
Branch: 1 branch
BranchTrueFalseTotal
if defined $method 24 5 29
1833  
1834 ##############################
1835 ## Sampling code:
1836 ## just transform and interpolate.
1837 ## ( Kind of an anticlimax after all that, eh? )
1838 29 ▶ if (!$integrate) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($integrate) 17 12 29
1839 17 my $x = $in->interpND($idx,{method=>$method, bound=>$bound});
1840 17 $out->slice(":") .= $x; # trivial slice prevents header overwrite...
1841 17 return $out;
1842 }
1843  
1844 ##############################
1845 ## Anti-aliasing code:
1846 ## Condition the input and call the pixelwise C interpolator.
1847 ##
1848  
1849 12 ▶ barf "PDL::Transform::map: Too many dims in transformation\n"
Branch: 1 branch
BranchTrueFalseTotal
if $in->ndims < $idx->ndims - 1 0 12 12
1850 if $in->ndims < $idx->ndims-1;
1851  
1852 ####################
1853 ## Condition the broadcasting -- pixelwise interpolator only broadcasts
1854 ## in 1 dimension, so squish all broadcast dimensions into 1, if necessary
1855 12 my @iddims = $idx->dims;
1856 12 ▶ my $in2 = $in->ndims == $#iddims
Branch: 1 branch
BranchTrueFalseTotal
$in->ndims == $#iddims ? : 12 0 12
1857 ? $in->dummy(-1,1)
1858 : $in->reorder($nd..$in->ndims-1, 0..$nd-1)
1859 ->clump($in->ndims - $nd)
1860 ->mv(0,-1);
1861  
1862 ####################
1863 # Allocate the output array
1864 12 my $o2 = PDL->new_from_specification($in2->type,
1865 @iddims[1..$#iddims],
1866 $in2->dim(-1)
1867 );
1868  
1869 ####################
1870 # Pack boundary string if necessary
1871 12 ▶ if (defined $bound) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $bound) 12 0 12
1872 12 ▶ if (ref $bound eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $bound eq 'ARRAY') { } 0 12 12
elsif (not $bound =~ /^[0123ftepx]+$/ and $bound =~ /^([0123ftepx])/i) { } 0 23 23
1873 0 my ($s,$el);
1874 0 foreach $el(@$bound) {
1875 0 ▶ barf "Illegal boundary value '$el' in range"
Branch: 1 branch
BranchTrueFalseTotal
unless $el =~ /^([0123fFtTeEpPmM])/ 0 0 0
1876 unless( $el =~ m/^([0123fFtTeEpPmM])/ );
1877 0 $s .= $1;
1878 }
1879 0 $bound = $s;
1880 ▶ } elsif ($bound !~ m/^[0123ftepx]+$/ && $bound =~ m/^([0123ftepx])/i) {
Condition66%2/3
not $bound =~ /^[0123ftepx]+$/ and $bound =~ /^([0123ftepx])/i
!ll&&!rl&&r
1110
MC/DC0%0/2
not $bound =~ /^[0123ftepx]+$/ and $bound =~ /^([0123ftepx])/i
not $bound =~ /^[0123ftepx]+$/ $bound =~ /^([0123ftepx])/i
Truth table66%2/3
not(A) and B
A= not $bound =~ /^[0123ftepx]+$/B= $bound =~ /^([0123ftepx])/i
ABresult
0X0
100
111
1881 0 $bound = $1;
1882 }
1883 }
1884  
1885 ####################
1886 # Get the blur and minimum-sv values
1887 12 my $blur = _opt($opt,['blur','Blur'],1.0);
1888 12 my $svmin = _opt($opt,['sv','SV'],1.0);
1889 12 my $big = _opt($opt,['big','Big'],1.0);
1890 12 my $flux = _opt($opt,['phot','photometry'],0);
1891 12 my @idims = $in->dims;
1892  
1893 12 $flux = ($flux =~ m/^[1fF]/);
1894 12 $big = $big * max(pdl(@idims[0..$nd]));
1895 12 ▶ $blur = $blur->at(0) if ref $blur;
Branch: 1 branch
BranchTrueFalseTotal
if ref $blur 0 12 12
1896 12 ▶ $svmin = $svmin->at(0) if ref $svmin;
Branch: 1 branch
BranchTrueFalseTotal
if ref $svmin 0 12 12
1897  
1898 12 ▶ my $bv = $in->badflag ? $in->badvalue->sclr : 0;
Branch: 1 branch
BranchTrueFalseTotal
$in->badflag ? : 1 11 12
1899  
1900 ### The first argument is a dummy to set $GENERIC.
1901 12 ▶ $idx = double($idx) unless($idx->type == double);
Branch: 1 branch
BranchTrueFalseTotal
unless $idx->type == double() 0 12 12
1902 12 ▶ print "Calling _map_int...\n" if $PDL::Transform::debug;
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 12 12
1903 12 &PDL::_map_int( $in2->flat->index(0),
1904 $in2, $o2, $idx,
1905 $bound, $method, $big, $blur, $svmin, $flux, $bv);
1906  
1907 12 my @rdims = (@iddims[1..$#iddims], @idims[$#iddims..$#idims]);
1908 {
1909 12 $out->slice(":") .= $o2->reshape(@rdims);
1910 }
1911 12 return $out;
1912 }
1913  
1914 +==EOD_map_perlcode==
1915  
1916 );
1917  
1918  
1919 pp_add_exported('unmap');
1920 pp_addpm(<<'+======EOD_unmap======');
1921  
1922 ######################################################################
1923  
1924 =head2 unmap
1925  
1926 =for sig
1927  
1928 Signature: (data(); PDL::Transform a; template(); \%opt)
1929  
1930 =for usage
1931  
1932 $out_image = $in_image->unmap($t,[<options>],[<template>]);
1933 $out_image = $t->unmap($in_image,[<options>],[<template>]);
1934  
1935 =for ref
1936  
1937 Map an image or N-D dataset using the inverse as a coordinate transform.
1938  
1939 This convenience function just inverts $t and calls L</map> on
1940 the inverse; everything works the same otherwise. For convenience, it
1941 is both a PDL method and a PDL::Transform method.
1942  
1943 =cut
1944  
1945 *PDL::unmap = \&unmap;
1946 0 ▶sub unmap {
Subroutine unmap: not called CC=3 SCAR=24.8
Pod documented
1947 0 my($me) = shift;
1948 0 my($data) = shift;
1949 my(@params) = @_;
1950 0 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($data, "PDL::Transform") and UNIVERSAL::isa($me, "PDL")) 0 0 0
Condition0%0/3
UNIVERSAL::isa($data, "PDL::Transform") and UNIVERSAL::isa($me, "PDL")
!ll&&!rl&&r
000
MC/DC0%0/2
UNIVERSAL::isa($data, "PDL::Transform") and UNIVERSAL::isa($me, "PDL")
UNIVERSAL::isa($data, "PDL::Transform") UNIVERSAL::isa($me, "PDL")
Truth table0%0/3
A and B
A= UNIVERSAL::isa($data, "PDL::Transform")B= UNIVERSAL::isa($me, "PDL")
ABresult
0X0
100
111
1951 0 if (UNIVERSAL::isa($data,'PDL::Transform') && UNIVERSAL::isa($me,'PDL')) {
1952 0 my $x = $data;
1953 0 $data = $me;
1954 $me = $x;
1955 }
1956 0  
1957 return $me->inverse->map($data,@params);
1958 }
1959  
1960 +======EOD_unmap======
1961  
1962 pp_add_exported('t_inverse');
1963 pp_addpm(<<'+======EOD_t_inverse======');
1964  
1965 =head2 t_inverse
1966  
1967 =for usage
1968  
1969 $t2 = t_inverse($t);
1970 $t2 = $t->inverse;
1971 $t2 = $t ** -1;
1972 $t2 = !$t;
1973  
1974 =for ref
1975  
1976 Return the inverse of a PDL::Transform. This just reverses the
1977 func/inv, idim/odim, itype/otype, and iunit/ounit pairs. Note that
1978 sometimes you end up with a transform that cannot be applied or
1979 mapped, because either the mathematical inverse doesn't exist or the
1980 inverse func isn't implemented.
1981  
1982 You can invert a transform by raising it to a negative power, or by
1983 negating it with '!'.
1984  
1985 The inverse transform remains connected to the main transform because
1986 they both point to the original parameters hash. That turns out to be
1987 useful.
1988  
1989 =cut
1990  
1991 *t_inverse = \&inverse;
1992  
1993 20 ▶sub inverse {
Subroutine inverse: called CC=2 SCAR=7.1
Pod undocumented
1994 my($me) = shift;
1995 20 ▶ barf("PDL::Transform::inverse: got a transform with no inverse")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"inv"} 0 20 20
1996 unless defined $me->{inv};
1997 bless {
1998 %$me, # force explicit copy of top-level
1999 inv => $me->{func},
2000 func => $me->{inv},
2001 (map +("o$_"=>$me->{"i$_"}, "i$_"=>$me->{"o$_"}), qw(dim type unit)),
2002 20 name => "(inverse ".$me->{name}.")",
2003 is_inverse => !($me->{is_inverse}),
2004 }, ref $me;
2005 }
2006  
2007 +======EOD_t_inverse======
2008  
2009 pp_add_exported('t_compose');
2010 pp_addpm(<<'+======EOD_t_compose======');
2011  
2012 =head2 t_compose
2013  
2014 =for usage
2015  
2016 $f2 = t_compose($f, $g,[...]);
2017 $f2 = $f->compose($g[,$h,$i,...]);
2018 $f2 = $f x $g x ...;
2019  
2020 =for ref
2021  
2022 Function composition: f(g(x)), f(g(h(x))), ...
2023  
2024 You can also compose transforms using the overloaded matrix-multiplication
2025 (nee repeat) operator 'x'.
2026  
2027 This is accomplished by inserting a splicing code ref into the C<func>
2028 and C<inv> slots. It combines multiple compositions into a single
2029 list of transforms to be executed in order, from last to first (in
2030 keeping with standard mathematical notation). If one of the functions is
2031 itself a composition, it is interpolated into the list rather than left
2032 separate. Ultimately, linear transformations may also be combined within
2033 the list.
2034  
2035 No checking is done that the itype/otype and iunit/ounit fields are
2036 compatible -- that may happen later, or you can implement it yourself
2037 if you like.
2038  
2039 =cut
2040  
2041 @PDL::Transform::Composition::ISA = ('PDL::Transform');
2042 sub PDL::Transform::Composition::stringify {
2043 0 ▶ package PDL::Transform::Composition;
Subroutine stringify: not called CC=1 SCAR=6.9
2044 shift->SUPER::stringify;
2045 }
2046  
2047 *t_compose = \&compose;
2048 33 ▶sub compose {
Subroutine compose: called CC=9 SCAR=22.7
Pod undocumented
2049 33 local($_);
2050 33 my(@funcs) = @_;
2051 my($me) = PDL::Transform->new;
2052 33 ▶ # No inputs case: return the identity function
Branch: 1 branch
BranchTrueFalseTotal
unless @funcs 0 33 33
2053 33 return $me if !@funcs;
2054 33 $me->{name} = "";
2055 33 my @clist;
2056 69 ▶ for my $f (@funcs) {
Branch: 1 branch
BranchTrueFalseTotal
if $f->{"idim"} > $me->{"idim"} 27 42 69
2057 69 ▶ $me->{idim} = $f->{idim} if $f->{idim} > $me->{idim};
Branch: 1 branch
BranchTrueFalseTotal
if $f->{"odim"} > $me->{"odim"} 27 42 69
2058 69 ▶ $me->{odim} = $f->{odim} if $f->{odim} > $me->{odim};
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($f, 'PDL::Transform::Composition')) { } 10 59 69
2059 10 ▶ if (UNIVERSAL::isa($f,"PDL::Transform::Composition")) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->{'is_inverse'}) { } 0 10 10
2060 0 if ($f->{is_inverse}) {
2061 0 for (reverse(@{$f->{params}->{clist}})) {
2062 0 push(@clist,$_->inverse);
2063 $me->{name} .= " o inverse ( ".$_->{name}." )";
2064 }
2065 10 } else {
2066 20 for (@{$f->{params}->{clist}}) {
2067 20 push(@clist,$_);
2068 $me->{name} .= " o ".$_->{name};
2069 }
2070 }
2071 59 } else { # Not a composition -- just push the transform onto the list.
2072 59 push(@clist,$f);
2073 $me->{name} .= " o ".$f->{name};
2074 }
2075 33 }
2076 33 $me->{name}=~ s/^ o //; # Get rid of leading composition mark
2077 33 $me->{otype} = $funcs[0]->{otype};
2078 33 $me->{ounit} = $funcs[0]->{ounit};
2079 33 $me->{itype} = $funcs[-1]->{itype};
2080 33 $me->{iunit} = $funcs[-1]->{iunit};
2081 $me->{params}->{clist} = \@clist;
2082 19 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=5 SCAR=17.0
2083 19 my ($data,$p) = @_;
2084 19 my ($ip) = $data->is_inplace;
2085 for my $t ( reverse @{$p->{clist}} ) {
2086 48 ▶ croak("Error: tried to apply a PDL::Transform with no function inside a composition!\n offending transform: $t\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t->{"func"} and ref $t->{"func"} eq "CODE" 0 48 48
Condition33%1/3
defined $t->{"func"} and ref $t->{"func"} eq "CODE"
!ll&&!rl&&r
0048
MC/DC0%0/2
defined $t->{"func"} and ref $t->{"func"} eq "CODE"
defined $t->{"func"} ref $t->{"func"} eq "CODE"
Truth table33%1/3
A and B
A= defined $t->{"func"}B= ref $t->{"func"} eq "CODE"
ABresult
0X0
100
111
2087 48 ▶ unless(defined($t->{func}) and ref($t->{func}) eq 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
$ip ? : 0 48 48
2088 $data = $t->{func}($ip ? $data->inplace : $data, $t->{params});
2089 19 }
2090 19 $data->is_inplace(0); # clear inplace flag (avoid core bug with inplace)
2091 33 $data;
2092 };
2093 12 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=5 SCAR=17.0
2094 12 my ($data,$p) = @_;
2095 12 my $ip = $data->is_inplace;
2096 for my $t ( @{$p->{clist}} ) {
2097 35 ▶ croak("Error: tried to invert a non-invertible PDL::Transform inside a composition!\n offending transform: $t\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t->{"inv"} and ref $t->{"inv"} eq "CODE" 0 35 35
Condition33%1/3
defined $t->{"inv"} and ref $t->{"inv"} eq "CODE"
!ll&&!rl&&r
0035
MC/DC0%0/2
defined $t->{"inv"} and ref $t->{"inv"} eq "CODE"
defined $t->{"inv"} ref $t->{"inv"} eq "CODE"
Truth table33%1/3
A and B
A= defined $t->{"inv"}B= ref $t->{"inv"} eq "CODE"
ABresult
0X0
100
111
2098 35 ▶ unless(defined($t->{inv}) and ref($t->{inv}) eq 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
$ip ? : 0 35 35
2099 $data = &{$t->{inv}}($ip ? $data->inplace : $data, $t->{params});
2100 12 }
2101 33 $data;
2102 33 };
2103 return bless($me,'PDL::Transform::Composition');
2104 }
2105 +======EOD_t_compose======
2106  
2107  
2108 pp_add_exported('t_wrap');
2109 pp_addpm(<<'+======EOD_t_wrap======');
2110  
2111 =head2 t_wrap
2112  
2113 =for usage
2114  
2115 $g1fg = $f->wrap($g);
2116 $g1fg = t_wrap($f,$g);
2117  
2118 =for ref
2119  
2120 Shift a transform into a different space by 'wrapping' it with a second.
2121  
2122 This is just a convenience function for two
2123 L</t_compose> calls. C<< $x->wrap($y) >> is the same as
2124 C<(!$y) x $x x $y>: the resulting transform first hits the data with
2125 $y, then with $x, then with the inverse of $y.
2126  
2127 For example, to shift the origin of rotation, do this:
2128  
2129 $im = rfits('m51.fits');
2130 $tf = t_fits($im);
2131 $tr = t_linear({rot=>30});
2132 $im1 = $tr->map($tr); # Rotate around pixel origin
2133 $im2 = $tr->map($tr->wrap($tf)); # Rotate round FITS scientific origin
2134  
2135 =cut
2136  
2137 *t_wrap = \&wrap;
2138  
2139 1 ▶sub wrap {
Subroutine wrap: called CC=1 SCAR=0.0
Pod undocumented
2140 1 my($f) = shift;
2141 my($g) = shift;
2142 1  
2143 return $g->inverse->compose($f,$g);
2144 }
2145  
2146  
2147  
2148 ######################################################################
2149 29 ▶ 
Subroutine _compose_op: called CC=2 SCAR=7.2
2150 29 ▶# Composition operator -- handles 'x'.
Branch: 1 branch
BranchTrueFalseTotal
$c ? : 0 29 29
2151 sub _compose_op {
2152 my($x,$y,$c) = @_;
2153 $c ? compose($y,$x) : compose($x,$y);
2154 }
2155  
2156 0 ▶# Raise-to-power operator -- handles '**'.
Subroutine _pow_op: not called CC=7 SCAR=40.3
2157  
2158 0 ▶sub _pow_op {
Branch: 1 branch
BranchTrueFalseTotal
if $c or UNIVERSAL::isa($y, "PDL::Transform") 0 0 0
Condition0%0/3
$c or UNIVERSAL::isa($y, "PDL::Transform")
l!l&&r!l&&!r
000
MC/DC0%0/2
$c or UNIVERSAL::isa($y, "PDL::Transform")
$c UNIVERSAL::isa($y, "PDL::Transform")
Truth table0%0/3
A or B
A= $cB= UNIVERSAL::isa($y, "PDL::Transform")
ABresult
1X1
011
000
2159 my($x,$y,$c) = @_;
2160  
2161 0 ▶ barf("Can't raise anything to the power of a transform")
Branch: 1 branch
BranchTrueFalseTotal
if $y < 0 0 0 0
2162 if $c || UNIVERSAL::isa($y,'PDL::Transform');
2163  
2164 0 ▶ $x = $x->inverse
Branch: 1 branch
BranchTrueFalseTotal
if abs $y == 1 0 0 0
2165 0 ▶ if $y < 0;
Branch: 1 branch
BranchTrueFalseTotal
if abs $y == 0 0 0 0
2166  
2167 0 return $x if abs($y) == 1;
2168 0 return PDL::Transform->new if abs($y) == 0;
2169 0  
2170 my(@l);
2171 for my $i(1..abs($y)) {
2172 0 push(@l,$x);
2173 }
2174  
2175 t_compose(@l);
2176 }
2177  
2178 +======EOD_t_wrap======
2179  
2180  
2181 pp_add_exported('t_identity');
2182 pp_addpm(<<'+======EOD_t_identity======');
2183  
2184 =head2 t_identity
2185  
2186 =for usage
2187  
2188 my $xform = t_identity
2189 my $xform = PDL::Transform->new;
2190  
2191 =for ref
2192  
2193 Generic constructor generates the identity transform.
2194  
2195 This constructor really is trivial -- it is mainly used by the other transform
2196 constructors. It takes no parameters and returns the identity transform.
2197  
2198 =cut
2199 36 ▶ 
Subroutine _identity: called CC=1 SCAR=0.0
2200 32 ▶sub _identity { return shift; }
Subroutine t_identity: called CC=1 SCAR=0.0
Pod documented
2201 sub t_identity { new PDL::Transform(@_) };
2202  
2203 141 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
2204 141 my($class) = shift;
2205 my $me = {name=>'identity',
2206 idim => 0,
2207 odim => 0,
2208 func=>\&PDL::Transform::_identity,
2209 inv=>\&PDL::Transform::_identity,
2210 params=>{}
2211 };
2212 141  
2213 return bless $me,$class;
2214 }
2215  
2216 +======EOD_t_identity======
2217  
2218  
2219 pp_add_exported('t_lookup');
2220 pp_addpm(<<'+======EOD_t_lookup======');
2221  
2222 =head2 t_lookup
2223  
2224 =for usage
2225  
2226 $f = t_lookup($lookup, {<options>});
2227  
2228 =for ref
2229  
2230 Transform by lookup into an explicit table.
2231  
2232 You specify an N+1-D PDL that is interpreted as an N-D lookup table of
2233 column vectors (vector index comes last). The last dimension has
2234 order equal to the output dimensionality of the transform.
2235  
2236 For added flexibility in data space, you can specify pre-lookup linear
2237 scaling and offset of the data. Of course you can specify the
2238 interpolation method to be used. The linear scaling stuff is a little
2239 primitive; if you want more, try composing the linear transform with
2240 this one.
2241  
2242 The prescribed values in the lookup table are treated as
2243 pixel-centered: that is, if your input array has N elements per row
2244 then valid data exist between the locations (-0.5) and (N-0.5) in
2245 lookup pixel space, because the pixels (which are numbered from 0 to
2246 N-1) are centered on their locations.
2247  
2248 Lookup is done using L<interpND|PDL::Primitive/interpND>, so the boundary conditions
2249 and broadcasting behaviour follow from that.
2250  
2251 The indexed-over dimensions come first in the table, followed by a
2252 single dimension containing the column vector to be output for each
2253 set of other dimensions -- ie to output 2-vectors from 2 input
2254 parameters, each of which can range from 0 to 49, you want an index
2255 that has dimension list (50,50,2). For the identity lookup table
2256 you could use C<cat(xvals(50,50),yvals(50,50))>.
2257  
2258 If you want to output a single value per input vector, you still need
2259 that last index broadcasting dimension -- if necessary, use C<dummy(-1,1)>.
2260  
2261 The lookup index scaling is: out = lookup[ (scale * data) + offset ].
2262  
2263 A simplistic table inversion routine is included. This means that
2264 you can (for example) use the C<map> method with C<t_lookup> transformations.
2265 But the table inversion is exceedingly slow, and not practical for tables
2266 larger than about 100x100. The inversion table is calculated in its
2267 entirety the first time it is needed, and then cached until the object is
2268 destroyed.
2269  
2270 Options are listed below; there are several synonyms for each.
2271  
2272 =over 3
2273  
2274 =item s, scale, Scale
2275  
2276 (default 1.0) Specifies the linear amount of scaling to be done before
2277 lookup. You can feed in a scalar or an N-vector; other values may cause
2278 trouble. If you want to save space in your table, then specify smaller
2279 scale numbers.
2280  
2281 =item o, offset, Offset
2282  
2283 (default 0.0) Specifies the linear amount of offset before lookup.
2284 This is only a scalar, because it is intended to let you switch to
2285 corner-centered coordinates if you want to (just feed in o=-0.25).
2286  
2287 =item b, bound, boundary, Boundary
2288  
2289 Boundary condition to be fed to L<interpND|PDL::Primitive/interpND>
2290  
2291 =item m, method, Method
2292  
2293 Interpolation method to be fed to L<interpND|PDL::Primitive/interpND>
2294  
2295 =back
2296  
2297 =head3 EXAMPLE
2298  
2299 =for example
2300  
2301 # To scale logarithmically the Y axis of m51, try:
2302 $x = float rfits('m51.fits');
2303 $lookup = xvals(128,128) -> cat( 10**(yvals(128,128)/50) * 256/10**2.55 );
2304 $t = t_lookup($lookup);
2305 $y = $t->map($x);
2306 # To do the same thing but with a smaller lookup table, try:
2307 $lookup = 16 * xvals(17,17)->cat(10**(yvals(17,17)/(100/16)) * 16/10**2.55);
2308 $t = t_lookup($lookup,{scale=>1/16.0});
2309 $y = $t->map($x);
2310  
2311 (Notice that, although the lookup table coordinates are is divided by 16,
2312 it is a 17x17 -- so linear interpolation works right to the edge of the original
2313 domain.)
2314  
2315 =head3 NOTES
2316  
2317 Inverses are "only weakly supported" -- the best way to do it might be by
2318 judicious use of map() on the forward transformation.
2319  
2320 the type/unit fields are ignored.
2321  
2322 =cut
2323  
2324 1 ▶sub t_lookup {
Subroutine t_lookup: called CC=4 SCAR=14.8
Pod documented
2325 1 my($class) = 'PDL::Transform';
2326 1 my($source)= shift;
2327 my($o) = shift;
2328 1 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $o and ref $source eq "HASH") 0 1 1
Condition33%1/3
not defined $o and ref $source eq "HASH"
!ll&&!rl&&r
100
MC/DC0%0/2
not defined $o and ref $source eq "HASH"
not defined $o ref $source eq "HASH"
Truth table33%1/3
not(A) and B
A= not defined $oB= ref $source eq "HASH"
ABresult
0X0
100
111
2329 0 if (!defined($o) && ((ref $source) eq 'HASH')) {
2330 0 Carp::cluck("lookup transform called as sub not method; using 'PDL::Transform' as class...\n");
2331 0 $o = $source;
2332 0 $source = $class;
2333 $class = "PDL::Transform";
2334 }
2335 1 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
unless ref $o eq "HASH" 0 1 1
2336 $o = {} unless(ref $o eq 'HASH');
2337 1  
2338 my($me) = $class->new;
2339 1  
2340 1 my($bound) = _opt($o,['b','bound','boundary','Boundary']);
2341 my($method)= _opt($o,['m','meth','method','Method']);
2342 1  
2343 1 $me->{idim} = $source->ndims - 1;
2344 $me->{odim} = $source->dim($source->ndims-1);
2345  
2346 1 $me->{params} = {
2347 table => $source,
2348 scale => _opt($o,['s','scale','Scale'],1.0),
2349 offset => _opt($o,['o','off','offset','Offset'],0.0),
2350 interpND_opt => {
2351 method => $method,
2352 bound => $bound,
2353 bad => _opt($o,['bad'],0)
2354 }
2355 };
2356  
2357 2 ▶ 
Subroutine __ANON__: called CC=5 SCAR=18.1
2358 my $lookup_func = sub {
2359 2 ▶ my($data,$p,$table,$scale,$offset) = @_;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data and UNIVERSAL::isa($data, "PDL") 0 2 2
Condition33%1/3
ref $data and UNIVERSAL::isa($data, "PDL")
!ll&&!rl&&r
002
MC/DC0%0/2
ref $data and UNIVERSAL::isa($data, "PDL")
ref $data UNIVERSAL::isa($data, "PDL")
Truth table33%1/3
A and B
A= ref $dataB= UNIVERSAL::isa($data, "PDL")
ABresult
0X0
100
111
2360  
2361 2 $data = pdl($data)
2362 unless ((ref $data) && (UNIVERSAL::isa($data,'PDL')));
2363 2 ▶ $main::foo = $data;
Branch: 1 branch
BranchTrueFalseTotal
if ($data->dim(0) > $me->{"idim"}) 0 2 2
2364 0  
2365 if ($data->dim(0) > $me->{idim}) {
2366 barf("Too many dims (".$data->dim(0).") for your table (".$me->{idim}.")\n");
2367 };
2368  
2369 my($x)= ($table
2370 ->interpND(float($data) * $scale + $offset,
2371 2 $p->{interpND_opt}
2372 )
2373 );
2374  
2375 2  
2376 2 ▶ # Put the index dimension (and broadcasted indices) back at the front of
Branch: 1 branch
BranchTrueFalseTotal
$x->ndims > $data->ndims - 1 ? : 2 0 2
2377 # the dimension list.
2378 my($dnd) = $data->ndims - 1;
2379 return ($x -> ndims > $data->ndims - 1) ?
2380 ($x->reorder( $dnd..($dnd + $table->ndims - $data->dim(0)-1)
2381 1 , 0..$data->ndims-2
2382 )
2383 1 ▶ ) : $x;
Subroutine __ANON__: called CC=1 SCAR=0.0
2384 };
2385  
2386 $me->{func} = sub {my($data,$p) = @_; &$lookup_func($data,$p,$p->{table},$p->{scale},$p->{offset})};
2387  
2388 1 ▶ #######
Subroutine __ANON__: called CC=15 SCAR=29.8
2389 1 ## Lazy inverse -- find it if and only if we need it...
2390 1 ▶ $me->{inv} = sub {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $p->{"itable"}) 1 0 1
2391 1 ▶ my $data = shift;
Branch: 1 branch
BranchTrueFalseTotal
if ($me->{"idim"} != $me->{"odim"}) 0 1 1
2392 0 my $p = shift;
2393 if (!defined($p->{'itable'})) {
2394 1 ▶ if ($me->{idim} != $me->{odim}) {
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose or $PDL::debug or $PDL::Transform::debug 0 1 1
Condition33%2/6
$PDL::verbose or $PDL::debug or $PDL::Transform::debug
l!l&&r!l&&!r
001
$PDL::verbose or $PDL::debug
l!l&&r!l&&!r
001
MC/DC0%0/3
$PDL::verbose or $PDL::debug or $PDL::Transform::debug
$PDL::verbose $PDL::debug $PDL::Transform::debug
Truth table25%1/4
A or B or C
A= $PDL::verboseB= $PDL::debugC= $PDL::Transform::debug
ABCresult
1XX1
01X1
0011
0000
2395 1 barf("t_lookup: can't calculate an inverse of a projection operation! (idim != odim)");
2396 1 }
2397 1 print "t_lookup: Warning, table inversion is only weakly supported. \n I'll try to invert it using a pretty boneheaded algorithm...\n (If it takes too long, consider writing a faster algorithm!)\n Calculating inverse table (will be cached)...\n" if $PDL::verbose || $PDL::debug || $PDL::Transform::debug;
2398 my $itable = zeroes($p->{table});
2399 my $minvals = $p->{table}->clump($me->{idim})->minimum;
2400 1 my $maxvals = $p->{table}->clump($me->{idim})->maximum;
2401  
2402 1 # Scale so that the range runs from 0 through the top pixel in the table
2403 my $scale = ( $itable->shape->slice("0:-2")-1 ) /
2404 1 (($maxvals - $minvals)+ (($maxvals-$minvals) == 0));
2405 1 my $offset = - ($minvals * $scale);
2406  
2407 1 ▶ $p->{iscale} = $scale;
Condition50%1/2
$p->{'enl_scale'} || 10
l!l
01
MC/DC0%0/1
$p->{'enl_scale'} || 10
$p->{'enl_scale'}
Truth table50%1/2
A
A= $p->{'enl_scale'}
Aresult
11
00
2408 1 $p->{ioffset} = $offset;
2409  
2410 my $enl_scale = $p->{'enl_scale'} || 10;
2411 my $smallcoords = ndcoords((pdl($enl_scale * 2 + 1)->at(0)) x $me->{idim})/ $enl_scale - 1;
2412 1  
2413 # $oloop runs over (point, index) for all points in the output table, in
2414 # $p->{table} output space
2415 my $oloop = ndcoords($itable->mv(-1,0)->slice("(0)"))->
2416 double->
2417 1 mv(0,-1)->
2418 1 clump($itable->ndims-1); # oloop: (pixel, index)
2419 {
2420 $oloop->mv(-1,0) -= $offset;
2421 $oloop->mv(-1,0) /= $scale;
2422 }
2423  
2424 # The Right Thing to do here is to take the outer product of $itable and $otable, then collapse
2425 1 ▶ # to find minimum distance. But memory demands for that would be HUGE. Instead we do an
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::verbose or $PDL::debug or $PDL::Transform::debug 0 1 1
Condition33%2/6
$PDL::verbose or $PDL::debug or $PDL::Transform::debug
l!l&&r!l&&!r
001
$PDL::verbose or $PDL::debug
l!l&&r!l&&!r
001
MC/DC0%0/3
$PDL::verbose or $PDL::debug or $PDL::Transform::debug
$PDL::verbose $PDL::debug $PDL::Transform::debug
Truth table25%1/4
A or B or C
A= $PDL::verboseB= $PDL::debugC= $PDL::Transform::debug
ABCresult
1XX1
01X1
0011
0000
2426 1 # elementwise calculation.
2427  
2428 1 print "t_lookup: inverting ".$oloop->dim(0)." points...\n" if $PDL::verbose || $PDL::debug || $PDL::Transform::debug;
2429 my $pt = $p->{table}->mv(-1,0); # pt runs (index, x,y,...)
2430 1  
2431 my $itable_flattened = zeroes($oloop);
2432 25  
2433 25 for my $i (0..$oloop->dim(0)-1) {
2434 25  
2435 25 my $olp = $oloop->slice("($i)"); # olp runs (index)
2436 my $diff = ($pt - $olp); # diff runs (index, x, y, ...)
2437 my $r2 = ($diff * $diff)->sumover; # r2 runs (x,y,...)
2438 25 my $c = whichND($r2==$r2->min)->slice(":,(0)"); # c runs (index)
2439  
2440 25 # Now zero in on the neighborhood around the point of closest approach.
2441 25 my $neighborhood = $p->{table}->interpND($c + $smallcoords,{method=>'linear',bound=>'t'})->
2442 25 mv(-1,0); # neighborhood runs (index, dx, dy,...)
2443 $diff = $neighborhood - $olp; # diff runs (index, dx, dy, ...)
2444 25 $r2 = ($diff * $diff)->sumover; # r2 runs (dx,dy,...)
2445 my $dc = $smallcoords->mv(0,-1)->indexND(0+whichND($r2==$r2->min)->slice(":,(0)"));
2446  
2447 25  
2448 my $coord = $c + $dc;
2449 25 ▶ # At last, we've found the best-fit to an enl_scale'th of an input-table pixel.
Branch: 1 branch
BranchTrueFalseTotal
if $i % 1000 == 0 and $PDL::verbose || $PDL::debug || $PDL::Transform::debug 0 25 25
Condition44%4/9
$i % 1000 == 0 and $PDL::verbose || $PDL::debug || $PDL::Transform::debug
!ll&&!rl&&r
2410
$PDL::verbose or $PDL::debug or $PDL::Transform::debug
l!l&&r!l&&!r
001
$PDL::verbose or $PDL::debug
l!l&&r!l&&!r
001
MC/DC0%0/4
$i % 1000 == 0 and $PDL::verbose || $PDL::debug || $PDL::Transform::debug
$i % 1000 == 0 $PDL::verbose $PDL::debug $PDL::Transform::debug
Truth table40%2/5
A and B or C or D
A= $i % 1000 == 0B= $PDL::verboseC= $PDL::debugD= $PDL::Transform::debug
ABCDresult
0XXX0
10000
11XX1
101X1
10011
2450 # Back it out to input-science coordinates, and stuff it in the inverse table.
2451 $itable_flattened->slice("($i)") .= $coord;
2452  
2453 1 print " $i..." if $i%1000==0 && ($PDL::verbose || $PDL::debug || $PDL::Transform::debug);
2454 1 }
2455 1  
2456 {
2457 $itable->clump($itable->ndims-1) .= $itable_flattened;
2458 1 $itable->mv(-1,0) -= $p->{offset};
2459 $itable->mv(-1,0) /= $p->{scale};
2460 1 }
2461 1  
2462 $p->{itable} = $itable;
2463 1 }
2464 &$lookup_func($data,$p, $p->{itable},$p->{iscale},$p->{ioffset}) ;
2465 1 };
2466  
2467  
2468 $me->{name} = 'Lookup';
2469  
2470 return $me;
2471 }
2472  
2473 +======EOD_t_lookup======
2474  
2475 pp_add_exported('t_linear');
2476 pp_addpm(<<'+======EOD_t_linear======');
2477  
2478 =head2 t_linear
2479  
2480 =for usage
2481  
2482 $f = t_linear({options});
2483  
2484 =for ref
2485  
2486 Linear (affine) transformations with optional offset
2487  
2488 t_linear implements simple matrix multiplication with offset,
2489 also known as the affine transformations.
2490  
2491 You specify the linear transformation with pre-offset, a mixing
2492 matrix, and a post-offset. That overspecifies the transformation, so
2493 you can choose your favorite method to specify the transform you want.
2494 The inverse transform is automagically generated, provided that it
2495 actually exists (the transform matrix is invertible). Otherwise, the
2496 inverse transform just croaks.
2497  
2498 Extra dimensions in the input vector are ignored, so if you pass a
2499 3xN vector into a 3-D linear transformation, the final dimension is passed
2500 through unchanged.
2501  
2502 The options you can usefully pass in are:
2503  
2504 =over 3
2505  
2506 =item s, scale, Scale
2507  
2508 A scaling scalar (heh), vector, or matrix. If you specify a vector
2509 it is treated as a diagonal matrix (for convenience). It gets
2510 left-multiplied with the transformation matrix you specify (or the
2511 identity), so that if you specify both a scale and a matrix the
2512 scaling is done after the rotation or skewing or whatever.
2513  
2514 =item r, rot, rota, rotation, Rotation
2515  
2516 A rotation angle in degrees -- useful for 2-D and 3-D data only. If
2517 you pass in a scalar, it specifies a rotation from the 0th axis toward
2518 the 1st axis. If you pass in a 3-vector as either a PDL or an array
2519 ref (as in "rot=>[3,4,5]"), then it is treated as a set of Euler
2520 angles in three dimensions, and a rotation matrix is generated that
2521 does the following, in order:
2522  
2523 =over 3
2524  
2525 =item * Rotate by rot->(2) degrees from 0th to 1st axis
2526  
2527 =item * Rotate by rot->(1) degrees from the 2nd to the 0th axis
2528  
2529 =item * Rotate by rot->(0) degrees from the 1st to the 2nd axis
2530  
2531 =back
2532  
2533 The rotation matrix is left-multiplied with the transformation matrix
2534 you specify, so that if you specify both rotation and a general matrix
2535 the rotation happens after the more general operation -- though that is
2536 deprecated.
2537  
2538 Of course, you can duplicate this functionality -- and get more
2539 general -- by generating your own rotation matrix and feeding it in
2540 with the C<matrix> option.
2541  
2542 =item m, matrix, Matrix
2543  
2544 The transformation matrix. It does not even have to be square, if you want
2545 to change the dimensionality of your input. If it is invertible (note:
2546 must be square for that), then you automagically get an inverse transform too.
2547  
2548 =item pre, preoffset, offset, Offset
2549  
2550 The vector to be added to the data before they get multiplied by the matrix
2551 (equivalent of CRVAL in FITS, if you are converting from scientific to
2552 pixel units).
2553  
2554 =item post, postoffset, shift, Shift
2555  
2556 The vector to be added to the data after it gets multiplied by the matrix
2557 (equivalent of CRPIX-1 in FITS, if you're converting from scientific to pixel
2558 units).
2559  
2560 =item d, dim, dims, Dims
2561  
2562 Most of the time it is obvious how many dimensions you want to deal
2563 with: if you supply a matrix, it defines the transformation; if you
2564 input offset vectors in the C<pre> and C<post> options, those define
2565 the number of dimensions. But if you only supply scalars, there is no way
2566 to tell and the default number of dimensions is 2. This provides a way
2567 to do, e.g., 3-D scaling: just set C<< {s=><scale-factor>, dims=>3} >> and
2568 you are on your way.
2569  
2570 =item idim
2571  
2572 =item odim
2573  
2574 =item iunit
2575  
2576 =item ounit
2577  
2578 =item itype
2579  
2580 =item otype
2581  
2582 These are incorporated in the object, though not much is done with them
2583 yet as of 2.094.
2584  
2585 =back
2586  
2587 =cut
2588  
2589 { package PDL::Transform::Linear;
2590 our @ISA = ('PDL::Transform');
2591 *_opt = \&PDL::Transform::_opt;
2592 *barf = \&PDL::Transform::barf;
2593 1 ▶*identity = \&PDL::MatrixOps::identity;
Subroutine BEGIN: called CC=1 SCAR=0.0
2594 use PDL::Constants qw(DEG2RAD);
2595 18 ▶ 
Subroutine t_linear: called CC=1 SCAR=0.0
Pod documented
2596 sub PDL::Transform::t_linear { PDL::Transform::Linear->new(@_); }
2597  
2598 41 ▶sub new {
Subroutine new: called CC=39 SCAR=39.2
2599 41 my($class) = shift;
2600 41 ▶ my($o) = $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if $#_ % 2 == 0 and not defined $_[-1] 5 36 41
Condition100%3/3
$#_ % 2 == 0 and not defined $_[-1]
!ll&&!rl&&r
12245
MC/DC100%2/2
$#_ % 2 == 0 and not defined $_[-1]
$#_ % 2 == 0 not defined $_[-1]
Truth table100%3/3
A and not(B)
A= $#_ % 2 == 0B= not defined $_[-1]
ABresult
0X0
100
111
2601 pop @_ if (($#_ % 2 ==0) && !defined($_[-1]));
2602 #suppresses a warning if @_ has an odd number of elements and the
2603 #last is undef
2604 41 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $o) 17 24 41
2605 17 if (!(ref $o)) {
2606 $o = {@_};
2607 }
2608 41  
2609 my($me) = __PACKAGE__->SUPER::new;
2610 41  
2611 $me->{name} = "linear";
2612 41  
2613 $me->{params}{pre} = _opt($o,['pre','Pre','preoffset','offset',
2614 'Offset','PreOffset','Preoffset'],0);
2615 41 ▶ $me->{params}{pre} = PDL->pdl($me->{params}{pre})
Branch: 1 branch
BranchTrueFalseTotal
if defined $me->{"params"}{"pre"} 41 0 41
2616 if defined $me->{params}{pre};
2617 41  
2618 $me->{params}{post} = _opt($o,['post','Post','postoffset','PostOffset',
2619 'shift','Shift'],0);
2620 41 ▶ $me->{params}{post} = PDL->pdl($me->{params}{post})
Branch: 1 branch
BranchTrueFalseTotal
if defined $me->{"params"}{"post"} 41 0 41
2621 if defined $me->{params}{post};
2622 41  
2623 $me->{params}{matrix} = _opt($o,['m','matrix','Matrix','mat','Mat']);
2624 41 ▶ $me->{params}{matrix} = PDL->pdl($me->{params}{matrix})
Branch: 1 branch
BranchTrueFalseTotal
if defined $me->{"params"}{"matrix"} 27 14 41
2625 if defined $me->{params}{matrix};
2626 41  
2627 41 $me->{params}{rot} = _opt($o,['r','rot','rota','rotation','Rotation'], 0);
2628 $me->{params}{rot} = PDL->pdl($me->{params}{rot});
2629 41  
2630 41 ▶ my $o_dims = _opt($o,['d','dim','dims','Dims']);
Branch: 1 branch
BranchTrueFalseTotal
if defined $o_dims 5 36 41
2631 $o_dims = PDL->pdl($o_dims) if defined($o_dims);
2632 41  
2633 41 ▶ my $scale = _opt($o,['s','scale','Scale']);
Branch: 1 branch
BranchTrueFalseTotal
if defined $scale 8 33 41
2634 $scale = PDL->pdl($scale) if defined($scale);
2635  
2636 # Figure out the number of dimensions to transform, and,
2637 # if necessary, generate a new matrix.
2638 41  
2639 41 ▶ my $rot = $me->{params}{rot};
Branch: 1 branch
BranchTrueFalseTotal
if (defined $me->{'params'}{'matrix'}) { } 27 14 41
2640 27 if (defined($me->{params}{matrix})) {
2641 27 my $mat = $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
2642 27 $me->{idim} = $mat->dim(0);
2643 $me->{odim} = $mat->dim(1);
2644  
2645 14 ▶ } else {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $me->{"params"}{"rot"} and UNIVERSAL::isa($me->{"params"}{"rot"}, "PDL")) 14 0 14
Condition33%1/3
defined $me->{"params"}{"rot"} and UNIVERSAL::isa($me->{"params"}{"rot"}, "PDL")
!ll&&!rl&&r
0014
MC/DC0%0/2
defined $me->{"params"}{"rot"} and UNIVERSAL::isa($me->{"params"}{"rot"}, "PDL")
defined $me->{"params"}{"rot"} UNIVERSAL::isa($me->{"params"}{"rot"}, "PDL")
Truth table33%1/3
A and B
A= defined $me->{"params"}{"rot"}B= UNIVERSAL::isa($me->{"params"}{"rot"}, "PDL")
ABresult
0X0
100
111
2646 if (defined($me->{params}->{rot}) &&
2647 14 ▶ UNIVERSAL::isa($me->{params}->{rot},'PDL')) {
Branch: 1 branch
BranchTrueFalseTotal
if $me->{"params"}{"rot"}->nelem == 1 12 2 14
2648 14 ▶ $me->{idim} = $me->{odim} = 2 if $me->{params}{rot}->nelem == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $me->{"params"}{"rot"}->nelem == 3 2 12 14
2649 $me->{idim} = $me->{odim} = 3 if $me->{params}{rot}->nelem == 3;
2650 }
2651 14 ▶ 
Branch: 5 branches
BranchTrueFalseTotal
if (defined $scale and UNIVERSAL::isa($scale, 'PDL') and $scale->getndims > 0) { } 6 8 14
elsif (defined $me->{'params'}{'pre'} and UNIVERSAL::isa($me->{'params'}{'pre'}, 'PDL') and $me->{'params'}{'pre'}->getndims > 0) { } 4 4 8
elsif (defined $me->{'params'}{'post'} and UNIVERSAL::isa($me->{'params'}{'post'}, 'PDL') and $me->{'params'}{'post'}->getndims > 0) { } 0 4 4
elsif (defined $o_dims) { } 1 3 4
elsif (UNIVERSAL::isa($rot, 'PDL') and (my $nrots = $rot->nelem) > 1) { } 1 2 3
Condition83%5/6
defined $scale and UNIVERSAL::isa($scale, "PDL") and $scale->getndims > 0
!ll&&!rl&&r
626
defined $scale and UNIVERSAL::isa($scale, "PDL")
!ll&&!rl&&r
608
MC/DC66%2/3
defined $scale and UNIVERSAL::isa($scale, "PDL") and $scale->getndims > 0
defined $scale UNIVERSAL::isa($scale, "PDL") $scale->getndims > 0
Truth table75%3/4
A and B and C
A= defined $scaleB= UNIVERSAL::isa($scale, "PDL")C= $scale->getndims > 0
ABCresult
0XX0
10X0
1100
1111
2652 if (defined($scale) &&
2653 UNIVERSAL::isa($scale,'PDL') &&
2654 6 $scale->getndims > 0) {
2655 6 $me->{idim} = $me->{odim} = $scale->dim(0);
2656 $me->{odim} = $scale->dim(0);
2657 ▶ 
Condition50%3/6
defined $me->{"params"}{"pre"} and UNIVERSAL::isa($me->{"params"}{"pre"}, "PDL") and $me->{"params"}{"pre"}->getndims > 0
!ll&&!rl&&r
044
defined $me->{"params"}{"pre"} and UNIVERSAL::isa($me->{"params"}{"pre"}, "PDL")
!ll&&!rl&&r
008
MC/DC33%1/3
defined $me->{"params"}{"pre"} and UNIVERSAL::isa($me->{"params"}{"pre"}, "PDL") and $me->{"params"}{"pre"}->getndims > 0
defined $me->{"params"}{"pre"} UNIVERSAL::isa($me->{"params"}{"pre"}, "PDL") $me->{"params"}{"pre"}->getndims > 0
Truth table50%2/4
A and B and C
A= defined $me->{"params"}{"pre"}B= UNIVERSAL::isa($me->{"params"}{"pre"}, "PDL")C= $me->{"params"}{"pre"}->getndims > 0
ABCresult
0XX0
10X0
1100
1111
2658 } elsif (defined($me->{params}{pre}) &&
2659 UNIVERSAL::isa($me->{params}{pre},'PDL') &&
2660 4 $me->{params}{pre}->getndims > 0) {
2661 $me->{idim} = $me->{odim} = $me->{params}{pre}->dim(0);
2662 ▶ 
Condition33%2/6
defined $me->{"params"}{"post"} and UNIVERSAL::isa($me->{"params"}{"post"}, "PDL") and $me->{"params"}{"post"}->getndims > 0
!ll&&!rl&&r
040
defined $me->{"params"}{"post"} and UNIVERSAL::isa($me->{"params"}{"post"}, "PDL")
!ll&&!rl&&r
004
MC/DC0%0/3
defined $me->{"params"}{"post"} and UNIVERSAL::isa($me->{"params"}{"post"}, "PDL") and $me->{"params"}{"post"}->getndims > 0
defined $me->{"params"}{"post"} UNIVERSAL::isa($me->{"params"}{"post"}, "PDL") $me->{"params"}{"post"}->getndims > 0
Truth table25%1/4
A and B and C
A= defined $me->{"params"}{"post"}B= UNIVERSAL::isa($me->{"params"}{"post"}, "PDL")C= $me->{"params"}{"post"}->getndims > 0
ABCresult
0XX0
10X0
1100
1111
2663 } elsif (defined($me->{params}{post}) &&
2664 UNIVERSAL::isa($me->{params}{post},'PDL') &&
2665 0 $me->{params}{post}->getndims > 0) {
2666 $me->{idim} = $me->{odim} = $me->{params}{post}->dim(0);
2667 1 } elsif (defined($o_dims)) {
2668 ▶ $me->{idim} = $me->{odim} = $o_dims;
Condition66%2/3
UNIVERSAL::isa($rot, "PDL") and (my $nrots = $rot->nelem) > 1
!ll&&!rl&&r
021
MC/DC50%1/2
UNIVERSAL::isa($rot, "PDL") and (my $nrots = $rot->nelem) > 1
UNIVERSAL::isa($rot, "PDL") (my $nrots = $rot->nelem) > 1
Truth table66%2/3
A and B
A= UNIVERSAL::isa($rot, "PDL")B= (my $nrots = $rot->nelem) > 1
ABresult
0X0
100
111
2669 1 } elsif (UNIVERSAL::isa($rot,'PDL') && (my $nrots = $rot->nelem) > 1) {
2670 $me->{idim} = $me->{odim} = $nrots;
2671 2 ▶ } else {
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 2 2
2672 2 print "PDL::Transform::Linear: assuming 2-D transform (set dims option to change)\n" if $PDL::Transform::debug;
2673 $me->{idim} = $me->{odim} = 2;
2674 }
2675 14  
2676 14 $me->{params}->{matrix} = PDL->zeroes($me->{idim},$me->{odim});
2677 $me->{params}->{matrix}->diagonal(0,1) .= 1;
2678 }
2679  
2680 41 ▶ ### Handle rotation option
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rot) 41 0 41
2681 if (defined($rot)) {
2682 # Subrotation closure -- rotates from axis $d->(0) --> $d->(1).
2683 6 ▶ my $subrot = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
2684 6 my($d,$angle,$m)=@_;
2685 6 my($i) = identity($m->dim(0));
2686 my($subm) = $i->dice($d,$d);
2687 6 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($angle, "PDL") 0 6 6
2688 $angle = $angle->at(0)
2689 if UNIVERSAL::isa($angle,'PDL');
2690 6  
2691 6 my($x) = $angle * DEG2RAD;
2692 6 $subm .= $subm x PDL->pdl([cos($x),-sin($x)],[sin($x),cos($x)]);
2693 41 $m .= $m x $i;
2694 };
2695 41 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($rot, 'PDL') and $rot->nelem > 1) { } 2 39 41
Condition66%2/3
UNIVERSAL::isa($rot, "PDL") and $rot->nelem > 1
!ll&&!rl&&r
0392
MC/DC50%1/2
UNIVERSAL::isa($rot, "PDL") and $rot->nelem > 1
UNIVERSAL::isa($rot, "PDL") $rot->nelem > 1
Truth table66%2/3
A and B
A= UNIVERSAL::isa($rot, "PDL")B= $rot->nelem > 1
ABresult
0X0
100
111
2696 2 ▶ if (UNIVERSAL::isa($rot,'PDL') && $rot->nelem > 1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rot->ndims == 2) { } 0 2 2
elsif ($rot->nelem == 3) { } 2 0 2
2697 0 if ($rot->ndims == 2) {
2698 $me->{params}{matrix} x= $rot;
2699 2 } elsif ($rot->nelem == 3) {
2700 my $rm = identity(3);
2701  
2702 # Do these in reverse order to make it more like
2703 2 # function composition!
2704 2 &$subrot(PDL->pdl(0,1),$rot->at(2),$rm);
2705 2 &$subrot(PDL->pdl(2,0),$rot->at(1),$rm);
2706 &$subrot(PDL->pdl(1,2),$rot->at(0),$rm);
2707 2  
2708 $me->{params}{matrix} .= $me->{params}{matrix} x $rm;
2709 0 } else {
2710 barf("PDL::Transform::Linear: Got a strange rot option -- giving up.\n");
2711 }
2712 39 ▶ } else {
Branch: 1 branch
BranchTrueFalseTotal
if ($rot != 0 and $me->{"params"}{"matrix"}->dim(0) > 1) 0 39 39
Condition33%1/3
$rot != 0 and $me->{"params"}{"matrix"}->dim(0) > 1
!ll&&!rl&&r
3900
MC/DC0%0/2
$rot != 0 and $me->{"params"}{"matrix"}->dim(0) > 1
$rot != 0 $me->{"params"}{"matrix"}->dim(0) > 1
Truth table33%1/3
A and B
A= $rot != 0B= $me->{"params"}{"matrix"}->dim(0) > 1
ABresult
0X0
100
111
2713 0 if ($rot != 0 and $me->{params}{matrix}->dim(0)>1) {
2714 &$subrot(PDL->pdl(0,1),$rot,$me->{params}{matrix});
2715 }
2716 }
2717 }
2718  
2719 41 # Apply scaling
2720 41 ▶ $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
Branch: 1 branch
BranchTrueFalseTotal
if defined $scale 8 33 41
2721 $me->{params}{matrix}->diagonal(0,1) *= $scale
2722 if defined($scale);
2723  
2724 41 # Check for an inverse and apply it if possible
2725 41 ▶ my($o2);
Branch: 1 branch
BranchTrueFalseTotal
if ($me->{'params'}{'matrix'}->det($o2 = {'lu', undef})) { } 41 0 41
2726 41 if ($me->{params}{matrix}->det($o2 = {lu=>undef})) {
2727 $me->{params}{inverse} = $me->{params}{matrix}->inv($o2);
2728 0 } else {
2729 delete $me->{params}{inverse};
2730 }
2731 41  
2732 41 $me->{params}{idim} = $me->{idim};
2733 $me->{params}{odim} = $me->{odim};
2734 41  
2735 164 ▶ for (qw(iunit ounit itype otype)) {
Branch: 1 branch
BranchTrueFalseTotal
unless defined(my $val = _opt($o, [$_])) 160 4 164
2736 4 next unless defined (my $val = _opt($o,[$_]));
2737 $me->{$_} = $val;
2738 }
2739  
2740 ##############################
2741 # The meat -- just shift, matrix-multiply, and shift again.
2742 43 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
2743 43 my ($in,$opt) = @_;
2744 43 ▶ my $d = $opt->{matrix}->dim(0)-1;
Branch: 1 branch
BranchTrueFalseTotal
if $in->dim(0) <= $d 0 43 43
2745 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
2746 43 if $in->dim(0) <= $d;
2747 43 my $x = $in->slice("0:$d")->copy + $opt->{pre};
2748 43 my $out = $in->new_or_inplace;
2749 43 $out->slice("0:$d") .= $x x $opt->{matrix} + $opt->{post};
2750 41 return $out;
2751 };
2752  
2753 16 ▶ $me->{inv} = (defined $me->{params}{inverse}) ? sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
2754 16 my ($in,$opt) = @_;
2755 16 ▶ my $d = $opt->{inverse}->dim(0)-1;
Branch: 1 branch
BranchTrueFalseTotal
if $in->dim(0) <= $d 0 16 16
2756 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
2757 16 if $in->dim(0) <= $d;
2758 16 my $x = $in->slice("0:$d")->copy - $opt->{post};
2759 16 my $out = $in->new_or_inplace;
2760 16 $out->slice("0:$d") .= $x x $opt->{inverse} - $opt->{pre};
2761 41 ▶ $out;
Branch: 1 branch
BranchTrueFalseTotal
defined $me->{'params'}{'inverse'} ? : 41 0 41
2762 } : undef;
2763 41  
2764 return $me;
2765 }
2766  
2767 0 ▶sub stringify {
Subroutine stringify: not called CC=10 SCAR=47.0
2768 0 my($me) = shift; my($out) = SUPER::stringify $me;
2769 my $mp = $me->{params};
2770 0 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (not $me->{'is_inverse'}) { } 0 0 0
2771 if (!($me->{is_inverse})){
2772 0 ▶ $out .= "Pre-add: ".($mp->{pre})."\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"pre"} 0 0 0
2773 if defined $mp->{pre};
2774  
2775 0 ▶ $out .= "Post-add: ".($mp->{post})."\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"post"} 0 0 0
2776 if defined $mp->{post};
2777  
2778 0 ▶ $out .= "Forward matrix:".($mp->{matrix})
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"matrix"} 0 0 0
2779 if defined $mp->{matrix};
2780  
2781 0 ▶ $out .= "Inverse matrix:".($mp->{inverse})
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"inverse"} 0 0 0
2782 if defined $mp->{inverse};
2783 } else {
2784 0 ▶ $out .= "Pre-add: ".(-$mp->{post})."\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"post"} 0 0 0
2785 if defined $mp->{post};
2786  
2787 0 ▶ $out .= "Post-add: ".(-$mp->{pre})."\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"pre"} 0 0 0
2788 if defined $mp->{pre};
2789  
2790 0 ▶ $out .= "Forward matrix:".($mp->{inverse})
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"inverse"} 0 0 0
2791 if defined $mp->{inverse};
2792  
2793 0 ▶ $out .= "Inverse matrix:".($mp->{matrix})
Branch: 1 branch
BranchTrueFalseTotal
if defined $mp->{"matrix"} 0 0 0
2794 if defined $mp->{matrix};
2795 }
2796 0  
2797 0 $out =~ s/\n/\n /go;
2798 $out;
2799 }
2800 }
2801  
2802 +======EOD_t_linear======
2803  
2804 pp_add_exported('t_scale');
2805 pp_addpm(<<'+======EOD_t_scale======');
2806  
2807 =head2 t_scale
2808  
2809 =for usage
2810  
2811 $f = t_scale(<scale>)
2812  
2813 =for ref
2814  
2815 Convenience interface to L</t_linear>.
2816  
2817 t_scale produces a transform that scales around the origin by a fixed
2818 amount. It acts exactly the same as C<<< t_linear(Scale=>$scale) >>>.
2819  
2820 =cut
2821  
2822 3 ▶sub t_scale {
Subroutine t_scale: called CC=2 SCAR=7.4
Pod documented
2823 3 my($scale) = shift;
2824 3 ▶ my($y) = shift;
Branch: 1 branch
BranchTrueFalseTotal
if ref $y eq "HASH" 0 3 3
2825 return t_linear(scale=>$scale,%{$y})
2826 if ref $y eq 'HASH';
2827 3 t_linear(Scale=>$scale,$y,@_);
2828 }
2829  
2830 +======EOD_t_scale======
2831  
2832 pp_add_exported('t_offset ');
2833 pp_addpm(<<'+======EOD_t_offset ======');
2834  
2835 =head2 t_offset
2836  
2837 =for usage
2838  
2839 $f = t_offset(<shift>)
2840  
2841 =for ref
2842  
2843 Convenience interface to L</t_linear>.
2844  
2845 t_offset produces a transform that shifts the origin to a new location.
2846 It acts exactly the same as C<<< t_linear(Pre=>$shift) >>>.
2847  
2848 =cut
2849  
2850 1 ▶sub t_offset {
Subroutine t_offset: called CC=2 SCAR=7.4
Pod documented
2851 1 my($pre) = shift;
2852 1 ▶ my($y) = shift;
Branch: 1 branch
BranchTrueFalseTotal
if ref $y eq "HASH" 0 1 1
2853 return t_linear(pre=>$pre,%{$y})
2854 if ref $y eq 'HASH';
2855  
2856 1 t_linear(pre=>$pre,$y,@_);
2857 }
2858  
2859 +======EOD_t_offset ======
2860  
2861 pp_add_exported('t_rot');
2862 pp_addpm(<<'+======EOD_t_rot======');
2863  
2864 =head2 t_rot
2865  
2866 =for usage
2867  
2868 $f = t_rot(\@rotation_in_degrees)
2869  
2870 =for ref
2871  
2872 Convenience interface to L</t_linear>.
2873  
2874 t_rot produces a rotation transform in 2-D (scalar), 3-D (3-vector), or
2875 N-D (matrix). It acts exactly the same as C<< t_linear(rot=>shift) >>.
2876  
2877 =cut
2878  
2879 *t_rot = \&t_rotate;
2880 1 ▶sub t_rotate {
Subroutine t_rotate: called CC=2 SCAR=7.4
Pod undocumented
2881 1 my $rot = shift;
2882 1 ▶ my($y) = shift;
Branch: 1 branch
BranchTrueFalseTotal
if ref $y eq "HASH" 0 1 1
2883 return t_linear(rot=>$rot,%{$y})
2884 if ref $y eq 'HASH';
2885  
2886 1 t_linear(rot=>$rot,$y,@_);
2887 }
2888  
2889 +======EOD_t_rot======
2890  
2891  
2892  
2893 pp_add_exported('t_fits');
2894 pp_addpm(<<'+======EOD_t_fits======');
2895  
2896 =head2 t_fits
2897  
2898 =for usage
2899  
2900 $f = t_fits($fits,[option]);
2901  
2902 =for ref
2903  
2904 FITS pixel-to-scientific transformation with inverse
2905  
2906 You feed in a hash ref or a PDL with one of those as a header, and you
2907 get back a transform that converts 0-originated, pixel-centered
2908 coordinates into scientific coordinates via the transformation in the
2909 FITS header. For most FITS headers, the transform is reversible, so
2910 applying the inverse goes the other way. This is just an instance
2911 of PDL::Transform::Linear, but with unit/type support
2912 using the FITS header you supply.
2913  
2914 For now, this transform is rather limited -- it really ought to
2915 accept units differences and stuff like that, but they are just
2916 ignored for now. Probably that would require putting units into
2917 the whole transform framework.
2918  
2919 This transform implements the linear transform part of the WCS FITS
2920 standard outlined in Greisen & Calabata 2002 (A&A in press; find it at
2921 L<https://arxiv.org/abs/astro-ph/0207407>).
2922  
2923 As a special case, you can pass in the boolean option "ignore_rgb"
2924 (default 0), and if you pass in a 3-D FITS header in which the last
2925 dimension has exactly 3 elements, it will be ignored in the output
2926 transformation. That turns out to be handy for handling rgb images.
2927  
2928 =cut
2929  
2930 23 ▶sub t_fits {
Subroutine t_fits: called CC=29 SCAR=43.0
Pod documented
2931 23 my($hdr) = shift;
2932 my($opt) = shift;
2933 23 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opt ne "HASH") 2 21 23
2934 2 ▶ if (ref $opt ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
defined $opt ? : 0 2 2
2935 $opt = defined $opt ? {$opt,@_} : {} ;
2936 }
2937 23 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if defined $hdr and UNIVERSAL::isa($hdr, "PDL") 23 0 23
Condition33%1/3
defined $hdr and UNIVERSAL::isa($hdr, "PDL")
!ll&&!rl&&r
0023
MC/DC0%0/2
defined $hdr and UNIVERSAL::isa($hdr, "PDL")
defined $hdr UNIVERSAL::isa($hdr, "PDL")
Truth table33%1/3
A and B
A= defined $hdrB= UNIVERSAL::isa($hdr, "PDL")
ABresult
0X0
100
111
2938 $hdr = $hdr->gethdr
2939 if defined $hdr && UNIVERSAL::isa($hdr,'PDL');
2940  
2941 23 ▶ croak('t_fits requires a FITS header hash\n')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $hdr or ref $hdr ne "HASH" or not defined $hdr->{"NAXIS"} 0 23 23
Condition33%2/6
not defined $hdr or ref $hdr ne "HASH" or not defined $hdr->{"NAXIS"}
l!l&&r!l&&!r
0023
not defined $hdr or ref $hdr ne "HASH"
l!l&&r!l&&!r
0023
MC/DC0%0/3
not defined $hdr or ref $hdr ne "HASH" or not defined $hdr->{"NAXIS"}
not defined $hdr ref $hdr ne "HASH" not defined $hdr->{"NAXIS"}
Truth table25%1/4
not(A) or B or not(C)
A= not defined $hdrB= ref $hdr ne "HASH"C= not defined $hdr->{"NAXIS"}
ABCresult
1XX1
01X1
0011
0000
2942 if !defined $hdr || ref $hdr ne 'HASH' || !defined($hdr->{NAXIS});
2943 23 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($n, "PDL") 0 23 23
2944 my($n) = $hdr->{NAXIS}; $n = $n->at(0) if UNIVERSAL::isa($n,'PDL');
2945  
2946 23 ▶ $n = 2
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"ignore_rgb"} and $n == 3 and $hdr->{"NAXIS3"} == 3 0 23 23
Condition50%3/6
$opt->{"ignore_rgb"} and $n == 3 and $hdr->{"NAXIS3"} == 3
!ll&&!rl&&r
2300
$opt->{"ignore_rgb"} and $n == 3
!ll&&!rl&&r
2210
MC/DC0%0/3
$opt->{"ignore_rgb"} and $n == 3 and $hdr->{"NAXIS3"} == 3
$opt->{"ignore_rgb"} $n == 3 $hdr->{"NAXIS3"} == 3
Truth table50%2/4
A and B and C
A= $opt->{"ignore_rgb"}B= $n == 3C= $hdr->{"NAXIS3"} == 3
ABCresult
0XX0
10X0
1100
1111
2947 if $opt->{ignore_rgb} && $n==3 && $hdr->{NAXIS3} == 3;
2948 23  
2949 23 my($matrix) = PDL->zeroes($n,$n);
2950 23 my($pre) = PDL->zeroes($n);
2951 my($post) = PDL->zeroes($n);
2952  
2953 ##############################
2954 # Scaling: Use CDi_j formalism if present; otherwise use the
2955 # older PCi_j + CDELTi formalism.
2956 23  
2957 my(@hgrab);
2958 23 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
if (@hgrab = grep(/^CD\d{1,3}_\d{1,3}$/, sort(keys %$hdr))) { } 1 22 23
2959 if (@hgrab = grep(m/^CD\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2960 #
2961 # CDi_j formalism
2962 1 #
2963 4 for my $h(@hgrab) {
2964 4 $h =~ m/CD(\d{1,3})_(\d{1,3})/; # Should always match
2965 $matrix->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
2966 1 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 1 1
2967 print "t_fits: Detected CDi_j matrix: \n",$matrix,"\n"
2968 if $PDL::Transform::debug;
2969  
2970 } else {
2971  
2972 #
2973 # PCi_j + CDELTi formalism
2974 # If PCi_j aren't present, and N=2, then try using CROTA or
2975 # CROTA2 to generate a rotation matrix instead.
2976 #
2977 22  
2978 22 my($cdm) = PDL->zeroes($n,$n);
2979 my($cd) = $cdm->diagonal(0,1);
2980 22  
2981 22 my($cpm) = PDL->zeroes($n,$n);
2982 22 $cpm->diagonal(0,1) .= 1; # PC: diagonal defaults to unity
2983 $cd .= 1;
2984 22 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (@hgrab = grep(/^PC\d{1,3}_\d{1,3}$/, sort(keys %$hdr))) { } 0 22 22
elsif ($n == 2 and grep defined($hdr->{$_}), ('CROTA', 'CROTA1', 'CROTA2')) { } 0 22 22
2985  
2986 0 if (@hgrab = grep(m/^PC\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2987 0 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
$h =~ /PC(\d{1,3})_(\d{1,3})$/ or die "t_fits - match failed! This should never happen!" 0 0 0
2988 0 for my $h(@hgrab) {
2989 $h =~ m/PC(\d{1,3})_(\d{1,3})$/ || die "t_fits - match failed! This should never happen!";
2990 0 ▶ $cpm->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug and @hgrab 0 0 0
Condition0%0/3
$PDL::Transform::debug and @hgrab
!ll&&!rl&&r
000
MC/DC0%0/2
$PDL::Transform::debug and @hgrab
$PDL::Transform::debug @hgrab
Truth table0%0/3
A and B
A= $PDL::Transform::debugB= @hgrab
ABresult
0X0
100
111
2991 }
2992 print "t_fits: Detected PCi_j matrix: \n",$cpm,"\n"
2993 ▶ if $PDL::Transform::debug && @hgrab;
Condition33%1/3
$n == 2 and grep defined($hdr->{$_}), ("CROTA", "CROTA1", "CROTA2")
!ll&&!rl&&r
0220
MC/DC0%0/2
$n == 2 and grep defined($hdr->{$_}), ("CROTA", "CROTA1", "CROTA2")
$n == 2 grep defined($hdr->{$_}), ("CROTA", "CROTA1", "CROTA2")
Truth table33%1/3
A and B
A= $n == 2B= grep defined($hdr->{$_}), ("CROTA", "CROTA1", "CROTA2")
ABresult
0X0
100
111
2994  
2995 } elsif ($n==2 && grep defined $hdr->{$_}, qw(CROTA CROTA1 CROTA2)) {
2996  
2997 0 ▶ ## CROTA is deprecated; CROTA1 was used for a while but is unofficial;
Condition0%0/6
($hdr->{"CROTA2"} // $hdr->{"CROTA"}) // $hdr->{"CROTA1"}
l!l&&r!l&&!r
000
$hdr->{"CROTA2"} // $hdr->{"CROTA"}
l!l&&r!l&&!r
000
MC/DC0%0/3
($hdr->{"CROTA2"} // $hdr->{"CROTA"}) // $hdr->{"CROTA1"}
$hdr->{"CROTA2"} $hdr->{"CROTA"} $hdr->{"CROTA1"}
Truth table0%0/4
A // B // C
A= $hdr->{"CROTA2"}B= $hdr->{"CROTA"}C= $hdr->{"CROTA1"}
ABCresult
1XX1
01X1
0011
0000
2998 ## CROTA2 is encouraged instead.
2999 0 my $cr = $hdr->{CROTA2} // $hdr->{CROTA} // $hdr->{CROTA1};
3000  
3001 $cr *= DEG2RAD();
3002 0 # Rotation matrix rotates counterclockwise to get from sci to pixel coords
3003 # (detector has been rotated ccw, according to FITS standard)
3004 $cpm .= pdl( [cos($cr), sin($cr)],[-sin($cr),cos($cr)] );
3005  
3006 22 }
3007 44  
3008 for my $i(1..$n) {
3009 $cd->slice("(".($i-1).")") .= $hdr->{"CDELT$i"};
3010 22 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if all($cd == 0) 0 22 22
3011 #If there are no CDELTs, then we assume they are all 1.0
3012 22 $cd+=1 if (all($cd==0));
3013  
3014 $matrix = $cdm x $cpm;
3015 23 }
3016 23  
3017 46 my($i1) = 0;
3018 46 for my $i(1..$n) {
3019 46 $pre->slice("($i1)") .= 1 - $hdr->{"CRPIX$i"};
3020 $post->slice("($i1)") .= $hdr->{"CRVAL$i"};
3021 $i1++;
3022 23 }
3023  
3024 my $me = PDL::Transform::Linear->new({
3025 23 pre=>$pre, post=>$post, matrix=>$matrix
3026 });
3027 23 $me->{name} = 'FITS';
3028 23  
3029 23 my (@otype,@ounit,@itype,@iunit);
3030 46 my @names = qw(X Y Z);
3031 46 for my $i(1..$hdr->{NAXIS}) {
3032 46 ▶ push(@otype,$hdr->{"CTYPE$i"});
Branch: 1 branch
BranchTrueFalseTotal
$i - 1 <= $#names ? : 46 0 46
3033 46 push(@ounit,$hdr->{"CUNIT$i"});
3034 push(@itype,"Image ". ( ($i-1<=$#names) ? $names[$i-1] : "${i}th dim" ));
3035 23 push(@iunit,"Pixels");
3036 23 }
3037 23 $me->{otype} = \@otype;
3038 23 $me->{itype} = \@itype;
3039 $me->{ounit} = \@ounit;
3040 $me->{iunit} = \@iunit;
3041  
3042 # Check for nonlinear projection...
3043 # if ($hdr->{CTYPE1} =~ m/(\w\w\w\w)\-(\w\w\w)/) {
3044 # print "Nonlinear transformation found... ignoring nonlinear part...\n";
3045 23 # }
3046  
3047 return $me;
3048 }
3049  
3050 +======EOD_t_fits======
3051  
3052  
3053  
3054  
3055  
3056 pp_add_exported('t_code ');
3057 pp_addpm(<<'+======EOD_t_code ======');
3058  
3059 =head2 t_code
3060  
3061 =for usage
3062  
3063 $f = t_code(<func>,[<inv>],[options]);
3064  
3065 =for ref
3066  
3067 Transform implementing arbitrary perl code.
3068  
3069 This is a way of getting quick-and-dirty new transforms. You pass in
3070 anonymous (or otherwise) code refs pointing to subroutines that
3071 implement the forward and, optionally, inverse transforms. The
3072 subroutines should accept a data PDL followed by a parameter hash ref,
3073 and return the transformed data PDL. The parameter hash ref can be
3074 set via the options, if you want to.
3075  
3076 Options that are accepted are:
3077  
3078 =over 3
3079  
3080 =item p,params
3081  
3082 The parameter hash that will be passed back to your code (defaults to the
3083 empty hash).
3084  
3085 =item n,name
3086  
3087 The name of the transform (defaults to "code").
3088  
3089 =item i, idim (default 2)
3090  
3091 The number of input dimensions (additional ones should be passed through
3092 unchanged)
3093  
3094 =item o, odim (default 2)
3095  
3096 The number of output dimensions
3097  
3098 =item itype
3099  
3100 The type of the input dimensions, in an array ref (optional and advisory)
3101  
3102 =item otype
3103  
3104 The type of the output dimension, in an array ref (optional and advisory)
3105  
3106 =item iunit
3107  
3108 The units that are expected for the input dimensions (optional and advisory)
3109  
3110 =item ounit
3111  
3112 The units that are returned in the output (optional and advisory).
3113  
3114 =back
3115  
3116 The code variables are executable perl code, either as a code ref or
3117 as a string that will be eval'ed to produce code refs. If you pass in
3118 a string, it gets eval'ed at call time to get a code ref. If it compiles
3119 OK but does not return a code ref, then it gets re-evaluated with "sub {
3120 ... }" wrapped around it, to get a code ref.
3121  
3122 Note that code callbacks like this can be used to do really weird
3123 things and generate equally weird results -- caveat scriptor!
3124  
3125 =cut
3126  
3127 1 ▶sub t_code {
Subroutine t_code: called CC=10 SCAR=25.7
Pod documented
3128 1 my($class) = 'PDL::Transform';
3129 1 ▶ my($func, $inv, $o) = @_;
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inv eq "HASH") 0 1 1
3130 0 if (ref $inv eq 'HASH') {
3131 0 $o = $inv;
3132 $inv = undef;
3133 }
3134 1  
3135 1 ▶ my($me) = $class->new;
Condition50%1/2
_opt($o, ['n', 'name', 'Name']) || 'code'
l!l
01
MC/DC0%0/1
_opt($o, ['n', 'name', 'Name']) || 'code'
_opt($o, ['n', 'name', 'Name'])
Truth table50%1/2
A
A= _opt($o, ['n', 'name', 'Name'])
Aresult
11
00
3136 1 $me->{name} = _opt($o,['n','name','Name']) || "code";
3137 1 $me->{func} = $func;
3138 1 ▶ $me->{inv} = $inv;
Condition50%1/2
_opt($o, ['p', 'params', 'Params']) || {}
l!l
01
MC/DC0%0/1
_opt($o, ['p', 'params', 'Params']) || {}
_opt($o, ['p', 'params', 'Params'])
Truth table50%1/2
A
A= _opt($o, ['p', 'params', 'Params'])
Aresult
11
00
3139 1 ▶ $me->{params} = _opt($o,['p','params','Params']) || {};
Condition50%1/2
_opt($o, ['i', 'idim']) || 2
l!l
01
MC/DC0%0/1
_opt($o, ['i', 'idim']) || 2
_opt($o, ['i', 'idim'])
Truth table50%1/2
A
A= _opt($o, ['i', 'idim'])
Aresult
11
00
3140 1 ▶ $me->{idim} = _opt($o,['i','idim']) || 2;
Condition50%1/2
_opt($o, ['o', 'odim']) || 2
l!l
01
MC/DC0%0/1
_opt($o, ['o', 'odim']) || 2
_opt($o, ['o', 'odim'])
Truth table50%1/2
A
A= _opt($o, ['o', 'odim'])
Aresult
11
00
3141 1 ▶ $me->{odim} = _opt($o,['o','odim']) || 2;
Condition50%1/2
_opt($o, ['itype']) || []
l!l
01
MC/DC0%0/1
_opt($o, ['itype']) || []
_opt($o, ['itype'])
Truth table50%1/2
A
A= _opt($o, ['itype'])
Aresult
11
00
3142 1 ▶ $me->{itype} = _opt($o,['itype']) || [];
Condition50%1/2
_opt($o, ['otype']) || []
l!l
01
MC/DC0%0/1
_opt($o, ['otype']) || []
_opt($o, ['otype'])
Truth table50%1/2
A
A= _opt($o, ['otype'])
Aresult
11
00
3143 1 ▶ $me->{otype} = _opt($o,['otype']) || [];
Condition50%1/2
_opt($o, ['iunit']) || []
l!l
01
MC/DC0%0/1
_opt($o, ['iunit']) || []
_opt($o, ['iunit'])
Truth table50%1/2
A
A= _opt($o, ['iunit'])
Aresult
11
00
3144 1 ▶ $me->{iunit} = _opt($o,['iunit']) || [];
Condition50%1/2
_opt($o, ['ounit']) || []
l!l
01
MC/DC0%0/1
_opt($o, ['ounit']) || []
_opt($o, ['ounit'])
Truth table50%1/2
A
A= _opt($o, ['ounit'])
Aresult
11
00
3145 $me->{ounit} = _opt($o,['ounit']) || [];
3146 1  
3147 $me;
3148 }
3149  
3150 +======EOD_t_code ======
3151  
3152  
3153  
3154 pp_add_exported('t_cylindrical');
3155 pp_add_exported('t_radial');
3156 pp_addpm(<<'+======EOD_t_cylindrical======');
3157  
3158 =head2 t_cylindrical
3159  
3160 C<t_cylindrical> is an alias for C<t_radial>
3161  
3162 =head2 t_radial
3163  
3164 =for usage
3165  
3166 $f = t_radial(<options>);
3167  
3168 =for ref
3169  
3170 Convert Cartesian to radial/cylindrical coordinates. (2-D/3-D; with inverse)
3171  
3172 Converts 2-D Cartesian to radial (theta,r) coordinates. You can choose
3173 direct or conformal conversion. Direct conversion preserves radial
3174 distance from the origin; conformal conversion preserves local angles,
3175 so that each small-enough part of the image only appears to be scaled
3176 and rotated, not stretched. Conformal conversion puts the radius on a
3177 logarithmic scale, so that scaling of the original image plane is
3178 equivalent to a simple offset of the transformed image plane.
3179  
3180 If you use three or more dimensions, the higher dimensions are ignored,
3181 yielding a conversion from Cartesian to cylindrical coordinates, which
3182 is why there are two aliases for the same transform. If you use higher
3183 dimensionality than 2, you must manually specify the origin or you will
3184 get dimension mismatch errors when you apply the transform.
3185  
3186 Theta runs B<clockwise> instead of the more usual counterclockwise; that is
3187 to preserve the mirror sense of small structures.
3188  
3189 OPTIONS:
3190  
3191 =over 3
3192  
3193 =item d, direct, Direct
3194  
3195 Generate (theta,r) coordinates out (this is the default); incompatible
3196 with Conformal. Theta is in radians, and the radial coordinate is
3197 in the units of distance in the input plane.
3198  
3199 =item r0, c, conformal, Conformal
3200  
3201 If defined, this floating-point value causes t_radial to generate
3202 (theta, ln(r/r0)) coordinates out. Theta is in radians, and the
3203 radial coordinate varies by 1 for each e-folding of the r0-scaled
3204 distance from the input origin. The logarithmic scaling is useful for
3205 viewing both large and small things at the same time, and for keeping
3206 shapes of small things preserved in the image.
3207  
3208 =item o, origin, Origin [default (0,0,0)]
3209  
3210 This is the origin of the expansion. Pass in a PDL or an array ref.
3211  
3212 =item u, unit, Unit [default 'radians']
3213  
3214 This is the angular unit to be used for the azimuth.
3215  
3216 =back
3217  
3218 EXAMPLES
3219  
3220 These examples do transformations back into the same size image as they
3221 started from; by suitable use of the "transform" option to
3222 L</unmap> you can send them to any size array you like.
3223  
3224 Examine radial structure in M51:
3225 Here, we scale the output to stretch 2*pi radians out to the
3226 full image width in the horizontal direction, and to stretch 1 radius out
3227 to a diameter in the vertical direction.
3228  
3229 $x = rfits('m51.fits');
3230 $ts = t_linear(s => [250/2.0/3.14159, 2]); # Scale to fill orig. image
3231 $tu = t_radial(o => [130,130]); # Expand around galactic core
3232 $y = $x->map($ts x $tu);
3233  
3234 Examine radial structure in M51 (conformal):
3235 Here, we scale the output to stretch 2*pi radians out to the full image width
3236 in the horizontal direction, and scale the vertical direction by the exact
3237 same amount to preserve conformality of the operation. Notice that
3238 each piece of the image looks "natural" -- only scaled and not stretched.
3239  
3240 $x = rfits('m51.fits')
3241 $ts = t_linear(s=> 250/2.0/3.14159); # Note scalar (heh) scale.
3242 $tu = t_radial(o=> [130,130], r0=>5); # 5 pix. radius -> bottom of image
3243 $y = $ts->compose($tu)->unmap($x);
3244  
3245  
3246 1 ▶=cut
Subroutine BEGIN: called CC=1 SCAR=0.0
3247  
3248 use PDL::Constants qw(RAD2DEG);
3249 2 ▶*t_cylindrical = \&t_radial;
Subroutine t_radial: called CC=7 SCAR=20.0
Pod documented
3250 2 sub t_radial {
3251 2 ▶ my($class) = 'PDL::Transform';
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o ne "HASH") 2 0 2
3252 2 my($o) = $_[0];
3253 if (ref $o ne 'HASH') {
3254 $o = { @_ };
3255 2 }
3256  
3257 2 my($me) = $class->new;
3258  
3259 2 ▶ $me->{params}{origin} = _opt($o,['o','origin','Origin']);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $me->{"params"}{"origin"} 2 0 2
3260 2 $me->{params}{origin} = pdl(0,0)
3261 unless defined($me->{params}{origin});
3262 2 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
3263 2  
3264  
3265 2 $me->{params}{r0} = _opt($o,['r0','R0','c','conformal','Conformal']);
3266 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
3267 2 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
$me->{'params'}{'u'} =~ /^d/i ? : 0 2 2
3268 2 ▶ $me->{params}{u} = _opt($o,['u','unit','Unit'],'radians');
Branch: 1 branch
BranchTrueFalseTotal
if $PDL::Transform::debug 0 2 2
3269 ### Replace this kludge with a units call
3270 2 $me->{params}{angunit} = ($me->{params}{u} =~ m/^d/i) ? RAD2DEG : 1.0;
3271 print "radial: conversion is $me->{params}{angunit}\n" if $PDL::Transform::debug;
3272 2  
3273 2 $me->{name} = "radial (direct)";
3274  
3275 2 ▶ $me->{idim} = 2;
Branch: 1 branch
BranchTrueFalseTotal
if ($me->{'params'}{'r0'}) { } 0 2 2
3276 0 ▶ $me->{odim} = 2;
Branch: 1 branch
BranchTrueFalseTotal
$me->{'params'}{'r0'} != 1.0 ? : 0 0 0
3277 0  
3278 if ($me->{params}{r0}) {
3279 2 $me->{otype} = ["Azimuth", "Ln radius" . ($me->{params}->{r0} != 1.0 ? "/$me->{params}->{r0}" : "")];
3280 2 $me->{ounit} = [$me->{params}->{u},'']; # true-but-null prevents copying
3281 } else {
3282 $me->{otype} = ["Azimuth","Radius"];
3283 $me->{ounit} = [$me->{params}->{u},'']; # false value copies prev. unit
3284 }
3285 1 ▶ 
Subroutine __ANON__: called CC=2 SCAR=6.9
3286 $me->{func} = sub {
3287 1  
3288 my($data,$o) = @_;
3289 1  
3290 1 my($out) = ($data->new_or_inplace);
3291  
3292 1 my($d) = $data->copy;
3293 1 $d->slice("0:1") -= $o->{origin};
3294  
3295 my($d0) = $d->slice("(0)");
3296 1 my($d1) = $d->slice("(1)");
3297  
3298 # (mod operator on atan2 puts everything in the interval [0,2*PI).)
3299 1 ▶ $out->slice("(0)") .= (atan2(-$d1,$d0) % (2*PDL::Transform::PI())) * $me->{params}->{angunit};
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'r0'} ? : 0 1 1
3300  
3301 $out->slice("(1)") .= (defined $o->{r0}) ?
3302 1 0.5 * log( ($d1*$d1 + $d0 * $d0) / ($o->{r0} * $o->{r0}) ) :
3303 2 sqrt($d1*$d1 + $d0*$d0);
3304  
3305 $out;
3306 };
3307 1 ▶ 
Subroutine __ANON__: called CC=3 SCAR=11.1
3308 1 ▶ $me->{inv} = sub {
Branch: 1 branch
BranchTrueFalseTotal
$d->is_inplace ? : 0 1 1
3309  
3310 my($d,$o) = @_;
3311 my($d0,$d1,$out)=
3312 ( ($d->is_inplace) ?
3313 ($d->slice("(0)")->copy, $d->slice("(1)")->copy->dummy(0,2), $d) :
3314 1 ($d->slice("(0)"), $d->slice("(1)")->dummy(0,2), $d->copy)
3315 );
3316 1  
3317 1 $d0 /= $me->{params}->{angunit};
3318 1 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'r0'} ? : 0 1 1
3319 1 my($os) = $out->slice("0:1");
3320 $os .= append(cos($d0)->dummy(0,1),-sin($d0)->dummy(0,1));
3321 1 $os *= defined $o->{r0} ? ($o->{r0} * exp($d1)) : $d1;
3322 2 $os += $o->{origin};
3323  
3324 2 $out;
3325 };
3326  
3327  
3328 $me;
3329 }
3330  
3331 +======EOD_t_cylindrical======
3332  
3333 pp_add_exported('t_quadratic');
3334 pp_addpm(<<'+======EOD_t_quadratic======');
3335  
3336 =head2 t_quadratic
3337  
3338 =for usage
3339  
3340 $t = t_quadratic(<options>);
3341  
3342 =for ref
3343  
3344 Quadratic scaling -- cylindrical pincushion (n-d; with inverse)
3345  
3346 Quadratic scaling emulates pincushion in a cylindrical optical system:
3347 separate quadratic scaling is applied to each axis. You can apply
3348 separate distortion along any of the principal axes. If you want
3349 different axes, use L</t_wrap> and L</t_linear> to rotate
3350 them to the correct angle. The scaling options may be scalars or
3351 vectors; if they are scalars then the expansion is isotropic.
3352  
3353 The formula for the expansion is:
3354  
3355 f(a) = ( <a> + <strength> * a^2/<L_0> ) / (abs(<strength>) + 1)
3356  
3357 where <strength> is a scaling coefficient and <L_0> is a fundamental
3358 length scale. Negative values of <strength> result in a pincushion
3359 contraction.
3360  
3361 Note that, because quadratic scaling does not have a strict inverse for
3362 coordinate systems that cross the origin, we cheat slightly and use
3363 $x * abs($x) rather than $x**2. This does the Right thing for pincushion
3364 and barrel distortion, but means that t_quadratic does not behave exactly
3365 like t_cubic with a null cubic strength coefficient.
3366  
3367 OPTIONS
3368  
3369 =over 3
3370  
3371 =item o,origin,Origin
3372  
3373 The origin of the pincushion. (default is the, er, origin).
3374  
3375 =item l,l0,length,Length,r0
3376  
3377 The fundamental scale of the transformation -- the radius that remains
3378 unchanged. (default=1)
3379  
3380 =item s,str,strength,Strength
3381  
3382 The relative strength of the pincushion. (default = 0.1)
3383  
3384 =item d, dim, dims, Dims
3385  
3386 The number of dimensions to quadratically scale (default is the
3387 dimensionality of your input vectors)
3388  
3389  
3390 =back
3391  
3392 =cut
3393 2 ▶ 
Subroutine t_quadratic: called CC=2 SCAR=7.1
Pod documented
3394 2 sub t_quadratic {
3395 2 ▶ my($class) = 'PDL::Transform';
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o ne "HASH") 2 0 2
3396 2 my($o) = $_[0];
3397 if (ref $o ne 'HASH') {
3398 2 $o = {@_};
3399 }
3400 2 my($me) = $class->new;
3401 2  
3402 2 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3403 2 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
3404 2 $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
3405 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
3406 $me->{name} = "quadratic";
3407 1 ▶ 
Subroutine __ANON__: called CC=3 SCAR=11.7
3408 1 $me->{func} = sub {
3409 1 ▶ my($data,$o) = @_;
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'dim'} ? : 0 1 1
3410 1 my($dd) = $data->copy - $o->{origin};
3411 1 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3412 1 $d += $o->{str} * ($d * abs($d)) / $o->{l0};
3413 1 ▶ $d /= (abs($o->{str}) + 1);
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) 0 1 1
3414 0 $d += $o->{origin};
3415 0 if ($data->is_inplace) {
3416 $data .= $dd;
3417 1 return $data;
3418 2 }
3419 $dd;
3420 };
3421 1 ▶ 
Subroutine __ANON__: called CC=3 SCAR=11.4
3422 1 $me->{inv} = sub {
3423 1 ▶ my($data,$opt) = @_;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'dim'} ? : 0 1 1
3424 1 my($dd) = $data->copy ;
3425 1 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
3426 1 my($o) = $opt->{origin};
3427 my($s) = $opt->{str};
3428 1 my($l) = $opt->{l0};
3429  
3430 1 $d .= ((-1 + sqrt(1 + 4 * $s/$l * abs($d-$o) * (1+abs($s))))
3431 1 ▶ / 2 / $s * $l) * (1 - 2*($d < $o));
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) 0 1 1
3432 0 $d += $o;
3433 0 if ($data->is_inplace) {
3434 $data .= $dd;
3435 1 return $data;
3436 2 }
3437 2 $dd;
3438 };
3439 $me;
3440 }
3441  
3442 +======EOD_t_quadratic======
3443  
3444 pp_add_exported('t_cubic');
3445 pp_addpm(<<'+======EOD_t_cubic=======');
3446  
3447 =head2 t_cubic
3448  
3449 =for usage
3450  
3451 $t = t_cubic(<options>);
3452  
3453 =for ref
3454  
3455 Cubic scaling - cubic pincushion (n-d; with inverse)
3456  
3457 Cubic scaling is a generalization of t_quadratic to a purely
3458 cubic expansion.
3459  
3460 The formula for the expansion is:
3461  
3462 f(a) = ( a' + st * a'^3/L_0^2 ) / (1 + abs(st)) + origin
3463  
3464 where a'=(a-origin). That is a simple pincushion
3465 expansion/contraction that is fixed at a distance of L_0 from the
3466 origin.
3467  
3468 Because there is no quadratic term the result is always invertible with
3469 one real root, and there is no mucking about with complex numbers or
3470 multivalued solutions.
3471  
3472  
3473 OPTIONS
3474  
3475 =over 3
3476  
3477 =item o,origin,Origin
3478  
3479 The origin of the pincushion. (default is the, er, origin).
3480  
3481 =item l,l0,length,Length,r0
3482  
3483 The fundamental scale of the transformation -- the radius that remains
3484 unchanged. (default=1)
3485  
3486 =item d, dim, dims, Dims
3487  
3488 The number of dimensions to treat (default is the
3489 dimensionality of your input vectors)
3490  
3491 =back
3492  
3493 =cut
3494  
3495 4 ▶# needed since due to floating-point approx, is not *exactly* a cube-root
Subroutine _cuberoot: called CC=1 SCAR=0.0
3496 4 sub _cuberoot {
3497 4 my $x = shift;
3498 my $as = 1 - 2*($x<0);
3499 return $as * (abs($x) ** (1/3));
3500 };
3501  
3502 # solve:
3503 # A x^3 + B x^2 + C x + D = 0
3504 # B is zero so this is greatly simplified; the discriminant is always negative
3505 2 ▶# so there is always exactly one real root.
Subroutine _solve_depressed_cubic: called CC=1 SCAR=0.0
3506 2 sub _solve_depressed_cubic {
3507 2 my ($A, $C, $D) = @_;
3508 2 my $alpha = 27 * $A * $A * $D;
3509 2 my $beta = 3 * $A * $C;
3510 my $inner_root = sqrt( $alpha * $alpha + 4 * $beta * $beta * $beta );
3511 (-1 / (3 * $A)) *
3512 (
3513 + _cuberoot( 0.5 * ( $alpha + $inner_root ) )
3514 + _cuberoot( 0.5 * ( $alpha - $inner_root ) )
3515 )
3516 }
3517 2 ▶ 
Subroutine t_cubic: called CC=2 SCAR=7.1
Pod documented
3518 2 sub t_cubic {
3519 2 ▶ my ($class) = 'PDL::Transform';
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o ne "HASH") 2 0 2
3520 2 my($o) = $_[0];
3521 if (ref $o ne 'HASH') {
3522 2 $o = {@_};
3523 }
3524 2 my($me) = $class->new;
3525 2  
3526 2 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims'],undef);
3527 2 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3528 2 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
3529 $me->{params}->{st} = _opt($o,['s','st','str'],pdl(0));
3530 $me->{name} = "cubic";
3531 1 ▶ 
Subroutine __ANON__: called CC=3 SCAR=11.4
3532 1 $me->{func} = sub {
3533 1 ▶ my($data,$o) = @_;
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'dim'} ? : 0 1 1
3534 my($dd) = $data->copy;
3535 1 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3536  
3537 1 $d -= $o->{origin};
3538  
3539 my $dl0 = $d / $o->{l0};
3540  
3541 # f(x) = x + x**3 * ($o->{st} / $o->{l0}**2):
3542 # A = ($o->{st}/$dl0**2)
3543 # B = 0
3544 1 # C = 1
3545 1 # D = -f(x)
3546 $d += $o->{st} * $d * $dl0 * $dl0;
3547 1 $d /= ($o->{st}**2 + 1);
3548  
3549 1 ▶ $d += $o->{origin};
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) 0 1 1
3550 0  
3551 0 if ($data->is_inplace) {
3552 $data .= $dd;
3553 1 return $data;
3554 2 }
3555 return $dd;
3556 };
3557 1 ▶ 
Subroutine __ANON__: called CC=3 SCAR=11.4
3558 1 $me->{inv} = sub {
3559 my($data,$o) = @_;
3560 1 my($l) = $o->{l0};
3561 1 ▶ 
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'dim'} ? : 0 1 1
3562 my($dd) = $data->copy;
3563 1 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3564 1  
3565 $d -= $o->{origin};
3566 $d *= ($o->{st}+1);
3567 1  
3568 # First: create coefficients for mnemonics.
3569 1 my ($A, $C, $D) = ( $o->{st} / $l / $l, 1, - $d );
3570  
3571 1 $d .= _solve_depressed_cubic($A, $C, $D);
3572  
3573 1 ▶ $d += $me->{params}{origin};
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) { } 0 1 1
3574 0  
3575 0 if ($data->is_inplace) {
3576 $data .= $dd;
3577 1 return $data;
3578 } else {
3579 2 return $dd;
3580 }
3581 2 };
3582  
3583 $me;
3584 }
3585  
3586 +======EOD_t_cubic=======
3587  
3588  
3589 pp_add_exported('t_quartic');
3590 pp_addpm(<<'======EOD_t_quartic======');
3591  
3592 =head2 t_quartic
3593  
3594 =for usage
3595  
3596 $t = t_quartic(<options>);
3597  
3598 =for ref
3599  
3600 Quartic scaling -- quartic pincushion (n-d; with inverse)
3601  
3602 Quartic scaling is a generalization of t_quadratic to a quartic
3603 expansion. Only even powers of the input coordinates are retained,
3604 and (as with t_quadratic) sign is preserved, making it an odd function
3605 although a true quartic transformation would be an even function.
3606  
3607 You can apply separate distortion along any of the principal axes. If
3608 you want different axes, use L</t_wrap> and
3609 L</t_linear> to rotate them to the correct angle. The
3610 scaling options may be scalars or vectors; if they are scalars then
3611 the expansion is isotropic.
3612  
3613 The formula for the expansion is:
3614  
3615 f(a) = ( <a> + <strength> * a^4/<L_0>^3 ) / (abs(<strength>) + 1)
3616  
3617 where <strength> is a scaling coefficient and <L_0> is a fundamental
3618 length scale. Negative values of <strength> result in a pincushion
3619 contraction.
3620  
3621 Note that, because quartic scaling does not have a strict inverse for
3622 coordinate systems that cross the origin, we cheat slightly and use
3623 $x**3 * abs($x) rather than $x**4. This does the Right thing for pincushion
3624 and barrel distortion.
3625  
3626 OPTIONS
3627  
3628 =over 3
3629  
3630 =item o,origin,Origin
3631  
3632 The origin of the pincushion. (default is the, er, origin).
3633  
3634 =item l,l0,length,Length,r0
3635  
3636 The fundamental scale of the transformation -- the radius that remains
3637 unchanged. (default=1)
3638  
3639 =item s,str,strength,Strength
3640  
3641 The relative strength of the pincushion. (default = 0.1)
3642  
3643 =item d, dim, dims, Dims
3644  
3645 The number of dimensions to quartically scale (default is the
3646 dimensionality of your input vectors)
3647  
3648 =back
3649  
3650 =cut
3651  
3652 # like sub _solve_depressed_cubic but for multi real solutions, returns 1
3653 # uses https://en.wikipedia.org/wiki/Casus_irreducibilis#Trigonometric_solution_in_terms_of_real_quantities
3654 0 ▶sub _solve_depressed_cubic_multi {
Subroutine _solve_depressed_cubic_multi: not called CC=2 SCAR=17.9
3655 0 require PDL::Math;
3656 0 ▶ my ($p, $q) = @_;
Branch: 1 branch
BranchTrueFalseTotal
if $p->ge(0)->any 0 0 0
3657 0 barf "inverse t_quartic: \$p must be negative" if $p->ge(0)->any;
3658 0 my $acos = PDL::Math::acos(3*$q/(2*$p) * sqrt(-3/$p));
3659 0 my $cos = cos($acos/3);
3660 2 * sqrt(-$p/3) * $cos;
3661 }
3662  
3663 2 ▶sub t_quartic {
Subroutine t_quartic: called CC=2 SCAR=7.0
Pod documented
3664 2 my($class) = 'PDL::Transform';
3665 2 ▶ my($o) = $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o ne "HASH") 2 0 2
3666 2 if (ref $o ne 'HASH') {
3667 $o = {@_};
3668 2 }
3669 my($me) = $class->new;
3670 2  
3671 2 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3672 2 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
3673 2 $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
3674 2 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
3675 $me->{name} = "quartic";
3676  
3677 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
3678 1 my($data,$o) = @_;
3679 1 ▶ my($dd) = $data->copy - $o->{origin};
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'dim'} ? : 0 1 1
3680 1 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3681 1 $d += $o->{str} * ($d**3 * abs($d)) / ($o->{l0} ** 3);
3682 1 $d /= (abs($o->{str}) + 1);
3683 1 ▶ $d += $o->{origin};
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) 0 1 1
3684 0 if ($data->is_inplace) {
3685 0 $data .= $dd;
3686 return $data;
3687 1 }
3688 2 $dd;
3689 };
3690  
3691 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
3692 1 my($data,$opt) = @_;
3693 1 ▶ my($dd) = $data->copy ;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'dim'} ? : 0 1 1
3694 1 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
3695 1 my($o) = $opt->{origin};
3696 1 my($s) = $opt->{str};
3697 my($l) = $opt->{l0};
3698  
3699 # Formula (ignoring the sign-preserve, since the xform
3700 # always moves away from origin):
3701 # sdiv = (abs(s) + 1)
3702 # b = ( <a> + <strength> * a^4/<L_0>^3 ) / (abs(<strength>) + 1)
3703 # = (a + s*a^4/L^3) / sdiv
3704 # b * sdiv = a + s*a^4/L^3
3705 # a + s*a^4/L^3 - b * sdiv = 0
3706 # a^4*s/L^3 + a - b * sdiv = 0 # ordered by degree
3707 # A = s/L^3
3708 # B = 1
3709 # C = -b * sdiv
3710 1  
3711 1 my $sign = (1 - 2*($d < $o));
3712 my ($A, $B, $C) = ($s/($l ** 3), 1, -abs($d-$o) * (1+abs($s)));
3713  
3714 # Roots are (https://math.stackexchange.com/questions/3658305/is-there-formula-that-solves-quartic-equation-ax4bxc-0):
3715 # x = s +- sqrt(-B/4As - s^2)
3716 # where s^2 = S satisfies cubic equation:
3717 # S^3 - S*C/4A - (B/8A)^2 = 0
3718 1  
3719 1 my $p = -$C / (4*$A);
3720 1 my $q = -($B/(8*$A)) ** 2;
3721 1 my $S = _solve_depressed_cubic(1, $p, $q);
3722 1 my $sqrt_S = sqrt($S);
3723 my $x = -$sqrt_S + sqrt($B / (4*$A*$sqrt_S) - $S);
3724 1  
3725 1 $d .= $x * $sign;
3726 1 ▶ $d += $o;
Branch: 1 branch
BranchTrueFalseTotal
if ($data->is_inplace) 0 1 1
3727 0 if ($data->is_inplace) {
3728 0 $data .= $dd;
3729 return $data;
3730 1 }
3731 2 $dd;
3732 2 };
3733 $me;
3734 }
3735  
3736 ======EOD_t_quartic======
3737  
3738 pp_add_exported('t_spherical');
3739 pp_addpm(<<'+======EOD_t_spherical======');
3740  
3741 =head2 t_spherical
3742  
3743 =for usage
3744  
3745 $t = t_spherical(<options>);
3746  
3747 =for ref
3748  
3749 Convert Cartesian to spherical coordinates. (3-D; with inverse)
3750  
3751 Convert 3-D Cartesian to spherical (theta, phi, r) coordinates. Theta
3752 is longitude, centered on 0, and phi is latitude, also centered on 0.
3753 Unless you specify Euler angles, the pole points in the +Z direction
3754 and the prime meridian is in the +X direction. The default is for
3755 theta and phi to be in radians; you can select degrees if you want
3756 them.
3757  
3758 Just as the L</t_radial> 2-D transform acts like a 3-D
3759 cylindrical transform by ignoring third and higher dimensions,
3760 Spherical acts like a hypercylindrical transform in four (or higher)
3761 dimensions. Also as with L</t_radial>, you must manually specify
3762 the origin if you want to use more dimensions than 3.
3763  
3764 To deal with latitude & longitude on the surface of a sphere (rather
3765 than full 3-D coordinates), see
3766 L<t_unit_sphere|PDL::Transform::Cartography/t_unit_sphere>.
3767  
3768 OPTIONS:
3769  
3770 =over 3
3771  
3772 =item o, origin, Origin [default (0,0,0)]
3773  
3774 This is the Cartesian origin of the spherical expansion. Pass in a PDL
3775 or an array ref.
3776  
3777 =item e, euler, Euler [default (0,0,0)]
3778  
3779 This is a 3-vector containing Euler angles to change the angle of the
3780 pole and ordinate. The first two numbers are the (theta, phi) angles
3781 of the pole in a (+Z,+X) spherical expansion, and the last is the
3782 angle that the new prime meridian makes with the meridian of a simply
3783 tilted sphere. This is implemented by composing the output transform
3784 with a PDL::Transform::Linear object.
3785  
3786 =item u, unit, Unit (default radians)
3787  
3788 This option sets the angular unit to be used. Acceptable values are
3789 "degrees","radians", or reasonable substrings thereof (e.g. "deg", and
3790 "rad", but "d" and "r" are deprecated). Once genuine unit processing
3791 comes online (a la Math::Units) any angular unit should be OK.
3792  
3793 =back
3794  
3795 =cut
3796  
3797 1 ▶sub t_spherical {
Subroutine t_spherical: called CC=5 SCAR=16.5
Pod documented
3798 1 my($class) = 'PDL::Transform';
3799 1 ▶ my($o) = $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if (ref $o ne "HASH") 1 0 1
3800 1 if (ref $o ne 'HASH') {
3801 $o = { @_ } ;
3802 }
3803 1  
3804 my($me) = $class->new;
3805 1  
3806 1 $me->{idim}=3;
3807 $me->{odim}=3;
3808 1  
3809 1 ▶ $me->{params}->{origin} = _opt($o,['o','origin','Origin']);
Condition33%1/3
$me->{"params"}{"origin"} //= "PDL"->zeroes(3)
l!l&&r!l&&!r
010
MC/DC0%0/2
$me->{"params"}{"origin"} //= "PDL"->zeroes(3)
$me->{"params"}{"origin"} "PDL"->zeroes(3)
Truth table33%1/3
A //= B
A= $me->{"params"}{"origin"}B= "PDL"->zeroes(3)
ABresult
1X1
011
000
3810 1 $me->{params}->{origin} //= PDL->zeroes(3);
3811 $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});
3812 1  
3813 $me->{params}->{deg} = _opt($o,['d','degrees','Degrees']);
3814 1  
3815 1 ▶ my $unit = _opt($o,['u','unit','Unit']);
Branch: 1 branch
BranchTrueFalseTotal
$unit && $unit =~ /^d/i ? : 0 1 1
Condition33%1/3
$unit and $unit =~ /^d/i
!ll&&!rl&&r
100
MC/DC0%0/2
$unit and $unit =~ /^d/i
$unit $unit =~ /^d/i
Truth table33%1/3
A and B
A= $unitB= $unit =~ /^d/i
ABresult
0X0
100
111
3816 $me->{params}{angunit} = ($unit && $unit =~ m/^d/i) ?
3817 DEG2RAD() : undef;
3818 1  
3819 $me->{name} = "spherical";
3820  
3821 1 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
3822 1 my ($data,$o) = @_;
3823 1 my $d = $data->copy - $o->{origin};
3824 1 ▶ my ($d0,$d1,$d2) = ($d->slice("(0)"),$d->slice("(1)"),$d->slice("(2)"));
Branch: 1 branch
BranchTrueFalseTotal
$d->is_inplace ? : 0 1 1
3825 1 my $out = ($d->is_inplace) ? $data : $data->copy;
3826 1 $out->slice("(0)") .= PDL::atan2($d1, $d0);
3827 1 $out->slice("(2)") .= PDL::sqrt($d0*$d0 + $d1*$d1 + $d2*$d2);
3828 $out->slice("(1)") .= PDL::asin($d2 / $out->slice("(2)"));
3829 1 ▶ $out->slice("0:1") /= $o->{angunit}
Branch: 1 branch
BranchTrueFalseTotal
if defined $o->{"angunit"} 0 1 1
3830 1 if defined $o->{angunit};
3831 1 $out;
3832 };
3833  
3834 1 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
3835 1 ▶ my ($d,$o) = @_;
Condition50%1/2
$o->{"angunit"} // 1
l!l
01
MC/DC0%0/1
$o->{"angunit"} // 1
$o->{"angunit"}
Truth table50%1/2
A
A= $o->{"angunit"}
Aresult
11
00
3836 1 PDL::t_spherical_inv($d, $o->{origin}, $o->{angunit} // 1);
3837 };
3838 1  
3839 $me;
3840 }
3841 +======EOD_t_spherical======
3842 pp_def('t_spherical_inv',
3843 Pars => 'in(tri=3); origin(tri); [o] out(tri)',
3844 OtherPars => 'PDL_Anyval angunit',
3845 OtherParsDefaults => {angunit=>'(PDL_Anyval){ PDL_CLD, {.H=1} }'},
3846 Inplace => [qw(in out)],
3847 GenericTypes => $ALL,
3848 Code => <<'EOF',
3849 PDL_CLDouble angunit;
3850 ANYVAL_TO_CTYPE(angunit, PDL_CLDouble, $COMP(angunit));
3851 broadcastloop %{
3852 PDL_CLDouble theta = angunit * $in(tri=>0), phi = angunit * $in(tri=>1), r = $in(tri=>2);
3853 $out(tri=>2) = r * sin(phi);
3854 PDL_CLDouble x = $out(tri=>0) = r * cos(phi);
3855 $out(tri=>1) = x * sin(theta);
3856 $out(tri=>0) *= cos(theta);
3857 loop(tri) %{ $out() += $origin(); %}
3858 %}
3859 EOF
3860 Doc => undef,
3861 );
3862  
3863 pp_add_exported('t_projective');
3864 pp_addpm(<<'+======EOD_t_projective======');
3865  
3866 =head2 t_projective
3867  
3868 =for usage
3869  
3870 $t = t_projective(<options>);
3871  
3872 =for ref
3873  
3874 Projective transformation
3875  
3876 Projective transforms are simple quadratic, quasi-linear
3877 transformations. They are the simplest transformation that
3878 can continuously warp an image plane so that C<ncoords + 2> arbitrarily chosen
3879 points exactly map to the same number of other arbitrarily chosen points. They
3880 have the property that straight lines remain straight after transformation.
3881  
3882 =for example
3883  
3884 # perspective projection 3D -> 2D
3885 $t_proj = t_projective(
3886 src => pdl('1 1 1; -1 1 1; -1 -1 1; 1 -1 1; 2 2 2; -2 -2 2'),
3887 dst => pdl('0 1000; 1000 1000; 1000 0; 0 0; 0 1000; 1000 0'),
3888 );
3889 # orthographic projection 3D -> 2D
3890 # warning, numerically unstable as the Direct Linear Transform
3891 # is for perspective not this
3892 $t_proj = t_projective(
3893 # near top-left, near top-right, near bottom-left near bottom-right
3894 # far middle, far mid-right
3895 src => my $src32 = pdl('-1 1 -1; 1 1 -1; -1 -1 -1; 1 -1 -1; 0 0 1; 1 0 1'),
3896 dst => my $dst32 = pdl('0 0; 1000 0; 0 1000; 1000 1000; 500 500; 1000 500'),
3897 );
3898  
3899 You can specify your projective transformation directly in homogeneous
3900 coordinates, or (as of 2.104, not just in 2 dimensions) as a set
3901 of unique points that
3902 are mapped one to the other by the transformation.
3903  
3904 Projective transforms are quasi-linear because they are most easily
3905 described as a linear transformation in homogeneous coordinates
3906 (e.g. (x',y',w) where w is a normalization factor: x = x'/w, etc.).
3907 In those coordinates, an N-D projective transformation is represented
3908 as simple multiplication of an N+1-vector by an M+1 x N+1 matrix,
3909 whose lower-right corner value is 1.
3910  
3911 If the bottom row of the matrix consists of all zeroes, then the
3912 transformation reduces to a linear affine transformation (as in
3913 L</t_linear>).
3914  
3915 If the bottom row of the matrix contains nonzero elements, then the
3916 transformed x,y,z,etc. coordinates are related to the original coordinates
3917 by a quadratic polynomial, because the normalization factor 'w' allows
3918 a second factor of x,y, and/or z to enter the equations.
3919  
3920 OPTIONS:
3921  
3922 =over 3
3923  
3924 =item m, mat, matrix, Matrix
3925  
3926 If specified, this is the homogeneous-coordinate matrix to use.
3927 Works with non-square matrix, so M+1 x N+1, for an N-to-M-dimensional
3928 transformation.
3929  
3930 =item src, from, I<and> dst, to
3931  
3932 If specified, this is the sets of points that should be mapped one
3933 to the other. Both C<src> and C<dst> must have the same number of
3934 points (C<N>).
3935 That number must be, where C<m,n> are the number of destination, source
3936 dimensions: C<((m+1)*(n+1)-1)/n>.
3937 The ndarrays are dimensioned C<(coords,N)>.
3938 The homogeneous-coordinate matrix is calculated from them.
3939 For example, specifying
3940  
3941 src => pdl([ [0,0], [0,1], [5,9], [9,4] ])
3942 dst => pdl([ [0,0], [0,1], [5,8], [9,3] ])
3943  
3944 maps the origin and the point (0,1) to themselves, the point (5,9)
3945 to (5,8), and the point (9,4) to (9,3).
3946  
3947 Added in 2.104. Works on any number of dimensions.
3948  
3949 =item p, point, points, Points
3950  
3951 You are encouraged to use the more general C<src,dst> options given above.
3952  
3953 If specified, this is the set of C<ncoords + 2> points that should
3954 be mapped one to the other. Feed in a
3955 C<2 x 2 x 4> PDL, where the 0 dimension runs over
3956 coordinate, the 1 dimension runs between input
3957 and output, and the 2 dimension runs over points. For example, specifying
3958  
3959 p => pdl([ [[0,0],[0,0]], [[0,1],[0,1]], [[5,9],[5,8]], [[9,4],[9,3]] ])
3960  
3961 maps the origin and the point (0,1) to themselves, the point (5,9)
3962 to (5,8), and the point (9,4) to (9,3).
3963  
3964 This is similar to the behavior of fitwarp2d with a quadratic polynomial.
3965  
3966 =back
3967  
3968 =cut
3969  
3970 0 ▶sub sub_eps_to_0 {
Subroutine sub_eps_to_0: not called CC=1 SCAR=6.9
Pod undocumented
3971 0 my ($m, $eps) = @_;
3972 $m * (abs($m) > $eps)
3973 }
3974  
3975 12 ▶sub _normalise_points {
Subroutine _normalise_points: called CC=1 SCAR=0.0
3976 12 my ($pts) = @_;
3977 12 my $d = $pts->dim(0); # pts: (dim,N) matrix where each row is a point
3978 12 my $centroid = $pts->t->avgover;
3979 my $shifted = $pts - $centroid; # shift points to origin
3980 12 # 2. Scale so average distance to origin is sqrt(dim)
3981 my $scale = sqrt($d) / avg($shifted->magnover); # keep coord vals close to 1
3982 12 # T combines scaling and translation: T = Scale * Translate
3983 12 my $T = identity($d + 1);
3984 12 $T->diagonal(0,1)->slice(":-2") .= $scale;
3985 12 $T->slice("(-1),:-2") .= -$scale * $centroid;
3986 12 my $pts_h = $pts->append(1) x $T->t; # Convert to homogeneous coords, apply T
3987 ($pts_h, $T);
3988 }
3989  
3990 6 ▶sub block_rotate :lvalue {
Subroutine block_rotate: called CC=2 SCAR=7.0
Pod undocumented
3991 6 ▶ my ($m, $width) = @_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $width 0 6 6
3992 6 die "block_rotate: given undef width" if !defined $width;
3993 6 my $height = $m->dim(1);
3994 $m->rotate(-$width*sequence(indx,$height))->slice('0:'.($width-1));
3995 }
3996  
3997 # Construct the system of N equations to find the projective transform
3998 6 ▶sub construct_DLT {
Subroutine construct_DLT: called CC=2 SCAR=6.9
Pod undocumented
3999 6 ▶ my ($pts_src, $pts_dst) = @_;
Branch: 1 branch
BranchTrueFalseTotal
unless $pts_src->dim(1) == $pts_dst->dim(1) 0 6 6
4000 die "t_projective: must supply same number of src and dst points\n"
4001 6 unless $pts_src->dim(1) == $pts_dst->dim(1);
4002 6 my ($pts_src_h, $T_src) = _normalise_points($pts_src); # (n+1,N) homogeneous
4003 6 my ($pts_dst_h, $T_dst) = _normalise_points($pts_dst); # (m+1,N) homogeneous
4004 6 my ($src_dim, $N) = $pts_src_h->dims; # n+1
4005 6 my ($dst_dim) = $pts_dst_h->dims; # m+1
4006 6 my $num_eqs = $N * ($dst_dim - 1); # Each point match provides (m) equations
4007 6 my $num_vars = $src_dim * $dst_dim;
4008 my $A = zeroes($num_vars-$src_dim, $num_eqs);
4009 # Mapping: xp_last * (P_j * x) - xp_j * (P_last * x) = 0
4010 6 # Fill coefficients for the j-th row of P
4011 6 my $mult = $pts_dst_h->slice(-1) * $pts_src_h;
4012 block_rotate($A, $src_dim) .= $mult->dummy(1,$dst_dim-1)->clump(1,2);
4013 6 # Fill coefficients for the last row of P
4014 6 $A = $A->append(-outer($pts_src_h, $pts_dst_h->slice(":-2"))->clump(1,2));
4015 ($A, $T_src, $T_dst);
4016 }
4017  
4018 5 ▶sub solve_DLT {
Subroutine solve_DLT: called CC=1 SCAR=0.0
Pod undocumented
4019 5 my ($A, $T_src, $T_dst) = @_;
4020 5 my ($U, $S, $V) = svd($A, 1); # full SVD
4021 5 my $P_norm = $V->slice(-1)->reshape(map $_->dim(0), $T_src, $T_dst); # reshape smallest singular value vector
4022 $T_dst->inv x $P_norm x $T_src; # Denormalize
4023 }
4024  
4025 6 ▶sub t_projective {
Subroutine t_projective: called CC=11 SCAR=24.4
Pod documented
4026 6 ▶ my $class = 'PDL::Transform';
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 6 6
4027 my $o = ref $_[0] eq 'HASH' ? $_[0] : { @_ };
4028 6  
4029 6 my $me = $class->new;
4030 $me->{name} = "projective";
4031  
4032 6 ### Set options...
4033 $me->{params}{idim} = $me->{idim} = _opt($o,['d','dim','Dim']);
4034 6  
4035 6 ▶ my $matrix;
Branch: 1 branch
BranchTrueFalseTotal
if (defined($matrix = _opt($o, ['m', 'matrix', 'Matrix']))) { } 1 5 6
4036 1 if (defined ($matrix=_opt($o,['m','matrix','Matrix']))) {
4037 1 ▶ $matrix = PDL->topdl($matrix);
Condition33%1/3
$me->{"params"}{"idim"} //= $matrix->dim(0) - 1
l!l&&r!l&&!r
010
MC/DC0%0/2
$me->{"params"}{"idim"} //= $matrix->dim(0) - 1
$me->{"params"}{"idim"} $matrix->dim(0) - 1
Truth table33%1/3
A //= B
A= $me->{"params"}{"idim"}B= $matrix->dim(0) - 1
ABresult
1X1
011
000
4038 $me->{params}{idim} //= $matrix->dim(0)-1;
4039 1 ▶ die "t_projective: matrix not compatible with given dimension (should be N+1xN+1)\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $me->{"params"}{"idim"} == $matrix->dim(0) - 1 0 1 1
4040 unless $me->{params}{idim} == $matrix->dim(0)-1;
4041 5 } else {
4042 5 ▶ my ($p, $pts_src, $pts_dst) = _opt($o,['p','point','points','Point','Points']);
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p) { } 1 4 5
4043 1 if (defined $p) {
4044 1 ▶ $p = PDL->topdl($p);
Branch: 1 branch
BranchTrueFalseTotal
unless $p->dims == 3 and all($p->shape == pdl(2, 2, 4)) 0 1 1
Condition33%1/3
$p->dims == 3 and all($p->shape == pdl(2, 2, 4))
!ll&&!rl&&r
001
MC/DC0%0/2
$p->dims == 3 and all($p->shape == pdl(2, 2, 4))
$p->dims == 3 all($p->shape == pdl(2, 2, 4))
Truth table33%1/3
A and B
A= $p->dims == 3B= all($p->shape == pdl(2, 2, 4))
ABresult
0X0
100
111
4045 die "t_projective: points must be ncoord x 2(in,out) x ncoord+2(point)"
4046 1 unless $p->dims==3 && all($p->shape == pdl(2,2,4));
4047 ($pts_src, $pts_dst) = $p->mv(1,-1)->dog;
4048 4 } else {
4049 ($pts_src, $pts_dst) = map _opt($o,$_), ['src','from'], ['dst','to'];
4050 5 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if grep((!defined($_)), $pts_src, $pts_dst) 0 5 5
4051 die "t_projective: must supply either 'p', 'm', or 'src' and 'dst' options"
4052 5 if grep !defined, $pts_src, $pts_dst;
4053 my ($A, $T_src, $T_dst) = construct_DLT($pts_src, $pts_dst);
4054 5 # Solve the system
4055 $matrix = solve_DLT($A, $T_src, $T_dst);
4056 6 }
4057 6 ▶ $me->{params}{matrix} = $matrix;
Branch: 1 branch
BranchTrueFalseTotal
if $matrix->dim(0) == $matrix->dim(1) 3 3 6
4058 $me->{params}{matinv} = $matrix->inv if $matrix->dim(0) == $matrix->dim(1);
4059 6 ▶ 
Condition100%2/2
$me->{"params"}{"idim"} //= 2
l!l
15
MC/DC100%1/1
$me->{"params"}{"idim"} //= 2
$me->{"params"}{"idim"}
Truth table100%2/2
A
A= $me->{"params"}{"idim"}
Aresult
11
00
4060 $me->{idim} = $me->{odim} = $me->{params}{odim} = $me->{params}{idim} //= 2;
4061  
4062 5 ▶ $me->{func} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4063 5 my ($data,$o) = @_;
4064 5 my $out = $data->append(1) x $o->{matrix}->t;
4065 6 $out->slice("0:-2")/$out->slice("-1");
4066 };
4067  
4068 2 ▶ $me->{inv} = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
4069 my ($data,$o) = @_;
4070 2 ▶ die "t_projective: uninvertible projection due to dimension change"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $o->{"matinv"} 0 2 2
4071 2 if !defined $o->{matinv};
4072 2 my $out = $data->append(1) x $o->{matinv}->t;
4073 6 $out->slice("0:-2")/$out->slice("-1");
4074 };
4075 6  
4076 $me;
4077 }
4078  
4079 +======EOD_t_projective======
4080  
4081 pp_done();
« blib/lib/PDL/IO/FITS.pm ↑ Summary lib/PDL/MatrixOps.pd »