blib/lib/PDL/Transform.pm

filter: Statementstmt 82.3% 14 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 85.0% 17 / 20 CC 1 SCAR 0.0
CC
1
Cov
82%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/PDL/Slices-pp-broadcastI.c ↑ Summary lib/PDL/Slices-pp-xchg.c »
1 #
2 # GENERATED WITH PDL::PP from lib/PDL/Transform.pd! Don't modify!
3 #
4 package PDL::Transform;
5  
6 1 our @EXPORT_OK = qw(apply invert map map unmap t_inverse t_compose t_wrap t_identity t_lookup t_linear t_scale t_offset t_rot t_fits t_code t_cylindrical t_radial t_quadratic t_cubic t_quartic t_spherical t_spherical_inv t_projective );
7 1 our %EXPORT_TAGS = (Func=>\@EXPORT_OK);
8  
9 1 ▶use PDL::Core;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use PDL::Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use DynaLoader;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14
15 1 our @ISA = ( 'PDL::Exporter','DynaLoader' );
16 1 push @PDL::Core::PP, __PACKAGE__;
17 1 bootstrap PDL::Transform ;
18  
19  
20  
21  
22  
23  
24  
25  
26 #line 5 "lib/PDL/Transform.pd"
27  
28 =head1 NAME
29  
30 PDL::Transform - Coordinate transforms, image warping, and N-D functions
31  
32 =head1 SYNOPSIS
33  
34 use PDL::Transform;
35  
36 my $t = PDL::Transform::<type>->new(<opt>)
37  
38 $out = $t->apply($in) # Apply transform to some N-vectors (Transform method)
39 $out = $in->apply($t) # Apply transform to some N-vectors (PDL method)
40  
41 $im1 = $t->map($im); # Transform image coordinates (Transform method)
42 $im1 = $im->map($t); # Transform image coordinates (PDL method)
43  
44 $t2 = $t->compose($t1); # compose two transforms
45 $t2 = $t x $t1; # compose two transforms (by analogy to matrix mult.)
46  
47 $t3 = $t2->inverse(); # invert a transform
48 $t3 = !$t2; # invert a transform (by analogy to logical "not")
49  
50 =head1 DESCRIPTION
51  
52 PDL::Transform is a convenient way to represent coordinate
53 transformations and resample images. It embodies functions mapping
54 R^N -> R^M, both with and without inverses. Provision exists for
55 parametrizing functions, and for composing them. You can use this
56 part of the Transform object to keep track of arbitrary functions
57 mapping R^N -> R^M with or without inverses.
58  
59 The simplest way to use a Transform object is to transform vector
60 data between coordinate systems. The L</apply> method
61 accepts a PDL whose 0th dimension is coordinate index (all other
62 dimensions are broadcasted over) and transforms the vectors into the new
63 coordinate system.
64  
65 Transform also includes image resampling, via the L</map> method.
66 You define a coordinate transform using a Transform object, then use
67 it to remap an image PDL. The output is a remapped, resampled image.
68  
69 You can define and compose several transformations, then apply them
70 all at once to an image. The image is interpolated only once, when
71 all the composed transformations are applied.
72  
73 In keeping with standard practice, but somewhat counterintuitively,
74 the L</map> engine uses the inverse transform to map coordinates
75 FROM the destination dataspace (or image plane) TO the source dataspace;
76 hence PDL::Transform keeps track of both the forward and inverse transform.
77  
78 For terseness and convenience, most of the constructors are exported
79 into the current package with the name C<< t_<transform> >>, so the following
80 (for example) are synonyms:
81  
82 $t = PDL::Transform::Radial->new; # Long way
83  
84 $t = t_radial(); # Short way
85  
86 Several math operators are overloaded, so that you can compose and
87 invert functions with expression syntax instead of method syntax (see below).
88  
89 =head1 EXAMPLE
90  
91 Coordinate transformations and mappings are a little counterintuitive
92 at first. Here are some examples of transforms in action:
93  
94 use PDL::Transform;
95 use PDL::Graphics::Simple;
96 $x = rfits('m51.fits'); # Substitute path if necessary!
97 $ts = t_linear(Scale=>3); # Scaling transform
98  
99 $w = pgswin(xs);
100 $w->plot(with=>'image', $x);
101  
102 ## Grow m51 by a factor of 3; origin is at lower left.
103 $y = $ts->map($x,{pix=>1}); # pix option uses direct pixel coord system
104 $w->plot(with=>'image', $y);
105  
106 ## Shrink m51 by a factor of 3; origin still at lower left.
107 $c = $ts->unmap($x, {pix=>1});
108 $w->plot(with=>'image', $c);
109  
110 ## Grow m51 by a factor of 3; origin is at scientific origin.
111 $d = $ts->map($x,$x->hdr); # FITS hdr template prevents autoscaling
112 $w->plot(with=>'image', $d);
113  
114 ## Shrink m51 by a factor of 3; origin is still at sci. origin.
115 $e = $ts->unmap($x,$x->hdr);
116 $w->plot(with=>'image', $e);
117  
118 ## A no-op: shrink m51 by a factor of 3, then autoscale back to size
119 $f = $ts->map($x); # No template causes autoscaling of output
120  
121 =head1 OPERATOR OVERLOADS
122  
123 =over 3
124  
125 =item '!'
126  
127 The bang is a unary inversion operator. It binds exactly as
128 tightly as the normal bang operator.
129  
130 =item 'x'
131  
132 By analogy to matrix multiplication, 'x' is the compose operator, so these
133 two expressions are equivalent:
134  
135 $f->inverse()->compose($g)->compose($f) # long way
136 !$f x $g x $f # short way
137  
138 Both of those expressions are equivalent to the mathematical expression
139 f^-1 o g o f, or f^-1(g(f(x))).
140  
141 =item '**'
142  
143 By analogy to numeric powers, you can apply an operator a positive
144 integer number of times with the ** operator:
145  
146 $f->compose($f)->compose($f) # long way
147 $f**3 # short way
148  
149 =back
150  
151 =head1 INTERNALS
152  
153 Transforms are perl hashes. Here's a list of the meaning of each key:
154  
155 =over 3
156  
157 =item func
158  
159 Ref to a subroutine that evaluates the transformed coordinates. It's
160 called with the input coordinate, and the "params" hash. This
161 springboarding is done via explicit ref rather than by subclassing,
162 for convenience both in coding new transforms (just add the
163 appropriate sub to the module) and in adding custom transforms at
164 run-time. Note that, if possible, new C<func>s should support
165 L<inplace|PDL::Core/inplace> operation to save memory when the data are flagged
166 inplace. But C<func> should always return its result even when
167 flagged to compute in-place.
168  
169 C<func> should treat the 0th dimension of its input as a dimensional
170 index (running 0..N-1 for R^N operation) and broadcast over all other input
171 dimensions.
172  
173 =item inv
174  
175 Ref to an inverse method that reverses the transformation. It must
176 accept the same "params" hash that the forward method accepts. This
177 key can be left undefined in cases where there is no inverse.
178  
179 =item idim, odim
180  
181 Number of useful dimensions for indexing on the input and output sides
182 (ie the order of the 0th dimension of the coordinates to be fed in or
183 that come out). If this is set to 0, then as many are allocated as needed.
184  
185 =item name
186  
187 A shorthand name for the transformation (convenient for debugging).
188 You should plan on using UNIVERAL::isa to identify classes of
189 transformation, e.g. all linear transformations should be subclasses
190 of PDL::Transform::Linear. That makes it easier to add smarts to,
191 e.g., the compose() method.
192  
193 =item itype
194  
195 An array containing the name of the quantity that is expected from the
196 input ndarray for the transform, for each dimension. This field is advisory,
197 and can be left blank if there's no obvious quantity associated with
198 the transform. This is analogous to the CTYPEn field used in FITS headers.
199  
200 =item oname
201  
202 Same as itype, but reporting what quantity is delivered for each
203 dimension.
204  
205 =item iunit
206  
207 The units expected on input, if a specific unit (e.g. degrees) is expected.
208 This field is advisory, and can be left blank if there's no obvious
209 unit associated with the transform.
210  
211 =item ounit
212  
213 Same as iunit, but reporting what quantity is delivered for each dimension.
214  
215 =item params
216  
217 Hash ref containing relevant parameters or anything else the func needs to
218 work right.
219  
220 =item is_inverse
221  
222 Bit indicating whether the transform has been inverted. That is useful
223 for some stringifications (see the PDL::Transform::Linear
224 stringifier), and may be useful for other things.
225  
226 =back
227  
228 Transforms should be inplace-aware where possible, to prevent excessive
229 memory usage.
230  
231 If you define a new type of transform, consider generating a new stringify
232 method for it. Just define the sub "stringify" in the subclass package.
233 It should call SUPER::stringify to generate the first line (though
234 the PDL::Transform::Composition bends this rule by tweaking the
235 top-level line), then output (indented) additional lines as necessary to
236 fully describe the transformation.
237  
238 =head1 NOTES
239  
240 Transforms have a mechanism for labeling the units and type of each
241 coordinate, but it is just advisory. A routine to identify and, if
242 necessary, modify units by scaling would be a good idea. Currently,
243 it just assumes that the coordinates are correct for (e.g.) FITS
244 scientific-to-pixel transformations.
245  
246 Composition works OK but should probably be done in a more
247 sophisticated way so that, for example, linear transformations are
248 combined at the matrix level instead of just strung together
249 pixel-to-pixel.
250  
251 =head1 MODULE INTERFACE
252  
253 There are both operators and constructors. The constructors are all
254 exported, all begin with "t_", and all return objects that are subclasses
255 of PDL::Transform.
256  
257 The L</apply>, L</invert>, L</map>,
258 and L</unmap> methods are also exported to the C<PDL> package: they
259 are both Transform methods and PDL methods.
260  
261 =cut
262  
263 use strict;
264 use warnings;
265 #line 266 "lib/PDL/Transform.pm"
266  
267  
268 =head1 FUNCTIONS
269  
270 =cut
271  
272  
273  
274  
275  
276 #line 307 "lib/PDL/Transform.pd"
277  
278 =head2 apply
279  
280 =for sig
281  
282 Signature: (data(); PDL::Transform t)
283  
284 =for usage
285  
286 $out = $data->apply($t);
287 $out = $t->apply($data);
288  
289 =for ref
290  
291 Apply a transformation to some input coordinates.
292  
293 In the example, C<$t> is a PDL::Transform and C<$data> is a PDL to
294 be interpreted as a collection of N-vectors (with index in the 0th
295 dimension). The output is a similar but transformed PDL.
296  
297 For convenience, this is both a PDL method and a Transform method.
298  
299 =cut
300  
301 use Carp;
302  
303 *PDL::apply = \&apply;
304 sub apply {
305 my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
306 croak "apply requires both a PDL and a PDL::Transform.\n"
307 unless UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL');
308 croak "Applying a PDL::Transform with no func! Oops.\n"
309 unless(defined($me->{func}) and ref($me->{func}) eq 'CODE');
310 my $result = $me->{func}->($from,$me->{params});
311 $result->is_inplace(0); # clear inplace flag, just in case.
312 if (defined $from->gethdr && $from->hdr->{NAXIS}) {
313 my $nd = $me->{odim} || $me->{idim} || 2;
314 for my $d (1..$nd) {
315 $result->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
316 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
317 $me->{otype}[$d-1])
318 || $from->hdr->{"CTYPE$d"}
319 || "");
320 $result->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
321 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
322 $me->{ounit}[$d-1])
323 || $from->hdr->{"CUNIT$d"}
324 || $from->hdr->{"CTYPE$d"}
325 || "");
326 }
327 }
328 return $result;
329 }
330  
331 #line 365 "lib/PDL/Transform.pd"
332  
333 =head2 invert
334  
335 =for sig
336  
337 Signature: (data(); PDL::Transform t)
338  
339 =for usage
340  
341 $out = $t->invert($data);
342 $out = $data->invert($t);
343  
344 =for ref
345  
346 Apply an inverse transformation to some input coordinates.
347  
348 In the example, C<$t> is a PDL::Transform and C<$data> is an ndarray to
349 be interpreted as a collection of N-vectors (with index in the 0th
350 dimension). The output is a similar ndarray.
351  
352 For convenience this is both a PDL method and a PDL::Transform method.
353  
354 =cut
355  
356 *PDL::invert = \&invert;
357 sub invert {
358 my ($me, $from) = UNIVERSAL::isa($_[0],'PDL') ? @_[1,0] : @_;
359 croak "invert requires a PDL and a PDL::Transform (did you want 'inverse' instead?)\n"
360 unless UNIVERSAL::isa($me,'PDL::Transform') && UNIVERSAL::isa($from,'PDL');
361 croak "Inverting a PDL::Transform with no inverse! Oops.\n"
362 unless(defined($me->{inv}) and ref($me->{inv}) eq 'CODE');
363 my $result = $me->{inv}->($from, $me->{params});
364 $result->is_inplace(0); # make sure inplace flag is clear.
365 return $result;
366 }
367 #line 368 "lib/PDL/Transform.pm"
368  
369  
370 =head2 map
371  
372 =for sig
373  
374 Signature: (data(); PDL::Transform t)
375  
376 =for usage
377  
378 $y = $x->map($xform,[<template>],[\%opt]); # Distort $x with transform $xform
379 $y = $x->map(t_identity,[$pdl],[\%opt]); # rescale $x to match $pdl's dims.
380  
381 =for ref
382  
383 Resample an image or N-D dataset using a coordinate transform.
384  
385 The data are resampled so that the new pixel indices are proportional
386 to the transformed coordinates rather than the original ones.
387  
388 The operation uses the inverse transform: each output pixel location
389 is inverse-transformed back to a location in the original dataset, and
390 the value is interpolated or sampled appropriately and copied into the
391 output domain. A variety of sampling options are available, trading
392 off speed and mathematical correctness.
393  
394 For convenience, this is both a PDL method and a PDL::Transform method.
395  
396 C<map> is FITS-aware: if there is a FITS header in the input data,
397 then the coordinate transform acts on the scientific coordinate system
398 rather than the pixel coordinate system.
399  
400 By default, the output coordinates are separated from pixel coordinates
401 by a single layer of indirection. You can specify the mapping between
402 output transform (scientific) coordinates to pixel coordinates using
403 the C<orange> and C<irange> options (see below), or by supplying a
404 FITS header in the template.
405  
406 If you don't specify an output transform, then the output is
407 autoscaled: C<map> transforms a few vectors in the forward direction
408 to generate a mapping that will put most of the data on the image
409 plane, for most transformations. The calculated mapping gets stuck in the
410 output's FITS header.
411  
412 Autoscaling is especially useful for rescaling images -- if you specify
413 the identity transform and allow autoscaling, you duplicate the
414 functionality of L<rescale2d|PDL::Image2D/rescale2d>, but with more
415 options for interpolation.
416  
417 You can operate in pixel space, and avoid autoscaling of the output,
418 by setting the C<nofits> option (see below).
419  
420 The output has the same data type as the input. This is a feature,
421 but it can lead to strange-looking banding behaviors if you use
422 interpolation on an integer input variable.
423  
424 The C<template> can be one of:
425  
426 =over 3
427  
428 =item * a PDL
429  
430 The PDL and its header are copied to the output array, which is then
431 populated with data. If the PDL has a FITS header, then the FITS
432 transform is automatically applied so that $t applies to the output
433 scientific coordinates and not to the output pixel coordinates. In
434 this case the NAXIS fields of the FITS header are ignored.
435  
436 =item * a FITS header stored as a hash ref
437  
438 The FITS NAXIS fields are used to define the output array, and the
439 FITS transformation is applied to the coordinates so that $t applies to the
440 output scientific coordinates.
441  
442 =item * a list ref
443  
444 This is a list of dimensions for the output array. The code estimates
445 appropriate pixel scaling factors to fill the available space. The
446 scaling factors are placed in the output FITS header.
447  
448 =item * nothing
449  
450 In this case, the input image size is used as a template, and scaling
451 is done as with the list ref case (above).
452  
453 =back
454  
455 OPTIONS:
456  
457 The following options are interpreted:
458  
459 =over 3
460  
461 =item b, bound, boundary, Boundary (default = 'truncate')
462  
463 This is the boundary condition to be applied to the input image; it is
464 passed verbatim to L<range|PDL::Slices/range> or
465 L<interpND|PDL::Primitive/interpND> in the sampling or interpolating
466 stage. Other values are 'forbid','extend', and 'periodic'. You can
467 abbreviate this to a single letter. The default 'truncate' causes the
468 entire notional space outside the original image to be filled with 0.
469  
470 =item pix, Pixel, nf, nofits, NoFITS (default = 0)
471  
472 If you set this to a true value, then FITS headers and interpretation
473 are ignored; the transformation is treated as being in raw pixel coordinates.
474  
475 =item j, J, just, justify, Justify (default = 0)
476  
477 If you set this to 1, then output pixels are autoscaled to have unit
478 aspect ratio in the output coordinates. If you set it to a non-1
479 value, then it is the aspect ratio between the first dimension and all
480 subsequent dimensions -- or, for a 2-D transformation, the scientific
481 pixel aspect ratio. Values less than 1 shrink the scale in the first
482 dimension compared to the other dimensions; values greater than 1
483 enlarge it compared to the other dimensions.
484  
485 =item ir, irange, input_range, Input_Range
486  
487 This is a way to modify the autoscaling. It specifies the range of
488 input scientific (not necessarily pixel) coordinates that you want to be
489 mapped to the output image. It can be either a nested array ref or
490 an ndarray. The 0th dim (outside coordinate in the array ref) is
491 dimension index in the data; the 1st dim should have order 2.
492 For example, passing in either [[-1,2],[3,4]] or pdl([[-1,2],[3,4]])
493 limites the map to the quadrilateral in input space defined by the
494 four points (-1,3), (-1,4), (2,4), and (2,3).
495  
496 As with plain autoscaling, the quadrilateral gets sparsely sampled by
497 the autoranger, so pathological transformations can give you strange
498 results.
499  
500 This parameter is overridden by C<orange>, below.
501  
502 =item or, orange, output_range, Output_Range
503  
504 This sets the window of output space that is to be sampled onto the
505 output array. It works exactly like C<irange>, except that it specifies
506 a quadrilateral in output space. Since the output pixel array is itself
507 a quadrilateral, you get pretty much exactly what you asked for.
508  
509 This parameter overrides C<irange>, if both are specified. It forces
510 rectification of the output (so that scientific axes align with the pixel
511 grid).
512  
513 =item r, rect, rectify
514  
515 This option defaults TRUE and controls how autoscaling is performed. If
516 it is true or undefined, then autoscaling adjusts so that pixel coordinates
517 in the output image are proportional to individual scientific coordinates.
518 If it is false, then autoscaling automatically applies the inverse of any
519 input FITS transformation *before* autoscaling the pixels. In the special
520 case of linear transformations, this preserves the rectangular shape of the
521 original pixel grid and makes output pixel coordinate proportional to input
522 coordinate.
523  
524 =item m, method, Method
525  
526 This option controls the interpolation method to be used.
527 Interpolation greatly affects both speed and quality of output. For
528 most cases the option is directly passed to
529 L<interpND|PDL::Primitive/interpND> for interpolation. Possible
530 options, in order from fastest to slowest, are:
531  
532 =over 3
533  
534 =item * s, sample (default for ints)
535  
536 Pixel values in the output plane are sampled from the closest data value
537 in the input plane. This is very fast but not very accurate for either
538 magnification or decimation (shrinking). It is the default for templates
539 of integer type.
540  
541 =item * l, linear (default for floats)
542  
543 Pixel values are linearly interpolated from the closest data value in the
544 input plane. This is reasonably fast but only accurate for magnification.
545 Decimation (shrinking) of the image causes aliasing and loss of photometry
546 as features fall between the samples. It is the default for floating-point
547 templates.
548  
549 =item * c, cubic
550  
551 Pixel values are interpolated using an N-cubic scheme from a 4-pixel
552 N-cube around each coordinate value. As with linear interpolation,
553 this is only accurate for magnification.
554  
555 =item * f, fft
556  
557 Pixel values are interpolated using the term coefficients of the
558 Fourier transform of the original data. This is the most appropriate
559 technique for some kinds of data, but can yield undesired "ringing" for
560 expansion of normal images. Best suited to studying images with
561 repetitive or wavelike features.
562  
563 =item * h, hanning
564  
565 Pixel values are filtered through a spatially-variable filter tuned to
566 the computed Jacobian of the transformation, with hanning-window
567 (cosine) pixel rolloff in each dimension. This prevents aliasing in the
568 case where the image is distorted or shrunk, but allows small amounts
569 of aliasing at pixel edges wherever the image is enlarged.
570  
571 =item * g, gaussian, j, jacobian
572  
573 Pixel values are filtered through a spatially-variable filter tuned to
574 the computed Jacobian of the transformation, with radial Gaussian
575 rolloff. This is the most accurate resampling method, in the sense of
576 introducing the fewest artifacts into a properly sampled data set.
577 This method uses a lookup table to speed up calculation of the Gaussian
578 weighting.
579  
580 =item * G
581  
582 This method works exactly like 'g' (above), except that the Gaussian
583 values are computed explicitly for every sample -- which is considerably
584 slower.
585  
586 =back
587  
588 =item blur, Blur (default = 1.0)
589  
590 This value scales the input-space footprint of each output pixel in
591 the gaussian and hanning methods. It's retained for historical
592 reasons. Larger values yield blurrier images; values significantly
593 smaller than unity cause aliasing. The parameter has slightly
594 different meanings for Gaussian and Hanning interpolation. For
595 Hanning interpolation, numbers smaller than unity control the
596 sharpness of the border at the edge of each pixel (so that blur=>0 is
597 equivalent to sampling for non-decimating transforms). For
598 Gaussian interpolation, the blur factor parameter controls the
599 width parameter of the Gaussian around the center of each pixel.
600  
601 =item sv, SV (default = 1.0)
602  
603 This value lets you set the lower limit of the transformation's
604 singular values in the hanning and gaussian methods, limiting the
605 minimum radius of influence associated with each output pixel. Large
606 numbers yield smoother interpolation in magnified parts of the image
607 but don't affect reduced parts of the image.
608  
609 =item big, Big (default = 0.5)
610  
611 This is the largest allowable input spot size which may be mapped to a
612 single output pixel by the hanning and gaussian methods, in units of
613 the largest non-broadcast input dimension. (i.e. the default won't let
614 you reduce the original image to less than 5 pixels across). This places
615 a limit on how long the processing can take for pathological transformations.
616 Smaller numbers keep the code from hanging for a long time; larger numbers
617 provide for photometric accuracy in more pathological cases. Numbers larger
618 than 1.0 are silly, because they allow the entire input array to be compressed
619 into a region smaller than a single pixel.
620  
621 Wherever an output pixel would require averaging over an area that is too
622 big in input space, it instead gets NaN or the bad value.
623  
624 =item phot, photometry, Photometry
625  
626 This lets you set the style of photometric conversion to be used in the
627 hanning or gaussian methods. You may choose:
628  
629 =over 3
630  
631 =item * 0, s, surf, surface, Surface (default)
632  
633 (this is the default): surface brightness is preserved over the transformation,
634 so features maintain their original intensity. This is what the sampling
635 and interpolation methods do.
636  
637 =item * 1, f, flux, Flux
638  
639 Total flux is preserved over the transformation, so that the brightness
640 integral over image regions is preserved. Parts of the image that are
641 shrunk wind up brighter; parts that are enlarged end up fainter.
642  
643 =back
644  
645 =back
646  
647 VARIABLE FILTERING:
648  
649 The 'hanning' and 'gaussian' methods of interpolation give
650 photometrically accurate resampling of the input data for arbitrary
651 transformations. At each pixel, the code generates a linear
652 approximation to the input transformation, and uses that linearization
653 to estimate the "footprint" of the output pixel in the input space.
654 The output value is a weighted average of the appropriate input spaces.
655  
656 A caveat about these methods is that they assume the transformation is
657 continuous. Transformations that contain discontinuities will give
658 incorrect results near the discontinuity. In particular, the 180th
659 meridian isn't handled well in lat/lon mapping transformations (see
660 L<PDL::Transform::Cartography>) -- pixels along the 180th meridian get
661 the average value of everything along the parallel occupied by the
662 pixel. This flaw is inherent in the assumptions that underly creating
663 a Jacobian matrix. Maybe someone will write code to work around it.
664 Maybe that someone is you.
665  
666 BAD VALUES:
667  
668 C<map()> supports bad values in the data array. Bad values in the input
669 array are propagated to the output array. The 'g' and 'h' methods will
670 do some smoothing over bad values: if more than 1/3 of the weighted
671 input-array footprint of a given output pixel is bad, then the output
672 pixel gets marked bad.
673  
674 =head2 match
675  
676 =for usage
677  
678 $y = $x->match($c); # Match $c's header and size
679 $y = $x->match([100,200]); # Rescale to 100x200 pixels
680 $y = $x->match([100,200],{rect=>1}); # Rescale and remove rotation/skew.
681  
682 =for ref
683  
684 Resample a scientific image to the same coordinate system as another.
685  
686 The example above is syntactic sugar for
687  
688 $y = $x->map(t_identity, $c, ...);
689  
690 it resamples the input PDL with the identity transformation in
691 scientific coordinates, and matches the pixel coordinate system to
692 $c's FITS header.
693  
694 There is one difference between match and map: match makes the
695 C<rectify> option to C<map> default to 0, not 1. This only affects
696 matching where autoscaling is required (i.e. the array ref example
697 above). By default, that example simply scales $x to the new size and
698 maintains any rotation or skew in its scientific-to-pixel coordinate
699 transform.
700  
701 =pod
702  
703 Broadcasts over its inputs.
704  
705 =for bad
706  
707 C<map> does not process bad values.
708 It will set the bad-value flag of all output ndarrays if the flag is set for any of the input ndarrays.
709  
710 =cut
711  
712  
713  
714  
715  
716 #line 1530 "lib/PDL/Transform.pd"
717  
718 sub PDL::match {
719 # Set default for rectification to 0 for simple matching...
720 push @_, {} if ref($_[-1]) ne 'HASH';
721 my @k = grep(m/^r(e(c(t)?)?)?/,sort keys %{$_[-1]});
722 #line 1535 "lib/PDL/Transform.pd"
723 unless(@k) {
724 $_[-1]->{rectify} = 0;
725 }
726 t_identity()->map(@_);
727 }
728  
729 *PDL::map = \&map;
730 sub map {
731 my ($me, $in, $tmp, $opt) = @_;
732 ($in, $me) = ($me, $in)
733 if UNIVERSAL::isa($me,'PDL') && UNIVERSAL::isa($in,'PDL::Transform');
734 barf ("PDL::Transform::map: source is not defined or is not a PDL\n")
735 unless(defined $in and UNIVERSAL::isa($in,'PDL'));
736 barf ("PDL::Transform::map: source is empty\n")
737 unless($in->nelem);
738 # Check for options-but-no-template case
739 ($opt, $tmp) = ($tmp, undef)
740 if ref $tmp eq 'HASH' && !defined($opt)
741 && !defined($tmp->{NAXIS}); # FITS headers all have NAXIS.
742 croak("PDL::Transform::map: Option 'p' was ambiguous and has been removed. You probably want 'pix' or 'phot'.") if exists($opt->{'p'});
743 $tmp = [$in->dims] unless defined $tmp; # no //= because of Devel::Cover bug
744  
745 # Generate an appropriate output ndarray for values to go in
746 my ($out, @odims, $ohdr);
747 if (UNIVERSAL::isa($tmp,'PDL')) {
748 @odims = $tmp->dims;
749 if (defined(my $x = $tmp->gethdr)) { $ohdr = {%$x} }
750 } elsif (ref $tmp eq 'HASH') {
751 # (must be a fits header -- or would be filtered above)
752 @odims = map $tmp->{"NAXIS$_"}, 1..$tmp->{NAXIS};
753 $ohdr = {%$tmp}; # copy FITS header into output
754 } elsif (ref $tmp eq 'ARRAY') {
755 @odims = @$tmp;
756 } else {
757 barf("map: confused about dimensions of the output array...\n");
758 }
759  
760 if (scalar(@odims) < scalar($in->dims)) {
761 my @idims = $in->dims;
762 push(@odims, splice(@idims,scalar(@odims)));
763 }
764  
765 $out = PDL->new_from_specification($in->type,@odims);
766 $out->sethdr($ohdr) if defined($ohdr);
767  
768 # set badflag on output all the time if possible, to account for boundary violations
769 $out->badflag(1);
770  
771 ##############################
772 ## Figure out the dimensionality of the
773 ## transform itself (extra dimensions come along for the ride)
774 my $nd = $me->{odim} || $me->{idim} || 2;
775 my @dd = my @sizes = $out->dims;
776 splice @dd,$nd; # Cut out dimensions after the end
777  
778 # Check that there are elements in the output fields...
779 barf "map: output has no dims!\n"
780 unless(@dd);
781 my $ddtotal = 1;
782 $ddtotal *= $_ for @dd;
783 barf "map: output has no elements (at least one dim is 0)!\n"
784 unless($ddtotal);
785  
786 ##############################
787 # If necessary, generate an appropriate FITS header for the output.
788  
789 my $nofits = _opt($opt, ['nf','nofits','NoFITS','pix','pixel','Pixel']);
790  
791 ##############################
792 # Autoscale by transforming a subset of the input points' coordinates
793 # to the output range, and pick a FITS header that fits the output
794 # coordinates into the given template.
795 #
796 # Autoscaling always produces a simple, linear mapping in the FITS header.
797 # We support more complex mappings (via t_fits) but only to match a pre-existing
798 # FITS header (which doesn't use autoscaling).
799 #
800 # If the rectify option is set (the default) then the image is rectified
801 # in scientific coordinates; if it is clear, then the existing matrix
802 # is used, preserving any shear or rotation in the coordinate system.
803 # Since we eschew CROTA whenever possible, the CDi_j formalism is used instead.
804 my $f_in = (defined($in->hdr->{NAXIS}) ? t_fits($in,{ignore_rgb=>1}) : t_identity());
805  
806 unless((defined $out->gethdr && $out->hdr->{NAXIS}) or $nofits) {
807 print "generating output FITS header..." if $PDL::Transform::debug;
808  
809 $out->sethdr($in->hdr_copy) # Copy extraneous fields...
810 if defined $in->hdr;
811  
812 my $samp_ratio = 300;
813  
814 my $orange = _opt($opt, ['or','orange','output_range','Output_Range'],
815 undef);
816  
817 my $omin;
818 my $omax;
819 my $osize;
820  
821 my $rectify = _opt($opt,['r','rect','rectify','Rectify'],1);
822  
823 if (defined $orange) {
824 # orange always rectifies the coordinates -- the output scientific
825 # coordinates *must* align with the axes, or orange wouldn't make
826 # sense.
827 print "using user's orange..." if $PDL::Transform::debug;
828 $orange = pdl($orange) unless(UNIVERSAL::isa($orange,'PDL'));
829 barf "map: orange must be 2xN for an N-D transform"
830 unless ( (($orange->dim(1)) == $nd )
831 && $orange->ndims == 2);
832  
833 $omin = $orange->slice("(0)");
834 $omax = $orange->slice("(1)");
835 $osize = $omax - $omin;
836  
837 $rectify = 1;
838  
839 } else {
840  
841 ##############################
842 # Real autoscaling happens here.
843  
844 if (!$rectify and ref( $f_in ) !~ /Linear/i) {
845 if ( $f_in->{name} ne 'identity' ) {
846 print STDERR "Warning: map can't preserve nonlinear FITS distortions while autoscaling.\n";
847 }
848 $rectify=1;
849 }
850  
851 my $f_tr = ( $rectify ?
852 $me x $f_in :
853 ( ($me->{name} eq 'identity') ? # Simple optimization for match()
854 $me : # identity -- just matching
855 !$f_in x $me x $f_in # common case
856 )
857 );
858  
859 my $samps = (pdl(($in->dims)[0..$nd-1]))->clip(0,$samp_ratio);
860  
861 my $coords = ndcoords(($samps + 1)->list);
862  
863 my $t;
864 my $irange = _opt($opt, ['ir','irange','input_range','Input_Range'],
865 undef);
866  
867 # If input range is defined, sample that quadrilateral -- else
868 # sample the quad defined by the boundaries of the input image.
869 if (defined $irange) {
870 print "using user's irange..." if $PDL::Transform::debug;
871 $irange = pdl($irange) unless(UNIVERSAL::isa($irange,'PDL'));
872 barf "map: irange must be 2xN for an N-D transform"
873 unless ( (($irange->dim(1)) == $nd )
874 && $irange->ndims == 2);
875  
876 $coords *= ($irange->slice("(1)") - $irange->slice("(0)")) / $samps;
877 $coords += $irange->slice("(0)");
878 $coords -= 0.5; # offset to pixel corners...
879 $t = $me;
880 } else {
881 $coords *= pdl(($in->dims)[0..$nd-1]) / $samps;
882 $coords -= 0.5; # offset to pixel corners...
883 $t = $f_tr;
884 }
885 my $ocoords = $t->apply($coords)->mv(0,-1)->clump($nd);
886  
887 # discard non-finite entries
888 my $oc2 = $ocoords->range(
889 which(
890 $ocoords->
891 transpose->
892 sumover->
893 isfinite
894 )
895 ->dummy(0,1)
896 );
897  
898 $omin = $oc2->minimum;
899 $omax = $oc2->maximum;
900  
901 $osize = $omax - $omin;
902 my $tosize;
903 ($tosize = $osize->where($osize == 0)) .= 1.0;
904 }
905  
906 my ($scale) = $osize / pdl(($out->dims)[0..$nd-1]);
907  
908 my $justify = _opt($opt,['j','J','just','justify','Justify'],0);
909 if ($justify) {
910 $scale->slice("0") *= $justify;
911 $scale .= $scale->max;
912 $scale->slice("0") /= $justify;
913 }
914  
915 print "done with autoscale. Making fits header....\n" if $PDL::Transform::debug;
916 if ( $rectify ) {
917 # Rectified header generation -- make a simple coordinate header with no
918 # rotation or skew.
919 print "rectify\n" if $PDL::Transform::debug;
920 for my $d(1..$nd) {
921 $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2 ;
922 $out->hdr->{"CDELT$d"} = $scale->at($d-1);
923 $out->hdr->{"CRVAL$d"} = ( $omin->at($d-1) + $omax->at($d-1) ) /2 ;
924 $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
925 $out->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
926 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
927 $me->{otype}[$d-1])
928 || $in->hdr->{"CTYPE$d"}
929 || "");
930 $out->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
931 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
932 $me->{ounit}[$d-1])
933 || $in->hdr->{"CUNIT$d"}
934 || $in->hdr->{"CTYPE$d"}
935 || "");
936 }
937 $out->hdr->{"NAXIS"} = $nd;
938  
939 $out->hdr->{"SIMPLE"} = 'T';
940 $out->hdr->{"HISTORY"} .= "Header written by PDL::Transform::Cartography::map";
941  
942 ### Eliminate fancy newfangled output header pointing tags if they exist
943 ### These are the CROTA<n>, PCi_j, and CDi_j.
944 delete @{$out->hdr}{
945 grep /(^CROTA\d*$)|(^(CD|PC)\d+_\d+[A-Z]?$)/, keys %{$out->hdr}
946 #line 1761 "lib/PDL/Transform.pd"
947 };
948 } else {
949 # Non-rectified output -- generate a CDi_j matrix instead of the simple formalism.
950 # We have to deal with a linear transformation: we've got: (scaling) x !input x (t x input),
951 # where input is a linear transformation with offset and scaling is a simple scaling. We have
952 # the scaling parameters and the matrix for !input -- we have only to merge them and then we
953 # can write out the FITS header in CDi_j form.
954 print "non-rectify\n" if $PDL::Transform::debug;
955 my $midpoint_val = (pdl(($out->dims)[0..$nd-1])/2 * $scale)->apply( $f_in );
956 print "midpoint_val is $midpoint_val\n" if $PDL::Transform::debug;
957 # linear transformation
958 unless(ref($f_in) =~ m/Linear/) {
959 croak("Whups -- got a nonlinear t_fits transformation. Can't deal with it.");
960 }
961  
962 my $inv_sc_mat = PDL::MatrixOps::stretcher($scale);
963 my $mat = $f_in->{params}->{matrix} x $inv_sc_mat;
964 print "scale is $scale; mat is $mat\n" if $PDL::Transform::debug;
965  
966 print "looping dims 1..$nd: " if $PDL::Transform::debug;
967 for my $d(1..$nd) {
968 print "$d..." if $PDL::Transform::debug;
969 $out->hdr->{"CRPIX$d"} = 1 + ($out->dim($d-1)-1)/2;
970 $out->hdr->{"CRVAL$d"} = $midpoint_val->at($d-1);
971 $out->hdr->{"NAXIS$d"} = $out->dim($d-1);
972 $out->hdr->{"CTYPE$d"} = ( (!defined($me->{otype}) ? "" :
973 ref($me->{otype}) ne 'ARRAY' ? $me->{otype} :
974 $me->{otype}[$d-1])
975 || $in->hdr->{"CTYPE$d"}
976 || "");
977 $out->hdr->{"CUNIT$d"} = ( (!defined($me->{ounit}) ? "" :
978 ref($me->{ounit}) ne 'ARRAY' ? $me->{ounit} :
979 $me->{ounit}[$d-1])
980 || $in->hdr->{"CUNIT$d"}
981 || $in->hdr->{"CTYPE$d"}
982 || "");
983 for my $e(1..$nd) {
984 $out->hdr->{"CD${d}_${e}"} = $mat->at($d-1,$e-1);
985 print "setting CD${d}_${e} to ".$mat->at($d-1,$e-1)."\n" if $PDL::Transform::debug;
986 }
987 }
988  
989 ## Eliminate competing header pointing tags if they exist
990 delete @{$out->hdr}{
991 grep /(^CROTA\d*$)|(^(PC)\d+_\d+[A-Z]?$)|(CDELT\d*$)/, keys %{$out->hdr}
992 #line 1806 "lib/PDL/Transform.pd"
993 };
994 }
995 }
996  
997 $out->hdrcpy(1);
998  
999 ##############################
1000 # Sandwich the transform between the input and output plane FITS headers.
1001 unless($nofits) {
1002 $me = !t_fits($out,{ignore_rgb=>1}) x $me x $f_in;
1003 }
1004  
1005 ##############################
1006 ## Figure out the interpND options
1007 my $method = _opt($opt,['m','method','Method'],undef);
1008 my $bound = _opt($opt,['b','bound','boundary','Boundary'],'t');
1009  
1010 ##############################
1011 ## Rubber meets the road: calculate the inverse transformed points.
1012 my $ndc = PDL::Basic::ndcoords(@dd);
1013 my $idx = $me->invert($ndc->double);
1014  
1015 barf "map: Transformation had no inverse\n" unless defined($idx);
1016  
1017 ##############################
1018 ## Integrate ? (Jacobian, Gaussian, Hanning)
1019 my $integrate = ($method =~ m/^[jghJGH]/) if defined($method);
1020  
1021 ##############################
1022 ## Sampling code:
1023 ## just transform and interpolate.
1024 ## ( Kind of an anticlimax after all that, eh? )
1025 if (!$integrate) {
1026 my $x = $in->interpND($idx,{method=>$method, bound=>$bound});
1027 $out->slice(":") .= $x; # trivial slice prevents header overwrite...
1028 return $out;
1029 }
1030  
1031 ##############################
1032 ## Anti-aliasing code:
1033 ## Condition the input and call the pixelwise C interpolator.
1034 ##
1035  
1036 barf "PDL::Transform::map: Too many dims in transformation\n"
1037 if $in->ndims < $idx->ndims-1;
1038  
1039 ####################
1040 ## Condition the broadcasting -- pixelwise interpolator only broadcasts
1041 ## in 1 dimension, so squish all broadcast dimensions into 1, if necessary
1042 my @iddims = $idx->dims;
1043 my $in2 = $in->ndims == $#iddims
1044 ? $in->dummy(-1,1)
1045 : $in->reorder($nd..$in->ndims-1, 0..$nd-1)
1046 ->clump($in->ndims - $nd)
1047 ->mv(0,-1);
1048  
1049 ####################
1050 # Allocate the output array
1051 my $o2 = PDL->new_from_specification($in2->type,
1052 @iddims[1..$#iddims],
1053 $in2->dim(-1)
1054 );
1055  
1056 ####################
1057 # Pack boundary string if necessary
1058 if (defined $bound) {
1059 if (ref $bound eq 'ARRAY') {
1060 my ($s,$el);
1061 foreach $el(@$bound) {
1062 barf "Illegal boundary value '$el' in range"
1063 unless( $el =~ m/^([0123fFtTeEpPmM])/ );
1064 $s .= $1;
1065 }
1066 $bound = $s;
1067 } elsif ($bound !~ m/^[0123ftepx]+$/ && $bound =~ m/^([0123ftepx])/i) {
1068 $bound = $1;
1069 }
1070 }
1071  
1072 ####################
1073 # Get the blur and minimum-sv values
1074 my $blur = _opt($opt,['blur','Blur'],1.0);
1075 my $svmin = _opt($opt,['sv','SV'],1.0);
1076 my $big = _opt($opt,['big','Big'],1.0);
1077 my $flux = _opt($opt,['phot','photometry'],0);
1078 my @idims = $in->dims;
1079  
1080 $flux = ($flux =~ m/^[1fF]/);
1081 $big = $big * max(pdl(@idims[0..$nd]));
1082 $blur = $blur->at(0) if ref $blur;
1083 $svmin = $svmin->at(0) if ref $svmin;
1084  
1085 my $bv = $in->badflag ? $in->badvalue->sclr : 0;
1086  
1087 ### The first argument is a dummy to set $GENERIC.
1088 $idx = double($idx) unless($idx->type == double);
1089 print "Calling _map_int...\n" if $PDL::Transform::debug;
1090 &PDL::_map_int( $in2->flat->index(0),
1091 $in2, $o2, $idx,
1092 $bound, $method, $big, $blur, $svmin, $flux, $bv);
1093  
1094 my @rdims = (@iddims[1..$#iddims], @idims[$#iddims..$#idims]);
1095 {
1096 $out->slice(":") .= $o2->reshape(@rdims);
1097 }
1098 return $out;
1099 }
1100 #line 1101 "lib/PDL/Transform.pm"
1101  
1102 0 *map = \&PDL::map;
1103  
1104  
1105  
1106  
1107  
1108 #line 1920 "lib/PDL/Transform.pd"
1109  
1110 ######################################################################
1111  
1112 =head2 unmap
1113  
1114 =for sig
1115  
1116 Signature: (data(); PDL::Transform a; template(); \%opt)
1117  
1118 =for usage
1119  
1120 $out_image = $in_image->unmap($t,[<options>],[<template>]);
1121 $out_image = $t->unmap($in_image,[<options>],[<template>]);
1122  
1123 =for ref
1124  
1125 Map an image or N-D dataset using the inverse as a coordinate transform.
1126  
1127 This convenience function just inverts $t and calls L</map> on
1128 the inverse; everything works the same otherwise. For convenience, it
1129 is both a PDL method and a PDL::Transform method.
1130  
1131 =cut
1132  
1133 *PDL::unmap = \&unmap;
1134 sub unmap {
1135 my($me) = shift;
1136 my($data) = shift;
1137 my(@params) = @_;
1138  
1139 if (UNIVERSAL::isa($data,'PDL::Transform') && UNIVERSAL::isa($me,'PDL')) {
1140 my $x = $data;
1141 $data = $me;
1142 $me = $x;
1143 }
1144  
1145 return $me->inverse->map($data,@params);
1146 }
1147  
1148 #line 1963 "lib/PDL/Transform.pd"
1149  
1150 =head2 t_inverse
1151  
1152 =for usage
1153  
1154 $t2 = t_inverse($t);
1155 $t2 = $t->inverse;
1156 $t2 = $t ** -1;
1157 $t2 = !$t;
1158  
1159 =for ref
1160  
1161 Return the inverse of a PDL::Transform. This just reverses the
1162 func/inv, idim/odim, itype/otype, and iunit/ounit pairs. Note that
1163 sometimes you end up with a transform that cannot be applied or
1164 mapped, because either the mathematical inverse doesn't exist or the
1165 inverse func isn't implemented.
1166  
1167 You can invert a transform by raising it to a negative power, or by
1168 negating it with '!'.
1169  
1170 The inverse transform remains connected to the main transform because
1171 they both point to the original parameters hash. That turns out to be
1172 useful.
1173  
1174 =cut
1175  
1176 *t_inverse = \&inverse;
1177  
1178 sub inverse {
1179 my($me) = shift;
1180 barf("PDL::Transform::inverse: got a transform with no inverse")
1181 unless defined $me->{inv};
1182 bless {
1183 %$me, # force explicit copy of top-level
1184 inv => $me->{func},
1185 func => $me->{inv},
1186 (map +("o$_"=>$me->{"i$_"}, "i$_"=>$me->{"o$_"}), qw(dim type unit)),
1187 name => "(inverse ".$me->{name}.")",
1188 is_inverse => !($me->{is_inverse}),
1189 }, ref $me;
1190 }
1191  
1192 #line 2010 "lib/PDL/Transform.pd"
1193  
1194 =head2 t_compose
1195  
1196 =for usage
1197  
1198 $f2 = t_compose($f, $g,[...]);
1199 $f2 = $f->compose($g[,$h,$i,...]);
1200 $f2 = $f x $g x ...;
1201  
1202 =for ref
1203  
1204 Function composition: f(g(x)), f(g(h(x))), ...
1205  
1206 You can also compose transforms using the overloaded matrix-multiplication
1207 (nee repeat) operator 'x'.
1208  
1209 This is accomplished by inserting a splicing code ref into the C<func>
1210 and C<inv> slots. It combines multiple compositions into a single
1211 list of transforms to be executed in order, from last to first (in
1212 keeping with standard mathematical notation). If one of the functions is
1213 itself a composition, it is interpolated into the list rather than left
1214 separate. Ultimately, linear transformations may also be combined within
1215 the list.
1216  
1217 No checking is done that the itype/otype and iunit/ounit fields are
1218 compatible -- that may happen later, or you can implement it yourself
1219 if you like.
1220  
1221 =cut
1222  
1223 @PDL::Transform::Composition::ISA = ('PDL::Transform');
1224 sub PDL::Transform::Composition::stringify {
1225 package PDL::Transform::Composition;
1226 shift->SUPER::stringify;
1227 }
1228  
1229 *t_compose = \&compose;
1230 sub compose {
1231 local($_);
1232 my(@funcs) = @_;
1233 my($me) = PDL::Transform->new;
1234 # No inputs case: return the identity function
1235 return $me if !@funcs;
1236 $me->{name} = "";
1237 my @clist;
1238 for my $f (@funcs) {
1239 $me->{idim} = $f->{idim} if $f->{idim} > $me->{idim};
1240 $me->{odim} = $f->{odim} if $f->{odim} > $me->{odim};
1241 if (UNIVERSAL::isa($f,"PDL::Transform::Composition")) {
1242 if ($f->{is_inverse}) {
1243 for (reverse(@{$f->{params}->{clist}})) {
1244 push(@clist,$_->inverse);
1245 $me->{name} .= " o inverse ( ".$_->{name}." )";
1246 }
1247 } else {
1248 for (@{$f->{params}->{clist}}) {
1249 push(@clist,$_);
1250 $me->{name} .= " o ".$_->{name};
1251 }
1252 }
1253 } else { # Not a composition -- just push the transform onto the list.
1254 push(@clist,$f);
1255 $me->{name} .= " o ".$f->{name};
1256 }
1257 }
1258 $me->{name}=~ s/^ o //; # Get rid of leading composition mark
1259 $me->{otype} = $funcs[0]->{otype};
1260 $me->{ounit} = $funcs[0]->{ounit};
1261 $me->{itype} = $funcs[-1]->{itype};
1262 $me->{iunit} = $funcs[-1]->{iunit};
1263 $me->{params}->{clist} = \@clist;
1264 $me->{func} = sub {
1265 my ($data,$p) = @_;
1266 my ($ip) = $data->is_inplace;
1267 for my $t ( reverse @{$p->{clist}} ) {
1268 croak("Error: tried to apply a PDL::Transform with no function inside a composition!\n offending transform: $t\n")
1269 unless(defined($t->{func}) and ref($t->{func}) eq 'CODE');
1270 $data = $t->{func}($ip ? $data->inplace : $data, $t->{params});
1271 }
1272 $data->is_inplace(0); # clear inplace flag (avoid core bug with inplace)
1273 $data;
1274 };
1275 $me->{inv} = sub {
1276 my ($data,$p) = @_;
1277 my $ip = $data->is_inplace;
1278 for my $t ( @{$p->{clist}} ) {
1279 croak("Error: tried to invert a non-invertible PDL::Transform inside a composition!\n offending transform: $t\n")
1280 unless(defined($t->{inv}) and ref($t->{inv}) eq 'CODE');
1281 $data = &{$t->{inv}}($ip ? $data->inplace : $data, $t->{params});
1282 }
1283 $data;
1284 };
1285 return bless($me,'PDL::Transform::Composition');
1286 }
1287  
1288 #line 2109 "lib/PDL/Transform.pd"
1289  
1290 =head2 t_wrap
1291  
1292 =for usage
1293  
1294 $g1fg = $f->wrap($g);
1295 $g1fg = t_wrap($f,$g);
1296  
1297 =for ref
1298  
1299 Shift a transform into a different space by 'wrapping' it with a second.
1300  
1301 This is just a convenience function for two
1302 L</t_compose> calls. C<< $x->wrap($y) >> is the same as
1303 C<(!$y) x $x x $y>: the resulting transform first hits the data with
1304 $y, then with $x, then with the inverse of $y.
1305  
1306 For example, to shift the origin of rotation, do this:
1307  
1308 $im = rfits('m51.fits');
1309 $tf = t_fits($im);
1310 $tr = t_linear({rot=>30});
1311 $im1 = $tr->map($tr); # Rotate around pixel origin
1312 $im2 = $tr->map($tr->wrap($tf)); # Rotate round FITS scientific origin
1313  
1314 =cut
1315  
1316 *t_wrap = \&wrap;
1317  
1318 sub wrap {
1319 my($f) = shift;
1320 my($g) = shift;
1321  
1322 return $g->inverse->compose($f,$g);
1323 }
1324  
1325 ######################################################################
1326  
1327 # Composition operator -- handles 'x'.
1328 sub _compose_op {
1329 my($x,$y,$c) = @_;
1330 $c ? compose($y,$x) : compose($x,$y);
1331 }
1332  
1333 # Raise-to-power operator -- handles '**'.
1334  
1335 sub _pow_op {
1336 my($x,$y,$c) = @_;
1337  
1338 barf("Can't raise anything to the power of a transform")
1339 if $c || UNIVERSAL::isa($y,'PDL::Transform');
1340  
1341 $x = $x->inverse
1342 if $y < 0;
1343  
1344 return $x if abs($y) == 1;
1345 return PDL::Transform->new if abs($y) == 0;
1346  
1347 my(@l);
1348 for my $i(1..abs($y)) {
1349 push(@l,$x);
1350 }
1351  
1352 t_compose(@l);
1353 }
1354  
1355 #line 2182 "lib/PDL/Transform.pd"
1356  
1357 =head2 t_identity
1358  
1359 =for usage
1360  
1361 my $xform = t_identity
1362 my $xform = PDL::Transform->new;
1363  
1364 =for ref
1365  
1366 Generic constructor generates the identity transform.
1367  
1368 This constructor really is trivial -- it is mainly used by the other transform
1369 constructors. It takes no parameters and returns the identity transform.
1370  
1371 =cut
1372  
1373 sub _identity { return shift; }
1374 sub t_identity { new PDL::Transform(@_) };
1375  
1376 sub new {
1377 my($class) = shift;
1378 my $me = {name=>'identity',
1379 idim => 0,
1380 odim => 0,
1381 func=>\&PDL::Transform::_identity,
1382 inv=>\&PDL::Transform::_identity,
1383 params=>{}
1384 };
1385  
1386 return bless $me,$class;
1387 }
1388  
1389 #line 2220 "lib/PDL/Transform.pd"
1390  
1391 =head2 t_lookup
1392  
1393 =for usage
1394  
1395 $f = t_lookup($lookup, {<options>});
1396  
1397 =for ref
1398  
1399 Transform by lookup into an explicit table.
1400  
1401 You specify an N+1-D PDL that is interpreted as an N-D lookup table of
1402 column vectors (vector index comes last). The last dimension has
1403 order equal to the output dimensionality of the transform.
1404  
1405 For added flexibility in data space, you can specify pre-lookup linear
1406 scaling and offset of the data. Of course you can specify the
1407 interpolation method to be used. The linear scaling stuff is a little
1408 primitive; if you want more, try composing the linear transform with
1409 this one.
1410  
1411 The prescribed values in the lookup table are treated as
1412 pixel-centered: that is, if your input array has N elements per row
1413 then valid data exist between the locations (-0.5) and (N-0.5) in
1414 lookup pixel space, because the pixels (which are numbered from 0 to
1415 N-1) are centered on their locations.
1416  
1417 Lookup is done using L<interpND|PDL::Primitive/interpND>, so the boundary conditions
1418 and broadcasting behaviour follow from that.
1419  
1420 The indexed-over dimensions come first in the table, followed by a
1421 single dimension containing the column vector to be output for each
1422 set of other dimensions -- ie to output 2-vectors from 2 input
1423 parameters, each of which can range from 0 to 49, you want an index
1424 that has dimension list (50,50,2). For the identity lookup table
1425 you could use C<cat(xvals(50,50),yvals(50,50))>.
1426  
1427 If you want to output a single value per input vector, you still need
1428 that last index broadcasting dimension -- if necessary, use C<dummy(-1,1)>.
1429  
1430 The lookup index scaling is: out = lookup[ (scale * data) + offset ].
1431  
1432 A simplistic table inversion routine is included. This means that
1433 you can (for example) use the C<map> method with C<t_lookup> transformations.
1434 But the table inversion is exceedingly slow, and not practical for tables
1435 larger than about 100x100. The inversion table is calculated in its
1436 entirety the first time it is needed, and then cached until the object is
1437 destroyed.
1438  
1439 Options are listed below; there are several synonyms for each.
1440  
1441 =over 3
1442  
1443 =item s, scale, Scale
1444  
1445 (default 1.0) Specifies the linear amount of scaling to be done before
1446 lookup. You can feed in a scalar or an N-vector; other values may cause
1447 trouble. If you want to save space in your table, then specify smaller
1448 scale numbers.
1449  
1450 =item o, offset, Offset
1451  
1452 (default 0.0) Specifies the linear amount of offset before lookup.
1453 This is only a scalar, because it is intended to let you switch to
1454 corner-centered coordinates if you want to (just feed in o=-0.25).
1455  
1456 =item b, bound, boundary, Boundary
1457  
1458 Boundary condition to be fed to L<interpND|PDL::Primitive/interpND>
1459  
1460 =item m, method, Method
1461  
1462 Interpolation method to be fed to L<interpND|PDL::Primitive/interpND>
1463  
1464 =back
1465  
1466 =head3 EXAMPLE
1467  
1468 =for example
1469  
1470 # To scale logarithmically the Y axis of m51, try:
1471 $x = float rfits('m51.fits');
1472 $lookup = xvals(128,128) -> cat( 10**(yvals(128,128)/50) * 256/10**2.55 );
1473 $t = t_lookup($lookup);
1474 $y = $t->map($x);
1475 # To do the same thing but with a smaller lookup table, try:
1476 $lookup = 16 * xvals(17,17)->cat(10**(yvals(17,17)/(100/16)) * 16/10**2.55);
1477 $t = t_lookup($lookup,{scale=>1/16.0});
1478 $y = $t->map($x);
1479  
1480 (Notice that, although the lookup table coordinates are is divided by 16,
1481 it is a 17x17 -- so linear interpolation works right to the edge of the original
1482 domain.)
1483  
1484 =head3 NOTES
1485  
1486 Inverses are "only weakly supported" -- the best way to do it might be by
1487 judicious use of map() on the forward transformation.
1488  
1489 the type/unit fields are ignored.
1490  
1491 =cut
1492  
1493 sub t_lookup {
1494 my($class) = 'PDL::Transform';
1495 my($source)= shift;
1496 my($o) = shift;
1497  
1498 if (!defined($o) && ((ref $source) eq 'HASH')) {
1499 Carp::cluck("lookup transform called as sub not method; using 'PDL::Transform' as class...\n");
1500 $o = $source;
1501 $source = $class;
1502 $class = "PDL::Transform";
1503 }
1504  
1505 $o = {} unless(ref $o eq 'HASH');
1506  
1507 my($me) = $class->new;
1508  
1509 my($bound) = _opt($o,['b','bound','boundary','Boundary']);
1510 my($method)= _opt($o,['m','meth','method','Method']);
1511  
1512 $me->{idim} = $source->ndims - 1;
1513 $me->{odim} = $source->dim($source->ndims-1);
1514  
1515 $me->{params} = {
1516 table => $source,
1517 scale => _opt($o,['s','scale','Scale'],1.0),
1518 offset => _opt($o,['o','off','offset','Offset'],0.0),
1519 interpND_opt => {
1520 method => $method,
1521 bound => $bound,
1522 bad => _opt($o,['bad'],0)
1523 }
1524 };
1525  
1526 my $lookup_func = sub {
1527 my($data,$p,$table,$scale,$offset) = @_;
1528  
1529 $data = pdl($data)
1530 unless ((ref $data) && (UNIVERSAL::isa($data,'PDL')));
1531 $main::foo = $data;
1532  
1533 if ($data->dim(0) > $me->{idim}) {
1534 barf("Too many dims (".$data->dim(0).") for your table (".$me->{idim}.")\n");
1535 };
1536  
1537 my($x)= ($table
1538 ->interpND(float($data) * $scale + $offset,
1539 $p->{interpND_opt}
1540 )
1541 );
1542  
1543 # Put the index dimension (and broadcasted indices) back at the front of
1544 # the dimension list.
1545 my($dnd) = $data->ndims - 1;
1546 return ($x -> ndims > $data->ndims - 1) ?
1547 ($x->reorder( $dnd..($dnd + $table->ndims - $data->dim(0)-1)
1548 , 0..$data->ndims-2
1549 )
1550 ) : $x;
1551 };
1552  
1553 $me->{func} = sub {my($data,$p) = @_; &$lookup_func($data,$p,$p->{table},$p->{scale},$p->{offset})};
1554  
1555 #######
1556 ## Lazy inverse -- find it if and only if we need it...
1557 $me->{inv} = sub {
1558 my $data = shift;
1559 my $p = shift;
1560 if (!defined($p->{'itable'})) {
1561 if ($me->{idim} != $me->{odim}) {
1562 barf("t_lookup: can't calculate an inverse of a projection operation! (idim != odim)");
1563 }
1564 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;
1565 my $itable = zeroes($p->{table});
1566 my $minvals = $p->{table}->clump($me->{idim})->minimum;
1567 my $maxvals = $p->{table}->clump($me->{idim})->maximum;
1568  
1569 # Scale so that the range runs from 0 through the top pixel in the table
1570 my $scale = ( $itable->shape->slice("0:-2")-1 ) /
1571 (($maxvals - $minvals)+ (($maxvals-$minvals) == 0));
1572 my $offset = - ($minvals * $scale);
1573  
1574 $p->{iscale} = $scale;
1575 $p->{ioffset} = $offset;
1576  
1577 my $enl_scale = $p->{'enl_scale'} || 10;
1578 my $smallcoords = ndcoords((pdl($enl_scale * 2 + 1)->at(0)) x $me->{idim})/ $enl_scale - 1;
1579  
1580 # $oloop runs over (point, index) for all points in the output table, in
1581 # $p->{table} output space
1582 my $oloop = ndcoords($itable->mv(-1,0)->slice("(0)"))->
1583 double->
1584 mv(0,-1)->
1585 clump($itable->ndims-1); # oloop: (pixel, index)
1586 {
1587 $oloop->mv(-1,0) -= $offset;
1588 $oloop->mv(-1,0) /= $scale;
1589 }
1590  
1591 # The Right Thing to do here is to take the outer product of $itable and $otable, then collapse
1592 # to find minimum distance. But memory demands for that would be HUGE. Instead we do an
1593 # elementwise calculation.
1594  
1595 print "t_lookup: inverting ".$oloop->dim(0)." points...\n" if $PDL::verbose || $PDL::debug || $PDL::Transform::debug;
1596 my $pt = $p->{table}->mv(-1,0); # pt runs (index, x,y,...)
1597  
1598 my $itable_flattened = zeroes($oloop);
1599  
1600 for my $i (0..$oloop->dim(0)-1) {
1601  
1602 my $olp = $oloop->slice("($i)"); # olp runs (index)
1603 my $diff = ($pt - $olp); # diff runs (index, x, y, ...)
1604 my $r2 = ($diff * $diff)->sumover; # r2 runs (x,y,...)
1605 my $c = whichND($r2==$r2->min)->slice(":,(0)"); # c runs (index)
1606  
1607 # Now zero in on the neighborhood around the point of closest approach.
1608 my $neighborhood = $p->{table}->interpND($c + $smallcoords,{method=>'linear',bound=>'t'})->
1609 mv(-1,0); # neighborhood runs (index, dx, dy,...)
1610 $diff = $neighborhood - $olp; # diff runs (index, dx, dy, ...)
1611 $r2 = ($diff * $diff)->sumover; # r2 runs (dx,dy,...)
1612 my $dc = $smallcoords->mv(0,-1)->indexND(0+whichND($r2==$r2->min)->slice(":,(0)"));
1613  
1614 my $coord = $c + $dc;
1615 # At last, we've found the best-fit to an enl_scale'th of an input-table pixel.
1616 # Back it out to input-science coordinates, and stuff it in the inverse table.
1617 $itable_flattened->slice("($i)") .= $coord;
1618  
1619 print " $i..." if $i%1000==0 && ($PDL::verbose || $PDL::debug || $PDL::Transform::debug);
1620 }
1621  
1622 {
1623 $itable->clump($itable->ndims-1) .= $itable_flattened;
1624 $itable->mv(-1,0) -= $p->{offset};
1625 $itable->mv(-1,0) /= $p->{scale};
1626 }
1627  
1628 $p->{itable} = $itable;
1629 }
1630 &$lookup_func($data,$p, $p->{itable},$p->{iscale},$p->{ioffset}) ;
1631 };
1632  
1633 $me->{name} = 'Lookup';
1634  
1635 return $me;
1636 }
1637  
1638 #line 2476 "lib/PDL/Transform.pd"
1639  
1640 =head2 t_linear
1641  
1642 =for usage
1643  
1644 $f = t_linear({options});
1645  
1646 =for ref
1647  
1648 Linear (affine) transformations with optional offset
1649  
1650 t_linear implements simple matrix multiplication with offset,
1651 also known as the affine transformations.
1652  
1653 You specify the linear transformation with pre-offset, a mixing
1654 matrix, and a post-offset. That overspecifies the transformation, so
1655 you can choose your favorite method to specify the transform you want.
1656 The inverse transform is automagically generated, provided that it
1657 actually exists (the transform matrix is invertible). Otherwise, the
1658 inverse transform just croaks.
1659  
1660 Extra dimensions in the input vector are ignored, so if you pass a
1661 3xN vector into a 3-D linear transformation, the final dimension is passed
1662 through unchanged.
1663  
1664 The options you can usefully pass in are:
1665  
1666 =over 3
1667  
1668 =item s, scale, Scale
1669  
1670 A scaling scalar (heh), vector, or matrix. If you specify a vector
1671 it is treated as a diagonal matrix (for convenience). It gets
1672 left-multiplied with the transformation matrix you specify (or the
1673 identity), so that if you specify both a scale and a matrix the
1674 scaling is done after the rotation or skewing or whatever.
1675  
1676 =item r, rot, rota, rotation, Rotation
1677  
1678 A rotation angle in degrees -- useful for 2-D and 3-D data only. If
1679 you pass in a scalar, it specifies a rotation from the 0th axis toward
1680 the 1st axis. If you pass in a 3-vector as either a PDL or an array
1681 ref (as in "rot=>[3,4,5]"), then it is treated as a set of Euler
1682 angles in three dimensions, and a rotation matrix is generated that
1683 does the following, in order:
1684  
1685 =over 3
1686  
1687 =item * Rotate by rot->(2) degrees from 0th to 1st axis
1688  
1689 =item * Rotate by rot->(1) degrees from the 2nd to the 0th axis
1690  
1691 =item * Rotate by rot->(0) degrees from the 1st to the 2nd axis
1692  
1693 =back
1694  
1695 The rotation matrix is left-multiplied with the transformation matrix
1696 you specify, so that if you specify both rotation and a general matrix
1697 the rotation happens after the more general operation -- though that is
1698 deprecated.
1699  
1700 Of course, you can duplicate this functionality -- and get more
1701 general -- by generating your own rotation matrix and feeding it in
1702 with the C<matrix> option.
1703  
1704 =item m, matrix, Matrix
1705  
1706 The transformation matrix. It does not even have to be square, if you want
1707 to change the dimensionality of your input. If it is invertible (note:
1708 must be square for that), then you automagically get an inverse transform too.
1709  
1710 =item pre, preoffset, offset, Offset
1711  
1712 The vector to be added to the data before they get multiplied by the matrix
1713 (equivalent of CRVAL in FITS, if you are converting from scientific to
1714 pixel units).
1715  
1716 =item post, postoffset, shift, Shift
1717  
1718 The vector to be added to the data after it gets multiplied by the matrix
1719 (equivalent of CRPIX-1 in FITS, if you're converting from scientific to pixel
1720 units).
1721  
1722 =item d, dim, dims, Dims
1723  
1724 Most of the time it is obvious how many dimensions you want to deal
1725 with: if you supply a matrix, it defines the transformation; if you
1726 input offset vectors in the C<pre> and C<post> options, those define
1727 the number of dimensions. But if you only supply scalars, there is no way
1728 to tell and the default number of dimensions is 2. This provides a way
1729 to do, e.g., 3-D scaling: just set C<< {s=><scale-factor>, dims=>3} >> and
1730 you are on your way.
1731  
1732 =item idim
1733  
1734 =item odim
1735  
1736 =item iunit
1737  
1738 =item ounit
1739  
1740 =item itype
1741  
1742 =item otype
1743  
1744 These are incorporated in the object, though not much is done with them
1745 yet as of 2.094.
1746  
1747 =back
1748  
1749 =cut
1750  
1751 { package PDL::Transform::Linear;
1752 our @ISA = ('PDL::Transform');
1753 *_opt = \&PDL::Transform::_opt;
1754 *barf = \&PDL::Transform::barf;
1755 *identity = \&PDL::MatrixOps::identity;
1756 use PDL::Constants qw(DEG2RAD);
1757  
1758 sub PDL::Transform::t_linear { PDL::Transform::Linear->new(@_); }
1759  
1760 sub new {
1761 my($class) = shift;
1762 my($o) = $_[0];
1763 pop @_ if (($#_ % 2 ==0) && !defined($_[-1]));
1764 #suppresses a warning if @_ has an odd number of elements and the
1765 #last is undef
1766  
1767 if (!(ref $o)) {
1768 $o = {@_};
1769 }
1770  
1771 my($me) = __PACKAGE__->SUPER::new;
1772  
1773 $me->{name} = "linear";
1774  
1775 $me->{params}{pre} = _opt($o,['pre','Pre','preoffset','offset',
1776 'Offset','PreOffset','Preoffset'],0);
1777 $me->{params}{pre} = PDL->pdl($me->{params}{pre})
1778 if defined $me->{params}{pre};
1779  
1780 $me->{params}{post} = _opt($o,['post','Post','postoffset','PostOffset',
1781 'shift','Shift'],0);
1782 $me->{params}{post} = PDL->pdl($me->{params}{post})
1783 if defined $me->{params}{post};
1784  
1785 $me->{params}{matrix} = _opt($o,['m','matrix','Matrix','mat','Mat']);
1786 $me->{params}{matrix} = PDL->pdl($me->{params}{matrix})
1787 if defined $me->{params}{matrix};
1788  
1789 $me->{params}{rot} = _opt($o,['r','rot','rota','rotation','Rotation'], 0);
1790 $me->{params}{rot} = PDL->pdl($me->{params}{rot});
1791  
1792 my $o_dims = _opt($o,['d','dim','dims','Dims']);
1793 $o_dims = PDL->pdl($o_dims) if defined($o_dims);
1794  
1795 my $scale = _opt($o,['s','scale','Scale']);
1796 $scale = PDL->pdl($scale) if defined($scale);
1797  
1798 # Figure out the number of dimensions to transform, and,
1799 # if necessary, generate a new matrix.
1800  
1801 my $rot = $me->{params}{rot};
1802 if (defined($me->{params}{matrix})) {
1803 my $mat = $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
1804 $me->{idim} = $mat->dim(0);
1805 $me->{odim} = $mat->dim(1);
1806  
1807 } else {
1808 if (defined($me->{params}->{rot}) &&
1809 UNIVERSAL::isa($me->{params}->{rot},'PDL')) {
1810 $me->{idim} = $me->{odim} = 2 if $me->{params}{rot}->nelem == 1;
1811 $me->{idim} = $me->{odim} = 3 if $me->{params}{rot}->nelem == 3;
1812 }
1813  
1814 if (defined($scale) &&
1815 UNIVERSAL::isa($scale,'PDL') &&
1816 $scale->getndims > 0) {
1817 $me->{idim} = $me->{odim} = $scale->dim(0);
1818 $me->{odim} = $scale->dim(0);
1819  
1820 } elsif (defined($me->{params}{pre}) &&
1821 UNIVERSAL::isa($me->{params}{pre},'PDL') &&
1822 $me->{params}{pre}->getndims > 0) {
1823 $me->{idim} = $me->{odim} = $me->{params}{pre}->dim(0);
1824  
1825 } elsif (defined($me->{params}{post}) &&
1826 UNIVERSAL::isa($me->{params}{post},'PDL') &&
1827 $me->{params}{post}->getndims > 0) {
1828 $me->{idim} = $me->{odim} = $me->{params}{post}->dim(0);
1829 } elsif (defined($o_dims)) {
1830 $me->{idim} = $me->{odim} = $o_dims;
1831 } elsif (UNIVERSAL::isa($rot,'PDL') && (my $nrots = $rot->nelem) > 1) {
1832 $me->{idim} = $me->{odim} = $nrots;
1833 } else {
1834 print "PDL::Transform::Linear: assuming 2-D transform (set dims option to change)\n" if $PDL::Transform::debug;
1835 $me->{idim} = $me->{odim} = 2;
1836 }
1837  
1838 $me->{params}->{matrix} = PDL->zeroes($me->{idim},$me->{odim});
1839 $me->{params}->{matrix}->diagonal(0,1) .= 1;
1840 }
1841  
1842 ### Handle rotation option
1843 if (defined($rot)) {
1844 # Subrotation closure -- rotates from axis $d->(0) --> $d->(1).
1845 my $subrot = sub {
1846 my($d,$angle,$m)=@_;
1847 my($i) = identity($m->dim(0));
1848 my($subm) = $i->dice($d,$d);
1849  
1850 $angle = $angle->at(0)
1851 if UNIVERSAL::isa($angle,'PDL');
1852  
1853 my($x) = $angle * DEG2RAD;
1854 $subm .= $subm x PDL->pdl([cos($x),-sin($x)],[sin($x),cos($x)]);
1855 $m .= $m x $i;
1856 };
1857  
1858 if (UNIVERSAL::isa($rot,'PDL') && $rot->nelem > 1) {
1859 if ($rot->ndims == 2) {
1860 $me->{params}{matrix} x= $rot;
1861 } elsif ($rot->nelem == 3) {
1862 my $rm = identity(3);
1863  
1864 # Do these in reverse order to make it more like
1865 # function composition!
1866 &$subrot(PDL->pdl(0,1),$rot->at(2),$rm);
1867 &$subrot(PDL->pdl(2,0),$rot->at(1),$rm);
1868 &$subrot(PDL->pdl(1,2),$rot->at(0),$rm);
1869  
1870 $me->{params}{matrix} .= $me->{params}{matrix} x $rm;
1871 } else {
1872 barf("PDL::Transform::Linear: Got a strange rot option -- giving up.\n");
1873 }
1874 } else {
1875 if ($rot != 0 and $me->{params}{matrix}->dim(0)>1) {
1876 &$subrot(PDL->pdl(0,1),$rot,$me->{params}{matrix});
1877 }
1878 }
1879 }
1880  
1881 # Apply scaling
1882 $me->{params}{matrix} = $me->{params}{matrix}->slice(":,:");
1883 $me->{params}{matrix}->diagonal(0,1) *= $scale
1884 if defined($scale);
1885  
1886 # Check for an inverse and apply it if possible
1887 my($o2);
1888 if ($me->{params}{matrix}->det($o2 = {lu=>undef})) {
1889 $me->{params}{inverse} = $me->{params}{matrix}->inv($o2);
1890 } else {
1891 delete $me->{params}{inverse};
1892 }
1893  
1894 $me->{params}{idim} = $me->{idim};
1895 $me->{params}{odim} = $me->{odim};
1896  
1897 for (qw(iunit ounit itype otype)) {
1898 next unless defined (my $val = _opt($o,[$_]));
1899 $me->{$_} = $val;
1900 }
1901  
1902 ##############################
1903 # The meat -- just shift, matrix-multiply, and shift again.
1904 $me->{func} = sub {
1905 my ($in,$opt) = @_;
1906 my $d = $opt->{matrix}->dim(0)-1;
1907 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
1908 if $in->dim(0) <= $d;
1909 my $x = $in->slice("0:$d")->copy + $opt->{pre};
1910 my $out = $in->new_or_inplace;
1911 $out->slice("0:$d") .= $x x $opt->{matrix} + $opt->{post};
1912 return $out;
1913 };
1914  
1915 $me->{inv} = (defined $me->{params}{inverse}) ? sub {
1916 my ($in,$opt) = @_;
1917 my $d = $opt->{inverse}->dim(0)-1;
1918 barf("Linear transform: transform is @{[$d+1]}-D; data is ".$in->dim(0))
1919 if $in->dim(0) <= $d;
1920 my $x = $in->slice("0:$d")->copy - $opt->{post};
1921 my $out = $in->new_or_inplace;
1922 $out->slice("0:$d") .= $x x $opt->{inverse} - $opt->{pre};
1923 $out;
1924 } : undef;
1925  
1926 return $me;
1927 }
1928  
1929 sub stringify {
1930 my($me) = shift; my($out) = SUPER::stringify $me;
1931 my $mp = $me->{params};
1932  
1933 if (!($me->{is_inverse})){
1934 $out .= "Pre-add: ".($mp->{pre})."\n"
1935 if defined $mp->{pre};
1936  
1937 $out .= "Post-add: ".($mp->{post})."\n"
1938 if defined $mp->{post};
1939  
1940 $out .= "Forward matrix:".($mp->{matrix})
1941 if defined $mp->{matrix};
1942  
1943 $out .= "Inverse matrix:".($mp->{inverse})
1944 if defined $mp->{inverse};
1945 } else {
1946 $out .= "Pre-add: ".(-$mp->{post})."\n"
1947 if defined $mp->{post};
1948  
1949 $out .= "Post-add: ".(-$mp->{pre})."\n"
1950 if defined $mp->{pre};
1951  
1952 $out .= "Forward matrix:".($mp->{inverse})
1953 if defined $mp->{inverse};
1954  
1955 $out .= "Inverse matrix:".($mp->{matrix})
1956 if defined $mp->{matrix};
1957 }
1958  
1959 $out =~ s/\n/\n /go;
1960 $out;
1961 }
1962 }
1963  
1964 #line 2805 "lib/PDL/Transform.pd"
1965  
1966 =head2 t_scale
1967  
1968 =for usage
1969  
1970 $f = t_scale(<scale>)
1971  
1972 =for ref
1973  
1974 Convenience interface to L</t_linear>.
1975  
1976 t_scale produces a transform that scales around the origin by a fixed
1977 amount. It acts exactly the same as C<<< t_linear(Scale=>$scale) >>>.
1978  
1979 =cut
1980  
1981 sub t_scale {
1982 my($scale) = shift;
1983 my($y) = shift;
1984 return t_linear(scale=>$scale,%{$y})
1985 #line 2826 "lib/PDL/Transform.pd"
1986 if ref $y eq 'HASH';
1987 t_linear(Scale=>$scale,$y,@_);
1988 }
1989  
1990 #line 2833 "lib/PDL/Transform.pd"
1991  
1992 =head2 t_offset
1993  
1994 =for usage
1995  
1996 $f = t_offset(<shift>)
1997  
1998 =for ref
1999  
2000 Convenience interface to L</t_linear>.
2001  
2002 t_offset produces a transform that shifts the origin to a new location.
2003 It acts exactly the same as C<<< t_linear(Pre=>$shift) >>>.
2004  
2005 =cut
2006  
2007 sub t_offset {
2008 my($pre) = shift;
2009 my($y) = shift;
2010 return t_linear(pre=>$pre,%{$y})
2011 #line 2854 "lib/PDL/Transform.pd"
2012 if ref $y eq 'HASH';
2013  
2014 t_linear(pre=>$pre,$y,@_);
2015 }
2016  
2017 #line 2862 "lib/PDL/Transform.pd"
2018  
2019 =head2 t_rot
2020  
2021 =for usage
2022  
2023 $f = t_rot(\@rotation_in_degrees)
2024  
2025 =for ref
2026  
2027 Convenience interface to L</t_linear>.
2028  
2029 t_rot produces a rotation transform in 2-D (scalar), 3-D (3-vector), or
2030 N-D (matrix). It acts exactly the same as C<< t_linear(rot=>shift) >>.
2031  
2032 =cut
2033  
2034 *t_rot = \&t_rotate;
2035 sub t_rotate {
2036 my $rot = shift;
2037 my($y) = shift;
2038 return t_linear(rot=>$rot,%{$y})
2039 #line 2884 "lib/PDL/Transform.pd"
2040 if ref $y eq 'HASH';
2041  
2042 t_linear(rot=>$rot,$y,@_);
2043 }
2044  
2045 #line 2894 "lib/PDL/Transform.pd"
2046  
2047 =head2 t_fits
2048  
2049 =for usage
2050  
2051 $f = t_fits($fits,[option]);
2052  
2053 =for ref
2054  
2055 FITS pixel-to-scientific transformation with inverse
2056  
2057 You feed in a hash ref or a PDL with one of those as a header, and you
2058 get back a transform that converts 0-originated, pixel-centered
2059 coordinates into scientific coordinates via the transformation in the
2060 FITS header. For most FITS headers, the transform is reversible, so
2061 applying the inverse goes the other way. This is just an instance
2062 of PDL::Transform::Linear, but with unit/type support
2063 using the FITS header you supply.
2064  
2065 For now, this transform is rather limited -- it really ought to
2066 accept units differences and stuff like that, but they are just
2067 ignored for now. Probably that would require putting units into
2068 the whole transform framework.
2069  
2070 This transform implements the linear transform part of the WCS FITS
2071 standard outlined in Greisen & Calabata 2002 (A&A in press; find it at
2072 L<https://arxiv.org/abs/astro-ph/0207407>).
2073  
2074 As a special case, you can pass in the boolean option "ignore_rgb"
2075 (default 0), and if you pass in a 3-D FITS header in which the last
2076 dimension has exactly 3 elements, it will be ignored in the output
2077 transformation. That turns out to be handy for handling rgb images.
2078  
2079 =cut
2080  
2081 sub t_fits {
2082 my($hdr) = shift;
2083 my($opt) = shift;
2084  
2085 if (ref $opt ne 'HASH') {
2086 $opt = defined $opt ? {$opt,@_} : {} ;
2087 }
2088  
2089 $hdr = $hdr->gethdr
2090 if defined $hdr && UNIVERSAL::isa($hdr,'PDL');
2091  
2092 croak('t_fits requires a FITS header hash\n')
2093 if !defined $hdr || ref $hdr ne 'HASH' || !defined($hdr->{NAXIS});
2094  
2095 my($n) = $hdr->{NAXIS}; $n = $n->at(0) if UNIVERSAL::isa($n,'PDL');
2096  
2097 $n = 2
2098 if $opt->{ignore_rgb} && $n==3 && $hdr->{NAXIS3} == 3;
2099  
2100 my($matrix) = PDL->zeroes($n,$n);
2101 my($pre) = PDL->zeroes($n);
2102 my($post) = PDL->zeroes($n);
2103  
2104 ##############################
2105 # Scaling: Use CDi_j formalism if present; otherwise use the
2106 # older PCi_j + CDELTi formalism.
2107  
2108 my(@hgrab);
2109  
2110 if (@hgrab = grep(m/^CD\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2111 #
2112 # CDi_j formalism
2113 #
2114 for my $h(@hgrab) {
2115 $h =~ m/CD(\d{1,3})_(\d{1,3})/; # Should always match
2116 $matrix->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
2117 }
2118 print "t_fits: Detected CDi_j matrix: \n",$matrix,"\n"
2119 if $PDL::Transform::debug;
2120  
2121 } else {
2122  
2123 #
2124 # PCi_j + CDELTi formalism
2125 # If PCi_j aren't present, and N=2, then try using CROTA or
2126 # CROTA2 to generate a rotation matrix instead.
2127 #
2128  
2129 my($cdm) = PDL->zeroes($n,$n);
2130 my($cd) = $cdm->diagonal(0,1);
2131  
2132 my($cpm) = PDL->zeroes($n,$n);
2133 $cpm->diagonal(0,1) .= 1; # PC: diagonal defaults to unity
2134 $cd .= 1;
2135  
2136 if (@hgrab = grep(m/^PC\d{1,3}_\d{1,3}$/,sort keys %$hdr)) { # assignment
2137  
2138 for my $h(@hgrab) {
2139 $h =~ m/PC(\d{1,3})_(\d{1,3})$/ || die "t_fits - match failed! This should never happen!";
2140 $cpm->slice("(".($1-1)."),(".($2-1).")") .= $hdr->{$h};
2141 }
2142 print "t_fits: Detected PCi_j matrix: \n",$cpm,"\n"
2143 if $PDL::Transform::debug && @hgrab;
2144  
2145 } elsif ($n==2 && grep defined $hdr->{$_}, qw(CROTA CROTA1 CROTA2)) {
2146  
2147 ## CROTA is deprecated; CROTA1 was used for a while but is unofficial;
2148 ## CROTA2 is encouraged instead.
2149 my $cr = $hdr->{CROTA2} // $hdr->{CROTA} // $hdr->{CROTA1};
2150  
2151 $cr *= DEG2RAD();
2152 # Rotation matrix rotates counterclockwise to get from sci to pixel coords
2153 # (detector has been rotated ccw, according to FITS standard)
2154 $cpm .= pdl( [cos($cr), sin($cr)],[-sin($cr),cos($cr)] );
2155  
2156 }
2157  
2158 for my $i(1..$n) {
2159 $cd->slice("(".($i-1).")") .= $hdr->{"CDELT$i"};
2160 }
2161 #If there are no CDELTs, then we assume they are all 1.0
2162 $cd+=1 if (all($cd==0));
2163  
2164 $matrix = $cdm x $cpm;
2165 }
2166  
2167 my($i1) = 0;
2168 for my $i(1..$n) {
2169 $pre->slice("($i1)") .= 1 - $hdr->{"CRPIX$i"};
2170 $post->slice("($i1)") .= $hdr->{"CRVAL$i"};
2171 $i1++;
2172 }
2173  
2174 my $me = PDL::Transform::Linear->new({
2175 pre=>$pre, post=>$post, matrix=>$matrix
2176 });
2177 $me->{name} = 'FITS';
2178  
2179 my (@otype,@ounit,@itype,@iunit);
2180 my @names = qw(X Y Z);
2181 for my $i(1..$hdr->{NAXIS}) {
2182 push(@otype,$hdr->{"CTYPE$i"});
2183 push(@ounit,$hdr->{"CUNIT$i"});
2184 push(@itype,"Image ". ( ($i-1<=$#names) ? $names[$i-1] : "${i}th dim" ));
2185 push(@iunit,"Pixels");
2186 }
2187 $me->{otype} = \@otype;
2188 $me->{itype} = \@itype;
2189 $me->{ounit} = \@ounit;
2190 $me->{iunit} = \@iunit;
2191  
2192 # Check for nonlinear projection...
2193 # if ($hdr->{CTYPE1} =~ m/(\w\w\w\w)\-(\w\w\w)/) {
2194 # print "Nonlinear transformation found... ignoring nonlinear part...\n";
2195 # }
2196  
2197 return $me;
2198 }
2199  
2200 #line 3057 "lib/PDL/Transform.pd"
2201  
2202 =head2 t_code
2203  
2204 =for usage
2205  
2206 $f = t_code(<func>,[<inv>],[options]);
2207  
2208 =for ref
2209  
2210 Transform implementing arbitrary perl code.
2211  
2212 This is a way of getting quick-and-dirty new transforms. You pass in
2213 anonymous (or otherwise) code refs pointing to subroutines that
2214 implement the forward and, optionally, inverse transforms. The
2215 subroutines should accept a data PDL followed by a parameter hash ref,
2216 and return the transformed data PDL. The parameter hash ref can be
2217 set via the options, if you want to.
2218  
2219 Options that are accepted are:
2220  
2221 =over 3
2222  
2223 =item p,params
2224  
2225 The parameter hash that will be passed back to your code (defaults to the
2226 empty hash).
2227  
2228 =item n,name
2229  
2230 The name of the transform (defaults to "code").
2231  
2232 =item i, idim (default 2)
2233  
2234 The number of input dimensions (additional ones should be passed through
2235 unchanged)
2236  
2237 =item o, odim (default 2)
2238  
2239 The number of output dimensions
2240  
2241 =item itype
2242  
2243 The type of the input dimensions, in an array ref (optional and advisory)
2244  
2245 =item otype
2246  
2247 The type of the output dimension, in an array ref (optional and advisory)
2248  
2249 =item iunit
2250  
2251 The units that are expected for the input dimensions (optional and advisory)
2252  
2253 =item ounit
2254  
2255 The units that are returned in the output (optional and advisory).
2256  
2257 =back
2258  
2259 The code variables are executable perl code, either as a code ref or
2260 as a string that will be eval'ed to produce code refs. If you pass in
2261 a string, it gets eval'ed at call time to get a code ref. If it compiles
2262 OK but does not return a code ref, then it gets re-evaluated with "sub {
2263 ... }" wrapped around it, to get a code ref.
2264  
2265 Note that code callbacks like this can be used to do really weird
2266 things and generate equally weird results -- caveat scriptor!
2267  
2268 =cut
2269  
2270 sub t_code {
2271 my($class) = 'PDL::Transform';
2272 my($func, $inv, $o) = @_;
2273 if (ref $inv eq 'HASH') {
2274 $o = $inv;
2275 $inv = undef;
2276 }
2277  
2278 my($me) = $class->new;
2279 $me->{name} = _opt($o,['n','name','Name']) || "code";
2280 $me->{func} = $func;
2281 $me->{inv} = $inv;
2282 $me->{params} = _opt($o,['p','params','Params']) || {};
2283 $me->{idim} = _opt($o,['i','idim']) || 2;
2284 $me->{odim} = _opt($o,['o','odim']) || 2;
2285 $me->{itype} = _opt($o,['itype']) || [];
2286 $me->{otype} = _opt($o,['otype']) || [];
2287 $me->{iunit} = _opt($o,['iunit']) || [];
2288 $me->{ounit} = _opt($o,['ounit']) || [];
2289  
2290 $me;
2291 }
2292  
2293 #line 3156 "lib/PDL/Transform.pd"
2294  
2295 =head2 t_cylindrical
2296  
2297 C<t_cylindrical> is an alias for C<t_radial>
2298  
2299 =head2 t_radial
2300  
2301 =for usage
2302  
2303 $f = t_radial(<options>);
2304  
2305 =for ref
2306  
2307 Convert Cartesian to radial/cylindrical coordinates. (2-D/3-D; with inverse)
2308  
2309 Converts 2-D Cartesian to radial (theta,r) coordinates. You can choose
2310 direct or conformal conversion. Direct conversion preserves radial
2311 distance from the origin; conformal conversion preserves local angles,
2312 so that each small-enough part of the image only appears to be scaled
2313 and rotated, not stretched. Conformal conversion puts the radius on a
2314 logarithmic scale, so that scaling of the original image plane is
2315 equivalent to a simple offset of the transformed image plane.
2316  
2317 If you use three or more dimensions, the higher dimensions are ignored,
2318 yielding a conversion from Cartesian to cylindrical coordinates, which
2319 is why there are two aliases for the same transform. If you use higher
2320 dimensionality than 2, you must manually specify the origin or you will
2321 get dimension mismatch errors when you apply the transform.
2322  
2323 Theta runs B<clockwise> instead of the more usual counterclockwise; that is
2324 to preserve the mirror sense of small structures.
2325  
2326 OPTIONS:
2327  
2328 =over 3
2329  
2330 =item d, direct, Direct
2331  
2332 Generate (theta,r) coordinates out (this is the default); incompatible
2333 with Conformal. Theta is in radians, and the radial coordinate is
2334 in the units of distance in the input plane.
2335  
2336 =item r0, c, conformal, Conformal
2337  
2338 If defined, this floating-point value causes t_radial to generate
2339 (theta, ln(r/r0)) coordinates out. Theta is in radians, and the
2340 radial coordinate varies by 1 for each e-folding of the r0-scaled
2341 distance from the input origin. The logarithmic scaling is useful for
2342 viewing both large and small things at the same time, and for keeping
2343 shapes of small things preserved in the image.
2344  
2345 =item o, origin, Origin [default (0,0,0)]
2346  
2347 This is the origin of the expansion. Pass in a PDL or an array ref.
2348  
2349 =item u, unit, Unit [default 'radians']
2350  
2351 This is the angular unit to be used for the azimuth.
2352  
2353 =back
2354  
2355 EXAMPLES
2356  
2357 These examples do transformations back into the same size image as they
2358 started from; by suitable use of the "transform" option to
2359 L</unmap> you can send them to any size array you like.
2360  
2361 Examine radial structure in M51:
2362 Here, we scale the output to stretch 2*pi radians out to the
2363 full image width in the horizontal direction, and to stretch 1 radius out
2364 to a diameter in the vertical direction.
2365  
2366 $x = rfits('m51.fits');
2367 $ts = t_linear(s => [250/2.0/3.14159, 2]); # Scale to fill orig. image
2368 $tu = t_radial(o => [130,130]); # Expand around galactic core
2369 $y = $x->map($ts x $tu);
2370  
2371 Examine radial structure in M51 (conformal):
2372 Here, we scale the output to stretch 2*pi radians out to the full image width
2373 in the horizontal direction, and scale the vertical direction by the exact
2374 same amount to preserve conformality of the operation. Notice that
2375 each piece of the image looks "natural" -- only scaled and not stretched.
2376  
2377 $x = rfits('m51.fits')
2378 $ts = t_linear(s=> 250/2.0/3.14159); # Note scalar (heh) scale.
2379 $tu = t_radial(o=> [130,130], r0=>5); # 5 pix. radius -> bottom of image
2380 $y = $ts->compose($tu)->unmap($x);
2381  
2382 =cut
2383  
2384 use PDL::Constants qw(RAD2DEG);
2385 *t_cylindrical = \&t_radial;
2386 sub t_radial {
2387 my($class) = 'PDL::Transform';
2388 my($o) = $_[0];
2389 if (ref $o ne 'HASH') {
2390 $o = { @_ };
2391 }
2392  
2393 my($me) = $class->new;
2394  
2395 $me->{params}{origin} = _opt($o,['o','origin','Origin']);
2396 $me->{params}{origin} = pdl(0,0)
2397 unless defined($me->{params}{origin});
2398 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
2399  
2400 $me->{params}{r0} = _opt($o,['r0','R0','c','conformal','Conformal']);
2401 $me->{params}{origin} = PDL->pdl($me->{params}{origin});
2402  
2403 $me->{params}{u} = _opt($o,['u','unit','Unit'],'radians');
2404 ### Replace this kludge with a units call
2405 $me->{params}{angunit} = ($me->{params}{u} =~ m/^d/i) ? RAD2DEG : 1.0;
2406 print "radial: conversion is $me->{params}{angunit}\n" if $PDL::Transform::debug;
2407  
2408 $me->{name} = "radial (direct)";
2409  
2410 $me->{idim} = 2;
2411 $me->{odim} = 2;
2412  
2413 if ($me->{params}{r0}) {
2414 $me->{otype} = ["Azimuth", "Ln radius" . ($me->{params}->{r0} != 1.0 ? "/$me->{params}->{r0}" : "")];
2415 $me->{ounit} = [$me->{params}->{u},'']; # true-but-null prevents copying
2416 } else {
2417 $me->{otype} = ["Azimuth","Radius"];
2418 $me->{ounit} = [$me->{params}->{u},'']; # false value copies prev. unit
2419 }
2420  
2421 $me->{func} = sub {
2422  
2423 my($data,$o) = @_;
2424  
2425 my($out) = ($data->new_or_inplace);
2426  
2427 my($d) = $data->copy;
2428 $d->slice("0:1") -= $o->{origin};
2429  
2430 my($d0) = $d->slice("(0)");
2431 my($d1) = $d->slice("(1)");
2432  
2433 # (mod operator on atan2 puts everything in the interval [0,2*PI).)
2434 $out->slice("(0)") .= (atan2(-$d1,$d0) % (2*PDL::Transform::PI())) * $me->{params}->{angunit};
2435  
2436 $out->slice("(1)") .= (defined $o->{r0}) ?
2437 0.5 * log( ($d1*$d1 + $d0 * $d0) / ($o->{r0} * $o->{r0}) ) :
2438 sqrt($d1*$d1 + $d0*$d0);
2439  
2440 $out;
2441 };
2442  
2443 $me->{inv} = sub {
2444  
2445 my($d,$o) = @_;
2446 my($d0,$d1,$out)=
2447 ( ($d->is_inplace) ?
2448 ($d->slice("(0)")->copy, $d->slice("(1)")->copy->dummy(0,2), $d) :
2449 ($d->slice("(0)"), $d->slice("(1)")->dummy(0,2), $d->copy)
2450 );
2451  
2452 $d0 /= $me->{params}->{angunit};
2453  
2454 my($os) = $out->slice("0:1");
2455 $os .= append(cos($d0)->dummy(0,1),-sin($d0)->dummy(0,1));
2456 $os *= defined $o->{r0} ? ($o->{r0} * exp($d1)) : $d1;
2457 $os += $o->{origin};
2458  
2459 $out;
2460 };
2461  
2462 $me;
2463 }
2464  
2465 #line 3334 "lib/PDL/Transform.pd"
2466  
2467 =head2 t_quadratic
2468  
2469 =for usage
2470  
2471 $t = t_quadratic(<options>);
2472  
2473 =for ref
2474  
2475 Quadratic scaling -- cylindrical pincushion (n-d; with inverse)
2476  
2477 Quadratic scaling emulates pincushion in a cylindrical optical system:
2478 separate quadratic scaling is applied to each axis. You can apply
2479 separate distortion along any of the principal axes. If you want
2480 different axes, use L</t_wrap> and L</t_linear> to rotate
2481 them to the correct angle. The scaling options may be scalars or
2482 vectors; if they are scalars then the expansion is isotropic.
2483  
2484 The formula for the expansion is:
2485  
2486 f(a) = ( <a> + <strength> * a^2/<L_0> ) / (abs(<strength>) + 1)
2487  
2488 where <strength> is a scaling coefficient and <L_0> is a fundamental
2489 length scale. Negative values of <strength> result in a pincushion
2490 contraction.
2491  
2492 Note that, because quadratic scaling does not have a strict inverse for
2493 coordinate systems that cross the origin, we cheat slightly and use
2494 $x * abs($x) rather than $x**2. This does the Right thing for pincushion
2495 and barrel distortion, but means that t_quadratic does not behave exactly
2496 like t_cubic with a null cubic strength coefficient.
2497  
2498 OPTIONS
2499  
2500 =over 3
2501  
2502 =item o,origin,Origin
2503  
2504 The origin of the pincushion. (default is the, er, origin).
2505  
2506 =item l,l0,length,Length,r0
2507  
2508 The fundamental scale of the transformation -- the radius that remains
2509 unchanged. (default=1)
2510  
2511 =item s,str,strength,Strength
2512  
2513 The relative strength of the pincushion. (default = 0.1)
2514  
2515 =item d, dim, dims, Dims
2516  
2517 The number of dimensions to quadratically scale (default is the
2518 dimensionality of your input vectors)
2519  
2520 =back
2521  
2522 =cut
2523  
2524 sub t_quadratic {
2525 my($class) = 'PDL::Transform';
2526 my($o) = $_[0];
2527 if (ref $o ne 'HASH') {
2528 $o = {@_};
2529 }
2530 my($me) = $class->new;
2531  
2532 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
2533 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
2534 $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
2535 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
2536 $me->{name} = "quadratic";
2537  
2538 $me->{func} = sub {
2539 my($data,$o) = @_;
2540 my($dd) = $data->copy - $o->{origin};
2541 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
2542 $d += $o->{str} * ($d * abs($d)) / $o->{l0};
2543 $d /= (abs($o->{str}) + 1);
2544 $d += $o->{origin};
2545 if ($data->is_inplace) {
2546 $data .= $dd;
2547 return $data;
2548 }
2549 $dd;
2550 };
2551  
2552 $me->{inv} = sub {
2553 my($data,$opt) = @_;
2554 my($dd) = $data->copy ;
2555 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
2556 my($o) = $opt->{origin};
2557 my($s) = $opt->{str};
2558 my($l) = $opt->{l0};
2559  
2560 $d .= ((-1 + sqrt(1 + 4 * $s/$l * abs($d-$o) * (1+abs($s))))
2561 / 2 / $s * $l) * (1 - 2*($d < $o));
2562 $d += $o;
2563 if ($data->is_inplace) {
2564 $data .= $dd;
2565 return $data;
2566 }
2567 $dd;
2568 };
2569 $me;
2570 }
2571  
2572 #line 3445 "lib/PDL/Transform.pd"
2573  
2574 =head2 t_cubic
2575  
2576 =for usage
2577  
2578 $t = t_cubic(<options>);
2579  
2580 =for ref
2581  
2582 Cubic scaling - cubic pincushion (n-d; with inverse)
2583  
2584 Cubic scaling is a generalization of t_quadratic to a purely
2585 cubic expansion.
2586  
2587 The formula for the expansion is:
2588  
2589 f(a) = ( a' + st * a'^3/L_0^2 ) / (1 + abs(st)) + origin
2590  
2591 where a'=(a-origin). That is a simple pincushion
2592 expansion/contraction that is fixed at a distance of L_0 from the
2593 origin.
2594  
2595 Because there is no quadratic term the result is always invertible with
2596 one real root, and there is no mucking about with complex numbers or
2597 multivalued solutions.
2598  
2599 OPTIONS
2600  
2601 =over 3
2602  
2603 =item o,origin,Origin
2604  
2605 The origin of the pincushion. (default is the, er, origin).
2606  
2607 =item l,l0,length,Length,r0
2608  
2609 The fundamental scale of the transformation -- the radius that remains
2610 unchanged. (default=1)
2611  
2612 =item d, dim, dims, Dims
2613  
2614 The number of dimensions to treat (default is the
2615 dimensionality of your input vectors)
2616  
2617 =back
2618  
2619 =cut
2620  
2621 # needed since due to floating-point approx, is not *exactly* a cube-root
2622 sub _cuberoot {
2623 my $x = shift;
2624 my $as = 1 - 2*($x<0);
2625 return $as * (abs($x) ** (1/3));
2626 };
2627  
2628 # solve:
2629 # A x^3 + B x^2 + C x + D = 0
2630 # B is zero so this is greatly simplified; the discriminant is always negative
2631 # so there is always exactly one real root.
2632 sub _solve_depressed_cubic {
2633 my ($A, $C, $D) = @_;
2634 my $alpha = 27 * $A * $A * $D;
2635 my $beta = 3 * $A * $C;
2636 my $inner_root = sqrt( $alpha * $alpha + 4 * $beta * $beta * $beta );
2637 (-1 / (3 * $A)) *
2638 (
2639 + _cuberoot( 0.5 * ( $alpha + $inner_root ) )
2640 + _cuberoot( 0.5 * ( $alpha - $inner_root ) )
2641 )
2642 }
2643  
2644 sub t_cubic {
2645 my ($class) = 'PDL::Transform';
2646 my($o) = $_[0];
2647 if (ref $o ne 'HASH') {
2648 $o = {@_};
2649 }
2650 my($me) = $class->new;
2651  
2652 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims'],undef);
2653 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
2654 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
2655 $me->{params}->{st} = _opt($o,['s','st','str'],pdl(0));
2656 $me->{name} = "cubic";
2657  
2658 $me->{func} = sub {
2659 my($data,$o) = @_;
2660 my($dd) = $data->copy;
2661 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
2662  
2663 $d -= $o->{origin};
2664  
2665 my $dl0 = $d / $o->{l0};
2666  
2667 # f(x) = x + x**3 * ($o->{st} / $o->{l0}**2):
2668 # A = ($o->{st}/$dl0**2)
2669 # B = 0
2670 # C = 1
2671 # D = -f(x)
2672 $d += $o->{st} * $d * $dl0 * $dl0;
2673 $d /= ($o->{st}**2 + 1);
2674  
2675 $d += $o->{origin};
2676  
2677 if ($data->is_inplace) {
2678 $data .= $dd;
2679 return $data;
2680 }
2681 return $dd;
2682 };
2683  
2684 $me->{inv} = sub {
2685 my($data,$o) = @_;
2686 my($l) = $o->{l0};
2687  
2688 my($dd) = $data->copy;
2689 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
2690  
2691 $d -= $o->{origin};
2692 $d *= ($o->{st}+1);
2693  
2694 # First: create coefficients for mnemonics.
2695 my ($A, $C, $D) = ( $o->{st} / $l / $l, 1, - $d );
2696  
2697 $d .= _solve_depressed_cubic($A, $C, $D);
2698  
2699 $d += $me->{params}{origin};
2700  
2701 if ($data->is_inplace) {
2702 $data .= $dd;
2703 return $data;
2704 } else {
2705 return $dd;
2706 }
2707 };
2708  
2709 $me;
2710 }
2711  
2712 #line 3590 "lib/PDL/Transform.pd"
2713  
2714 =head2 t_quartic
2715  
2716 =for usage
2717  
2718 $t = t_quartic(<options>);
2719  
2720 =for ref
2721  
2722 Quartic scaling -- quartic pincushion (n-d; with inverse)
2723  
2724 Quartic scaling is a generalization of t_quadratic to a quartic
2725 expansion. Only even powers of the input coordinates are retained,
2726 and (as with t_quadratic) sign is preserved, making it an odd function
2727 although a true quartic transformation would be an even function.
2728  
2729 You can apply separate distortion along any of the principal axes. If
2730 you want different axes, use L</t_wrap> and
2731 L</t_linear> to rotate them to the correct angle. The
2732 scaling options may be scalars or vectors; if they are scalars then
2733 the expansion is isotropic.
2734  
2735 The formula for the expansion is:
2736  
2737 f(a) = ( <a> + <strength> * a^4/<L_0>^3 ) / (abs(<strength>) + 1)
2738  
2739 where <strength> is a scaling coefficient and <L_0> is a fundamental
2740 length scale. Negative values of <strength> result in a pincushion
2741 contraction.
2742  
2743 Note that, because quartic scaling does not have a strict inverse for
2744 coordinate systems that cross the origin, we cheat slightly and use
2745 $x**3 * abs($x) rather than $x**4. This does the Right thing for pincushion
2746 and barrel distortion.
2747  
2748 OPTIONS
2749  
2750 =over 3
2751  
2752 =item o,origin,Origin
2753  
2754 The origin of the pincushion. (default is the, er, origin).
2755  
2756 =item l,l0,length,Length,r0
2757  
2758 The fundamental scale of the transformation -- the radius that remains
2759 unchanged. (default=1)
2760  
2761 =item s,str,strength,Strength
2762  
2763 The relative strength of the pincushion. (default = 0.1)
2764  
2765 =item d, dim, dims, Dims
2766  
2767 The number of dimensions to quartically scale (default is the
2768 dimensionality of your input vectors)
2769  
2770 =back
2771  
2772 =cut
2773  
2774 # like sub _solve_depressed_cubic but for multi real solutions, returns 1
2775 # uses https://en.wikipedia.org/wiki/Casus_irreducibilis#Trigonometric_solution_in_terms_of_real_quantities
2776 sub _solve_depressed_cubic_multi {
2777 require PDL::Math;
2778 my ($p, $q) = @_;
2779 barf "inverse t_quartic: \$p must be negative" if $p->ge(0)->any;
2780 my $acos = PDL::Math::acos(3*$q/(2*$p) * sqrt(-3/$p));
2781 my $cos = cos($acos/3);
2782 2 * sqrt(-$p/3) * $cos;
2783 }
2784  
2785 sub t_quartic {
2786 my($class) = 'PDL::Transform';
2787 my($o) = $_[0];
2788 if (ref $o ne 'HASH') {
2789 $o = {@_};
2790 }
2791 my($me) = $class->new;
2792  
2793 $me->{params}->{origin} = _opt($o,['o','origin','Origin'],pdl(0));
2794 $me->{params}->{l0} = _opt($o,['r0','l','l0','length','Length'],pdl(1));
2795 $me->{params}->{str} = _opt($o,['s','str','strength','Strength'],pdl(0.1));
2796 $me->{params}->{dim} = _opt($o,['d','dim','dims','Dims']);
2797 $me->{name} = "quartic";
2798  
2799 $me->{func} = sub {
2800 my($data,$o) = @_;
2801 my($dd) = $data->copy - $o->{origin};
2802 my($d) = (defined $o->{dim}) ? $dd->slice("0:".($o->{dim}-1)) : $dd;
2803 $d += $o->{str} * ($d**3 * abs($d)) / ($o->{l0} ** 3);
2804 $d /= (abs($o->{str}) + 1);
2805 $d += $o->{origin};
2806 if ($data->is_inplace) {
2807 $data .= $dd;
2808 return $data;
2809 }
2810 $dd;
2811 };
2812  
2813 $me->{inv} = sub {
2814 my($data,$opt) = @_;
2815 my($dd) = $data->copy ;
2816 my($d) = (defined $opt->{dim}) ? $dd->slice("0:".($opt->{dim}-1)) : $dd;
2817 my($o) = $opt->{origin};
2818 my($s) = $opt->{str};
2819 my($l) = $opt->{l0};
2820  
2821 # Formula (ignoring the sign-preserve, since the xform
2822 # always moves away from origin):
2823 # sdiv = (abs(s) + 1)
2824 # b = ( <a> + <strength> * a^4/<L_0>^3 ) / (abs(<strength>) + 1)
2825 # = (a + s*a^4/L^3) / sdiv
2826 # b * sdiv = a + s*a^4/L^3
2827 # a + s*a^4/L^3 - b * sdiv = 0
2828 # a^4*s/L^3 + a - b * sdiv = 0 # ordered by degree
2829 # A = s/L^3
2830 # B = 1
2831 # C = -b * sdiv
2832  
2833 my $sign = (1 - 2*($d < $o));
2834 my ($A, $B, $C) = ($s/($l ** 3), 1, -abs($d-$o) * (1+abs($s)));
2835  
2836 # Roots are (https://math.stackexchange.com/questions/3658305/is-there-formula-that-solves-quartic-equation-ax4bxc-0):
2837 # x = s +- sqrt(-B/4As - s^2)
2838 # where s^2 = S satisfies cubic equation:
2839 # S^3 - S*C/4A - (B/8A)^2 = 0
2840  
2841 my $p = -$C / (4*$A);
2842 my $q = -($B/(8*$A)) ** 2;
2843 my $S = _solve_depressed_cubic(1, $p, $q);
2844 my $sqrt_S = sqrt($S);
2845 my $x = -$sqrt_S + sqrt($B / (4*$A*$sqrt_S) - $S);
2846  
2847 $d .= $x * $sign;
2848 $d += $o;
2849 if ($data->is_inplace) {
2850 $data .= $dd;
2851 return $data;
2852 }
2853 $dd;
2854 };
2855 $me;
2856 }
2857  
2858 #line 3739 "lib/PDL/Transform.pd"
2859  
2860 =head2 t_spherical
2861  
2862 =for usage
2863  
2864 $t = t_spherical(<options>);
2865  
2866 =for ref
2867  
2868 Convert Cartesian to spherical coordinates. (3-D; with inverse)
2869  
2870 Convert 3-D Cartesian to spherical (theta, phi, r) coordinates. Theta
2871 is longitude, centered on 0, and phi is latitude, also centered on 0.
2872 Unless you specify Euler angles, the pole points in the +Z direction
2873 and the prime meridian is in the +X direction. The default is for
2874 theta and phi to be in radians; you can select degrees if you want
2875 them.
2876  
2877 Just as the L</t_radial> 2-D transform acts like a 3-D
2878 cylindrical transform by ignoring third and higher dimensions,
2879 Spherical acts like a hypercylindrical transform in four (or higher)
2880 dimensions. Also as with L</t_radial>, you must manually specify
2881 the origin if you want to use more dimensions than 3.
2882  
2883 To deal with latitude & longitude on the surface of a sphere (rather
2884 than full 3-D coordinates), see
2885 L<t_unit_sphere|PDL::Transform::Cartography/t_unit_sphere>.
2886  
2887 OPTIONS:
2888  
2889 =over 3
2890  
2891 =item o, origin, Origin [default (0,0,0)]
2892  
2893 This is the Cartesian origin of the spherical expansion. Pass in a PDL
2894 or an array ref.
2895  
2896 =item e, euler, Euler [default (0,0,0)]
2897  
2898 This is a 3-vector containing Euler angles to change the angle of the
2899 pole and ordinate. The first two numbers are the (theta, phi) angles
2900 of the pole in a (+Z,+X) spherical expansion, and the last is the
2901 angle that the new prime meridian makes with the meridian of a simply
2902 tilted sphere. This is implemented by composing the output transform
2903 with a PDL::Transform::Linear object.
2904  
2905 =item u, unit, Unit (default radians)
2906  
2907 This option sets the angular unit to be used. Acceptable values are
2908 "degrees","radians", or reasonable substrings thereof (e.g. "deg", and
2909 "rad", but "d" and "r" are deprecated). Once genuine unit processing
2910 comes online (a la Math::Units) any angular unit should be OK.
2911  
2912 =back
2913  
2914 =cut
2915  
2916 sub t_spherical {
2917 my($class) = 'PDL::Transform';
2918 my($o) = $_[0];
2919 if (ref $o ne 'HASH') {
2920 $o = { @_ } ;
2921 }
2922  
2923 my($me) = $class->new;
2924  
2925 $me->{idim}=3;
2926 $me->{odim}=3;
2927  
2928 $me->{params}->{origin} = _opt($o,['o','origin','Origin']);
2929 $me->{params}->{origin} //= PDL->zeroes(3);
2930 $me->{params}->{origin} = PDL->pdl($me->{params}->{origin});
2931  
2932 $me->{params}->{deg} = _opt($o,['d','degrees','Degrees']);
2933  
2934 my $unit = _opt($o,['u','unit','Unit']);
2935 $me->{params}{angunit} = ($unit && $unit =~ m/^d/i) ?
2936 DEG2RAD() : undef;
2937  
2938 $me->{name} = "spherical";
2939  
2940 $me->{func} = sub {
2941 my ($data,$o) = @_;
2942 my $d = $data->copy - $o->{origin};
2943 my ($d0,$d1,$d2) = ($d->slice("(0)"),$d->slice("(1)"),$d->slice("(2)"));
2944 my $out = ($d->is_inplace) ? $data : $data->copy;
2945 $out->slice("(0)") .= PDL::atan2($d1, $d0);
2946 $out->slice("(2)") .= PDL::sqrt($d0*$d0 + $d1*$d1 + $d2*$d2);
2947 $out->slice("(1)") .= PDL::asin($d2 / $out->slice("(2)"));
2948 $out->slice("0:1") /= $o->{angunit}
2949 if defined $o->{angunit};
2950 $out;
2951 };
2952  
2953 $me->{inv} = sub {
2954 my ($d,$o) = @_;
2955 PDL::t_spherical_inv($d, $o->{origin}, $o->{angunit} // 1);
2956 };
2957  
2958 $me;
2959 }
2960 #line 2961 "lib/PDL/Transform.pm"
2961  
2962 0 *t_spherical_inv = \&PDL::t_spherical_inv;
2963  
2964  
2965  
2966  
2967  
2968 #line 3864 "lib/PDL/Transform.pd"
2969  
2970 =head2 t_projective
2971  
2972 =for usage
2973  
2974 $t = t_projective(<options>);
2975  
2976 =for ref
2977  
2978 Projective transformation
2979  
2980 Projective transforms are simple quadratic, quasi-linear
2981 transformations. They are the simplest transformation that
2982 can continuously warp an image plane so that C<ncoords + 2> arbitrarily chosen
2983 points exactly map to the same number of other arbitrarily chosen points. They
2984 have the property that straight lines remain straight after transformation.
2985  
2986 =for example
2987  
2988 # perspective projection 3D -> 2D
2989 $t_proj = t_projective(
2990 src => pdl('1 1 1; -1 1 1; -1 -1 1; 1 -1 1; 2 2 2; -2 -2 2'),
2991 dst => pdl('0 1000; 1000 1000; 1000 0; 0 0; 0 1000; 1000 0'),
2992 );
2993 # orthographic projection 3D -> 2D
2994 # warning, numerically unstable as the Direct Linear Transform
2995 # is for perspective not this
2996 $t_proj = t_projective(
2997 # near top-left, near top-right, near bottom-left near bottom-right
2998 # far middle, far mid-right
2999 src => my $src32 = pdl('-1 1 -1; 1 1 -1; -1 -1 -1; 1 -1 -1; 0 0 1; 1 0 1'),
3000 dst => my $dst32 = pdl('0 0; 1000 0; 0 1000; 1000 1000; 500 500; 1000 500'),
3001 );
3002  
3003 You can specify your projective transformation directly in homogeneous
3004 coordinates, or (as of 2.104, not just in 2 dimensions) as a set
3005 of unique points that
3006 are mapped one to the other by the transformation.
3007  
3008 Projective transforms are quasi-linear because they are most easily
3009 described as a linear transformation in homogeneous coordinates
3010 (e.g. (x',y',w) where w is a normalization factor: x = x'/w, etc.).
3011 In those coordinates, an N-D projective transformation is represented
3012 as simple multiplication of an N+1-vector by an M+1 x N+1 matrix,
3013 whose lower-right corner value is 1.
3014  
3015 If the bottom row of the matrix consists of all zeroes, then the
3016 transformation reduces to a linear affine transformation (as in
3017 L</t_linear>).
3018  
3019 If the bottom row of the matrix contains nonzero elements, then the
3020 transformed x,y,z,etc. coordinates are related to the original coordinates
3021 by a quadratic polynomial, because the normalization factor 'w' allows
3022 a second factor of x,y, and/or z to enter the equations.
3023  
3024 OPTIONS:
3025  
3026 =over 3
3027  
3028 =item m, mat, matrix, Matrix
3029  
3030 If specified, this is the homogeneous-coordinate matrix to use.
3031 Works with non-square matrix, so M+1 x N+1, for an N-to-M-dimensional
3032 transformation.
3033  
3034 =item src, from, I<and> dst, to
3035  
3036 If specified, this is the sets of points that should be mapped one
3037 to the other. Both C<src> and C<dst> must have the same number of
3038 points (C<N>).
3039 That number must be, where C<m,n> are the number of destination, source
3040 dimensions: C<((m+1)*(n+1)-1)/n>.
3041 The ndarrays are dimensioned C<(coords,N)>.
3042 The homogeneous-coordinate matrix is calculated from them.
3043 For example, specifying
3044  
3045 src => pdl([ [0,0], [0,1], [5,9], [9,4] ])
3046 dst => pdl([ [0,0], [0,1], [5,8], [9,3] ])
3047  
3048 maps the origin and the point (0,1) to themselves, the point (5,9)
3049 to (5,8), and the point (9,4) to (9,3).
3050  
3051 Added in 2.104. Works on any number of dimensions.
3052  
3053 =item p, point, points, Points
3054  
3055 You are encouraged to use the more general C<src,dst> options given above.
3056  
3057 If specified, this is the set of C<ncoords + 2> points that should
3058 be mapped one to the other. Feed in a
3059 C<2 x 2 x 4> PDL, where the 0 dimension runs over
3060 coordinate, the 1 dimension runs between input
3061 and output, and the 2 dimension runs over points. For example, specifying
3062  
3063 p => pdl([ [[0,0],[0,0]], [[0,1],[0,1]], [[5,9],[5,8]], [[9,4],[9,3]] ])
3064  
3065 maps the origin and the point (0,1) to themselves, the point (5,9)
3066 to (5,8), and the point (9,4) to (9,3).
3067  
3068 This is similar to the behavior of fitwarp2d with a quadratic polynomial.
3069  
3070 =back
3071  
3072 =cut
3073  
3074 sub sub_eps_to_0 {
3075 my ($m, $eps) = @_;
3076 $m * (abs($m) > $eps)
3077 }
3078  
3079 sub _normalise_points {
3080 my ($pts) = @_;
3081 my $d = $pts->dim(0); # pts: (dim,N) matrix where each row is a point
3082 my $centroid = $pts->t->avgover;
3083 my $shifted = $pts - $centroid; # shift points to origin
3084 # 2. Scale so average distance to origin is sqrt(dim)
3085 my $scale = sqrt($d) / avg($shifted->magnover); # keep coord vals close to 1
3086 # T combines scaling and translation: T = Scale * Translate
3087 my $T = identity($d + 1);
3088 $T->diagonal(0,1)->slice(":-2") .= $scale;
3089 $T->slice("(-1),:-2") .= -$scale * $centroid;
3090 my $pts_h = $pts->append(1) x $T->t; # Convert to homogeneous coords, apply T
3091 ($pts_h, $T);
3092 }
3093  
3094 sub block_rotate :lvalue {
3095 my ($m, $width) = @_;
3096 die "block_rotate: given undef width" if !defined $width;
3097 my $height = $m->dim(1);
3098 $m->rotate(-$width*sequence(indx,$height))->slice('0:'.($width-1));
3099 }
3100  
3101 # Construct the system of N equations to find the projective transform
3102 sub construct_DLT {
3103 my ($pts_src, $pts_dst) = @_;
3104 die "t_projective: must supply same number of src and dst points\n"
3105 unless $pts_src->dim(1) == $pts_dst->dim(1);
3106 my ($pts_src_h, $T_src) = _normalise_points($pts_src); # (n+1,N) homogeneous
3107 my ($pts_dst_h, $T_dst) = _normalise_points($pts_dst); # (m+1,N) homogeneous
3108 my ($src_dim, $N) = $pts_src_h->dims; # n+1
3109 my ($dst_dim) = $pts_dst_h->dims; # m+1
3110 my $num_eqs = $N * ($dst_dim - 1); # Each point match provides (m) equations
3111 my $num_vars = $src_dim * $dst_dim;
3112 my $A = zeroes($num_vars-$src_dim, $num_eqs);
3113 # Mapping: xp_last * (P_j * x) - xp_j * (P_last * x) = 0
3114 # Fill coefficients for the j-th row of P
3115 my $mult = $pts_dst_h->slice(-1) * $pts_src_h;
3116 block_rotate($A, $src_dim) .= $mult->dummy(1,$dst_dim-1)->clump(1,2);
3117 # Fill coefficients for the last row of P
3118 $A = $A->append(-outer($pts_src_h, $pts_dst_h->slice(":-2"))->clump(1,2));
3119 ($A, $T_src, $T_dst);
3120 }
3121  
3122 sub solve_DLT {
3123 my ($A, $T_src, $T_dst) = @_;
3124 my ($U, $S, $V) = svd($A, 1); # full SVD
3125 my $P_norm = $V->slice(-1)->reshape(map $_->dim(0), $T_src, $T_dst); # reshape smallest singular value vector
3126 $T_dst->inv x $P_norm x $T_src; # Denormalize
3127 }
3128  
3129 sub t_projective {
3130 my $class = 'PDL::Transform';
3131 my $o = ref $_[0] eq 'HASH' ? $_[0] : { @_ };
3132  
3133 my $me = $class->new;
3134 $me->{name} = "projective";
3135  
3136 ### Set options...
3137 $me->{params}{idim} = $me->{idim} = _opt($o,['d','dim','Dim']);
3138  
3139 my $matrix;
3140 if (defined ($matrix=_opt($o,['m','matrix','Matrix']))) {
3141 $matrix = PDL->topdl($matrix);
3142 $me->{params}{idim} //= $matrix->dim(0)-1;
3143 die "t_projective: matrix not compatible with given dimension (should be N+1xN+1)\n"
3144 unless $me->{params}{idim} == $matrix->dim(0)-1;
3145 } else {
3146 my ($p, $pts_src, $pts_dst) = _opt($o,['p','point','points','Point','Points']);
3147 if (defined $p) {
3148 $p = PDL->topdl($p);
3149 die "t_projective: points must be ncoord x 2(in,out) x ncoord+2(point)"
3150 unless $p->dims==3 && all($p->shape == pdl(2,2,4));
3151 ($pts_src, $pts_dst) = $p->mv(1,-1)->dog;
3152 } else {
3153 ($pts_src, $pts_dst) = map _opt($o,$_), ['src','from'], ['dst','to'];
3154 }
3155 die "t_projective: must supply either 'p', 'm', or 'src' and 'dst' options"
3156 if grep !defined, $pts_src, $pts_dst;
3157 my ($A, $T_src, $T_dst) = construct_DLT($pts_src, $pts_dst);
3158 # Solve the system
3159 $matrix = solve_DLT($A, $T_src, $T_dst);
3160 }
3161 $me->{params}{matrix} = $matrix;
3162 $me->{params}{matinv} = $matrix->inv if $matrix->dim(0) == $matrix->dim(1);
3163  
3164 $me->{idim} = $me->{odim} = $me->{params}{odim} = $me->{params}{idim} //= 2;
3165  
3166 $me->{func} = sub {
3167 my ($data,$o) = @_;
3168 my $out = $data->append(1) x $o->{matrix}->t;
3169 $out->slice("0:-2")/$out->slice("-1");
3170 };
3171  
3172 $me->{inv} = sub {
3173 my ($data,$o) = @_;
3174 die "t_projective: uninvertible projection due to dimension change"
3175 if !defined $o->{matinv};
3176 my $out = $data->append(1) x $o->{matinv}->t;
3177 $out->slice("0:-2")/$out->slice("-1");
3178 };
3179  
3180 $me;
3181 }
3182  
3183 #line 248 "lib/PDL/Transform.pd"
3184  
3185 =head1 AUTHOR
3186  
3187 Copyright 2002, 2003 Craig DeForest. There is no warranty. You are allowed
3188 to redistribute this software under certain conditions. For details,
3189 see the file COPYING in the PDL distribution. If this file is
3190 separated from the PDL distribution, the copyright notice should be
3191 included in the file.
3192  
3193 =cut
3194  
3195 package PDL::Transform;
3196 use Carp;
3197 use overload '""' => \&_strval;
3198 use overload 'x' => \&_compose_op;
3199 use overload '**' => \&_pow_op;
3200 use overload '!' => \&t_inverse;
3201  
3202 use PDL::LiteF;
3203 use PDL::MatrixOps;
3204 use PDL::Constants qw(PI DEG2RAD);
3205  
3206 #### little helper kludge parses a list of synonyms
3207 sub _opt {
3208 my ($hash, $synonyms, $alt) = @_; # default $alt is undef -- ok.
3209 return $alt if !(my ($s) = grep defined $hash->{$_}, @$synonyms);
3210 UNIVERSAL::isa($alt,'PDL') ? PDL->pdl($hash->{$s}) : $hash->{$s};
3211 }
3212  
3213 ######################################################################
3214 #
3215 # Stringification hack. _strval just does a method search on stringify
3216 # for the object itself. This gets around the fact that stringification
3217 # overload is a subroutine call, not a method search.
3218 #
3219  
3220 sub _strval {
3221 my($me) = shift;
3222 $me->stringify();
3223 }
3224  
3225 ######################################################################
3226 #
3227 # PDL::Transform overall stringifier. Subclassed stringifiers should
3228 # call this routine first then append auxiliary information.
3229 #
3230 sub stringify {
3231 my($me) = shift;
3232 my($mestr) = (ref $me);
3233 $mestr =~ s/PDL::Transform:://;
3234 my $out = $mestr . " (" . $me->{name} . "): ";
3235 $out .= "fwd ". ((defined ($me->{func})) ? ( (ref($me->{func}) eq 'CODE') ? "ok" : "non-CODE(!!)" ): "missing")."; ";
3236 $out .= "inv ". ((defined ($me->{inv})) ? ( (ref($me->{inv}) eq 'CODE') ? "ok" : "non-CODE(!!)" ):"missing").".\n";
3237 }
3238 #line 3239 "lib/PDL/Transform.pm"
3239  
3240 # Exit with OK status
3241  
3242 0 1;
« lib/PDL/Slices-pp-broadcastI.c ↑ Summary lib/PDL/Slices-pp-xchg.c »