lib/PDL/Transform.pd

filter: Statementstmt 98.7% 386 / 391 Branchbran 21.7% 452 / 2082 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 33.8% 838 / 2473 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« lib/PDL/IO/Pnm-pp-pnmout.c ↑ Summary lib/PDL/Primitive-pp-pchip_chbs.c »
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  
242 use strict;
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 package PDL::Transform;
261 use Carp;
262 use overload '""' => \&_strval;
263 use overload 'x' => \&_compose_op;
264 use overload '**' => \&_pow_op;
265 use overload '!' => \&t_inverse;
266  
267 use PDL::LiteF;
268 use PDL::MatrixOps;
269 use PDL::Constants qw(PI DEG2RAD);
270  
271 #### little helper kludge parses a list of synonyms
272 sub _opt {
273 my ($hash, $synonyms, $alt) = @_; # default $alt is undef -- ok.
274 return $alt if !(my ($s) = grep defined $hash->{$_}, @$synonyms);
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 sub _strval {
286 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 sub stringify {
296 my($me) = shift;
297 my($mestr) = (ref $me);
298 $mestr =~ s/PDL::Transform:://;
299 my $out = $mestr . " (" . $me->{name} . "): ";
300 $out .= "fwd ". ((defined ($me->{func})) ? ( (ref($me->{func}) eq 'CODE') ? "ok" : "non-CODE(!!)" ): "missing")."; ";
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  
332 use Carp;
333  
334 *PDL::apply = \&apply;
335 sub apply {
336 my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
337 croak "apply requires both a PDL and a PDL::Transform.\n"
338 unless UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL');
339 croak "Applying a PDL::Transform with no func! Oops.\n"
340 unless(defined($me->{func}) and ref($me->{func}) eq 'CODE');
341 my $result = $me->{func}->($from,$me->{params});
342 $result->is_inplace(0); # clear inplace flag, just in case.
343 if (defined $from->gethdr && $from->hdr->{NAXIS}) {
344 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 $me->{otype}[$d-1])
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 || $from->hdr->{"CUNIT$d"}
355 || $from->hdr->{"CTYPE$d"}
356 || "");
357 }
358 }
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 sub invert {
392 my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
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 croak "Inverting a PDL::Transform with no inverse! Oops.\n"
396 unless(defined($me->{inv}) and ref($me->{inv}) eq 'CODE');
397 my $result = $me->{inv}->($from, $me->{params});
398 $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 922 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 922 eps = 1e-6;
420 922 slimit = nCol/4;
421 922 ▶ if (slimit < 6.0)
Branch: 1 branch
BranchTrueFalseTotal
if (slimit < 6.0) 1603 199 1802
422 922 slimit = 6;
423 922 SweepCount = 0;
424 922 e2 = 10.0*nRow*eps*eps;
425 922 tol = eps*.1;
426 922 EstColRank = nCol;
427 2764 ▶ for (i=0; i<nCol; i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<nCol; i++) { 1849 1113 2962
428 5527 ▶ for (j=0; j<nCol; j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j=0; j<nCol; j++) { 3714 1842 5556
429 3685 W[nCol*(nRow+i)+j] = 0.0;
430 }
431 1843 W[nCol*(nRow+i)+i] = 1.0; /* rjrw 7/7/99: moved this line out of j loop */
432 }
433 922 RotCount = EstColRank*(EstColRank-1)/2;
434 2344 ▶ while (RotCount != 0 && SweepCount <= slimit)
Branch: 2 branches
BranchTrueFalseTotal
while (RotCount != 0 && SweepCount <= slimit) 1451 921 2372
while (RotCount != 0 && SweepCount <= slimit) 1451 0 1451
435 {
436 1423 RotCount = EstColRank*(EstColRank-1)/2;
437 1423 SweepCount++;
438 2843 ▶ for (j=0; j<EstColRank-1; j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j=0; j<EstColRank-1; j++) 1451 1421 2872
439 {
440 2844 ▶ for (k=j+1; k<EstColRank; k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k=j+1; k<EstColRank; k++) 1450 1449 2899
441 {
442 1423 p = q = r = 0.0;
443 4265 ▶ for (i=0; i<nRow; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<nRow; i++) 2842 1478 4320
444 {
445 2844 x0 = W[nCol*i+j]; y0 = W[nCol*i+k];
446 2844 p += x0*y0; q += x0*x0; r += y0*y0;
447 }
448 1423 Z[j] = q; Z[k] = r;
449 1423 ▶ if (q >= r)
Branch: 1 branch
BranchTrueFalseTotal
if (q >= r) 921 557 1478
450 {
451 923 ▶ if (q<=e2*Z[0] || fabs(p)<=tol*q) RotCount--;
Branch: 2 branches
BranchTrueFalseTotal
if (q<=e2*Z[0] || fabs(p)<=tol*q) RotCount--; 921 57 978
if (q<=e2*Z[0] || fabs(p)<=tol*q) RotCount--; 921 0 921
452 else
453 {
454 2 p /= q; r = 1 - r/q; vt = sqrt(4*p*p+r*r);
455 2 c0 = sqrt(fabs(.5*(1+r/vt))); s0 = p/(vt*c0);
456 2 ▶ for (i=0; i<nRow+nCol; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<nRow+nCol; i++) 0 0 0
457 {
458 2 d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
459 1 W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
460 }
461 }
462 }
463 else
464 {
465 501 p /= r; q = q/r-1; vt = sqrt(4*p*p+q*q);
466 501 s0 = sqrt(fabs(.5*(1-q/vt)));
467 501 ▶ if (p<0) s0 = -s0;
Branch: 1 branch
BranchTrueFalseTotal
if (p<0) s0 = -s0; 345 155 500
468 501 c0 = p/(vt*s0);
469 2501 ▶ for (i=0; i<nRow+nCol; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<nRow+nCol; i++) 2000 500 2500
470 {
471 2001 d1 = W[nCol*i+j]; d2 = W[nCol*i+k];
472 2001 W[nCol*i+j] = d1*c0+d2*s0; W[nCol*i+k] = -d1*s0+d2*c0;
473 }
474 }
475 }
476 }
477 1422 ▶ while (EstColRank>=3 && Z[(EstColRank-1)]<=Z[0]*tol+tol*tol)
Branch: 2 branches
BranchTrueFalseTotal
while (EstColRank>=3 && Z[(EstColRank-1)]<=Z[0]*tol+tol*tol) 10 1466 1476
while (EstColRank>=3 && Z[(EstColRank-1)]<=Z[0]*tol+tol*tol) 0 55 55
478 881 EstColRank--;
479 }
480 1802 }
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 1120 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 923 PDL_Double max_sv = 0.0;
512  
513 923 ndims = map->ndims-1;
514  
515 /****** Accumulate the Jacobian */
516 /* Accumulate the offset into the map array */
517 2793 ▶ for (i=offset=0; i<ndims; i++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=offset=0; i<ndims; i++) 1842 976 2818
518 1872 offset += coords[i] * map->dimincs[i+1];
519  
520 951 jptr = tmp + ndims*ndims;
521  
522 2793 ▶ for (i=0; i<ndims; i++) { /* Loop over offset direction */
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<ndims; i++) { /* Loop over offset direction */ 1843 930 2773
523 1872 char bot = (coords[i] <=0);
524 1872 char top = (coords[i] >= map->dims[i+1]-1);
525 1899 ▶ char symmetric = !(bot || top);
Branch: 2 branches
BranchTrueFalseTotal
char symmetric = !(bot || top); 1646 206 1852
char symmetric = !(bot || top); 1449 216 1665
526 PDL_Double *ohi,*olo;
527 1899 PDL_Indx diff = map->dimincs[i+1];
528 1899 ▶ ohi = ((PDL_Double *)map->data) + ( offset + ( top ? 0 : diff ));
Branch: 1 branch
BranchTrueFalseTotal
ohi = ((PDL_Double *)map->data) + ( offset + ( top ? 0 : diff )); 1636 235 1871
529 1899 ▶ olo = ((PDL_Double *)map->data) + ( offset - ( bot ? 0 : diff ));
Branch: 1 branch
BranchTrueFalseTotal
olo = ((PDL_Double *)map->data) + ( offset - ( bot ? 0 : diff )); 1636 235 1871
530  
531 5583 ▶ for (j=0; j<ndims; j++) { /* Loop over dimension */
Branch: 1 branch
BranchTrueFalseTotal
for (j=0; j<ndims; j++) { /* Loop over dimension */ 3700 1855 5555
532 3741 PDL_Double jel = *ohi - *olo;
533  
534 3684 ohi += map->dimincs[0];
535 3684 olo += map->dimincs[0];
536  
537 3684 ▶ if (symmetric)
Branch: 1 branch
BranchTrueFalseTotal
if (symmetric) 2860 853 3713
538 2860 jel /= 2;
539 3741 *(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 976 jptr = tmp + ndims*ndims;
550 976 svptr = tmp + 3*ndims*ndims;
551 976 pdl_xform_svd(jptr,svptr,ndims,ndims);
552  
553 976 aptr = svptr;
554 2818 ▶ for (i=0;i<ndims;i++,aptr++)
Branch: 1 branch
BranchTrueFalseTotal
for (i=0;i<ndims;i++,aptr++) 1860 932 2792
555 1897 *aptr = sqrt(*aptr);
556  
557  
558 /* fix-up matrices here */
559 931 bptr = jptr;
560 2773 ▶ for (i=0; i<ndims;i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0; i<ndims;i++) { 1847 945 2792
561 1852 aptr = svptr;
562 5536 ▶ for (j=0;j<ndims;j++)
Branch: 1 branch
BranchTrueFalseTotal
for (j=0;j<ndims;j++) 3685 1865 5550
563 3694 *(bptr++) /= *(aptr++);
564 }
565  
566 /****** Store the determinant, and pad the singular values as necessary.*/
567 931 aptr = svptr;
568 950 det = 1.0;
569 2792 ▶ for (i=0;i<ndims;i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0;i<ndims;i++) { 1865 921 2786
570 1871 det *= *aptr;
571 1871 ▶ if (*aptr < sv_min)
Branch: 1 branch
BranchTrueFalseTotal
if (*aptr < sv_min) 1004 843 1847
572 1029 *aptr = sv_min;
573 1871 ▶ if (*aptr > max_sv )
Branch: 1 branch
BranchTrueFalseTotal
if (*aptr > max_sv ) 921 950 1871
574 950 max_sv = *aptr;
575 1871 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 950 aptr = tmp + ndims*ndims;
583 926 bptr = aptr + ndims*ndims;
584 926 jptr= tmp;
585  
586 2767 ▶ for (i=0;i<ndims;i++) {
Branch: 1 branch
BranchTrueFalseTotal
for (i=0;i<ndims;i++) { 1847 945 2792
587 5527 ▶ for (j=0;j<ndims;j++) {
Branch: 1 branch
BranchTrueFalseTotal
for (j=0;j<ndims;j++) { 3684 1871 5555
588 3685 *jptr = 0;
589  
590 11075 ▶ for (k=0;k<ndims;k++)
Branch: 1 branch
BranchTrueFalseTotal
for (k=0;k<ndims;k++) 7368 3713 11081
591 7368 *jptr += aptr[j*ndims + k] * bptr[k*ndims + i] / *svptr;
592  
593 3713 jptr++;
594 }
595 1842 svptr++;
596 }
597  
598 921 *jptr = det;
599 950 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 41 pdl *in = $COMP(in);
618 41 pdl *out = $COMP(out);
619 41 pdl *map = $COMP(map);
620  
621 41 PDL_Indx ndims = map->ndims -1; /* Number of dimensions we're working in */
622 41 PDL_Double tmp[3*ndims*ndims+ndims]; /* Workspace for prefrobnication */
623 41 PDL_Indx ovec[ndims]; /* output pixel loop vector */
624 41 PDL_Indx ivec[ndims]; /* input pixel loop vector */
625 41 PDL_Indx ibvec[ndims]; /* input pixel base offset vector */
626 41 PDL_Double dvec[ndims]; /* Residual vector for linearization */
627 41 PDL_Double tvec[ndims]; /* Temporary floating-point vector */
628 41 PDL_Double acc[in->dims[ndims]]; /* Broadcasted accumulator */
629 41 PDL_Double wgt[in->dims[ndims]]; /* Broadcasted weight accumulator */
630 21 PDL_Double wgt2[in->dims[ndims]]; /* Broadcasted weight accumulator for badval finding */
631 21 char bounds[ndims]; /* Boundary condition packed string */
632 21 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 21 $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 21 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 21 ▶ PDL_RETERROR(PDL_err, PDL->make_physical(in));
Branch: 12 branches
BranchTrueFalseTotal
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 11 18 29
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 9 20 29
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 9 9
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 9 0 9
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 14 14
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 5 4 9
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 0 5 5
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 8 8 16
PDL_RETERROR(PDL_err, PDL->make_physical(in)); 1 0 1
652 21 ▶ PDL_RETERROR(PDL_err, PDL->make_physical(out));
Branch: 12 branches
BranchTrueFalseTotal
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 9 9
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 14 14
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 9 9
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 8 1 9
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 8 8
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 16 0 16
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 16 7 23
PDL_RETERROR(PDL_err, PDL->make_physical(out)); 0 0 0
653 21 ▶ PDL_RETERROR(PDL_err, PDL->make_physical(map));
Branch: 12 branches
BranchTrueFalseTotal
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 1 1
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 1 1
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 1 1
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 1 1
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 6 6
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 2 2
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 2 0 2
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 2 0 2
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 0 0
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 0 11 11
PDL_RETERROR(PDL_err, PDL->make_physical(map)); 10 19 29
654  
655 /***
656 * Fill in the boundary condition array
657 */
658 {
659 char *bstr;
660 STRLEN blen;
661 12 bstr = SvPV($COMP(boundary),blen);
662  
663 12 ▶ if (blen == 0) {
Branch: 12 branches
BranchTrueFalseTotal
if (blen == 0) { 0 29 29
if (blen == 0) { 24 5 29
if (blen == 0) { 17 12 29
if (blen == 0) { 0 12 12
if (blen == 0) { 12 5 17
if (blen == 0) { 12 0 12
if (blen == 0) { 0 12 12
if (blen == 0) { 0 23 23
if (blen == 0) { 0 0 0
if (blen == 0) { 0 12 12
if (blen == 0) { 0 19 19
if (blen == 0) { 1 11 12
664 /* If no boundary is specified then every dim gets truncated */
665 PDL_Indx i;
666 0 ▶ for (i=0;i<ndims;i++)
Branch: 12 branches
BranchTrueFalseTotal
for (i=0;i<ndims;i++) 0 12 12
for (i=0;i<ndims;i++) 0 12 12
for (i=0;i<ndims;i++) 0 0 0
for (i=0;i<ndims;i++) 0 20 20
for (i=0;i<ndims;i++) 0 33 33
for (i=0;i<ndims;i++) 27 42 69
for (i=0;i<ndims;i++) 27 42 69
for (i=0;i<ndims;i++) 10 59 69
for (i=0;i<ndims;i++) 0 10 10
for (i=0;i<ndims;i++) 0 48 48
for (i=0;i<ndims;i++) 0 48 48
for (i=0;i<ndims;i++) 0 35 35
667 0 bounds[i] = 1;
668 } else {
669 PDL_Indx i;
670 36 ▶ for (i=0;i<ndims;i++) {
Branch: 12 branches
BranchTrueFalseTotal
for (i=0;i<ndims;i++) { 0 35 35
for (i=0;i<ndims;i++) { 0 29 29
for (i=0;i<ndims;i++) { 0 0 0
for (i=0;i<ndims;i++) { 0 0 0
for (i=0;i<ndims;i++) { 10 5 15
for (i=0;i<ndims;i++) { 0 0 0
for (i=0;i<ndims;i++) { 0 1 1
for (i=0;i<ndims;i++) { 0 1 1
for (i=0;i<ndims;i++) { 0 2 2
for (i=0;i<ndims;i++) { 0 2 2
for (i=0;i<ndims;i++) { 16 7 23
for (i=0;i<ndims;i++) { 1 0 1
671 24 ▶ switch(bstr[i < blen ? i : blen-1 ]) {
Branch: 12 branches
BranchTrueFalseTotal
switch(bstr[i < blen ? i : blen-1 ]) { 0 1 1
switch(bstr[i < blen ? i : blen-1 ]) { 0 1 1
switch(bstr[i < blen ? i : blen-1 ]) { 0 1 1
switch(bstr[i < blen ? i : blen-1 ]) { 0 25 25
switch(bstr[i < blen ? i : blen-1 ]) { 10 41 51
switch(bstr[i < blen ? i : blen-1 ]) { 17 24 41
switch(bstr[i < blen ? i : blen-1 ]) { 41 0 41
switch(bstr[i < blen ? i : blen-1 ]) { 41 0 41
switch(bstr[i < blen ? i : blen-1 ]) { 27 14 41
switch(bstr[i < blen ? i : blen-1 ]) { 5 36 41
switch(bstr[i < blen ? i : blen-1 ]) { 14 41 55
switch(bstr[i < blen ? i : blen-1 ]) { 27 14 41
672 0 case '0': case 'f': case 'F': /* forbid */
673 9 bounds[i] = 0;
674 5 break;
675 22 case '1': case 't': case 'T': /* truncate */
676 27 bounds[i] = 1;
677 31 break;
678 9 case '2': case 'e': case 'E': /* extend */
679 9 bounds[i] = 2;
680 9 break;
681 10 case '3': case 'p': case 'P': /* periodic */
682 10 bounds[i] = 3;
683 1 break;
684 1 case '4': case 'm': case 'M': /* mirror */
685 1 bounds[i] = 4;
686 1 break;
687 0 default:
688 0 $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 12 big = labs($COMP(big));
699 21 ▶ if (big <= 0)
Branch: 12 branches
BranchTrueFalseTotal
if (big <= 0) 14 0 14
if (big <= 0) 12 2 14
if (big <= 0) 2 12 14
if (big <= 0) 6 8 14
if (big <= 0) 4 9 13
if (big <= 0) 0 4 4
if (big <= 0) 1 3 4
if (big <= 0) 1 2 3
if (big <= 0) 0 2 2
if (big <= 0) 41 0 41
if (big <= 0) 2 46 48
if (big <= 0) 0 2 2
700 9 $CROAK("map: 'big' parameter must be >0");
701  
702 21 blur = fabs($COMP(blur));
703 21 ▶ if (blur < 0)
Branch: 12 branches
BranchTrueFalseTotal
if (blur < 0) 2 0 2
if (blur < 0) 0 39 39
if (blur < 0) 8 33 41
if (blur < 0) 41 0 41
if (blur < 0) 160 9 169
if (blur < 0) 41 0 41
if (blur < 0) 0 6 6
if (blur < 0) 0 43 43
if (blur < 0) 0 16 16
if (blur < 0) 0 0 0
if (blur < 0) 0 7 7
if (blur < 0) 0 0 0
704 9 $CROAK("map: 'blur' parameter must be >= 0");
705  
706 21 sv_min = fabs($COMP(sv_min));
707 21 ▶ if (sv_min < 0)
Branch: 12 branches
BranchTrueFalseTotal
if (sv_min < 0) 0 0 0
if (sv_min < 0) 0 0 0
if (sv_min < 0) 0 0 0
if (sv_min < 0) 0 0 0
if (sv_min < 0) 0 5 5
if (sv_min < 0) 0 0 0
if (sv_min < 0) 0 3 3
if (sv_min < 0) 0 1 1
if (sv_min < 0) 0 1 1
if (sv_min < 0) 2 21 23
if (sv_min < 0) 0 9 9
if (sv_min < 0) 23 0 23
708 9 $CROAK("map: 'sv_min' parameter must be >= 0");
709  
710 21 flux = $COMP(flux) != 0;
711  
712 {
713 char *mstr;
714 STRLEN mlen;
715 21 mstr = SvPV($COMP(method),mlen);
716  
717 21 ▶ if (mlen==0)
Branch: 12 branches
BranchTrueFalseTotal
if (mlen==0) 0 23 23
if (mlen==0) 0 23 23
if (mlen==0) 0 23 23
if (mlen==0) 1 22 23
if (mlen==0) 0 6 6
if (mlen==0) 0 22 22
if (mlen==0) 0 22 22
if (mlen==0) 0 0 0
if (mlen==0) 0 0 0
if (mlen==0) 0 22 22
if (mlen==0) 46 7 53
if (mlen==0) 0 1 1
718 9 method = 'h';
719 21 switch(*mstr) {
720 7 ▶ case 'h': // h - lookup-table hanning window
Branch: 12 branches
BranchTrueFalseTotal
case 'h': // h - lookup-table hanning window 2 0 2
case 'h': // h - lookup-table hanning window 2 0 2
case 'h': // h - lookup-table hanning window 0 2 2
case 'h': // h - lookup-table hanning window 0 2 2
case 'h': // h - lookup-table hanning window 1 2 3
case 'h': // h - lookup-table hanning window 0 0 0
case 'h': // h - lookup-table hanning window 0 1 1
case 'h': // h - lookup-table hanning window 0 1 1
case 'h': // h - lookup-table hanning window 0 1 1
case 'h': // h - lookup-table hanning window 2 0 2
case 'h': // h - lookup-table hanning window 1 6 7
case 'h': // h - lookup-table hanning window 0 1 1
721 if ( needs_hanning_calc ) {
722 5002 ▶ int i;
Branch: 12 branches
BranchTrueFalseTotal
int i; 0 1 1
int i; 0 1 1
int i; 2 0 2
int i; 0 1 1
int i; 2500 2 2502
int i; 0 1 1
int i; 0 1 1
int i; 0 0 0
int i; 2 0 2
int i; 0 1 1
int i; 2500 2 2502
int i; 0 1 1
723 5000 for (i=0;i<HANNING_LOOKUP_SIZE;i++) {
724 hanning_lookup[i] = 0.5 + 0.5 * cos(3.1415926536 / HANNING_LOOKUP_SIZE * i);
725 11 }
726 11 hanning_lookup[HANNING_LOOKUP_SIZE] = 0;
727 10 hanning_lookup[HANNING_LOOKUP_SIZE+1] = 0;
728 needs_hanning_calc = 0;
729 15 }
730 24 zeta = HANNING_LOOKUP_SIZE / blur; /* fall-through deliberate */
731 24 ▶ case 'H': // H - rigorous hanning window
Branch: 12 branches
BranchTrueFalseTotal
case 'H': // H - rigorous hanning window 0 1 1
case 'H': // H - rigorous hanning window 1 0 1
case 'H': // H - rigorous hanning window 0 1 1
case 'H': // H - rigorous hanning window 0 1 1
case 'H': // H - rigorous hanning window 2 1 3
case 'H': // H - rigorous hanning window 0 6 6
case 'H': // H - rigorous hanning window 0 6 6
case 'H': // H - rigorous hanning window 0 6 6
case 'H': // H - rigorous hanning window 1 5 6
case 'H': // H - rigorous hanning window 0 1 1
case 'H': // H - rigorous hanning window 7 4 11
case 'H': // H - rigorous hanning window 0 1 1
732 24 method = *mstr;
733 hanning_offset = (blur >= 1) ? 0 : 0.5 * (1.0 - blur);
734 19 break;
735 19  
736 case 'g': case 'j': // Gaussian and/or Jacobian, using lookup table
737 19 ▶ method = 'g';
Branch: 12 branches
BranchTrueFalseTotal
method = 'g'; 0 5 5
method = 'g'; 3 3 6
method = 'g'; 0 2 2
method = 'g'; 0 0 0
method = 'g'; 1 1 2
method = 'g'; 0 0 0
method = 'g'; 0 0 0
method = 'g'; 0 0 0
method = 'g'; 0 0 0
method = 'g'; 0 0 0
method = 'g'; 1 0 1
method = 'g'; 0 0 0
738 zeta = GAUSSIAN_LOOKUP_SIZE / GAUSSIAN_MAXVAL;
739 8010 ▶ 
Branch: 12 branches
BranchTrueFalseTotal
0 0 0
0 0 0
0 0 0
0 0 0
4000 1 4001
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
4000 1 4001
0 0 0
740 8008 if ( needs_gaussian_calc ) {
741 int i;
742 10 for (i=0;i<GAUSSIAN_LOOKUP_SIZE;i++) {
743 10 gaussian_lookup[i] = exp( - i * 1.386294 / zeta );
744 10 }
745 gaussian_lookup[GAUSSIAN_LOOKUP_SIZE] = 0;
746 11 gaussian_lookup[GAUSSIAN_LOOKUP_SIZE+1] = 0;
747 needs_gaussian_calc = 0;
748 2 }
749 1 break;
750 1  
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 37 ▶ /* Start of Real Work */
Branch: 12 branches
BranchTrueFalseTotal
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 10 5 15
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 0 0 0
/* Start of Real Work */ 14 7 21
/* Start of Real Work */ 0 0 0
764 24  
765 /* Initialize coordinate vector and map offset
766 13 */
767 13 for (i=0;i<ndims;i++)
768 25 ▶ ovec[i] = 0;
Branch: 12 branches
BranchTrueFalseTotal
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 5 5 10
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 0 0 0
ovec[i] = 0; 7 7 14
ovec[i] = 0; 0 0 0
769 37 ▶ 
Branch: 12 branches
BranchTrueFalseTotal
0 0 0
0 0 0
0 0 0
0 0 0
10 5 15
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
14 7 21
0 0 0
770 25 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 911 incs[i*npdls + 0] = map->dimincs[i+1];
775 }
776  
777 923 /* 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 923 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 923 }
802 2765 ▶#endif
Branch: 12 branches
BranchTrueFalseTotal
#endif 0 0 0
#endif 0 0 0
#endif 0 0 0
#endif 0 0 0
#endif 1000 500 1500
#endif 0 0 0
#endif 0 0 0
#endif 0 0 0
#endif 0 0 0
#endif 0 0 0
#endif 842 421 1263
#endif 0 0 0
803 1844  
804 1844 /* 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 2767 ▶ {
Branch: 12 branches
BranchTrueFalseTotal
{ 0 0 0
{ 0 0 0
{ 0 0 0
{ 0 0 0
{ 1000 500 1500
{ 0 0 0
{ 0 0 0
{ 0 0 0
{ 0 0 0
{ 0 0 0
{ 842 421 1263
{ 0 0 0
810 1846 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 922 }
815 1843 ▶ }
Branch: 12 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 500 500 1000
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 421 421 842
} 0 0 0
816 922  
817 /* Initialize input delta vector */
818 for (i=0;i<ndims;i++)
819 ivec[i] = -psize;
820 950  
821 1871 ▶ /* Initialize accumulators */
Branch: 12 branches
BranchTrueFalseTotal
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 500 500 1000
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 0 0 0
/* Initialize accumulators */ 421 421 842
/* Initialize accumulators */ 0 0 0
822 931 {
823 PDL_Double *ac = acc;
824 for (i=0; i < in->dims[ndims]; i++)
825 950 *(ac++) = 0.0;
826 1871 ▶ 
Branch: 12 branches
BranchTrueFalseTotal
0 0 0
0 0 0
0 0 0
0 0 0
500 500 1000
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
421 421 842
0 0 0
827 950 }
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 950 * Calculate the original offset into the data array, to enable
842 950 * delta calculations in the pixel loop
843 2792 ▶ *
Branch: 12 branches
BranchTrueFalseTotal
* 0 0 0
* 0 0 0
* 0 0 0
* 0 0 0
* 1000 500 1500
* 0 0 0
* 0 0 0
* 0 0 0
* 0 0 0
* 0 0 0
* 842 421 1263
* 0 0 0
844 1871 * i runs over dims; j holds the working integer index in the
845 1859 ▶ * current dim.
Branch: 24 branches
BranchTrueFalseTotal
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 600 400 1000
* current dim. 0 600 600
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 0 0 0
* current dim. 594 248 842
* current dim. 120 474 594
* current dim. 0 0 0
* current dim. 0 0 0
846 785 *
847 17 * This code matches the incrementation code at the bottom of the accumulation loop
848 12 */
849  
850 680 t_vio = 0; /* truncation-boundary violation count - don't bother if it is nonzero */
851 680 i_off = 0;
852 for (i=0;i<ndims; i++) {
853 680 j = ivec[i] + ibvec[i];
854 680 ▶ if (j<0 || j >= in->dims[i]) {
Branch: 12 branches
BranchTrueFalseTotal
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 400 0 400
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 0 0 0
if (j<0 || j >= in->dims[i]) { 208 60 268
if (j<0 || j >= in->dims[i]) { 0 0 0
855 620 switch(bounds[i]) {
856 60 case 0: /* no breakage allowed */
857 668 $CROAK("index out-of-bounds in map");
858 50 break;
859 50 case 1: /* truncation */
860 50 ▶ t_vio++;
Branch: 12 branches
BranchTrueFalseTotal
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 0 0 0
t_vio++; 20 30 50
t_vio++; 0 0 0
861 20 /* fall through */
862 62 case 2: /* extension -- crop */
863 62 if (j<0)
864 62 j=0;
865 62 else //if (j>=in->dims[i])
866 62 ▶ j = in->dims[i] - 1;
Branch: 12 branches
BranchTrueFalseTotal
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 0 0
j = in->dims[i] - 1; 0 50 50
j = in->dims[i] - 1; 0 0 0
867 12 break;
868 62 case 3: /* periodic -- mod it */
869 62 ▶ j %= in->dims[i];
Branch: 12 branches
BranchTrueFalseTotal
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 0 0 0
j %= in->dims[i]; 50 0 50
j %= in->dims[i]; 0 0 0
870 62 if (j<0)
871 62 j += in->dims[i];
872 break;
873 62 case 4: /* mirror -- reflect off the edges */
874 12 j += in->dims[i];
875 12 j %= (in->dims[i]*2);
876 if (j<0)
877 j += in->dims[i]*2;
878 j -= in->dims[i];
879 1854 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 2775 ▶ }
Branch: 12 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 1000 500 1500
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 842 421 1263
} 0 0 0
888 1854 }
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 24213 ▶ /* we walk through the array using dimincs and the old offset. This saves */
Branch: 12 branches
BranchTrueFalseTotal
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 9250 3250 12500
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
/* we walk through the array using dimincs and the old offset. This saves */ 7182 4519 11701
/* we walk through the array using dimincs and the old offset. This saves */ 0 0 0
911 /* about half of the time spent on index calculation. */
912 16432  
913 16432 do { /* Input accumulation loop */
914 16432 PDL_Double *cp;
915 49296 ▶ PDL_Double alpha; // weighting coefficient for the current point
Branch: 12 branches
BranchTrueFalseTotal
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 18500 9250 27750
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
PDL_Double alpha; // weighting coefficient for the current point 14364 7182 21546
PDL_Double alpha; // weighting coefficient for the current point 0 0 0
916 32864  
917 /* Calculate the weight of the current input point. Don't bother if we're
918 16432 * violating any truncation boundaries (in that case our value is zero, but
919 * for the interpolation we also set the weight to zero).
920 8191 */
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 8191 *(ap++) = *(ip++) - *(bp++);
928 8211  
929 19209 ▶ switch(method) {
Branch: 12 branches
BranchTrueFalseTotal
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 2645 1850 4495
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 0 0 0
switch(method) { 8353 6341 14694
switch(method) { 0 0 0
930 PDL_Double dd; // tmp space for calculations in filters
931  
932 case 'h':
933 11018 /* This is the Hanning window rolloff. It is a product of a simple */
934 10998 /* cos^2(theta) rolloff in each dimension. Using a lookup table */
935 /* is about 2x faster than using cos(theta) directly in each */
936 33027 ▶ /* weighting calculation, so we do. Using 2500 entries and linear */
Branch: 12 branches
BranchTrueFalseTotal
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 5290 2645 7935
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
/* weighting calculation, so we do. Using 2500 entries and linear */ 16706 8353 25059
/* weighting calculation, so we do. Using 2500 entries and linear */ 0 0 0
937 22029 /* 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 11031 dd = 0;
946 11031 ▶ ap = tvec;
Branch: 12 branches
BranchTrueFalseTotal
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 2645 0 2645
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 0 0 0
ap = tvec; 6875 1478 8353
ap = tvec; 0 0 0
947 9553 ▶ /* Get the matrix-multiply element for this dimension */
Branch: 12 branches
BranchTrueFalseTotal
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 1517 1128 2645
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 0 0 0
/* Get the matrix-multiply element for this dimension */ 5707 1168 6875
/* Get the matrix-multiply element for this dimension */ 0 0 0
948 7257 for (j=0;j<ndims; j++)
949 7257 dd += *(ap++) * *(cp++);
950  
951 2365 /* Do linear interpolation from the table */
952 2365 /* The table captures a hanning window centered 0.5 pixel from center. */
953 2365 ▶ /* We scale the filter by the blur parameter -- but if blur is less */
Branch: 12 branches
BranchTrueFalseTotal
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 1128 1128
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
/* We scale the filter by the blur parameter -- but if blur is less */ 0 1168 1168
/* We scale the filter by the blur parameter -- but if blur is less */ 0 0 0
954 10 /* than unity, we shrink the hanning blur window while keeping the 0.5 */
955 2296 /* value on the pixel edge at 0.5. For blur greater than unity, we */
956 2296 /* scale simply. */
957 beta = fabs(dd) - hanning_offset;
958 if (beta > 0) {
959 if (beta >= blur) {
960 8191 alpha = 0;
961 i = ndims;
962 1850 } else {
963 beta *= zeta;
964 lodex = beta;
965 1860 beta -= lodex; //lodex now has the integer part, beta has the fractional part
966 1860 if (lodex > HANNING_LOOKUP_SIZE)
967 4515 ▶ lodex = HANNING_LOOKUP_SIZE;
Branch: 12 branches
BranchTrueFalseTotal
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 2645 1850 4495
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
lodex = HANNING_LOOKUP_SIZE; 0 0 0
968 2665 hidex = lodex+1;
969 2704 //do a linear interpolation between the two nearest values
970 7994 ▶ alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta);
Branch: 12 branches
BranchTrueFalseTotal
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 5290 2645 7935
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
alpha *= hanning_lookup[hidex]*beta + hanning_lookup[lodex]*(1-beta); 0 0 0
971 5323 } /* end of interpolation branch */
972 2678 } /* end of beta > 0 branch */
973 2678 ▶ } /* end of dimension loop */
Branch: 12 branches
BranchTrueFalseTotal
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 1517 1128 2645
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
} /* end of dimension loop */ 0 0 0
974 1550 break;
975 1550  
976 case 'H':
977 1161 /* This is the Hanning window rolloff with explicit calculation, preserved */
978 /* in case someone actually wants the slower longer method. */
979 1883 alpha = 1;
980 cp = tmp;
981 4574 for (i=0; i<ndims; i++) {
982 dd = 0;
983 ap = tvec;
984 4574 for (j=0;j<ndims; j++)
985 4560 dd += *(ap++) * *(cp++);
986 13440 ▶ dd = (fabs(dd) - hanning_offset) / blur;
Branch: 12 branches
BranchTrueFalseTotal
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 7198 3700 10898
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
dd = (fabs(dd) - hanning_offset) / blur; 1682 841 2523
dd = (fabs(dd) - hanning_offset) / blur; 0 0 0
987 8899 if ( dd > 1 ) {
988 8899 alpha = 0;
989 26688 ▶ i = ndims;
Branch: 12 branches
BranchTrueFalseTotal
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 14396 7198 21594
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 0 0 0
i = ndims; 3364 1682 5046
i = ndims; 0 0 0
990 17808 } else
991 8899 alpha *= (0.5 + 0.5 * cos( dd * 3.1415926536 ));
992 8899 }
993 8892 ▶ break;
Branch: 12 branches
BranchTrueFalseTotal
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 832 6366 7198
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 100 1582 1682
break; 0 0 0
994 944  
995 944 case 'g':
996 /* This is the Gaussian rolloff. It does lookup into a precalculated exponential. */
997 {
998 4553 ▶ PDL_Double sum = 0;
Branch: 36 branches
BranchTrueFalseTotal
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 2868 832 3700
PDL_Double sum = 0; 2868 0 2868
PDL_Double sum = 0; 0 2868 2868
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 741 100 841
PDL_Double sum = 0; 741 0 741
PDL_Double sum = 0; 0 741 741
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
PDL_Double sum = 0; 0 0 0
999 967 cp = tmp;
1000 for (i=0; i<ndims;i++) {
1001 dd = 0;
1002 3644 ap = tvec;
1003 for (j=0;j<ndims;j++)
1004 3644 dd += *(ap++) * *(cp++);
1005 3621 dd /= blur;
1006 3610 sum += dd * dd;
1007 if (sum > GAUSSIAN_MAXVAL) {
1008 i = ndims; /* exit early if we're too far out */
1009 alpha = 0;
1010 4542 }
1011 }
1012 1851 if ( sum > GAUSSIAN_MAXVAL || !isfinite(sum) || isnan(sum) ) {
1013 alpha = 0;
1014 } else {
1015 PDL_Indx lodex,hidex;
1016 1879 PDL_Double beta = fabs(zeta * sum);
1017 1879  
1018 5198 ▶ lodex = beta;
Branch: 12 branches
BranchTrueFalseTotal
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 3348 1850 5198
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
lodex = beta; 0 0 0
1019 3348 beta -= lodex; // lodex now has the integer part, beta has the fractional part
1020 3348 hidex = lodex+1;
1021 10044 ▶ //do a linear interpolation between the two nearest values
Branch: 12 branches
BranchTrueFalseTotal
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 6696 3348 10044
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
//do a linear interpolation between the two nearest values 0 0 0
1022 6696 alpha = gaussian_lookup[hidex]*beta + gaussian_lookup[lodex]*(1 - beta);
1023 3348  
1024 3348 }
1025 3348 ▶ }
Branch: 12 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 892 2456 3348
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
1026 892 break;
1027  
1028 case 'G':
1029 1886 ▶ /* This is the Gaussian rolloff with explicit calculation, preserved */
Branch: 12 branches
BranchTrueFalseTotal
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 332 1518 1850
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
/* This is the Gaussian rolloff with explicit calculation, preserved */ 0 0 0
1030 364 /* in case someone actually wants the slower longer method. */
1031 {
1032 1659 PDL_Double sum = 0;
1033 cp = tmp;
1034 1991 for (i=0; i<ndims; i++) {
1035 141 dd = 0;
1036 1 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 16433 i = ndims; /* exit early if this pixel is too far outside the footprint of the ideal point */
1043 16433 }
1044 32865 ▶ 
Branch: 12 branches
BranchTrueFalseTotal
0 0 0
0 0 0
0 0 0
0 0 0
9250 9250 18500
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
7182 7182 14364
0 0 0
1045 16432 ▶ if (sum > GAUSSIAN_MAXVAL)
Branch: 24 branches
BranchTrueFalseTotal
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 9250 9250
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 306 6876 7182
if (sum > GAUSSIAN_MAXVAL) 306 0 306
if (sum > GAUSSIAN_MAXVAL) 0 0 0
if (sum > GAUSSIAN_MAXVAL) 0 0 0
1046 16432 alpha = 0;
1047 16432 else
1048 16432 alpha = exp(-sum * 1.386294); /* Gaussian, rt(2)-pix HWHM */
1049 }
1050 16433 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 24202 /* man's broadcastloop here, so we accumulate each broadcasted element separately. */
1058 53106 ▶ $GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off;
Branch: 24 branches
BranchTrueFalseTotal
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 25000 2500 27500
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 15000 10000 25000
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 23402 2203 25605
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 13904 9498 23402
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
$GENERIC() *dat = (($GENERIC() *)(in->data)) + i_off; 0 0 0
1059 PDL_Indx max = out->dims[ndims];
1060 28905 for ( i=0; i < max; i++ ) {
1061 28905 if ( (badval==0) || (*dat != badval) ) {
1062 acc[i] += *dat * alpha;
1063 dat += in->dimincs[ndims];
1064 28905 ▶ wgt[i] += alpha;
Branch: 24 branches
BranchTrueFalseTotal
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 14350 650 15000
wgt[i] += alpha; 14350 0 14350
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 12626 1278 13904
wgt[i] += alpha; 7651 4975 12626
wgt[i] += alpha; 0 0 0
wgt[i] += alpha; 0 0 0
1065 }
1066 22002 wgt2[i] += alpha; // Accumulate what weight we would have with no bad values
1067 }
1068 }
1069 6904 } /* end of t_vio check (i.e. of input accumulation) */
1070 4924  
1071  
1072 4924 ▶ /* Advance input accumulation loop. */
Branch: 12 branches
BranchTrueFalseTotal
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 400 250 650
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 0 0 0
/* Advance input accumulation loop. */ 642 3631 4273
/* Advance input accumulation loop. */ 0 0 0
1073 1043 /* We both increment the total vector and also advance the index. */
1074 3882 ▶ carry = 1;
Branch: 12 branches
BranchTrueFalseTotal
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 250 250
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 0 0 0
carry = 1; 950 2681 3631
carry = 1; 0 0 0
1075 952 for (i=0; i<ndims && carry; i++) {
1076 4925 /* Advance the current element of the offset vector */
1077 2 ivec[i]++;
1078 2 j = ivec[i] + ibvec[i];
1079 330  
1080 332 ▶ /* Advance the offset into the data array */
Branch: 12 branches
BranchTrueFalseTotal
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 0 0 0
/* Advance the offset into the data array */ 100 230 330
/* Advance the offset into the data array */ 0 0 0
1081 102 if ( j > 0 && j <= in->dims[i]-1 ) {
1082 /* Normal case -- just advance the input vector */
1083 232 i_off += in->dimincs[i];
1084 } else {
1085 331 /* Busted a boundary - either before or after. */
1086 1651 switch(bounds[i]){
1087 1651 case 0: /* no breakage allowed -- treat as truncation for interpolation */
1088 1651 case 1: /* truncation -- if we crossed the boundary mark ourselves out-of-bounds */
1089 1651 if ( j == 0 )
1090 1651 ▶ t_vio--;
Branch: 24 branches
BranchTrueFalseTotal
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 0 0 0
t_vio--; 1400 250 1650
t_vio--; 1150 250 1400
t_vio--; 0 0 0
t_vio--; 0 0 0
1091 1150 ▶ else if ( j == in->dims[i] )
Branch: 12 branches
BranchTrueFalseTotal
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 0 0 0
else if ( j == in->dims[i] ) 1000 150 1150
else if ( j == in->dims[i] ) 0 0 0
1092 1001 t_vio++;
1093 break;
1094 151 case 2: /* extension -- do nothing (so the same input point is re-used) */
1095 break;
1096 1651 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 28905 ▶ }
Branch: 12 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 12000 3000 15000
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 11280 2624 13904
} 0 0 0
1102 break;
1103 case 4: /* mirror -- advance or retreat depending on phase */
1104 27063 ▶ j += in->dims[i];
Branch: 12 branches
BranchTrueFalseTotal
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 2000 12000 14000
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 0 0 0
j += in->dims[i]; 1782 11280 13062
j += in->dims[i]; 0 0 0
1105 3783 j %= (in->dims[i]*2);
1106 j -= in->dims[i];
1107 23281 if ( j!=0 && j!= -in->dims[i] ) {
1108 if (j<0)
1109 i_off -= in->dimincs[i];
1110 5625 else
1111 5625 ▶ i_off += in->dimincs[i];
Branch: 12 branches
BranchTrueFalseTotal
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 3000 0 3000
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 0 0 0
i_off += in->dimincs[i]; 2024 600 2624
i_off += in->dimincs[i]; 0 0 0
1112 5025 }
1113 5025 ▶ break;
Branch: 24 branches
BranchTrueFalseTotal
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 3000 0 3000
break; 0 3000 3000
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 0 0 0
break; 2024 0 2024
break; 1130 894 2024
break; 0 0 0
break; 0 0 0
1114 1131 }
1115 5025 }
1116 5025  
1117 5025 ▶ /* Now check for carry */
Branch: 24 branches
BranchTrueFalseTotal
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 2600 400 3000
/* Now check for carry */ 0 2600 2600
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
/* Now check for carry */ 1382 642 2024
/* Now check for carry */ 180 1202 1382
/* Now check for carry */ 0 0 0
/* Now check for carry */ 0 0 0
1118 1223 if (ivec[i] <= psize) {
1119 5025 /* Normal case -- copy the current offset to the faster-running dim stashes */
1120 PDL_Indx k;
1121 601 for (k=0;k<i;k++) {
1122 index_stash[k] = i_off;
1123 }
1124 carry = 0;
1125 24226 ▶ 
Branch: 12 branches
BranchTrueFalseTotal
0 0 0
0 0 0
0 0 0
0 0 0
12000 500 12500
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
11280 421 11701
0 0 0
1126 } else { /* End of this scan -- recover the last position, and mark carry */
1127 i_off = index_stash[i];
1128 946 if (bounds[i]==1) {
1129 946 j = ivec[i] + ibvec[i];
1130 946 if ( j < 0 || j >= in->dims[i] )
1131 946 t_vio--;
1132 ivec[i] = -psize;
1133 j = ivec[i] + ibvec[i];
1134 2788 ▶ if ( j < 0 || j >= in->dims[i] )
Branch: 12 branches
BranchTrueFalseTotal
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 1000 500 1500
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 0 0 0
if ( j < 0 || j >= in->dims[i] ) 842 421 1263
if ( j < 0 || j >= in->dims[i] ) 0 0 0
1135 1867 t_vio++;
1136 carry = 1;
1137 946 ▶ } else {
Branch: 12 branches
BranchTrueFalseTotal
} else { 0 0 0
} else { 0 0 0
} else { 0 0 0
} else { 0 0 0
} else { 500 0 500
} else { 0 0 0
} else { 0 0 0
} else { 0 0 0
} else { 0 0 0
} else { 0 0 0
} else { 421 0 421
} else { 0 0 0
1138 ivec[i] = -psize;
1139 1867 ▶ }
Branch: 12 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 500 500 1000
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 421 421 842
} 0 0 0
1140 946 ▶ }
Branch: 24 branches
BranchTrueFalseTotal
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 500 0 500
} 500 0 500
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 0 0 0
} 326 95 421
} 326 0 326
} 0 0 0
} 0 0 0
1141 946 } /* End of counter-advance loop */
1142 922 } while (carry==0); /* end of total data accumulation loop (termination condition has carry on last dim) */
1143  
1144 {
1145 PDL_Double *ac = acc;
1146 1 PDL_Double *wg = wgt;
1147 1 ▶ PDL_Double *wg2 = wgt2;
Branch: 12 branches
BranchTrueFalseTotal
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
PDL_Double *wg2 = wgt2; 0 0 0
1148 1 ▶ $GENERIC() *dat = out->data;
Branch: 24 branches
BranchTrueFalseTotal
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
$GENERIC() *dat = out->data; 0 0 0
1149 1  
1150 1 /* Calculate output vector offset */
1151 for (i=0;i<ndims;i++)
1152 18 dat += out->dimincs[i] * ovec[i];
1153 41  
1154 if (!flux) {
1155 41 /* 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 41 PDL_Double det = tmp[ndims*ndims];
1164 41 ▶ for (i=0; i < out->dims[ndims]; i++) {
Branch: 12 branches
BranchTrueFalseTotal
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
for (i=0; i < out->dims[ndims]; i++) { 0 0 0
1165 17 if (*wg && (*wg2 / *wg) < 1.5 ) {
1166 41 ▶ *dat = *(ac++) / *(wg++) * det;
Branch: 12 branches
BranchTrueFalseTotal
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
*dat = *(ac++) / *(wg++) * det; 0 0 0
1167 41 wg2++;
1168 41 } else {
1169 *dat = badval;
1170 ac++; wg++; wg2++;
1171 }
1172 dat += out->dimincs[ndims];
1173 962 ▶ } /* end of for loop */
Branch: 12 branches
BranchTrueFalseTotal
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 5 495 500
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 0 0 0
} /* end of for loop */ 7 414 421
} /* end of for loop */ 0 0 0
1174 } /* end of flux flag set conditional */
1175 53 } /* 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 push @_, {} if ref($_[-1]) ne 'HASH';
1534 my @k = grep(m/^r(e(c(t)?)?)?/,sort keys %{$_[-1]});
1535 unless(@k) {
1536 $_[-1]->{rectify} = 0;
1537 }
1538 t_identity()->map(@_);
1539 }
1540  
1541  
1542 *PDL::map = \&map;
1543 sub map {
1544 my ($me, $in, $tmp, $opt) = @_;
1545 ($in, $me) = ($me, $in)
1546 if UNIVERSAL::isa($me,'PDL') && UNIVERSAL::isa($in,'PDL::Transform');
1547 barf ("PDL::Transform::map: source is not defined or is not a PDL\n")
1548 unless(defined $in and UNIVERSAL::isa($in,'PDL'));
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 if ref $tmp eq 'HASH' && !defined($opt)
1554 && !defined($tmp->{NAXIS}); # FITS headers all have NAXIS.
1555 croak("PDL::Transform::map: Option 'p' was ambiguous and has been removed. You probably want 'pix' or 'phot'.") if exists($opt->{'p'});
1556 $tmp = [$in->dims] unless defined $tmp; # no //= because of Devel::Cover bug
1557  
1558 # Generate an appropriate output ndarray for values to go in
1559 my ($out, @odims, $ohdr);
1560 if (UNIVERSAL::isa($tmp,'PDL')) {
1561 @odims = $tmp->dims;
1562 if (defined(my $x = $tmp->gethdr)) { $ohdr = {%$x} }
1563 } elsif (ref $tmp eq 'HASH') {
1564 # (must be a fits header -- or would be filtered above)
1565 @odims = map $tmp->{"NAXIS$_"}, 1..$tmp->{NAXIS};
1566 $ohdr = {%$tmp}; # copy FITS header into output
1567 } elsif (ref $tmp eq 'ARRAY') {
1568 @odims = @$tmp;
1569 } else {
1570 barf("map: confused about dimensions of the output array...\n");
1571 }
1572  
1573 if (scalar(@odims) < scalar($in->dims)) {
1574 my @idims = $in->dims;
1575 push(@odims, splice(@idims,scalar(@odims)));
1576 }
1577  
1578 $out = PDL->new_from_specification($in->type,@odims);
1579 $out->sethdr($ohdr) if defined($ohdr);
1580  
1581 # 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 ## transform itself (extra dimensions come along for the ride)
1587 my $nd = $me->{odim} || $me->{idim} || 2;
1588 my @dd = my @sizes = $out->dims;
1589 splice @dd,$nd; # Cut out dimensions after the end
1590  
1591 # Check that there are elements in the output fields...
1592 barf "map: output has no dims!\n"
1593 unless(@dd);
1594 my $ddtotal = 1;
1595 $ddtotal *= $_ for @dd;
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  
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 # Since we eschew CROTA whenever possible, the CDi_j formalism is used instead.
1617 my $f_in = (defined($in->hdr->{NAXIS}) ? t_fits($in,{ignore_rgb=>1}) : t_identity());
1618  
1619 unless((defined $out->gethdr && $out->hdr->{NAXIS}) or $nofits) {
1620 print "generating output FITS header..." if $PDL::Transform::debug;
1621  
1622 $out->sethdr($in->hdr_copy) # Copy extraneous fields...
1623 if defined $in->hdr;
1624  
1625 my $samp_ratio = 300;
1626  
1627 my $orange = _opt($opt, ['or','orange','output_range','Output_Range'],
1628 undef);
1629  
1630 my $omin;
1631 my $omax;
1632 my $osize;
1633  
1634  
1635 my $rectify = _opt($opt,['r','rect','rectify','Rectify'],1);
1636  
1637  
1638 if (defined $orange) {
1639 # orange always rectifies the coordinates -- the output scientific
1640 # coordinates *must* align with the axes, or orange wouldn't make
1641 # sense.
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 unless ( (($orange->dim(1)) == $nd )
1646 && $orange->ndims == 2);
1647  
1648 $omin = $orange->slice("(0)");
1649 $omax = $orange->slice("(1)");
1650 $osize = $omax - $omin;
1651  
1652 $rectify = 1;
1653  
1654 } else {
1655  
1656 ##############################
1657 # Real autoscaling happens here.
1658  
1659 if (!$rectify and ref( $f_in ) !~ /Linear/i) {
1660 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  
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 )
1672 );
1673  
1674 my $samps = (pdl(($in->dims)[0..$nd-1]))->clip(0,$samp_ratio);
1675  
1676 my $coords = ndcoords(($samps + 1)->list);
1677  
1678 my $t;
1679 my $irange = _opt($opt, ['ir','irange','input_range','Input_Range'],
1680 undef);
1681  
1682 # If input range is defined, sample that quadrilateral -- else
1683 # sample the quad defined by the boundaries of the input image.
1684 if (defined $irange) {
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 unless ( (($irange->dim(1)) == $nd )
1689 && $irange->ndims == 2);
1690  
1691 $coords *= ($irange->slice("(1)") - $irange->slice("(0)")) / $samps;
1692 $coords += $irange->slice("(0)");
1693 $coords -= 0.5; # offset to pixel corners...
1694 $t = $me;
1695 } else {
1696 $coords *= pdl(($in->dims)[0..$nd-1]) / $samps;
1697 $coords -= 0.5; # offset to pixel corners...
1698 $t = $f_tr;
1699 }
1700 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 ->dummy(0,1)
1711 );
1712  
1713 $omin = $oc2->minimum;
1714 $omax = $oc2->maximum;
1715  
1716 $osize = $omax - $omin;
1717 my $tosize;
1718 ($tosize = $osize->where($osize == 0)) .= 1.0;
1719 }
1720  
1721 my ($scale) = $osize / pdl(($out->dims)[0..$nd-1]);
1722  
1723 my $justify = _opt($opt,['j','J','just','justify','Justify'],0);
1724 if ($justify) {
1725 $scale->slice("0") *= $justify;
1726 $scale .= $scale->max;
1727 $scale->slice("0") /= $justify;
1728 }
1729  
1730 print "done with autoscale. Making fits header....\n" if $PDL::Transform::debug;
1731 if ( $rectify ) {
1732 # Rectified header generation -- make a simple coordinate header with no
1733 # rotation or skew.
1734 print "rectify\n" if $PDL::Transform::debug;
1735 for my $d(1..$nd) {
1736 $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 $out->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
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 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
1747 $me->{ounit}[$d-1])
1748 || $in->hdr->{"CUNIT$d"}
1749 || $in->hdr->{"CTYPE$d"}
1750 || "");
1751 }
1752 $out->hdr->{"NAXIS"} = $nd;
1753  
1754 $out->hdr->{"SIMPLE"} = 'T';
1755 $out->hdr->{"HISTORY"} .= "Header written by PDL::Transform::Cartography::map";
1756  
1757 ### 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 print "non-rectify\n" if $PDL::Transform::debug;
1769 my $midpoint_val = (pdl(($out->dims)[0..$nd-1])/2 * $scale)->apply( $f_in );
1770 print "midpoint_val is $midpoint_val\n" if $PDL::Transform::debug;
1771 # linear transformation
1772 unless(ref($f_in) =~ m/Linear/) {
1773 croak("Whups -- got a nonlinear t_fits transformation. Can't deal with it.");
1774 }
1775  
1776 my $inv_sc_mat = PDL::MatrixOps::stretcher($scale);
1777 my $mat = $f_in->{params}->{matrix} x $inv_sc_mat;
1778 print "scale is $scale; mat is $mat\n" if $PDL::Transform::debug;
1779  
1780 print "looping dims 1..$nd: " if $PDL::Transform::debug;
1781 for my $d(1..$nd) {
1782 print "$d..." if $PDL::Transform::debug;
1783 $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2;
1784 $out->hdr->{"CRVAL$d"} = $midpoint_val->at($d-1);
1785 $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 || $in->hdr->{"CTYPE$d"}
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 || $in->hdr->{"CTYPE$d"}
1796 || "");
1797 for my $e(1..$nd) {
1798 $out->hdr->{"CD${d}_${e}"} = $mat->at($d-1,$e-1);
1799 print "setting CD${d}_${e} to ".$mat->at($d-1,$e-1)."\n" if $PDL::Transform::debug;
1800 }
1801 }
1802  
1803 ## Eliminate competing header pointing tags if they exist
1804 delete @{$out->hdr}{
1805 grep /(^CROTA\d*$)|(^(PC)\d+_\d+[A-Z]?$)|(CDELT\d*$)/, keys %{$out->hdr}
1806 };
1807 }
1808 }
1809  
1810 $out->hdrcpy(1);
1811  
1812 ##############################
1813 # Sandwich the transform between the input and output plane FITS headers.
1814 unless($nofits) {
1815 $me = !t_fits($out,{ignore_rgb=>1}) x $me x $f_in;
1816 }
1817  
1818 ##############################
1819 ## Figure out the interpND options
1820 my $method = _opt($opt,['m','method','Method'],undef);
1821 my $bound = _opt($opt,['b','bound','boundary','Boundary'],'t');
1822  
1823 ##############################
1824 ## Rubber meets the road: calculate the inverse transformed points.
1825 my $ndc = PDL::Basic::ndcoords(@dd);
1826 my $idx = $me->invert($ndc->double);
1827  
1828 barf "map: Transformation had no inverse\n" unless defined($idx);
1829  
1830 ##############################
1831 ## Integrate ? (Jacobian, Gaussian, Hanning)
1832 my $integrate = ($method =~ m/^[jghJGH]/) if defined($method);
1833  
1834 ##############################
1835 ## Sampling code:
1836 ## just transform and interpolate.
1837 ## ( Kind of an anticlimax after all that, eh? )
1838 if (!$integrate) {
1839 my $x = $in->interpND($idx,{method=>$method, bound=>$bound});
1840 $out->slice(":") .= $x; # trivial slice prevents header overwrite...
1841 return $out;
1842 }
1843  
1844 ##############################
1845 ## Anti-aliasing code:
1846 ## Condition the input and call the pixelwise C interpolator.
1847 ##
1848  
1849 barf "PDL::Transform::map: Too many dims in transformation\n"
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 my @iddims = $idx->dims;
1856 my $in2 = $in->ndims == $#iddims
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 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 if (defined $bound) {
1872 if (ref $bound eq 'ARRAY') {
1873 my ($s,$el);
1874 foreach $el(@$bound) {
1875 barf "Illegal boundary value '$el' in range"
1876 unless( $el =~ m/^([0123fFtTeEpPmM])/ );
1877 $s .= $1;
1878 }
1879 $bound = $s;
1880 } elsif ($bound !~ m/^[0123ftepx]+$/ && $bound =~ m/^([0123ftepx])/i) {
1881 $bound = $1;
1882 }
1883 }
1884  
1885 ####################
1886 # Get the blur and minimum-sv values
1887 my $blur = _opt($opt,['blur','Blur'],1.0);
1888 my $svmin = _opt($opt,['sv','SV'],1.0);
1889 my $big = _opt($opt,['big','Big'],1.0);
1890 my $flux = _opt($opt,['phot','photometry'],0);
1891 my @idims = $in->dims;
1892  
1893 $flux = ($flux =~ m/^[1fF]/);
1894 $big = $big * max(pdl(@idims[0..$nd]));
1895 $blur = $blur->at(0) if ref $blur;
1896 $svmin = $svmin->at(0) if ref $svmin;
1897  
1898 my $bv = $in->badflag ? $in->badvalue->sclr : 0;
1899  
1900 ### The first argument is a dummy to set $GENERIC.
1901 $idx = double($idx) unless($idx->type == double);
1902 print "Calling _map_int...\n" if $PDL::Transform::debug;
1903 &PDL::_map_int( $in2->flat->index(0),
1904 $in2, $o2, $idx,
1905 $bound, $method, $big, $blur, $svmin, $flux, $bv);
1906  
1907 my @rdims = (@iddims[1..$#iddims], @idims[$#iddims..$#idims]);
1908 {
1909 $out->slice(":") .= $o2->reshape(@rdims);
1910 }
1911 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 sub unmap {
1947 my($me) = shift;
1948 my($data) = shift;
1949 my(@params) = @_;
1950  
1951 if (UNIVERSAL::isa($data,'PDL::Transform') && UNIVERSAL::isa($me,'PDL')) {
1952 my $x = $data;
1953 $data = $me;
1954 $me = $x;
1955 }
1956  
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 sub inverse {
1994 my($me) = shift;
1995 barf("PDL::Transform::inverse: got a transform with no inverse")
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 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 package PDL::Transform::Composition;
2044 shift->SUPER::stringify;
2045 }
2046  
2047 *t_compose = \&compose;
2048 sub compose {
2049 local($_);
2050 my(@funcs) = @_;
2051 my($me) = PDL::Transform->new;
2052 # No inputs case: return the identity function
2053 return $me if !@funcs;
2054 $me->{name} = "";
2055 my @clist;
2056 for my $f (@funcs) {
2057 $me->{idim} = $f->{idim} if $f->{idim} > $me->{idim};
2058 $me->{odim} = $f->{odim} if $f->{odim} > $me->{odim};
2059 if (UNIVERSAL::isa($f,"PDL::Transform::Composition")) {
2060 if ($f->{is_inverse}) {
2061 for (reverse(@{$f->{params}->{clist}})) {
2062 push(@clist,$_->inverse);
2063 $me->{name} .= " o inverse ( ".$_->{name}." )";
2064 }
2065 } else {
2066 for (@{$f->{params}->{clist}}) {
2067 push(@clist,$_);
2068 $me->{name} .= " o ".$_->{name};
2069 }
2070 }
2071 } else { # Not a composition -- just push the transform onto the list.
2072 push(@clist,$f);
2073 $me->{name} .= " o ".$f->{name};
2074 }
2075 }
2076 $me->{name}=~ s/^ o //; # Get rid of leading composition mark
2077 $me->{otype} = $funcs[0]->{otype};
2078 $me->{ounit} = $funcs[0]->{ounit};
2079 $me->{itype} = $funcs[-1]->{itype};
2080 $me->{iunit} = $funcs[-1]->{iunit};
2081 $me->{params}->{clist} = \@clist;
2082 $me->{func} = sub {
2083 my ($data,$p) = @_;
2084 my ($ip) = $data->is_inplace;
2085 for my $t ( reverse @{$p->{clist}} ) {
2086 croak("Error: tried to apply a PDL::Transform with no function inside a composition!\n offending transform: $t\n")
2087 unless(defined($t->{func}) and ref($t->{func}) eq 'CODE');
2088 $data = $t->{func}($ip ? $data->inplace : $data, $t->{params});
2089 }
2090 $data->is_inplace(0); # clear inplace flag (avoid core bug with inplace)
2091 $data;
2092 };
2093 $me->{inv} = sub {
2094 my ($data,$p) = @_;
2095 my $ip = $data->is_inplace;
2096 for my $t ( @{$p->{clist}} ) {
2097 croak("Error: tried to invert a non-invertible PDL::Transform inside a composition!\n offending transform: $t\n")
2098 unless(defined($t->{inv}) and ref($t->{inv}) eq 'CODE');
2099 $data = &{$t->{inv}}($ip ? $data->inplace : $data, $t->{params});
2100 }
2101 $data;
2102 };
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 sub wrap {
2140 my($f) = shift;
2141 my($g) = shift;
2142  
2143 return $g->inverse->compose($f,$g);
2144 }
2145  
2146  
2147  
2148 ######################################################################
2149  
2150 # Composition operator -- handles 'x'.
2151 sub _compose_op {
2152 my($x,$y,$c) = @_;
2153 $c ? compose($y,$x) : compose($x,$y);
2154 }
2155  
2156 # Raise-to-power operator -- handles '**'.
2157  
2158 sub _pow_op {
2159 my($x,$y,$c) = @_;
2160  
2161 barf("Can't raise anything to the power of a transform")
2162 if $c || UNIVERSAL::isa($y,'PDL::Transform');
2163  
2164 $x = $x->inverse
2165 if $y < 0;
2166  
2167 return $x if abs($y) == 1;
2168 return PDL::Transform->new if abs($y) == 0;
2169  
2170 my(@l);
2171 for my $i(1..abs($y)) {
2172 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  
2200 sub _identity { return shift; }
2201 sub t_identity { new PDL::Transform(@_) };
2202  
2203 sub new {
2204 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  
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 sub t_lookup {
2325 my($class) = 'PDL::Transform';
2326 my($source)= shift;
2327 my($o) = shift;
2328  
2329 if (!defined($o) && ((ref $source) eq 'HASH')) {
2330 Carp::cluck("lookup transform called as sub not method; using 'PDL::Transform' as class...\n");
2331 $o = $source;
2332 $source = $class;
2333 $class = "PDL::Transform";
2334 }
2335  
2336 $o = {} unless(ref $o eq 'HASH');
2337  
2338 my($me) = $class->new;
2339  
2340 my($bound) = _opt($o,['b','bound','boundary','Boundary']);
2341 my($method)= _opt($o,['m','meth','method','Method']);
2342  
2343 $me->{idim} = $source->ndims - 1;
2344 $me->{odim} = $source->dim($source->ndims-1);
2345  
2346 $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  
2358 my $lookup_func = sub {
2359 my($data,$p,$table,$scale,$offset) = @_;
2360  
2361 $data = pdl($data)
2362 unless ((ref $data) && (UNIVERSAL::isa($data,'PDL')));
2363 $main::foo = $data;
2364  
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 $p->{interpND_opt}
2372 )
2373 );
2374  
2375  
2376 # Put the index dimension (and broadcasted indices) back at the front of
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 , 0..$data->ndims-2
2382 )
2383 ) : $x;
2384 };
2385  
2386 $me->{func} = sub {my($data,$p) = @_; &$lookup_func($data,$p,$p->{table},$p->{scale},$p->{offset})};
2387  
2388 #######
2389 ## Lazy inverse -- find it if and only if we need it...
2390 $me->{inv} = sub {
2391 my $data = shift;
2392 my $p = shift;
2393 if (!defined($p->{'itable'})) {
2394 if ($me->{idim} != $me->{odim}) {
2395 barf("t_lookup: can't calculate an inverse of a projection operation! (idim != odim)");
2396 }
2397 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 my $maxvals = $p->{table}->clump($me->{idim})->maximum;
2401  
2402 # 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 (($maxvals - $minvals)+ (($maxvals-$minvals) == 0));
2405 my $offset = - ($minvals * $scale);
2406  
2407 $p->{iscale} = $scale;
2408 $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  
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 mv(0,-1)->
2418 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 # to find minimum distance. But memory demands for that would be HUGE. Instead we do an
2426 # elementwise calculation.
2427  
2428 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  
2431 my $itable_flattened = zeroes($oloop);
2432  
2433 for my $i (0..$oloop->dim(0)-1) {
2434  
2435 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 my $c = whichND($r2==$r2->min)->slice(":,(0)"); # c runs (index)
2439  
2440 # Now zero in on the neighborhood around the point of closest approach.
2441 my $neighborhood = $p->{table}->interpND($c + $smallcoords,{method=>'linear',bound=>'t'})->
2442 mv(-1,0); # neighborhood runs (index, dx, dy,...)
2443 $diff = $neighborhood - $olp; # diff runs (index, dx, dy, ...)
2444 $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  
2448 my $coord = $c + $dc;
2449 # At last, we've found the best-fit to an enl_scale'th of an input-table pixel.
2450 # Back it out to input-science coordinates, and stuff it in the inverse table.
2451 $itable_flattened->slice("($i)") .= $coord;
2452  
2453 print " $i..." if $i%1000==0 && ($PDL::verbose || $PDL::debug || $PDL::Transform::debug);
2454 }
2455  
2456 {
2457 $itable->clump($itable->ndims-1) .= $itable_flattened;
2458 $itable->mv(-1,0) -= $p->{offset};
2459 $itable->mv(-1,0) /= $p->{scale};
2460 }
2461  
2462 $p->{itable} = $itable;
2463 }
2464 &$lookup_func($data,$p, $p->{itable},$p->{iscale},$p->{ioffset}) ;
2465 };
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 *identity = \&PDL::MatrixOps::identity;
2594 use PDL::Constants qw(DEG2RAD);
2595  
2596 sub PDL::Transform::t_linear { PDL::Transform::Linear->new(@_); }
2597  
2598 sub new {
2599 my($class) = shift;
2600 my($o) = $_[0];
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  
2605 if (!(ref $o)) {
2606 $o = {@_};
2607 }
2608  
2609 my($me) = __PACKAGE__->SUPER::new;
2610  
2611 $me->{name} = "linear";
2612  
2613 $me->{params}{pre} = _opt($o,['pre','Pre','preoffset','offset',
2614 'Offset','PreOffset','Preoffset'],0);
2615 $me->{params}{pre} = PDL->pdl($me->{params}{pre})
2616 if defined $me->{params}{pre};
2617  
2618 $me->{params}{post} = _opt($o,['post','Post','postoffset','PostOffset',
2619 'shift','Shift'],0);
2620 $me->{params}{post} = PDL->pdl($me->{params}{post})
2621 if defined $me->{params}{post};
2622  
2623 $me->{params}{matrix} = _opt($o,['m','matrix','Matrix','mat','Mat']);
2624 $me->{params}{matrix} = PDL->pdl($me->{params}{matrix})
2625 if defined $me->{params}{matrix};
2626  
2627 $me->{params}{rot} = _opt($o,['r','rot','rota','rotation','Rotation'], 0);
2628 $me->{params}{rot} = PDL->pdl($me->{params}{rot});
2629  
2630 my $o_dims = _opt($o,['d','dim','dims','Dims']);
2631 $o_dims = PDL->pdl($o_dims) if defined($o_dims);
2632  
2633 my $scale = _opt($o,['s','scale','Scale']);
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  
2639 my $rot = $me->{params}{rot};
2640 if (defined($me->{params}{matrix})) {
2641 my $mat = $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
2642 $me->{idim} = $mat->dim(0);
2643 $me->{odim} = $mat->dim(1);
2644  
2645 } else {
2646 if (defined($me->{params}->{rot}) &&
2647 UNIVERSAL::isa($me->{params}->{rot},'PDL')) {
2648 $me->{idim} = $me->{odim} = 2 if $me->{params}{rot}->nelem == 1;
2649 $me->{idim} = $me->{odim} = 3 if $me->{params}{rot}->nelem == 3;
2650 }
2651  
2652 if (defined($scale) &&
2653 UNIVERSAL::isa($scale,'PDL') &&
2654 $scale->getndims > 0) {
2655 $me->{idim} = $me->{odim} = $scale->dim(0);
2656 $me->{odim} = $scale->dim(0);
2657  
2658 } elsif (defined($me->{params}{pre}) &&
2659 UNIVERSAL::isa($me->{params}{pre},'PDL') &&
2660 $me->{params}{pre}->getndims > 0) {
2661 $me->{idim} = $me->{odim} = $me->{params}{pre}->dim(0);
2662  
2663 } elsif (defined($me->{params}{post}) &&
2664 UNIVERSAL::isa($me->{params}{post},'PDL') &&
2665 $me->{params}{post}->getndims > 0) {
2666 $me->{idim} = $me->{odim} = $me->{params}{post}->dim(0);
2667 } elsif (defined($o_dims)) {
2668 $me->{idim} = $me->{odim} = $o_dims;
2669 } elsif (UNIVERSAL::isa($rot,'PDL') && (my $nrots = $rot->nelem) > 1) {
2670 $me->{idim} = $me->{odim} = $nrots;
2671 } else {
2672 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  
2676 $me->{params}->{matrix} = PDL->zeroes($me->{idim},$me->{odim});
2677 $me->{params}->{matrix}->diagonal(0,1) .= 1;
2678 }
2679  
2680 ### Handle rotation option
2681 if (defined($rot)) {
2682 # Subrotation closure -- rotates from axis $d->(0) --> $d->(1).
2683 my $subrot = sub {
2684 my($d,$angle,$m)=@_;
2685 my($i) = identity($m->dim(0));
2686 my($subm) = $i->dice($d,$d);
2687  
2688 $angle = $angle->at(0)
2689 if UNIVERSAL::isa($angle,'PDL');
2690  
2691 my($x) = $angle * DEG2RAD;
2692 $subm .= $subm x PDL->pdl([cos($x),-sin($x)],[sin($x),cos($x)]);
2693 $m .= $m x $i;
2694 };
2695  
2696 if (UNIVERSAL::isa($rot,'PDL') && $rot->nelem > 1) {
2697 if ($rot->ndims == 2) {
2698 $me->{params}{matrix} x= $rot;
2699 } elsif ($rot->nelem == 3) {
2700 my $rm = identity(3);
2701  
2702 # Do these in reverse order to make it more like
2703 # function composition!
2704 &$subrot(PDL->pdl(0,1),$rot->at(2),$rm);
2705 &$subrot(PDL->pdl(2,0),$rot->at(1),$rm);
2706 &$subrot(PDL->pdl(1,2),$rot->at(0),$rm);
2707  
2708 $me->{params}{matrix} .= $me->{params}{matrix} x $rm;
2709 } else {
2710 barf("PDL::Transform::Linear: Got a strange rot option -- giving up.\n");
2711 }
2712 } else {
2713 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 # Apply scaling
2720 $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
2721 $me->{params}{matrix}->diagonal(0,1) *= $scale
2722 if defined($scale);
2723  
2724 # Check for an inverse and apply it if possible
2725 my($o2);
2726 if ($me->{params}{matrix}->det($o2 = {lu=>undef})) {
2727 $me->{params}{inverse} = $me->{params}{matrix}->inv($o2);
2728 } else {
2729 delete $me->{params}{inverse};
2730 }
2731  
2732 $me->{params}{idim} = $me->{idim};
2733 $me->{params}{odim} = $me->{odim};
2734  
2735 for (qw(iunit ounit itype otype)) {
2736 next unless defined (my $val = _opt($o,[$_]));
2737 $me->{$_} = $val;
2738 }
2739  
2740 ##############################
2741 # The meat -- just shift, matrix-multiply, and shift again.
2742 $me->{func} = sub {
2743 my ($in,$opt) = @_;
2744 my $d = $opt->{matrix}->dim(0)-1;
2745 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
2746 if $in->dim(0) <= $d;
2747 my $x = $in->slice("0:$d")->copy + $opt->{pre};
2748 my $out = $in->new_or_inplace;
2749 $out->slice("0:$d") .= $x x $opt->{matrix} + $opt->{post};
2750 return $out;
2751 };
2752  
2753 $me->{inv} = (defined $me->{params}{inverse}) ? sub {
2754 my ($in,$opt) = @_;
2755 my $d = $opt->{inverse}->dim(0)-1;
2756 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
2757 if $in->dim(0) <= $d;
2758 my $x = $in->slice("0:$d")->copy - $opt->{post};
2759 my $out = $in->new_or_inplace;
2760 $out->slice("0:$d") .= $x x $opt->{inverse} - $opt->{pre};
2761 $out;
2762 } : undef;
2763  
2764 return $me;
2765 }
2766  
2767 sub stringify {
2768 my($me) = shift; my($out) = SUPER::stringify $me;
2769 my $mp = $me->{params};
2770  
2771 if (!($me->{is_inverse})){
2772 $out .= "Pre-add: ".($mp->{pre})."\n"
2773 if defined $mp->{pre};
2774  
2775 $out .= "Post-add: ".($mp->{post})."\n"
2776 if defined $mp->{post};
2777  
2778 $out .= "Forward matrix:".($mp->{matrix})
2779 if defined $mp->{matrix};
2780  
2781 $out .= "Inverse matrix:".($mp->{inverse})
2782 if defined $mp->{inverse};
2783 } else {
2784 $out .= "Pre-add: ".(-$mp->{post})."\n"
2785 if defined $mp->{post};
2786  
2787 $out .= "Post-add: ".(-$mp->{pre})."\n"
2788 if defined $mp->{pre};
2789  
2790 $out .= "Forward matrix:".($mp->{inverse})
2791 if defined $mp->{inverse};
2792  
2793 $out .= "Inverse matrix:".($mp->{matrix})
2794 if defined $mp->{matrix};
2795 }
2796  
2797 $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 sub t_scale {
2823 my($scale) = shift;
2824 my($y) = shift;
2825 return t_linear(scale=>$scale,%{$y})
2826 if ref $y eq 'HASH';
2827 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 sub t_offset {
2851 my($pre) = shift;
2852 my($y) = shift;
2853 return t_linear(pre=>$pre,%{$y})
2854 if ref $y eq 'HASH';
2855  
2856 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 sub t_rotate {
2881 my $rot = shift;
2882 my($y) = shift;
2883 return t_linear(rot=>$rot,%{$y})
2884 if ref $y eq 'HASH';
2885  
2886 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 sub t_fits {
2931 my($hdr) = shift;
2932 my($opt) = shift;
2933  
2934 if (ref $opt ne 'HASH') {
2935 $opt = defined $opt ? {$opt,@_} : {} ;
2936 }
2937  
2938 $hdr = $hdr->gethdr
2939 if defined $hdr && UNIVERSAL::isa($hdr,'PDL');
2940  
2941 croak('t_fits requires a FITS header hash\n')
2942 if !defined $hdr || ref $hdr ne 'HASH' || !defined($hdr->{NAXIS});
2943  
2944 my($n) = $hdr->{NAXIS}; $n = $n->at(0) if UNIVERSAL::isa($n,'PDL');
2945  
2946 $n = 2
2947 if $opt->{ignore_rgb} && $n==3 && $hdr->{NAXIS3} == 3;
2948  
2949 my($matrix) = PDL->zeroes($n,$n);
2950 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  
2957 my(@hgrab);
2958  
2959 if (@hgrab = grep(m/^CD\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2960 #
2961 # CDi_j formalism
2962 #
2963 for my $h(@hgrab) {
2964 $h =~ m/CD(\d{1,3})_(\d{1,3})/; # Should always match
2965 $matrix->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
2966 }
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  
2978 my($cdm) = PDL->zeroes($n,$n);
2979 my($cd) = $cdm->diagonal(0,1);
2980  
2981 my($cpm) = PDL->zeroes($n,$n);
2982 $cpm->diagonal(0,1) .= 1; # PC: diagonal defaults to unity
2983 $cd .= 1;
2984  
2985  
2986 if (@hgrab = grep(m/^PC\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2987  
2988 for my $h(@hgrab) {
2989 $h =~ m/PC(\d{1,3})_(\d{1,3})$/ || die "t_fits - match failed! This should never happen!";
2990 $cpm->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
2991 }
2992 print "t_fits: Detected PCi_j matrix: \n",$cpm,"\n"
2993 if $PDL::Transform::debug && @hgrab;
2994  
2995 } elsif ($n==2 && grep defined $hdr->{$_}, qw(CROTA CROTA1 CROTA2)) {
2996  
2997 ## CROTA is deprecated; CROTA1 was used for a while but is unofficial;
2998 ## CROTA2 is encouraged instead.
2999 my $cr = $hdr->{CROTA2} // $hdr->{CROTA} // $hdr->{CROTA1};
3000  
3001 $cr *= DEG2RAD();
3002 # 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 }
3007  
3008 for my $i(1..$n) {
3009 $cd->slice("(".($i-1).")") .= $hdr->{"CDELT$i"};
3010 }
3011 #If there are no CDELTs, then we assume they are all 1.0
3012 $cd+=1 if (all($cd==0));
3013  
3014 $matrix = $cdm x $cpm;
3015 }
3016  
3017 my($i1) = 0;
3018 for my $i(1..$n) {
3019 $pre->slice("($i1)") .= 1 - $hdr->{"CRPIX$i"};
3020 $post->slice("($i1)") .= $hdr->{"CRVAL$i"};
3021 $i1++;
3022 }
3023  
3024 my $me = PDL::Transform::Linear->new({
3025 pre=>$pre, post=>$post, matrix=>$matrix
3026 });
3027 $me->{name} = 'FITS';
3028  
3029 my (@otype,@ounit,@itype,@iunit);
3030 my @names = qw(X Y Z);
3031 for my $i(1..$hdr->{NAXIS}) {
3032 push(@otype,$hdr->{"CTYPE$i"});
3033 push(@ounit,$hdr->{"CUNIT$i"});
3034 push(@itype,"Image ". ( ($i-1<=$#names) ? $names[$i-1] : "${i}th dim" ));
3035 push(@iunit,"Pixels");
3036 }
3037 $me->{otype} = \@otype;
3038 $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 # }
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 sub t_code {
3128 my($class) = 'PDL::Transform';
3129 my($func, $inv, $o) = @_;
3130 if (ref $inv eq 'HASH') {
3131 $o = $inv;
3132 $inv = undef;
3133 }
3134  
3135 my($me) = $class->new;
3136 $me->{name} = _opt($o,['n','name','Name']) || "code";
3137 $me->{func} = $func;
3138 $me->{inv} = $inv;
3139 $me->{params} = _opt($o,['p','params','Params']) || {};
3140 $me->{idim} = _opt($o,['i','idim']) || 2;
3141 $me->{odim} = _opt($o,['o','odim']) || 2;
3142 $me->{itype} = _opt($o,['itype']) || [];
3143 $me->{otype} = _opt($o,['otype']) || [];
3144 $me->{iunit} = _opt($o,['iunit']) || [];
3145 $me->{ounit} = _opt($o,['ounit']) || [];
3146  
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 =cut
3247  
3248 use PDL::Constants qw(RAD2DEG);
3249 *t_cylindrical = \&t_radial;
3250 sub t_radial {
3251 my($class) = 'PDL::Transform';
3252 my($o) = $_[0];
3253 if (ref $o ne 'HASH') {
3254 $o = { @_ };
3255 }
3256  
3257 my($me) = $class->new;
3258  
3259 $me->{params}{origin} = _opt($o,['o','origin','Origin']);
3260 $me->{params}{origin} = pdl(0,0)
3261 unless defined($me->{params}{origin});
3262 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
3263  
3264  
3265 $me->{params}{r0} = _opt($o,['r0','R0','c','conformal','Conformal']);
3266 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
3267  
3268 $me->{params}{u} = _opt($o,['u','unit','Unit'],'radians');
3269 ### Replace this kludge with a units call
3270 $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  
3273 $me->{name} = "radial (direct)";
3274  
3275 $me->{idim} = 2;
3276 $me->{odim} = 2;
3277  
3278 if ($me->{params}{r0}) {
3279 $me->{otype} = ["Azimuth", "Ln radius" . ($me->{params}->{r0} != 1.0 ? "/$me->{params}->{r0}" : "")];
3280 $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  
3286 $me->{func} = sub {
3287  
3288 my($data,$o) = @_;
3289  
3290 my($out) = ($data->new_or_inplace);
3291  
3292 my($d) = $data->copy;
3293 $d->slice("0:1") -= $o->{origin};
3294  
3295 my($d0) = $d->slice("(0)");
3296 my($d1) = $d->slice("(1)");
3297  
3298 # (mod operator on atan2 puts everything in the interval [0,2*PI).)
3299 $out->slice("(0)") .= (atan2(-$d1,$d0) % (2*PDL::Transform::PI())) * $me->{params}->{angunit};
3300  
3301 $out->slice("(1)") .= (defined $o->{r0}) ?
3302 0.5 * log( ($d1*$d1 + $d0 * $d0) / ($o->{r0} * $o->{r0}) ) :
3303 sqrt($d1*$d1 + $d0*$d0);
3304  
3305 $out;
3306 };
3307  
3308 $me->{inv} = sub {
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 ($d->slice("(0)"), $d->slice("(1)")->dummy(0,2), $d->copy)
3315 );
3316  
3317 $d0 /= $me->{params}->{angunit};
3318  
3319 my($os) = $out->slice("0:1");
3320 $os .= append(cos($d0)->dummy(0,1),-sin($d0)->dummy(0,1));
3321 $os *= defined $o->{r0} ? ($o->{r0} * exp($d1)) : $d1;
3322 $os += $o->{origin};
3323  
3324 $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  
3394 sub t_quadratic {
3395 my($class) = 'PDL::Transform';
3396 my($o) = $_[0];
3397 if (ref $o ne 'HASH') {
3398 $o = {@_};
3399 }
3400 my($me) = $class->new;
3401  
3402 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3403 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
3404 $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  
3408 $me->{func} = sub {
3409 my($data,$o) = @_;
3410 my($dd) = $data->copy - $o->{origin};
3411 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3412 $d += $o->{str} * ($d * abs($d)) / $o->{l0};
3413 $d /= (abs($o->{str}) + 1);
3414 $d += $o->{origin};
3415 if ($data->is_inplace) {
3416 $data .= $dd;
3417 return $data;
3418 }
3419 $dd;
3420 };
3421  
3422 $me->{inv} = sub {
3423 my($data,$opt) = @_;
3424 my($dd) = $data->copy ;
3425 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
3426 my($o) = $opt->{origin};
3427 my($s) = $opt->{str};
3428 my($l) = $opt->{l0};
3429  
3430 $d .= ((-1 + sqrt(1 + 4 * $s/$l * abs($d-$o) * (1+abs($s))))
3431 / 2 / $s * $l) * (1 - 2*($d < $o));
3432 $d += $o;
3433 if ($data->is_inplace) {
3434 $data .= $dd;
3435 return $data;
3436 }
3437 $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 # needed since due to floating-point approx, is not *exactly* a cube-root
3496 sub _cuberoot {
3497 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 # so there is always exactly one real root.
3506 sub _solve_depressed_cubic {
3507 my ($A, $C, $D) = @_;
3508 my $alpha = 27 * $A * $A * $D;
3509 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  
3518 sub t_cubic {
3519 my ($class) = 'PDL::Transform';
3520 my($o) = $_[0];
3521 if (ref $o ne 'HASH') {
3522 $o = {@_};
3523 }
3524 my($me) = $class->new;
3525  
3526 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims'],undef);
3527 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3528 $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  
3532 $me->{func} = sub {
3533 my($data,$o) = @_;
3534 my($dd) = $data->copy;
3535 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3536  
3537 $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 # C = 1
3545 # D = -f(x)
3546 $d += $o->{st} * $d * $dl0 * $dl0;
3547 $d /= ($o->{st}**2 + 1);
3548  
3549 $d += $o->{origin};
3550  
3551 if ($data->is_inplace) {
3552 $data .= $dd;
3553 return $data;
3554 }
3555 return $dd;
3556 };
3557  
3558 $me->{inv} = sub {
3559 my($data,$o) = @_;
3560 my($l) = $o->{l0};
3561  
3562 my($dd) = $data->copy;
3563 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3564  
3565 $d -= $o->{origin};
3566 $d *= ($o->{st}+1);
3567  
3568 # First: create coefficients for mnemonics.
3569 my ($A, $C, $D) = ( $o->{st} / $l / $l, 1, - $d );
3570  
3571 $d .= _solve_depressed_cubic($A, $C, $D);
3572  
3573 $d += $me->{params}{origin};
3574  
3575 if ($data->is_inplace) {
3576 $data .= $dd;
3577 return $data;
3578 } else {
3579 return $dd;
3580 }
3581 };
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 sub _solve_depressed_cubic_multi {
3655 require PDL::Math;
3656 my ($p, $q) = @_;
3657 barf "inverse t_quartic: \$p must be negative" if $p->ge(0)->any;
3658 my $acos = PDL::Math::acos(3*$q/(2*$p) * sqrt(-3/$p));
3659 my $cos = cos($acos/3);
3660 2 * sqrt(-$p/3) * $cos;
3661 }
3662  
3663 sub t_quartic {
3664 my($class) = 'PDL::Transform';
3665 my($o) = $_[0];
3666 if (ref $o ne 'HASH') {
3667 $o = {@_};
3668 }
3669 my($me) = $class->new;
3670  
3671 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
3672 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
3673 $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
3674 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
3675 $me->{name} = "quartic";
3676  
3677 $me->{func} = sub {
3678 my($data,$o) = @_;
3679 my($dd) = $data->copy - $o->{origin};
3680 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
3681 $d += $o->{str} * ($d**3 * abs($d)) / ($o->{l0} ** 3);
3682 $d /= (abs($o->{str}) + 1);
3683 $d += $o->{origin};
3684 if ($data->is_inplace) {
3685 $data .= $dd;
3686 return $data;
3687 }
3688 $dd;
3689 };
3690  
3691 $me->{inv} = sub {
3692 my($data,$opt) = @_;
3693 my($dd) = $data->copy ;
3694 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
3695 my($o) = $opt->{origin};
3696 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  
3711 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  
3719 my $p = -$C / (4*$A);
3720 my $q = -($B/(8*$A)) ** 2;
3721 my $S = _solve_depressed_cubic(1, $p, $q);
3722 my $sqrt_S = sqrt($S);
3723 my $x = -$sqrt_S + sqrt($B / (4*$A*$sqrt_S) - $S);
3724  
3725 $d .= $x * $sign;
3726 $d += $o;
3727 if ($data->is_inplace) {
3728 $data .= $dd;
3729 return $data;
3730 }
3731 $dd;
3732 };
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 sub t_spherical {
3798 my($class) = 'PDL::Transform';
3799 my($o) = $_[0];
3800 if (ref $o ne 'HASH') {
3801 $o = { @_ } ;
3802 }
3803  
3804 my($me) = $class->new;
3805  
3806 $me->{idim}=3;
3807 $me->{odim}=3;
3808  
3809 $me->{params}->{origin} = _opt($o,['o','origin','Origin']);
3810 $me->{params}->{origin} //= PDL->zeroes(3);
3811 $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});
3812  
3813 $me->{params}->{deg} = _opt($o,['d','degrees','Degrees']);
3814  
3815 my $unit = _opt($o,['u','unit','Unit']);
3816 $me->{params}{angunit} = ($unit && $unit =~ m/^d/i) ?
3817 DEG2RAD() : undef;
3818  
3819 $me->{name} = "spherical";
3820  
3821 $me->{func} = sub {
3822 my ($data,$o) = @_;
3823 my $d = $data->copy - $o->{origin};
3824 my ($d0,$d1,$d2) = ($d->slice("(0)"),$d->slice("(1)"),$d->slice("(2)"));
3825 my $out = ($d->is_inplace) ? $data : $data->copy;
3826 $out->slice("(0)") .= PDL::atan2($d1, $d0);
3827 $out->slice("(2)") .= PDL::sqrt($d0*$d0 + $d1*$d1 + $d2*$d2);
3828 $out->slice("(1)") .= PDL::asin($d2 / $out->slice("(2)"));
3829 $out->slice("0:1") /= $o->{angunit}
3830 if defined $o->{angunit};
3831 $out;
3832 };
3833  
3834 $me->{inv} = sub {
3835 my ($d,$o) = @_;
3836 PDL::t_spherical_inv($d, $o->{origin}, $o->{angunit} // 1);
3837 };
3838  
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 sub sub_eps_to_0 {
3971 my ($m, $eps) = @_;
3972 $m * (abs($m) > $eps)
3973 }
3974  
3975 sub _normalise_points {
3976 my ($pts) = @_;
3977 my $d = $pts->dim(0); # pts: (dim,N) matrix where each row is a point
3978 my $centroid = $pts->t->avgover;
3979 my $shifted = $pts - $centroid; # shift points to origin
3980 # 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 # T combines scaling and translation: T = Scale * Translate
3983 my $T = identity($d + 1);
3984 $T->diagonal(0,1)->slice(":-2") .= $scale;
3985 $T->slice("(-1),:-2") .= -$scale * $centroid;
3986 my $pts_h = $pts->append(1) x $T->t; # Convert to homogeneous coords, apply T
3987 ($pts_h, $T);
3988 }
3989  
3990 sub block_rotate :lvalue {
3991 my ($m, $width) = @_;
3992 die "block_rotate: given undef width" if !defined $width;
3993 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 sub construct_DLT {
3999 my ($pts_src, $pts_dst) = @_;
4000 die "t_projective: must supply same number of src and dst points\n"
4001 unless $pts_src->dim(1) == $pts_dst->dim(1);
4002 my ($pts_src_h, $T_src) = _normalise_points($pts_src); # (n+1,N) homogeneous
4003 my ($pts_dst_h, $T_dst) = _normalise_points($pts_dst); # (m+1,N) homogeneous
4004 my ($src_dim, $N) = $pts_src_h->dims; # n+1
4005 my ($dst_dim) = $pts_dst_h->dims; # m+1
4006 my $num_eqs = $N * ($dst_dim - 1); # Each point match provides (m) equations
4007 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 # Fill coefficients for the j-th row of P
4011 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 # Fill coefficients for the last row of P
4014 $A = $A->append(-outer($pts_src_h, $pts_dst_h->slice(":-2"))->clump(1,2));
4015 ($A, $T_src, $T_dst);
4016 }
4017  
4018 sub solve_DLT {
4019 my ($A, $T_src, $T_dst) = @_;
4020 my ($U, $S, $V) = svd($A, 1); # full SVD
4021 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 sub t_projective {
4026 my $class = 'PDL::Transform';
4027 my $o = ref $_[0] eq 'HASH' ? $_[0] : { @_ };
4028  
4029 my $me = $class->new;
4030 $me->{name} = "projective";
4031  
4032 ### Set options...
4033 $me->{params}{idim} = $me->{idim} = _opt($o,['d','dim','Dim']);
4034  
4035 my $matrix;
4036 if (defined ($matrix=_opt($o,['m','matrix','Matrix']))) {
4037 $matrix = PDL->topdl($matrix);
4038 $me->{params}{idim} //= $matrix->dim(0)-1;
4039 die "t_projective: matrix not compatible with given dimension (should be N+1xN+1)\n"
4040 unless $me->{params}{idim} == $matrix->dim(0)-1;
4041 } else {
4042 my ($p, $pts_src, $pts_dst) = _opt($o,['p','point','points','Point','Points']);
4043 if (defined $p) {
4044 $p = PDL->topdl($p);
4045 die "t_projective: points must be ncoord x 2(in,out) x ncoord+2(point)"
4046 unless $p->dims==3 && all($p->shape == pdl(2,2,4));
4047 ($pts_src, $pts_dst) = $p->mv(1,-1)->dog;
4048 } else {
4049 ($pts_src, $pts_dst) = map _opt($o,$_), ['src','from'], ['dst','to'];
4050 }
4051 die "t_projective: must supply either 'p', 'm', or 'src' and 'dst' options"
4052 if grep !defined, $pts_src, $pts_dst;
4053 my ($A, $T_src, $T_dst) = construct_DLT($pts_src, $pts_dst);
4054 # Solve the system
4055 $matrix = solve_DLT($A, $T_src, $T_dst);
4056 }
4057 $me->{params}{matrix} = $matrix;
4058 $me->{params}{matinv} = $matrix->inv if $matrix->dim(0) == $matrix->dim(1);
4059  
4060 $me->{idim} = $me->{odim} = $me->{params}{odim} = $me->{params}{idim} //= 2;
4061  
4062 $me->{func} = sub {
4063 my ($data,$o) = @_;
4064 my $out = $data->append(1) x $o->{matrix}->t;
4065 $out->slice("0:-2")/$out->slice("-1");
4066 };
4067  
4068 $me->{inv} = sub {
4069 my ($data,$o) = @_;
4070 die "t_projective: uninvertible projection due to dimension change"
4071 if !defined $o->{matinv};
4072 my $out = $data->append(1) x $o->{matinv}->t;
4073 $out->slice("0:-2")/$out->slice("-1");
4074 };
4075  
4076 $me;
4077 }
4078  
4079 +======EOD_t_projective======
4080  
4081 pp_done();
« lib/PDL/IO/Pnm-pp-pnmout.c ↑ Summary lib/PDL/Primitive-pp-pchip_chbs.c »