File Coverage

blib/lib/PDLA/Core.pm
Criterion Covered Total %
statement 67 827 8.1
branch 1 492 0.2
condition 0 117 0.0
subroutine 20 118 16.9
pod 0 50 0.0
total 88 1604 5.4


line stmt bran cond sub pod time code
1             package PDLA::Core;
2              
3             # Core routines for PDLA module
4              
5 117     117   701 use strict;
  117         184  
  117         4286  
6 117     117   566 use warnings;
  117         173  
  117         4547  
7 117     117   58504 use PDLA::Exporter;
  117         256  
  117         706  
8             require PDLA; # for $VERSION
9 117     117   1393 use DynaLoader;
  117         188  
  117         9797  
10             our @ISA = qw( PDLA::Exporter DynaLoader );
11             our $VERSION = '2.013';
12             bootstrap PDLA::Core $VERSION;
13 117     117   63547 use PDLA::Types ':All';
  117         331  
  117         92835  
14              
15             our @EXPORT = qw( piddle pdl null barf ); # Only stuff always exported!
16             my @convertfuncs = map PDLA::Types::typefld($_,'convertfunc'), PDLA::Types::typesrtkeys();
17             my @exports_internal = qw(howbig threadids topdl);
18             my @exports_normal = (@EXPORT,
19             @convertfuncs,
20             qw(nelem dims shape null
21             convert inplace zeroes zeros ones list listindices unpdl
22             set at flows thread_define over reshape dog cat barf type diagonal
23             dummy mslice approx flat sclr squeeze
24             get_autopthread_targ set_autopthread_targ get_autopthread_actual
25             get_autopthread_size set_autopthread_size) );
26             our @EXPORT_OK = (@exports_internal, @exports_normal);
27             our %EXPORT_TAGS = (
28             Func => [@exports_normal],
29             Internal => [@exports_internal] );
30              
31             our ($level, @dims, $sep, $sep2, $match);
32              
33             # Important variables (place in PDLA namespace)
34             # (twice to eat "used only once" warning)
35              
36             $PDLA::debug = # Debugging info
37             $PDLA::debug = 0;
38             $PDLA::verbose = # Functions provide chatty information
39             $PDLA::verbose = 0;
40             $PDLA::use_commas = 0; # Whether to insert commas when printing arrays
41             $PDLA::floatformat = "%7g"; # Default print format for long numbers
42             $PDLA::doubleformat = "%10.8g";
43             $PDLA::undefval = 0; # Value to use instead of undef when creating PDLAs
44             $PDLA::toolongtoprint = 10000; # maximum pdl size to stringify for printing
45              
46             ################ Exportable functions of the Core ######################
47              
48             # log10() is now defined in ops.pd
49              
50             *howbig = \&PDLA::howbig; *unpdl = \&PDLA::unpdl;
51             *nelem = \&PDLA::nelem; *inplace = \&PDLA::inplace;
52             *dims = \&PDLA::dims; *list = \&PDLA::list;
53             *threadids = \&PDLA::threadids; *listindices = \&PDLA::listindices;
54             *null = \&PDLA::null; *set = \&PDLA::set;
55             *at = \&PDLA::at; *flows = \&PDLA::flows;
56             *sclr = \&PDLA::sclr; *shape = \&PDLA::shape;
57              
58             for (map {
59             [ PDLA::Types::typefld($_,'convertfunc'), PDLA::Types::typefld($_,'numval') ]
60             } PDLA::Types::typesrtkeys()) {
61             my ($conv, $val) = @$_;
62 117     117   783 no strict 'refs';
  117         185  
  117         41918  
63             *$conv = *{"PDLA::$conv"} = sub {
64             return bless [$val], "PDLA::Type" unless @_;
65             convert(alltopdl('PDLA', (scalar(@_)>1 ? [@_] : shift)), $val);
66             };
67             }
68              
69             BEGIN {
70 117     117   1228 *thread_define = \&PDLA::thread_define;
71 117         317 *convert = \&PDLA::convert; *over = \&PDLA::over;
  117         1265  
72 117         269 *dog = \&PDLA::dog; *cat = \&PDLA::cat;
  117         2291  
73 117         269 *type = \&PDLA::type; *approx = \&PDLA::approx;
  117         1070  
74 117         421 *diagonal = \&PDLA::diagonal;
75 117         285 *dummy = \&PDLA::dummy;
76 117         262 *mslice = \&PDLA::mslice;
77 117         948 *isempty = \&PDLA::isempty;
78 117         23455 *string = \&PDLA::string;
79             }
80              
81             =head1 NAME
82              
83             PDLA::Core - fundamental PDLA functionality and vectorization/threading
84              
85             =head1 DESCRIPTION
86              
87             Methods and functions for type conversions, PDLA creation,
88             type conversion, threading etc.
89              
90             =head1 SYNOPSIS
91              
92             use PDLA::Core; # Normal routines
93             use PDLA::Core ':Internal'; # Hairy routines
94              
95             =head1 VECTORIZATION/THREADING: METHOD AND NOMENCLATURE
96              
97             PDLA provides vectorized operations via a built-in engine.
98             Vectorization is called "threading" for historical reasons.
99             The threading engine implements simple rules for each operation.
100              
101             Each PDLA object has a "shape" that is a generalized N-dimensional
102             rectangle defined by a "dim list" of sizes in an arbitrary
103             set of dimensions. A PDLA with shape 2x3 has 6 elements and is
104             said to be two-dimensional, or may be referred to as a 2x3-PDLA.
105             The dimensions are indexed numerically starting at 0, so a
106             2x3-PDLA has a dimension 0 (or "dim 0") with size 2 and a 1 dimension
107             (or "dim 1") with size 3.
108              
109             PDLA generalizes *all* mathematical operations with the notion of
110             "active dims": each operator has zero or more active dims that are
111             used in carrying out the operation. Simple scalar operations like
112             scalar multiplication ('*') have 0 active dims. More complicated
113             operators can have more active dims. For example, matrix
114             multiplication ('x') has 2 active dims. Additional dims are
115             automatically vectorized across -- e.g. multiplying a 2x5-PDLA with a
116             2x5-PDLA requires 10 simple multiplication operations, and yields a
117             2x5-PDLA result.
118              
119             =head2 Threading rules
120              
121             In any PDLA expression, the active dims appropriate for each operator
122             are used starting at the 0 dim and working forward through the dim
123             list of each object. All additional dims after the active dims are
124             "thread dims". The thread dims do not have to agree exactly: they are
125             coerced to agree according to simple rules:
126              
127             =over 3
128              
129             =item * Null PDLAs match any dim list (see below).
130              
131             =item * Dims with sizes other than 1 must all agree in size.
132              
133             =item * Dims of size 1 are expanded as necessary.
134              
135             =item * Missing dims are expanded appropriately.
136              
137             =back
138              
139             The "size 1" rule implements "generalized scalar" operation, by
140             analogy to scalar multiplication. The "missing dims" rule
141             acknowledges the ambiguity between a missing dim and a dim of size 1.
142              
143             =head2 Null PDLAs
144              
145             PDLAs on the left-hand side of assignment can have the special value
146             "Null". A null PDLA has no dim list and no set size; its shape is
147             determined by the computed shape of the expression being assigned to
148             it. Null PDLAs contain no values and can only be assigned to. When
149             assigned to (e.g. via the C<.=> operator), they cease to be null PDLAs.
150              
151             To create a null PDLA, use Cnull()>.
152              
153             =head2 Empty PDLAs
154              
155             PDLAs can represent the empty set using "structured Empty" variables.
156             An empty PDLA is not a null PDLA.
157              
158             Any dim of a PDLA can be set explicitly to size 0. If so, the PDLA
159             contains zero values (because the total number of values is the
160             product of all the sizes in the PDLA's shape or dimlist).
161              
162             Scalar PDLAs are zero-dimensional and have no entries in the dim list,
163             so they cannot be empty. 1-D and higher PDLAs can be empty. Empty
164             PDLAs are useful for set operations, and are most commonly encountered
165             in the output from selection operators such as L
166             and L. Not all empty PDLAs have the same
167             threading properties -- e.g. a 2x0-PDLA represents a collection of
168             2-vectors that happens to contain no elements, while a simple 0-PDLA
169             represents a collection of scalar values (that also happens to contain
170             no elements).
171              
172             Note that 0 dims are not adjustable via the threading rules -- a dim
173             with size 0 can only match a corresponding dim of size 0 or 1.
174              
175             =head2 Thread rules and assignments
176              
177             Versions of PDLA through 2.4.10 have some irregularity with threading and
178             assignments. Currently the threading engine performs a full expansion of
179             both sides of the computed assignment operator C<.=> (which assigns values
180             to a pre-existing PDLA). This leads to counter-intuitive behavior in
181             some cases:
182              
183             =over 3
184              
185             =item * Generalized scalars and computed assignment
186              
187             If the PDLA on the left-hand side of C<.=> has a dim of size 1, it can be
188             treated as a generalized scalar, as in:
189              
190             $a = sequence(2,3);
191             $b = zeroes(1,3);
192             $b .= $a;
193              
194             In this case, C<$b> is automatically treated as a 2x3-PDLA during the
195             threading operation, but half of the values from C<$a> silently disappear.
196             The output is, as Kernighan and Ritchie would say, "undefined".
197              
198             Further, if the value on the right of C<.=> is empty, then C<.=> becomes
199             a silent no-op:
200              
201             $a = zeroes(0);
202             $b = zeroes(1);
203             $b .= $a+1;
204             print $b;
205              
206             will print C<[0]>. In this case, "$a+1" is empty, and "$b" is a generalized
207             scalar that is adjusted to be empty, so the assignment is carried out for
208             zero elements (a no-op).
209              
210             Both of these behaviors are considered harmful and should not be relied upon:
211             they may be patched away in a future version of PDLA.
212              
213             =item * Empty PDLAs and generalized scalars
214              
215             Generalized scalars (PDLAs with a dim of size 1) can match any size in the
216             corresponding dim, including 0. Thus,
217              
218             $a = ones(2,0);
219             $b = sequence(2,1);
220             $c = $a * $b;
221             print $c;
222              
223             prints C.
224              
225             This behavior is counterintuitive but desirable, and will be preserved
226             in future versions of PDLA.
227              
228             =back
229              
230             =head1 VARIABLES
231              
232             These are important variables of B scope and are placed
233             in the PDLA namespace.
234              
235             =head3 C<$PDLA::debug>
236              
237             =over 4
238              
239             When true, PDLA debugging information is printed.
240              
241             =back
242              
243             =head3 C<$PDLA::verbose>
244              
245             =over 4
246              
247             When true, PDLA functions provide chatty information.
248              
249             =back
250              
251             =head3 C<$PDLA::use_commas>
252              
253             =over 4
254              
255             Whether to insert commas when printing pdls
256              
257             =back
258              
259             =head3 C<$PDLA::floatformat>, C<$PDLA::doubleformat>
260              
261             =over 4
262              
263             The default print format for floats and doubles, repectively.
264             The default default values are:
265              
266             $PDLA::floatformat = "%7g";
267             $PDLA::doubleformat = "%10.8g";
268              
269             =back
270              
271             =head3 C<$PDLA::undefval>
272              
273             =over 4
274              
275             The value to use instead of C when creating pdls.
276              
277             =back
278              
279             =head3 C<$PDLA::toolongtoprint>
280              
281             =over 4
282              
283             The maximal size pdls to print (defaults to 10000 elements)
284              
285             =back
286              
287             =head1 FUNCTIONS
288              
289              
290             =head2 barf
291              
292             =for ref
293              
294             Standard error reporting routine for PDLA.
295              
296             C is the routine PDLA modules should call to report errors. This
297             is because C will report the error as coming from the correct
298             line in the module user's script rather than in the PDLA module.
299              
300             For now, barf just calls Carp::confess()
301              
302             Remember C is your friend. *Use* it!
303              
304             =for example
305              
306             At the perl level:
307              
308             barf("User has too low an IQ!");
309              
310             In C or XS code:
311              
312             barf("You have made %d errors", count);
313              
314             Note: this is one of the few functions ALWAYS exported
315             by PDLA::Core
316              
317             =cut
318              
319 117     117   1805 use Carp;
  117         239  
  117         81254  
320 0     0   0 sub barf { goto &Carp::confess }
321 0     0   0 sub cluck { goto &Carp::cluck }
322             *PDLA::barf = \&barf;
323             *PDLA::cluck = \&cluck;
324              
325             ########## Set Auto-PThread Based On Environment Vars ############
326             PDLA::set_autopthread_targ( $ENV{PDLA_AUTOPTHREAD_TARG} ) if( defined ( $ENV{PDLA_AUTOPTHREAD_TARG} ) );
327             PDLA::set_autopthread_size( $ENV{PDLA_AUTOPTHREAD_SIZE} ) if( defined ( $ENV{PDLA_AUTOPTHREAD_SIZE} ) );
328             ##################################################################
329              
330             =head2 pdl
331              
332             =for ref
333              
334             PDLA constructor - creates new piddle from perl scalars/arrays, piddles, and strings
335              
336             =for usage
337              
338             $a = pdl(SCALAR|ARRAY REFERENCE|ARRAY|STRING);
339              
340             =for example
341              
342             $a = pdl [1..10]; # 1D array
343             $a = pdl ([1..10]); # 1D array
344             $a = pdl (1,2,3,4); # Ditto
345             $b = pdl [[1,2,3],[4,5,6]]; # 2D 3x2 array
346             $b = pdl "[[1,2,3],[4,5,6]]"; # Ditto (slower)
347             $b = pdl "[1 2 3; 4 5 6]"; # Ditto
348             $b = pdl q[1 2 3; 4 5 6]; # Ditto, using the q quote operator
349             $b = pdl "1 2 3; 4 5 6"; # Ditto, less obvious, but still works
350             $b = pdl 42 # 0-dimensional scalar
351             $c = pdl $a; # Make a new copy
352             $a = pdl([1,2,3],[4,5,6]); # 2D
353             $a = pdl([[1,2,3],[4,5,6]]); # 2D
354              
355             Note the last two are equivalent - a list is automatically
356             converted to a list reference for syntactic convenience. i.e. you
357             can omit the outer C<[]>
358              
359             You can mix and match arrays, array refs, and PDLAs in your argument
360             list, and C will sort them out. You get back a PDLA whose last
361             (slowest running) dim runs across the top level of the list you hand
362             in, and whose first (fastest running) dim runs across the deepest
363             level that you supply.
364             At the moment, you cannot mix and match those arguments with string
365             arguments, though we can't imagine a situation in which you would
366             really want to do that.
367              
368             The string version of pdl also allows you to use the strings C, C,
369             and C, and it will insert the values that you mean (and set the bad flag
370             if you use C). You can mix and match case, though you shouldn't. Here are
371             some examples:
372              
373             $bad = pdl q[1 2 3 bad 5 6]; # Set fourth element to the bad value
374             $bad = pdl q[1 2 3 BAD 5 6]; # ditto
375             $bad = pdl q[1 2 inf bad 5]; # now third element is IEEE infinite value
376             $bad = pdl q[nan 2 inf -inf]; # first value is IEEE nan value
377              
378             The default constructor uses IEEE double-precision floating point numbers. You
379             can use other types, but you will get a warning if you try to use C with
380             integer types (it will be replaced with the C value) and you will get a
381             fatal error if you try to use C.
382              
383             Throwing a PDLA into the mix has the same effect as throwing in a list ref:
384              
385             pdl(pdl(1,2),[3,4])
386              
387             is the same as
388              
389             pdl([1,2],[3,4]).
390              
391             All of the dimensions in the list are "padded-out" with undefval to
392             meet the widest dim in the list, so (e.g.)
393              
394             $a = pdl([[1,2,3],[2]])
395              
396             gives you the same answer as
397              
398             $a = pdl([[1,2,3],[2,undef,undef]]);
399              
400              
401             C is a functional synonym for the 'new' constructor,
402             e.g.:
403              
404             $x = new PDLA [1..10];
405              
406             In order to control how undefs are handled in converting from perl lists to
407             PDLAs, one can set the variable C<$PDLA::undefval>.
408             For example:
409              
410             $foo = [[1,2,undef],[undef,3,4]];
411             $PDLA::undefval = -999;
412             $f = pdl $foo;
413             print $f
414             [
415             [ 1 2 -999]
416             [-999 3 4]
417             ]
418              
419             C<$PDLA::undefval> defaults to zero.
420              
421             As a final note, if you include an Empty PDLA in the list of objects to
422             construct into a PDLA, it is kept as a placeholder pane -- so if you feed
423             in (say) 7 objects, you get a size of 7 in the 0th dim of the output PDLA.
424             The placeholder panes are completely padded out. But if you feed in only
425             a single Empty PDLA, you get back the Empty PDLA (no padding).
426              
427             =cut
428              
429 0     0   0 sub pdl {PDLA->pdl(@_)}
430              
431 0     0   0 sub piddle {PDLA->pdl(@_)}
432              
433             =head2 null
434              
435             =for ref
436              
437             Returns a 'null' piddle.
438              
439             =for usage
440              
441             $x = null;
442              
443             C has a special meaning to L. It is used to
444             flag a special kind of empty piddle, which can grow to
445             appropriate dimensions to store a result (as opposed to
446             storing a result in an existing piddle).
447              
448             =for example
449              
450             pdl> sumover sequence(10,10), $ans=null;p $ans
451             [45 145 245 345 445 545 645 745 845 945]
452              
453             =cut
454              
455             sub PDLA::null{
456 0 0   0 0 0 my $class = scalar(@_) ? shift : undef; # if this sub called with no
457             # class ( i.e. like 'null()', instead
458             # of '$obj->null' or 'CLASS->null', setup
459              
460 0 0       0 if( defined($class) ){
461 0   0     0 $class = ref($class) || $class; # get the class name
462             }
463             else{
464 0         0 $class = 'PDLA'; # set class to the current package name if null called
465             # with no arguments
466             }
467              
468 0         0 return $class->initialize();
469             }
470              
471             =head2 nullcreate
472              
473             =for ref
474              
475             Returns a 'null' piddle.
476              
477             =for usage
478              
479             $x = PDLA->nullcreate($arg)
480              
481             This is an routine used by many of the threading primitives
482             (i.e. L,
483             L, etc.) to generate a null piddle for the
484             function's output that will behave properly for derived (or
485             subclassed) PDLA objects.
486              
487             For the above usage:
488             If C<$arg> is a PDLA, or a derived PDLA, then C<$arg-Enull> is returned.
489             If C<$arg> is a scalar (i.e. a zero-dimensional PDLA) then Cnull>
490             is returned.
491              
492             =for example
493              
494             PDLA::Derived->nullcreate(10)
495             returns PDLA::Derived->null.
496             PDLA->nullcreate($pdlderived)
497             returns $pdlderived->null.
498              
499             =cut
500              
501             sub PDLA::nullcreate{
502 0     0 0 0 my ($type,$arg) = @_;
503 0 0       0 return ref($arg) ? $arg->null : $type->null ;
504             }
505              
506             =head2 nelem
507              
508             =for ref
509              
510             Return the number of elements in a piddle
511              
512             =for usage
513              
514             $n = nelem($piddle); $n = $piddle->nelem;
515              
516             =for example
517              
518             $mean = sum($data)/nelem($data);
519              
520             =head2 dims
521              
522             =for ref
523              
524             Return piddle dimensions as a perl list
525              
526             =for usage
527              
528             @dims = $piddle->dims; @dims = dims($piddle);
529              
530             =for example
531              
532             pdl> p @tmp = dims zeroes 10,3,22
533             10 3 22
534              
535             See also L which returns a piddle instead.
536              
537             =head2 shape
538              
539             =for ref
540              
541             Return piddle dimensions as a piddle
542              
543             =for usage
544              
545             $shape = $piddle->shape; $shape = shape($piddle);
546              
547             =for example
548              
549             pdl> p $shape = shape zeroes 10,3,22
550             [10 3 22]
551              
552             See also L which returns a perl list.
553              
554             =head2 ndims
555              
556             =for ref
557              
558             Returns the number of dimensions in a piddle. Alias
559             for L.
560              
561             =head2 getndims
562              
563             =for ref
564              
565             Returns the number of dimensions in a piddle
566              
567             =for usage
568              
569             $ndims = $piddle->getndims;
570              
571             =for example
572              
573             pdl> p zeroes(10,3,22)->getndims
574             3
575              
576             =head2 dim
577              
578             =for ref
579              
580             Returns the size of the given dimension of a piddle. Alias
581             for L.
582              
583             =head2 getdim
584              
585             =for ref
586              
587             Returns the size of the given dimension.
588              
589             =for usage
590              
591             $dim0 = $piddle->getdim(0);
592              
593             =for example
594              
595             pdl> p zeroes(10,3,22)->getdim(1)
596             3
597              
598             Negative indices count from the end of the dims array.
599             Indices beyond the end will return a size of 1. This
600             reflects the idea that any pdl is equivalent to an
601             infinitely dimensional array in which only a finite number of
602             dimensions have a size different from one. For example, in that sense a
603             3D piddle of shape [3,5,2] is equivalent to a [3,5,2,1,1,1,1,1,....]
604             piddle. Accordingly,
605              
606             print $a->getdim(10000);
607              
608             will print 1 for most practically encountered piddles.
609              
610             =head2 topdl
611              
612             =for ref
613              
614             alternate piddle constructor - ensures arg is a piddle
615              
616             =for usage
617              
618             $a = topdl(SCALAR|ARRAY REFERENCE|ARRAY);
619              
620             The difference between L and C is that the
621             latter will just 'fall through' if the argument is
622             already a piddle. It will return a reference and I
623             a new copy.
624              
625             This is particulary useful if you are writing a function
626             which is doing some fiddling with internals and assumes
627             a piddle argument (e.g. for method calls). Using C
628             will ensure nothing breaks if passed with '2'.
629              
630             Note that C is not exported by default (see example
631             below for usage).
632              
633             =for example
634              
635             use PDLA::Core ':Internal'; # use the internal routines of
636             # the Core module
637              
638             $a = topdl 43; # $a is piddle with value '43'
639             $b = topdl $piddle; # fall through
640             $a = topdl (1,2,3,4); # Convert 1D array
641              
642             =head2 PDLA::get_datatype
643              
644             =for ref
645              
646             Internal: Return the numeric value identifying the piddle datatype
647              
648             =for usage
649              
650             $x = $piddle->get_datatype;
651              
652             Mainly used for internal routines.
653              
654             NOTE: get_datatype returns 'just a number' not any special
655             type object, unlike L.
656              
657             =head2 howbig
658              
659             =for ref
660              
661             Returns the sizeof a piddle datatype in bytes.
662              
663             Note that C is not exported by default (see example
664             below for usage).
665              
666             =for usage
667              
668             use PDLA::Core ':Internal'; # use the internal routines of
669             # the Core module
670              
671             $size = howbig($piddle->get_datatype);
672              
673             Mainly used for internal routines.
674              
675             NOTE: NOT a method! This is because get_datatype returns
676             'just a number' not any special object.
677              
678             =for example
679              
680             pdl> p howbig(ushort([1..10])->get_datatype)
681             2
682              
683              
684             =head2 get_dataref
685              
686             =for ref
687              
688             Return the internal data for a piddle, as a perl SCALAR ref.
689              
690             Most piddles hold their internal data in a packed perl string, to take
691             advantage of perl's memory management. This gives you direct access
692             to the string, which is handy when you need to manipulate the binary
693             data directly (e.g. for file I/O). If you modify the string, you'll
694             need to call L afterward, to make sure that the
695             piddle points to the new location of the underlying perl variable.
696              
697             Calling C automatically physicalizes your piddle (see
698             L). You definitely
699             don't want to do anything to the SV to truncate or deallocate the
700             string, unless you correspondingly call L to make the
701             PDLA match its new data dimension.
702              
703             You definitely don't want to use get_dataref unless you know what you
704             are doing (or are trying to find out): you can end up scrozzling
705             memory if you shrink or eliminate the string representation of the
706             variable. Here be dragons.
707              
708             =head2 upd_data
709              
710             =for ref
711              
712             Update the data pointer in a piddle to match its perl SV.
713              
714             This is useful if you've been monkeying with the packed string
715             representation of the PDLA, which you probably shouldn't be doing
716             anyway. (see L.)
717              
718             =cut
719              
720 0     0   0 sub topdl {PDLA->topdl(@_)}
721              
722             ####################### Overloaded operators #######################
723              
724             # This is to used warn if an operand is non-numeric or non-PDLA.
725             sub warn_non_numeric_op_wrapper {
726 117     117   297 my ($cb, $op_name) = @_;
727             return sub {
728 0     0     my ($op1, $op2) = @_;
729 0 0 0       unless( Scalar::Util::looks_like_number($op2)
      0        
730             || ( Scalar::Util::blessed($op2) && $op2->isa('PDLA') )
731             ) {
732 0           warn "'$op2' is not numeric nor a PDLA in operator $op_name";
733             };
734 0           $cb->(@_);
735             }
736 117         5608 }
737              
738             { package PDLA;
739             # use UNIVERSAL 'isa'; # need that later in info function
740 117     117   778 use Carp;
  117         199  
  117         147534  
741              
742             use overload (
743             "+" => \&PDLA::plus, # in1, in2
744             "*" => \&PDLA::mult, # in1, in2
745             "-" => \&PDLA::minus, # in1, in2, swap if true
746             "/" => \&PDLA::divide, # in1, in2, swap if true
747              
748 0     0   0 "+=" => sub { PDLA::plus ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
749 0     0   0 "*=" => sub { PDLA::mult ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
750 0     0   0 "-=" => sub { PDLA::minus ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
751 0     0   0 "/=" => sub { PDLA::divide ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
752              
753             ">" => \&PDLA::gt, # in1, in2, swap if true
754             "<" => \&PDLA::lt, # in1, in2, swap if true
755             "<=" => \&PDLA::le, # in1, in2, swap if true
756             ">=" => \&PDLA::ge, # in1, in2, swap if true
757             "==" => \&PDLA::eq, # in1, in2
758             "eq" => PDLA::Core::warn_non_numeric_op_wrapper(\&PDLA::eq, 'eq'),
759             # in1, in2
760             "!=" => \&PDLA::ne, # in1, in2
761              
762             "<<" => \&PDLA::shiftleft, # in1, in2, swap if true
763             ">>" => \&PDLA::shiftright, # in1, in2, swap if true
764             "|" => \&PDLA::or2, # in1, in2
765             "&" => \&PDLA::and2, # in1, in2
766             "^" => \&PDLA::xor, # in1, in2
767              
768 0     0   0 "<<=" => sub { PDLA::shiftleft ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
769 0     0   0 ">>=" => sub { PDLA::shiftright($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
770 0     0   0 "|=" => sub { PDLA::or2 ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
771 0     0   0 "&=" => sub { PDLA::and2 ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
772 0     0   0 "^=" => sub { PDLA::xor ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
773 0     0   0 "**=" => sub { PDLA::power ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
774 0     0   0 "%=" => sub { PDLA::modulo ($_[0], $_[1], $_[0], 0); $_[0]; }, # in1, in2, out, swap if true
  0         0  
775              
776 0     0   0 "sqrt" => sub { PDLA::sqrt ($_[0]); },
777 0     0   0 "abs" => sub { PDLA::abs ($_[0]); },
778 0     0   0 "sin" => sub { PDLA::sin ($_[0]); },
779 0     0   0 "cos" => sub { PDLA::cos ($_[0]); },
780              
781 0     0   0 "!" => sub { PDLA::not ($_[0]); },
782 0     0   0 "~" => sub { PDLA::bitnot ($_[0]); },
783              
784 0     0   0 "log" => sub { PDLA::log ($_[0]); },
785 0     0   0 "exp" => sub { PDLA::exp ($_[0]); },
786              
787             "**" => \&PDLA::power, # in1, in2, swap if true
788              
789             "atan2" => \&PDLA::atan2, # in1, in2, swap if true
790             "%" => \&PDLA::modulo, # in1, in2, swap if true
791              
792             "<=>" => \&PDLA::spaceship, # in1, in2, swap if true
793              
794 0     0   0 "=" => sub {$_[0]}, # Don't deep copy, just copy reference
795              
796             ".=" => sub {
797 0     0   0 my @args = reverse &PDLA::Core::rswap;
798 0         0 PDLA::Ops::assgn(@args);
799 0         0 return $args[1];
800             },
801              
802 0     0   0 'x' => sub{my $foo = $_[0]->null();
803 0         0 PDLA::Primitive::matmult(@_[0,1],$foo); $foo;},
  0         0  
804              
805 0 0   0   0 'bool' => sub { return 0 if $_[0]->isnull;
806 0 0       0 croak("multielement piddle in conditional expression")
807             unless $_[0]->nelem == 1;
808 0         0 $_[0]->clump(-1)->at(0); },
809 117     117   1036 "\"\"" => \&PDLA::Core::string );
  117         204  
  117         2547  
810             }
811              
812 0 0   0     sub rswap { if($_[2]) { return @_[1,0]; } else { return @_[0,1]; } }
  0            
  0            
813              
814             ##################### Data type/conversion stuff ########################
815              
816              
817             # XXX Optimize!
818              
819             sub PDLA::dims { # Return dimensions as @list
820 0     0 0   my $pdl = PDLA->topdl (shift);
821 0           my @dims = ();
822 0           for(0..$pdl->getndims()-1) {push @dims,($pdl->getdim($_))}
  0            
823 0           return @dims;
824             }
825              
826             sub PDLA::shape { # Return dimensions as a pdl
827 0     0 0   my $pdl = PDLA->topdl (shift);
828 0           my @dims = ();
829 0           for(0..$pdl->getndims()-1) {push @dims,($pdl->getdim($_))}
  0            
830 0           return pdl(\@dims);
831             }
832              
833             sub PDLA::howbig {
834 0     0 0   my $t = shift;
835 0 0         if("PDLA::Type" eq ref $t) {$t = $t->[0]}
  0            
836 0           PDLA::howbig_c($t);
837             }
838              
839             =head2 PDLA::threadids
840              
841             =for ref
842              
843             Returns the piddle thread IDs as a perl list
844              
845             Note that C is not exported by default (see example
846             below for usage).
847              
848             =for usage
849              
850             use PDLA::Core ':Internal'; # use the internal routines of
851             # the Core module
852              
853             @ids = threadids $piddle;
854              
855             =cut
856              
857             sub PDLA::threadids { # Return dimensions as @list
858 0     0 0   my $pdl = PDLA->topdl (shift);
859 0           my @dims = ();
860 0           for(0..$pdl->getnthreadids()) {push @dims,($pdl->getthreadid($_))}
  0            
861 0           return @dims;
862             }
863              
864             ################# Creation/copying functions #######################
865              
866              
867 0     0 0   sub PDLA::pdl { my $x = shift; return $x->new(@_) }
  0            
868              
869             =head2 doflow
870              
871             =for ref
872              
873             Turn on/off dataflow
874              
875             =for usage
876              
877             $x->doflow; doflow($x);
878              
879             =cut
880              
881             sub PDLA::doflow {
882 0     0 0   my $this = shift;
883 0           $this->set_dataflow_f(1);
884 0           $this->set_dataflow_b(1);
885             }
886              
887             =head2 flows
888              
889             =for ref
890              
891             Whether or not a piddle is indulging in dataflow
892              
893             =for usage
894              
895             something if $x->flows; $hmm = flows($x);
896              
897             =cut
898              
899             sub PDLA::flows {
900 0     0 0   my $this = shift;
901 0   0       return ($this->fflows || $this->bflows);
902             }
903              
904             =head2 PDLA::new
905              
906             =for ref
907              
908             new piddle constructor method
909              
910             =for usage
911              
912             $x = PDLA->new(SCALAR|ARRAY|ARRAY REF|STRING);
913              
914             =for example
915              
916             $x = PDLA->new(42); # new from a Perl scalar
917             $x = new PDLA 42; # ditto
918             $y = PDLA->new(@list_of_vals); # new from Perl list
919             $y = new PDLA @list_of_vals; # ditto
920             $z = PDLA->new(\@list_of_vals); # new from Perl list reference
921             $w = PDLA->new("[1 2 3]"); # new from Perl string, using
922             # Matlab constructor syntax
923              
924             Constructs piddle from perl numbers and lists
925             and strings with Matlab/Octave style constructor
926             syntax.
927              
928             The string input is fairly versatile though not
929             performance optimized. The goal is to make it
930             easy to copy and paste code from PDLA output and
931             to offer a familiar Matlab syntax for piddle
932             construction. As of May, 2010, it is a new
933             feature, so feel free to report bugs or suggest
934             new features. See documentation for L for
935             more examples of usage.
936              
937              
938             =cut
939              
940 117     117   124319 use Scalar::Util; # for looks_like_number test
  117         1211  
  117         11175  
941 117     117   666 use Carp 'carp'; # for carping (warnings in caller's context)
  117         193  
  117         24909  
942              
943             # This is the code that handles string arguments. It has now gotten quite large,
944             # so here's the basic explanation. I want to allow expressions like 2, 1e3, +4,
945             # bad, nan, inf, and more. Checking this can get tricky. This croaks when it
946             # finds:
947             # 1) strings of e or E that are longer than 1 character long (like eeee)
948             # 2) non-supported characters or strings
949             # 3) expressions that are syntactically erroneous, like '1 2 3 ]', which has an
950             # extra bracket
951             # 4) use of inf when the data type does not support inf (i.e. the integers)
952              
953             sub PDLA::Core::new_pdl_from_string {
954 0     0     my ($new, $original_value, $this, $type) = @_;
955 0           my $value = $original_value;
956              
957             # Check for input that would generate empty piddles as output:
958 0           my @types = PDLA::Types::types;
959 0 0 0       return zeroes($types[$type], 1)->where(zeroes(1) < 0)
960             if ($value eq '' or $value eq '[]');
961              
962             # I check for invalid characters later, but arbitrary strings of e will
963             # pass that check, so I'll check for that here, first.
964             # croak("PDLA::Core::new_pdl_from_string: I found consecutive copies of e but\n"
965             # . " I'm not sure what you mean. You gave me $original_value")
966             # if ($value =~ /ee/i);
967 0 0 0       croak("PDLA::Core::new_pdl_from_string: found 'e' as part of a larger word in $original_value")
968 117     117   122467 if $value =~ /e\p{IsAlpha}/ or $value =~ /\p{IsAlpha}e/;
  117         1307  
  117         4172  
969              
970             # Only a few characters are allowed in the expression, but we want to allow
971             # expressions like 'inf' and 'bad'. As such, convert those values to internal
972             # representations that will pass the invalid-character check. We'll replace
973             # them with Perl-evalute-able strings in a little bit. Here, I represent
974             # bad => EE
975             # nan => ee
976             # inf => Ee
977             # pi => eE
978             # --( Bad )--
979 0 0 0       croak("PDLA::Core::new_pdl_from_string: found 'bad' as part of a larger word in $original_value")
980             if $value =~ /bad\B/ or $value =~ /\Bbad/;
981 0           my ($has_bad) = ($value =~ s/\bbad\b/EE/gi);
982             # --( nan )--
983 0           my ($has_nan) = 0;
984 0 0 0       croak("PDLA::Core::new_pdl_from_string: found 'nan' as part of a larger word in $original_value")
985             if $value =~ /\Bnan/ or $value =~ /nan\B/;
986 0 0         $has_nan++ if ($value =~ s/\bnan\b/ee/gi);
987             # Strawberry Perl compatibility:
988 0 0         croak("PDLA::Core::new_pdl_from_string: found '1.#IND' as part of a larger word in $original_value")
989             if $value =~ /IND\B/i;
990 0 0         $has_nan++ if ($value =~ s/1\.\#IND/ee/gi);
991             # --( inf )--
992 0           my ($has_inf) = 0;
993             # Strawberry Perl compatibility:
994 0 0         croak("PDLA::Core::new_pdl_from_string: found '1.#INF' as part of a larger word in $original_value")
995             if $value =~ /INF\B/i;
996 0 0         $has_inf++ if ($value =~ s/1\.\#INF/Ee/gi);
997             # Other platforms:
998 0 0 0       croak("PDLA::Core::new_pdl_from_string: found 'inf' as part of a larger word in $original_value")
999             if $value =~ /inf\B/ or $value =~ /\Binf/;
1000 0 0         $has_inf++ if ($value =~ s/\binf\b/Ee/gi);
1001             # --( pi )--
1002 0 0 0       croak("PDLA::Core::new_pdl_from_string: found 'pi' as part of a larger word in $original_value")
1003             if $value =~ /pi\B/ or $value =~ /\Bpi/;
1004 0           $value =~ s/\bpi\b/eE/gi;
1005              
1006             # Some data types do not support nan and inf, so check for and warn or croak,
1007             # as appropriate:
1008 0 0 0       if ($has_nan and not $types[$type]->usenan) {
1009 0           carp("PDLA::Core::new_pdl_from_string: no nan for type $types[$type]; converting to bad value");
1010 0           $value =~ s/ee/EE/g;
1011 0           $has_bad += $has_nan;
1012 0           $has_nan = 0;
1013             }
1014 0 0 0       croak("PDLA::Core::new_pdl_from_string: type $types[$type] does not support inf")
1015             if ($has_inf and not $types[$type]->usenan);
1016              
1017             # Make the white-space uniform and see if any not-allowed characters are
1018             # present:
1019 0           $value =~ s/\s+/ /g;
1020 0 0         if (my ($disallowed) = ($value =~ /([^\[\]\+\-0-9;,.eE ]+)/)) {
1021 0           croak("PDLA::Core::new_pdl_from_string: found disallowed character(s) '$disallowed' in $original_value");
1022             }
1023              
1024             # Wrap the string in brackets [], so that the following works:
1025             # $a = new PDLA q[1 2 3];
1026             # We'll have to check for dimensions of size one after we've parsed
1027             # the string and built a PDLA from the resulting array.
1028 0           $value = '[' . $value . ']';
1029              
1030             # Make sure that each closing bracket followed by an opening bracket
1031             # has a comma in between them:
1032 0           $value =~ s/\]\s*\[/],[/g;
1033              
1034             # Semicolons indicate 'start a new row' and require special handling:
1035 0 0         if ($value =~ /;/) {
1036 0           $value =~ s/(\[[^\]]+;[^\]]+\])/[$1]/g;
1037 0           $value =~ s/;/],[/g;
1038             }
1039              
1040             # Remove ending decimal points and insert zeroes in front of starting
1041             # decimal points. This makes the white-space-to-comma replacement
1042             # in the next few lines much simpler.
1043 0           $value =~ s/(\d\.)(z|[^\d])/${1}0$2/g;
1044 0           $value =~ s/(\A|[^\d])\./${1}0./g;
1045              
1046             # Remove whitspace between signs and the numbers that follow them:
1047 0           $value =~ s/([+\-])\s+/$1/g;
1048              
1049             # # make unambiguous addition/subtraction (white-space on both sides
1050             # # of operator) by removing white-space from both sides
1051             # $value =~ s/([\dEe])\s+([+\-])\s+(?=[Ee\d])/$1$2/g;
1052              
1053             # Replace white-space separators with commas:
1054 0           $value =~ s/([.\deE])\s+(?=[+\-eE\d])/$1,/g;
1055              
1056             # Remove all other white space:
1057 0           $value =~ s/\s+//g;
1058              
1059             # Croak on operations with bad values. It might be nice to simply replace
1060             # these with bad values, but that is more difficult that I like, so I'm just
1061             # going to disallow that here:
1062 0 0 0       croak("PDLA::Core::new_pdl_from_string: Operations with bad values are not supported")
1063             if($value =~ /EE[+\-]/ or $value =~ /[+\-]EE/);
1064              
1065             # Check for things that will evaluate as functions and croak if found
1066 0 0         if (my ($disallowed) = ($value =~ /((\D+|\A)[eE]\d+)/)) {
1067 0           croak("PDLA::Core::new_pdl_from_string: syntax error, looks like an improper exponentiation: $disallowed\n"
1068             . "You originally gave me $original_value\n");
1069             }
1070              
1071             # Replace the place-holder strings with strings that will evaluate to their
1072             # correct numerical values when we run the eval:
1073 0           $value =~ s/\bEE\b/bad/g;
1074 0           my $bad = $types[$type]->badvalue;
1075 0           $value =~ s/\bee\b/nan/g;
1076 0           my $inf = -pdl(0)->log;
1077 0           $value =~ s/\bEe\b/inf/g;
1078 0           my $nnan = $inf - $inf;
1079 0           my $nan= $this->initialize();
1080 0           $nan->set_datatype($nnan->get_datatype);
1081 0           $nan->setdims([]);
1082              
1083             # pack("d*", "nan") will work here only on perls that numify the string "nan" to a NaN.
1084             # pack( "d*", (-1.0) ** 0.5 ) will hopefully work in more places, though it seems both
1085             # pack("d*", "nan") and pack( "d*", (-1.0) ** 0.5 ) fail on *old* MS Compilers (MSVC++ 6.0 and earlier).
1086             # sisyphus 4 Jan 2013.
1087 0           ${$nan->get_dataref} = pack( "d*", (-1.0) ** 0.5 );
  0            
1088              
1089 0           $nan->upd_data();
1090 0           $value =~ s/\beE\b/pi/g;
1091              
1092 0           my $val = eval{
1093             # Install the warnings handler:
1094 0           my $old_warn_handler = $SIG{__WARN__};
1095             local $SIG{__WARN__} = sub {
1096 0 0   0     if ($_[0] =~ /(Argument ".*" isn't numeric)/) {
    0          
1097             # Send the error through die. This is *always* get caught, so keep
1098             # it simple.
1099 0           die "Incorrectly formatted input: $1\n";
1100             }
1101             elsif ($old_warn_handler) {
1102 0           $old_warn_handler->(@_);
1103             }
1104             else {
1105 0           warn @_;
1106             }
1107 0           };
1108              
1109             # Let's see if we can parse it as an array-of-arrays:
1110 0           local $_ = $value;
1111 0           return PDLA::Core::parse_basic_string ($inf, $nan, $nnan, $bad);
1112             };
1113              
1114             # Respect BADVAL_USENAN
1115 0           require PDLA::Config;
1116 0 0         $has_bad += $has_inf + $has_nan if $PDLA::Config{BADVAL_USENAN};
1117              
1118 0 0         if (ref $val eq 'ARRAY') {
1119 0           my $to_return = PDLA::Core::pdl_avref($val,$this,$type);
1120 0 0         if( $to_return->dim(-1) == 1 ) {
1121 0 0         if( $to_return->dims > 1 ) {
    0          
1122             # remove potentially spurious last dimension
1123 0           $to_return = $to_return->mv(-1,1)->clump(2);
1124             } elsif( $to_return->dims == 1 ) {
1125             # fix scalar values
1126 0           $to_return->setdims([]);
1127             }
1128             }
1129             # Mark bad if appropriate
1130 0           $to_return->badflag($has_bad > 0);
1131 0           return $to_return;
1132             }
1133             else {
1134 0           my @message = ("PDLA::Core::new_pdl_from_string: string input='$original_value', string output='$value'" );
1135 0 0         if ($@) {
1136 0           push @message, $@;
1137             } else {
1138 0           push @message, "Internal error: unexpected output type ->$val<- is not ARRAY ref";
1139             }
1140 0           croak join("\n ", @message);
1141             }
1142             }
1143              
1144             sub PDLA::Core::parse_basic_string {
1145             # Assumes $_ holds the string of interest, and modifies that value
1146             # in-place.
1147              
1148 117     117   3190044 use warnings;
  117         1164  
  117         390231  
1149              
1150             # Takes a string with proper bracketing, etc, and returns an array-of-arrays
1151             # filled with numbers, suitable for use with pdl_avref. It uses recursive
1152             # descent to handle the nested nature of the data. The string should have
1153             # no whitespace and should be something that would evaluate into a Perl
1154             # array-of-arrays (except that strings like 'inf', etc, are allowed).
1155              
1156 0     0     my ($inf, $nan, $nnan, $bad) = @_;
1157              
1158             # First character should be a bracket:
1159 0 0         die "Internal error: input string -->$_<-- did not start with an opening bracket\n"
1160             unless s/^\[//;
1161              
1162 0           my @to_return;
1163             # Loop until we run into our closing bracket:
1164 0           my $sign = 1;
1165 0           my $expects_number = 0;
1166 0           SYMBOL: until (s/^\]//) {
1167             # If we have a bracket, then go recursive:
1168 0 0 0       if (/^\[/) {
    0 0        
    0          
    0          
    0          
    0          
    0          
    0          
    0          
1169 0 0         die "Expected a number but found a bracket at ... ", substr ($_, 0, 10), "...\n"
1170             if $expects_number;
1171 0           push @to_return, PDLA::Core::parse_basic_string(@_);
1172 0           next SYMBOL;
1173             }
1174             elsif (s/^\+//) {
1175 0 0         die "Expected number but found a plus sign at ... ", substr ($_, 0, 10), "...\n"
1176             if $expects_number;
1177 0           $expects_number = 1;
1178 0           redo SYMBOL;
1179             }
1180             elsif (s/^\-//) {
1181 0 0         die "Expected number but found a minus sign at ... ", substr ($_, 0, 10), "...\n"
1182             if $expects_number;
1183 0           $sign = -1;
1184 0           $expects_number = 1;
1185 0           redo SYMBOL;
1186             }
1187             elsif (s/^bad//i) {
1188 0           push @to_return, $bad;
1189             }
1190             elsif (s/^inf//i or s/1\.\#INF//i) {
1191 0           push @to_return, $sign * $inf;
1192             }
1193             elsif (s/^nan//i or s/^1\.\#IND//i) {
1194 0 0         if ($sign == -1) {
1195 0           push @to_return, $nnan;
1196             } else {
1197 0           push @to_return, $nan;
1198             }
1199             }
1200             elsif (s/^pi//i) {
1201 0           push @to_return, $sign * 4 * atan2(1, 1);
1202             }
1203             elsif (s/^e//i) {
1204 0           push @to_return, $sign * exp(1);
1205             }
1206             elsif (s/^([\d+\-e.]+)//i) {
1207             # Note that improper numbers are handled by the warning signal
1208             # handler
1209 0           push @to_return, $sign * $1;
1210             }
1211             else {
1212 0           die "Incorrectly formatted input at:\n ", substr ($_, 0, 10), "...\n";
1213             }
1214             }
1215             # Strip off any commas
1216             continue {
1217 0           $sign = 1;
1218 0           $expects_number = 0;
1219 0           s/^,//;
1220             }
1221              
1222 0           return \@to_return;
1223             }
1224              
1225             sub PDLA::new {
1226             # print "in PDLA::new\n";
1227 0     0 0   my $this = shift;
1228 0 0         return $this->copy if ref($this);
1229 0 0         my $type = ref($_[0]) eq 'PDLA::Type' ? ${shift @_}[0] : $PDLA_D;
  0            
1230 0 0         my $value = (@_ >1 ? [@_] : shift); # ref thyself
1231              
1232 0 0         unless(defined $value) {
1233 0 0 0       if($PDLA::debug && $PDLA::undefval) {
1234 0           print STDERR "Warning: PDLA::new converted undef to $PDLA::undefval ($PDLA::undefval)\n";
1235             }
1236 0           $value = $PDLA::undefval+0
1237             }
1238              
1239 0 0         return pdl_avref($value,$this,$type) if ref($value) eq "ARRAY";
1240 0           my $new = $this->initialize();
1241 0           $new->set_datatype($type);
1242              
1243              
1244 0 0         if (ref(\$value) eq "SCALAR") {
    0          
1245             # The string processing is extremely slow. Benchmarks indicated that it
1246             # takes 10x longer to process a scalar number compared with normal Perl
1247             # conversion of a string to a number. So, only use the string processing
1248             # if the input looks like a real string, i.e. it doesn't look like a plain
1249             # number. Note that for our purposes, looks_like_number incorrectly
1250             # handles the strings 'inf' and 'nan' on Windows machines. We want to send
1251             # those to the string processing, so this checks for them in a way that
1252             # short-circuits the looks_like_number check.
1253 0 0 0       if (PDLA::Core::is_scalar_SvPOK($value)
      0        
1254             and ($value =~ /inf/i or $value =~ /nan/i
1255             or !Scalar::Util::looks_like_number($value))) {
1256             # new was passed a string argument that doesn't look like a number
1257             # so we can process as a Matlab-style data entry format.
1258 0           return PDLA::Core::new_pdl_from_string($new,$value,$this,$type);
1259             } else {
1260 0           $new->setdims([]);
1261 0           ${$new->get_dataref} = pack( $pack[$new->get_datatype], $value );
  0            
1262 0           $new->upd_data();
1263             }
1264             }
1265             elsif (blessed($value)) { # Object
1266 0           $new = $value->copy;
1267             }
1268             else {
1269 0           barf("Can not interpret argument $value of type ".ref($value) );
1270             }
1271 0           return $new;
1272             }
1273              
1274              
1275             =head2 copy
1276              
1277             =for ref
1278              
1279             Make a physical copy of a piddle
1280              
1281             =for usage
1282              
1283             $new = $old->copy;
1284              
1285             Since C<$new = $old> just makes a new reference, the
1286             C method is provided to allow real independent
1287             copies to be made.
1288              
1289             =cut
1290              
1291             # Inheritable copy method
1292             #
1293             # XXX Must be fixed
1294             # Inplace is handled by the op currently.
1295              
1296             sub PDLA::copy {
1297 0     0 0   my $value = shift;
1298 0 0         barf("Argument is an ".ref($value)." not an object") unless blessed($value);
1299 0           my $option = shift;
1300 0 0         $option = "" if !defined $option;
1301 0 0         if ($value->is_inplace) { # Copy protection
1302 0           $value->set_inplace(0);
1303 0           return $value;
1304             }
1305             # threadI(-1,[]) is just an identity vafftrans with threadId copying ;)
1306 0           my $new = $value->threadI(-1,[])->sever;
1307 0           return $new;
1308             }
1309              
1310             =head2 PDLA::hdr_copy
1311              
1312             =for ref
1313              
1314             Return an explicit copy of the header of a PDLA.
1315              
1316             hdr_copy is just a wrapper for the internal routine _hdr_copy, which
1317             takes the hash ref itself. That is the routine which is used to make
1318             copies of the header during normal operations if the hdrcpy() flag of
1319             a PDLA is set.
1320              
1321             General-purpose deep copies are expensive in perl, so some simple
1322             optimization happens:
1323              
1324             If the header is a tied array or a blessed hash ref with an associated
1325             method called C, then that ->copy method is called. Otherwise, all
1326             elements of the hash are explicitly copied. References are recursively
1327             deep copied.
1328              
1329             This routine seems to leak memory.
1330              
1331             =cut
1332              
1333             sub PDLA::hdr_copy {
1334 0     0 0   my $pdl = shift;
1335 0           my $hdr = $pdl->gethdr;
1336 0           return PDLA::_hdr_copy($hdr);
1337             }
1338              
1339             # Same as hdr_copy but takes a hash ref instead of a PDLA.
1340             sub PDLA::_hdr_copy {
1341 0     0     my $hdr = shift;
1342 0           my $tobj;
1343              
1344 0 0         print "called _hdr_copy\n" if($PDLA::debug);
1345              
1346 0 0         unless( (ref $hdr)=~m/HASH/ ) {
1347 0 0         print"returning undef\n" if($PDLA::debug);
1348 0           return undef ;
1349             }
1350              
1351 0 0         if($tobj = tied %$hdr) { #
    0          
1352 0 0         print "tied..."if($PDLA::debug);
1353 0 0         if(UNIVERSAL::can($tobj,"copy")) {
1354 0           my %rhdr;
1355 0           tie(%rhdr, ref $tobj, $tobj->copy);
1356 0 0         print "returning\n" if($PDLA::debug);
1357 0           return \%rhdr;
1358             }
1359              
1360             # Astro::FITS::Header is special for now -- no copy method yet
1361             # but it is recognized. Once it gets a copy method this will become
1362             # vestigial:
1363              
1364 0 0         if(UNIVERSAL::isa($tobj,"Astro::FITS::Header")) {
1365 0 0         print "Astro::FITS::Header..." if($PDLA::debug);
1366 0           my @cards = $tobj->cards;
1367 0           my %rhdr;
1368 0           tie(%rhdr,"Astro::FITS::Header", new Astro::FITS::Header(Cards=>\@cards));
1369 0 0         print "returning\n" if($PDLA::debug);
1370 0           return \%rhdr;
1371             }
1372             }
1373             elsif(UNIVERSAL::can($hdr,"copy")) {
1374 0 0         print "found a copy method\n" if($PDLA::debug);
1375 0           return $hdr->copy;
1376             }
1377              
1378             # We got here if it's an unrecognized tie or if it's a vanilla hash.
1379 0 0         print "Making a hash copy..." if($PDLA::debug);
1380              
1381 0           return PDLA::_deep_hdr_copy($hdr);
1382              
1383             }
1384              
1385             #
1386             # Sleazy deep-copier that gets most cases
1387             # --CED 14-April-2003
1388             #
1389              
1390             sub PDLA::_deep_hdr_copy {
1391 0     0     my $val = shift;
1392              
1393 0 0         if(ref $val eq 'HASH') {
1394 0           my (%a,$key);
1395 0           for $key(keys %$val) {
1396 0           my $value = $val->{$key};
1397 0 0         $a{$key} = (ref $value) ? PDLA::_deep_hdr_copy($value) : $value;
1398             }
1399 0           return \%a;
1400             }
1401              
1402 0 0         if(ref $val eq 'ARRAY') {
1403 0           my (@a,$z);
1404 0           for $z(@$val) {
1405 0 0         push(@a,(ref $z) ? PDLA::_deep_hdr_copy($z) : $z);
1406             }
1407 0           return \@a;
1408             }
1409              
1410 0 0         if(ref $val eq 'SCALAR') {
1411 0           my $a = $$val;
1412 0           return \$a;
1413             }
1414              
1415 0 0         if(ref $val eq 'REF') {
1416 0           my $a = PDLA::_deep_hdr_copy($$val);
1417 0           return \$a;
1418             }
1419              
1420             # Special case for PDLAs avoids potential nasty header recursion...
1421 0 0         if(UNIVERSAL::isa($val,'PDLA')) {
1422 0           my $h;
1423 0 0         $val->hdrcpy(0) if($h = $val->hdrcpy); # assignment
1424 0           my $out = $val->copy;
1425 0 0         $val->hdrcpy($h) if($h);
1426 0           return $out;
1427             }
1428              
1429 0 0         if(UNIVERSAL::can($val,'copy')) {
1430 0           return $val->copy;
1431             }
1432              
1433 0           $val;
1434             }
1435              
1436              
1437             =head2 PDLA::unwind
1438              
1439             =for ref
1440              
1441             Return a piddle which is the same as the argument except
1442             that all threadids have been removed.
1443              
1444             =for usage
1445              
1446             $y = $x->unwind;
1447              
1448             =head2 PDLA::make_physical
1449              
1450             =for ref
1451              
1452             Make sure the data portion of a piddle can be accessed from XS code.
1453              
1454             =for example
1455              
1456             $a->make_physical;
1457             $a->call_my_xs_method;
1458              
1459             Ensures that a piddle gets its own allocated copy of data. This obviously
1460             implies that there are certain piddles which do not have their own data.
1461             These are so called I piddles that make use of the I
1462             optimisation (see L).
1463             They do not have their own copy of
1464             data but instead store only access information to some (or all) of another
1465             piddle's data.
1466              
1467             Note: this function should not be used unless absolutely neccessary
1468             since otherwise memory requirements might be severly increased. Instead
1469             of writing your own XS code with the need to call C you
1470             might want to consider using the PDLA preprocessor
1471             (see L)
1472             which can be used to transparently access virtual piddles without the
1473             need to physicalise them (though there are exceptions).
1474              
1475             =cut
1476              
1477             sub PDLA::unwind {
1478 0     0 0   my $value = shift;
1479 0           my $foo = $value->null();
1480 0           $foo .= $value->unthread();
1481 0           return $foo;
1482             }
1483              
1484             =head2 dummy
1485              
1486             =for ref
1487              
1488             Insert a 'dummy dimension' of given length (defaults to 1)
1489              
1490             No relation to the 'Dungeon Dimensions' in Discworld!
1491              
1492             Negative positions specify relative to last dimension,
1493             i.e. C appends one dimension at end,
1494             C inserts a dummy dimension in front of the
1495             last dim, etc.
1496              
1497             If you specify a dimension position larger than the existing
1498             dimension list of your PDLA, the PDLA gets automagically padded with extra
1499             dummy dimensions so that you get the dim you asked for, in the slot you
1500             asked for. This could cause you trouble if, for example,
1501             you ask for $a->dummy(5000,1) because $a will get 5,000 dimensions,
1502             each of rank 1.
1503              
1504             Because padding at the beginning of the dimension list moves existing
1505             dimensions from slot to slot, it's considered unsafe, so automagic
1506             padding doesn't work for large negative indices -- only for large
1507             positive indices.
1508              
1509             =for usage
1510              
1511             $y = $x->dummy($position[,$dimsize]);
1512              
1513             =for example
1514              
1515             pdl> p sequence(3)->dummy(0,3)
1516             [
1517             [0 0 0]
1518             [1 1 1]
1519             [2 2 2]
1520             ]
1521              
1522             pdl> p sequence(3)->dummy(3,2)
1523             [
1524             [
1525             [0 1 2]
1526             ]
1527             [
1528             [0 1 2]
1529             ]
1530             ]
1531              
1532             pdl> p sequence(3)->dummy(-3,2)
1533             Runtime error: PDLA: For safety, < -(dims+1) forbidden in dummy. min=-2, pos=-3
1534              
1535             =cut
1536              
1537             sub PDLA::dummy($$;$) {
1538 0     0 0   my ($pdl,$dim,$size) = @_;
1539 0 0         barf("Missing position argument to dummy()") unless defined $dim; # required argument
1540 0 0         $dim = $pdl->getndims+1+$dim if $dim < 0;
1541 0 0         $size = defined($size) ? (1 * $size) : 1; # make $size a number (sf feature # 3479009)
1542              
1543 0 0         barf("For safety, < -(dims+1) forbidden in dummy. min="
1544             . -($pdl->getndims+1).", pos=". ($dim-1-$pdl->getndims) ) if($dim<0);
1545              
1546             # Avoid negative repeat count warning that came with 5.21 and later.
1547 0           my $dim_diff = $dim - $pdl->getndims;
1548 0 0         my($s) = ',' x ( $dim_diff > 0 ? $pdl->getndims : $dim );
1549 0 0         $s .= '*1,' x ( $dim_diff > 0 ? $dim_diff : 0 );
1550 0           $s .= "*$size";
1551              
1552 0           $pdl->slice($s);
1553             }
1554              
1555              
1556             ## Cheesy, slow way
1557             # while ($dim>$pdl->getndims){
1558             # print STDERR "."; flush STDERR;
1559             # $pdl = $pdl->dummy($pdl->getndims,1);
1560             # }
1561             #
1562             # barf ("too high/low dimension in call to dummy, allowed min/max=0/"
1563             # . $_[0]->getndims)
1564             # if $dim>$pdl->getndims || $dim < 0;
1565             #
1566             # $_[2] = 1 if ($#_ < 2);
1567             # $pdl->slice((','x$dim)."*$_[2]");
1568              
1569             =head2 clump
1570              
1571             =for ref
1572              
1573             "clumps" several dimensions into one large dimension
1574              
1575             If called with one argument C<$n> clumps the first C<$n>
1576             dimensions into one. For example, if C<$a> has dimensions
1577             C<(5,3,4)> then after
1578              
1579             =for example
1580              
1581             $b = $a->clump(2); # Clump 2 first dimensions
1582              
1583             the variable C<$b> will have dimensions C<(15,4)>
1584             and the element C<$b-Eat(7,3)> refers to the element
1585             C<$a-Eat(1,2,3)>.
1586              
1587             Use C to flatten a piddle. The method L
1588             is provided as a convenient alias.
1589              
1590             Clumping with a negative dimension in general leaves that many
1591             dimensions behind -- e.g. clump(-2) clumps all of the first few
1592             dimensions into a single one, leaving a 2-D piddle.
1593              
1594             If C is called with an index list with more than one element
1595             it is treated as a list of dimensions that should be clumped together
1596             into one. The resulting
1597             clumped dim is placed at the position of the lowest index in the list.
1598             This convention ensures that C does the expected thing in
1599             the usual cases. The following example demonstrates typical usage:
1600              
1601             $a = sequence 2,3,3,3,5; # 5D piddle
1602             $c = $a->clump(1..3); # clump all the dims 1 to 3 into one
1603             print $c->info; # resulting 3D piddle has clumped dim at pos 1
1604             PDLA: Double D [2,27,5]
1605              
1606             =cut
1607              
1608             sub PDLA::clump {
1609 0     0 0   my $ndims = $_[0]->getndims;
1610 0 0         if ($#_ < 2) {
1611 0 0         return &PDLA::_clump_int($_[0],$_[1]) # Truncate clumping to actual dims
1612             if $_[1] > $ndims;
1613 0           return &PDLA::_clump_int(@_);
1614             } else {
1615 0           my ($this,@dims) = @_;
1616 0           my $targd = $ndims-1;
1617 0           my @dimmark = (0..$ndims-1);
1618 0 0         barf "too many dimensions" if @dims > $ndims;
1619 0           for my $dim (@dims) {
1620 0 0         barf "dimension index $dim larger than greatest dimension"
1621             if $dim > $ndims-1 ;
1622 0 0         $targd = $dim if $targd > $dim;
1623 0 0         barf "duplicate dimension $dim" if $dimmark[$dim]++ > $dim;
1624             }
1625 0           my $clumped = $this->thread(@dims)->unthread(0)->clump(scalar @dims);
1626 0 0         $clumped = $clumped->mv(0,$targd) if $targd > 0;
1627 0           return $clumped;
1628             }
1629             }
1630              
1631             =head2 thread_define
1632              
1633             =for ref
1634              
1635             define functions that support threading at the perl level
1636              
1637             =for example
1638              
1639             thread_define 'tline(a(n);b(n))', over {
1640             line $_[0], $_[1]; # make line compliant with threading
1641             };
1642              
1643              
1644             C provides some support for threading (see
1645             L) at the perl level. It allows you to do things for
1646             which you normally would have resorted to PDLA::PP (see L);
1647             however, it is most useful to wrap existing perl functions so that the
1648             new routine supports PDLA threading.
1649              
1650             C is used to define new I
1651             functions. Its first argument is a symbolic repesentation of the new
1652             function to be defined. The string is composed of the name of the new
1653             function followed by its signature (see L and L)
1654             in parentheses. The second argument is a subroutine that will be
1655             called with the slices of the actual runtime arguments as specified by
1656             its signature. Correct dimension sizes and minimal number of
1657             dimensions for all arguments will be checked (assuming the rules of
1658             PDLA threading, see L).
1659              
1660             The actual work is done by the C class which parses the signature
1661             string, does runtime dimension checks and the routine C that
1662             generates the loop over all appropriate slices of pdl arguments and creates
1663             pdls as needed.
1664              
1665             Similar to C and its C option it is possible to
1666             define the new function so that it accepts normal perl args as well as
1667             piddles. You do this by using the C parameter in the
1668             signature. The number of C specified will be passed
1669             unaltered into the subroutine given as the second argument of
1670             C. Let's illustrate this with an example:
1671              
1672             PDLA::thread_define 'triangles(inda();indb();indc()), NOtherPars => 2',
1673             PDLA::over {
1674             ${$_[3]} .= $_[4].join(',',map {$_->at} @_[0..2]).",-1,\n";
1675             };
1676              
1677             This defines a function C that takes 3 piddles as input
1678             plus 2 arguments which are passed into the routine unaltered. This routine
1679             is used to collect lists of indices into a perl scalar that is passed by
1680             reference. Each line is preceded by a prefix passed as C<$_[4]>. Here is
1681             typical usage:
1682              
1683             $txt = '';
1684             triangles(pdl(1,2,3),pdl(1),pdl(0),\$txt," "x10);
1685             print $txt;
1686              
1687             resulting in the following output
1688              
1689             1,1,0,-1,
1690             2,1,0,-1,
1691             3,1,0,-1,
1692              
1693             which is used in
1694             L
1695             to generate VRML output.
1696              
1697             Currently, this is probably not much more than a POP (proof of principle)
1698             but is hoped to be useful enough for some real life work.
1699              
1700             Check L for the format of the signature. Currently, the
1701             C<[t]> qualifier and all type qualifiers are ignored.
1702              
1703             =cut
1704              
1705 0     0 0   sub PDLA::over (&) { $_[0] }
1706             sub PDLA::thread_define ($$) {
1707 0     0 0   require PDLA::PP::Signature;
1708 0           my ($str,$sub) = @_;
1709 0           my $others = 0;
1710 0 0         if ($str =~ s/[,]*\s*NOtherPars\s*=>\s*([0-9]+)\s*[,]*//) {$others = $1}
  0            
1711 0 0         barf "invalid string $str" unless $str =~ /\s*([^(]+)\((.+)\)\s*$/x;
1712 0           my ($name,$sigstr) = ($1,$2);
1713 0 0         print "defining '$name' with signature '$sigstr' and $others extra args\n"
1714             if $PDLA::debug;
1715 0           my $sig = new PDLA::PP::Signature($sigstr);
1716 0           my $args = @{$sig->names}; # number of piddle arguments
  0            
1717 0 0         barf "no piddle args" if $args == 0;
1718 0           $args--;
1719             # TODO: $sig->dimcheck(@_) + proper creating generation
1720 0           my $def = "\@_[0..$args] = map {PDLA::Core::topdl(\$_)} \@_[0..$args];\n".
1721             '$sig->checkdims(@_);
1722             PDLA::threadover($others,@_,$sig->realdims,$sig->creating,$sub)';
1723 0           my $package = caller;
1724 0           local $^W = 0; # supress the 'not shared' warnings
1725 0 0         print "defining...\nsub $name { $def }\n" if $PDLA::debug;
1726 0           eval ("package $package; sub $name { $def }");
1727 0 0         barf "error defining $name: $@\n" if $@;
1728             }
1729              
1730             =head2 PDLA::thread
1731              
1732             =for ref
1733              
1734             Use explicit threading over specified dimensions (see also L)
1735              
1736             =for usage
1737              
1738             $b = $a->thread($dim,[$dim1,...])
1739              
1740             =for example
1741              
1742             $a = zeroes 3,4,5;
1743             $b = $a->thread(2,0);
1744              
1745             Same as L, i.e. uses thread id 1.
1746              
1747             =cut
1748              
1749             sub PDLA::thread {
1750 0     0 0   my $var = shift;
1751 0           $var->threadI(1,\@_);
1752             }
1753              
1754             =head2 diagonal
1755              
1756             =for ref
1757              
1758             Returns the multidimensional diagonal over the specified dimensions.
1759              
1760             =for usage
1761              
1762             $d = $x->diagonal(dim1, dim2,...)
1763              
1764             =for example
1765              
1766             pdl> $a = zeroes(3,3,3);
1767             pdl> ($b = $a->diagonal(0,1))++;
1768             pdl> p $a
1769             [
1770             [
1771             [1 0 0]
1772             [0 1 0]
1773             [0 0 1]
1774             ]
1775             [
1776             [1 0 0]
1777             [0 1 0]
1778             [0 0 1]
1779             ]
1780             [
1781             [1 0 0]
1782             [0 1 0]
1783             [0 0 1]
1784             ]
1785             ]
1786              
1787             =cut
1788              
1789             sub PDLA::diagonal {
1790 0     0 0   my $var = shift;
1791 0           $var->diagonalI(\@_);
1792             }
1793              
1794             =head2 PDLA::thread1
1795              
1796             =for ref
1797              
1798             Explicit threading over specified dims using thread id 1.
1799              
1800             =for usage
1801              
1802             $xx = $x->thread1(3,1)
1803              
1804             =for example
1805              
1806             Wibble
1807              
1808             Convenience function interfacing to
1809             L.
1810              
1811             =cut
1812              
1813             sub PDLA::thread1 {
1814 0     0 0   my $var = shift;
1815 0           $var->threadI(1,\@_);
1816             }
1817              
1818             =head2 PDLA::thread2
1819              
1820             =for ref
1821              
1822             Explicit threading over specified dims using thread id 2.
1823              
1824             =for usage
1825              
1826             $xx = $x->thread2(3,1)
1827              
1828             =for example
1829              
1830             Wibble
1831              
1832             Convenience function interfacing to
1833             L.
1834              
1835             =cut
1836              
1837             sub PDLA::thread2 {
1838 0     0 0   my $var = shift;
1839 0           $var->threadI(2,\@_);
1840             }
1841              
1842             =head2 PDLA::thread3
1843              
1844             =for ref
1845              
1846             Explicit threading over specified dims using thread id 3.
1847              
1848             =for usage
1849              
1850             $xx = $x->thread3(3,1)
1851              
1852             =for example
1853              
1854             Wibble
1855              
1856             Convenience function interfacing to
1857             L.
1858              
1859             =cut
1860              
1861             sub PDLA::thread3 {
1862 0     0 0   my $var = shift;
1863 0           $var->threadI(3,\@_);
1864             }
1865              
1866             my %info = (
1867             D => {
1868             Name => 'Dimension',
1869             Sub => \&PDLA::Core::dimstr,
1870             },
1871             T => {
1872             Name => 'Type',
1873             Sub => sub { return $_[0]->type->shortctype; },
1874             },
1875             S => {
1876             Name => 'State',
1877             Sub => sub { my $state = '';
1878             $state .= 'P' if $_[0]->allocated;
1879             $state .= 'V' if $_[0]->vaffine &&
1880             !$_[0]->allocated; # apparently can be both?
1881             $state .= '-' if $state eq ''; # lazy eval
1882             $state .= 'C' if $_[0]->anychgd;
1883             $state .= 'B' if $_[0]->badflag;
1884             $state;
1885             },
1886             },
1887             F => {
1888             Name => 'Flow',
1889             Sub => sub { my $flows = '';
1890             $flows = ($_[0]->bflows ? 'b':'') .
1891             '~' . ($_[0]->fflows ? 'f':'')
1892             if ($_[0]->flows);
1893             $flows;
1894             },
1895             },
1896             M => {
1897             Name => 'Mem',
1898             Sub => sub { my ($size,$unit) = ($_[0]->allocated ?
1899             $_[0]->nelem*
1900             PDLA::howbig($_[0]->get_datatype)/1024 : 0, 'KB');
1901             if ($size > 0.01*1024) { $size /= 1024;
1902             $unit = 'MB' };
1903             return sprintf "%6.2f%s",$size,$unit;
1904             },
1905             },
1906             C => {
1907             Name => 'Class',
1908             Sub => sub { ref $_[0] }
1909             },
1910             A => {
1911             Name => 'Address',
1912 117     117   1105 Sub => sub { use Config;
  117         1992  
  117         412982  
1913             my $ivdformat = $Config{ivdformat};
1914             $ivdformat =~ s/"//g;
1915             sprintf "%$ivdformat", $_[0]->address }
1916             },
1917             );
1918              
1919             my $allowed = join '',keys %info;
1920              
1921             # print the dimension information about a pdl in some appropriate form
1922             sub dimstr {
1923 0     0     my $this = shift;
1924              
1925 0           my @dims = $this->dims;
1926 0           my @ids = $this->threadids;
1927 0           my ($nids,$i) = ($#ids - 1,0);
1928 0           my $dstr = 'D ['. join(',',@dims[0..($ids[0]-1)]) .']';
1929 0 0         if ($nids > 0) {
1930 0           for $i (1..$nids) {
1931 0           $dstr .= " T$i [". join(',',@dims[$ids[$i]..$ids[$i+1]-1]) .']';
1932             }
1933             }
1934 0           return $dstr;
1935             }
1936              
1937             =head2 sever
1938              
1939             =for ref
1940              
1941             sever any links of this piddle to parent piddles
1942              
1943             In PDLA it is possible for a piddle to be just another
1944             view into another piddle's data. In that case we call
1945             this piddle a I and the original piddle owning
1946             the data its parent. In other languages these alternate views
1947             sometimes run by names such as I or I.
1948              
1949             Typical functions that return such piddles are C, C,
1950             C, etc. Sometimes, however, you would like to separate the
1951             I from its parent's data and just give it a life of
1952             its own (so that manipulation of its data doesn't change the parent).
1953             This is simply achieved by using C. For example,
1954              
1955             =for example
1956              
1957             $a = $pdl->index(pdl(0,3,7))->sever;
1958             $a++; # important: $pdl is not modified!
1959              
1960             In many (but not all) circumstances it acts therefore similar to
1961             L.
1962             However, in general performance is better with C and secondly,
1963             C doesn't lead to futile copying when used on piddles that
1964             already have their own data. On the other hand, if you really want to make
1965             sure to work on a copy of a piddle use L.
1966              
1967             $a = zeroes(20);
1968             $a->sever; # NOOP since $a is already its own boss!
1969              
1970             Again note: C I the same as L!
1971             For example,
1972              
1973             $a = zeroes(1); # $a does not have a parent, i.e. it is not a slice etc
1974             $b = $a->sever; # $b is now pointing to the same piddle as $a
1975             $b++;
1976             print $a;
1977             [1]
1978              
1979             but
1980              
1981             $a = zeroes(1);
1982             $b = $a->copy; # $b is now pointing to a new piddle
1983             $b++;
1984             print $a;
1985             [0]
1986              
1987              
1988             =head2 PDLA::info
1989              
1990             =for ref
1991              
1992             Return formatted information about a piddle.
1993              
1994             =for usage
1995              
1996             $x->info($format_string);
1997              
1998             =for example
1999              
2000             print $x->info("Type: %T Dim: %-15D State: %S");
2001              
2002             Returns a string with info about a piddle. Takes an optional
2003             argument to specify the format of information a la sprintf.
2004             Format specifiers are in the form C<%EwidthEEletterE>
2005             where the width is optional and the letter is one of
2006              
2007             =over 7
2008              
2009             =item T
2010              
2011             Type
2012              
2013             =item D
2014              
2015             Formatted Dimensions
2016              
2017             =item F
2018              
2019             Dataflow status
2020              
2021             =item S
2022              
2023             Some internal flags (P=physical,V=Vaffine,C=changed,B=may contain bad data)
2024              
2025             =item C
2026              
2027             Class of this piddle, i.e. C
2028              
2029             =item A
2030              
2031             Address of the piddle struct as a unique identifier
2032              
2033             =item M
2034              
2035             Calculated memory consumption of this piddle's data area
2036              
2037             =back
2038              
2039             =cut
2040              
2041             sub PDLA::info {
2042 0     0 0   my ($this,$str) = @_;
2043 0 0         $str = "%C: %T %D" unless defined $str;
2044 0 0         return ref($this)."->null"
2045             if PDLA::Core::dimstr($this) =~ /D \[0\]/;
2046 0           my @hash = split /(%[-,0-9]*[.]?[0-9]*\w)/, $str;
2047 0           my @args = ();
2048 0           my $nstr = '';
2049 0           for my $form (@hash) {
2050 0 0         if ($form =~ s/^%([-,0-9]*[.]?[0-9]*)(\w)$/%$1s/) {
2051 0 0         barf "unknown format specifier $2" unless defined $info{$2};
2052 0           push @args, &{$info{$2}->{Sub}}($this);
  0            
2053             }
2054 0           $nstr .= $form;
2055             }
2056 0           return sprintf $nstr, @args;
2057             }
2058              
2059             =head2 approx
2060              
2061             =for ref
2062              
2063             test for approximately equal values (relaxed C<==>)
2064              
2065             =for example
2066              
2067             # ok if all corresponding values in
2068             # piddles are within 1e-8 of each other
2069             print "ok\n" if all approx $a, $b, 1e-8;
2070              
2071             C is a relaxed form of the C<==> operator and
2072             often more appropriate for floating point types (C
2073             and C).
2074              
2075             Usage:
2076              
2077             =for usage
2078              
2079             $res = approx $a, $b [, $eps]
2080              
2081             The optional parameter C<$eps> is remembered across invocations
2082             and initially set to 1e-6, e.g.
2083              
2084             approx $a, $b; # last $eps used (1e-6 initially)
2085             approx $a, $b, 1e-10; # 1e-10
2086             approx $a, $b; # also 1e-10
2087              
2088             =cut
2089              
2090             my $approx = 1e-6; # a reasonable init value
2091             sub PDLA::approx {
2092 0     0 0   my ($a,$b,$eps) = @_;
2093 0 0         $eps = $approx unless defined $eps; # the default eps
2094 0           $approx = $eps; # remember last eps
2095             # NOTE: ($a-$b)->abs breaks for non-piddle inputs
2096 0           return abs($a-$b) < $eps;
2097             }
2098              
2099             =head2 mslice
2100              
2101             =for ref
2102              
2103             Convenience interface to L,
2104             allowing easier inclusion of dimensions in perl code.
2105              
2106             =for usage
2107              
2108             $a = $x->mslice(...);
2109              
2110             =for example
2111              
2112             # below is the same as $x->slice("5:7,:,3:4:2")
2113             $a = $x->mslice([5,7],X,[3,4,2]);
2114              
2115             =cut
2116              
2117             # called for colon-less args
2118             # preserves parens if present
2119 0 0   0     sub intpars { $_[0] =~ /\(.*\)/ ? '('.int($_[0]).')' : int $_[0] }
2120              
2121             sub PDLA::mslice {
2122 0     0 0   my($pdl) = shift;
2123             return $pdl->slice(join ',',(map {
2124 0           !ref $_ && $_ eq "X" ? ":" :
2125             ref $_ eq "ARRAY" ? $#$_ > 1 && @$_[2] == 0 ?
2126 0 0 0       "(".int(@$_[0]).")" : join ':', map {int $_} @$_ :
  0 0 0        
    0          
    0          
2127             !ref $_ ? intpars $_ :
2128             die "INVALID SLICE DEF $_"
2129             } @_));
2130             }
2131              
2132             =head2 nslice_if_pdl
2133              
2134             =for ref
2135              
2136             If C<$self> is a PDLA, then calls C with all but the last
2137             argument, otherwise $self->($_[-1]) is called where $_[-1} is the
2138             original argument string found during PDLA::NiceSlice filtering.
2139              
2140             DEVELOPER'S NOTE: this routine is found in Core.pm.PL but would be
2141             better placed in Slices/slices.pd. It is likely to be moved there
2142             and/or changed to "slice_if_pdl" for PDLA 3.0.
2143              
2144             =for usage
2145              
2146             $a = $x->nslice_if_pdl(...,'(args)');
2147              
2148             =cut
2149              
2150             sub PDLA::nslice_if_pdl {
2151 0     0 0   my ($pdl) = shift;
2152 0           my ($orig_args) = pop;
2153              
2154             # warn "PDLA::nslice_if_pdl called with (@_) args, originally ($orig_args)\n";
2155              
2156 0 0         if (ref($pdl) eq 'CODE') {
2157             # barf('PDLA::nslice_if_pdl tried to process a sub ref, please use &$subref() syntax')
2158 0           @_ = eval $orig_args;
2159 0           goto &$pdl;
2160             }
2161              
2162 0           unshift @_, $pdl;
2163 0           goto &PDLA::slice;
2164             }
2165              
2166             =head2 nslice
2167              
2168             =for ref
2169              
2170             c was an internally used interface for L,
2171             but is now merely a springboard to L. It is deprecated
2172             and likely to disappear in PDLA 3.0.
2173              
2174             =cut
2175             sub PDLA::nslice {
2176 0 0   0 0   unless($PDLA::nslice_warning_issued) {
2177 0           $PDLA::nslice_warning_issued = 1;
2178 0           warn "WARNING: deprecated call to PDLA::nslice detected. Use PDLA::slice instead.\n (Warning will be issued only once per session)\n";
2179             }
2180 0           goto &PDLA::slice;
2181             }
2182              
2183             sub blessed {
2184 0     0     my $ref = ref(shift);
2185 0 0         return $ref =~ /^(REF|SCALAR|ARRAY|HASH|CODE|GLOB||)$/ ? 0 : 1;
2186             }
2187              
2188             # Convert numbers to PDLA if not already
2189              
2190             sub PDLA::topdl {
2191 0 0   0 0   return $_[0]->new(@_[1..$#_]) if($#_ > 1); # PDLAify an ARRAY
2192 0 0         return $_[1] if blessed($_[1]); # Fall through
2193 0 0 0       return $_[0]->new($_[1]) if ref(\$_[1]) eq 'SCALAR' or
2194             ref($_[1]) eq 'ARRAY';
2195 0           barf("Can not convert a ".ref($_[1])." to a ".$_[0]);
2196 0           0;}
2197              
2198             # Convert everything to PDLA if not blessed
2199              
2200             sub alltopdl {
2201 0 0   0     return $_[1] if blessed($_[1]); # Fall through
2202 0           return $_[0]->new($_[1]);
2203 0           0;}
2204              
2205              
2206             =head2 inplace
2207              
2208             =for ref
2209              
2210             Flag a piddle so that the next operation is done 'in place'
2211              
2212             =for usage
2213              
2214             somefunc($x->inplace); somefunc(inplace $x);
2215              
2216             In most cases one likes to use the syntax C<$y = f($x)>, however
2217             in many case the operation C can be done correctly
2218             'in place', i.e. without making a new copy of the data for
2219             output. To make it easy to use this, we write C in such
2220             a way that it operates in-place, and use C to hint
2221             that a new copy should be disabled. This also makes for
2222             clear syntax.
2223              
2224             Obviously this will not work for all functions, and if in
2225             doubt see the function's documentation. However one
2226             can assume this is
2227             true for all elemental functions (i.e. those which just
2228             operate array element by array element like C).
2229              
2230             =for example
2231              
2232             pdl> $x = xvals zeroes 10;
2233             pdl> log10(inplace $x)
2234             pdl> p $x
2235             [-inf 0 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804 0.90308999 0.95424251]
2236              
2237             =cut
2238              
2239             # Flag pdl for in-place operations
2240              
2241             sub PDLA::inplace {
2242 0     0 0   my $pdl = PDLA->topdl(shift); $pdl->set_inplace(1); return $pdl;
  0            
  0            
2243             }
2244              
2245             # Copy if not inplace
2246              
2247              
2248             =head2 is_inplace
2249              
2250             =for ref
2251              
2252             Test the in-place flag on a piddle
2253              
2254             =for usage
2255              
2256             $out = ($in->is_inplace) ? $in : zeroes($in);
2257             $in->set_inplace(0)
2258              
2259             Provides access to the L hint flag, within the perl millieu.
2260             That way functions you write can be inplace aware... If given an
2261             argument the inplace flag will be set or unset depending on the value
2262             at the same time. Can be used for shortcut tests that delete the
2263             inplace flag while testing:
2264              
2265             $out = ($in->is_inplace(0)) ? $in : zeroes($in); # test & unset!
2266              
2267             =head2 set_inplace
2268              
2269             =for ref
2270              
2271             Set the in-place flag on a piddle
2272              
2273             =for usage
2274              
2275             $out = ($in->is_inplace) ? $in : zeroes($in);
2276             $in->set_inplace(0);
2277              
2278             Provides access to the L hint flag, within the perl millieu.
2279             Useful mainly for turning it OFF, as L turns it ON more
2280             conveniently.
2281              
2282             =head2 new_or_inplace
2283              
2284             =for usage
2285              
2286             $a = new_or_inplace(shift());
2287             $a = new_or_inplace(shift(),$preferred_type);
2288              
2289             =for ref
2290              
2291             Return back either the argument pdl or a copy of it depending on whether
2292             it be flagged in-place or no. Handy for building inplace-aware functions.
2293              
2294             If you specify a preferred type (must be one of the usual PDLA type strings,
2295             a list ref containing several of them, or a string containing several of them),
2296             then the copy is coerced into the first preferred type listed if it is not
2297             already one of the preferred types.
2298              
2299             Note that if the inplace flag is set, no coersion happens even if you specify
2300             a preferred type.
2301              
2302             =cut
2303              
2304             sub new_or_inplace {
2305 0     0     my $pdl = shift;
2306 0           my $preferred = shift;
2307 0           my $force = shift;
2308 0 0         if($pdl->is_inplace) {
2309 0           $pdl->set_inplace(0);
2310 0           return $pdl;
2311             } else {
2312 0 0         unless(defined($preferred)) {
2313 0           return $pdl->copy;
2314             } else {
2315 0 0         $preferred = join(",",@$preferred) if(ref($preferred) eq 'ARRAY');
2316 0           my $s = "".$pdl->type;
2317 0 0         if($preferred =~ m/(^|\,)$s(\,|$)/i) {
2318             # Got a match - the PDLA is one of the preferred types.
2319 0           return $pdl->copy();
2320             } else {
2321             # No match - promote it to the first in the list.
2322 0           $preferred =~ s/\,.*//;
2323 0           my $out = PDLA::new_from_specification('PDLA',new PDLA::Type($preferred),$pdl->dims);
2324 0           $out .= $pdl;
2325 0           return $out;
2326             }
2327             }
2328             }
2329 0           barf "PDLA::Core::new_or_inplace - This can never happen!";
2330             }
2331             *PDLA::new_or_inplace = \&new_or_inplace;
2332              
2333             # Allow specifications like zeroes(10,10) or zeroes($x)
2334             # or zeroes(inplace $x) or zeroes(float,4,3)
2335              
2336             =head2 PDLA::new_from_specification
2337              
2338             =for ref
2339              
2340             Internal method: create piddle by specification
2341              
2342             This is the argument processing method called by L
2343             and some other functions
2344             which constructs piddles from argument lists of the form:
2345              
2346             [type], $nx, $ny, $nz,...
2347              
2348             For C<$nx>, C<$ny>, etc. 0 and 1D piddles are allowed.
2349             Giving those has the same effect as if saying C<$arg-Elist>,
2350             e.g.
2351              
2352             1, pdl(5,2), 4
2353              
2354             is equivalent to
2355              
2356             1, 5, 2, 4
2357              
2358             Note, however, that in all functions using C
2359             calling C will probably not do what you want. So to play safe
2360             use (e.g. with zeroes)
2361              
2362             $pdl = zeroes $dimpdl->list;
2363              
2364             Calling
2365              
2366             $pdl = zeroes $dimpdl;
2367              
2368             will rather be equivalent to
2369              
2370             $pdl = zeroes $dimpdl->dims;
2371              
2372             However,
2373              
2374             $pdl = zeroes ushort, $dimpdl;
2375              
2376             will again do what you intended since it is interpreted
2377             as if you had said
2378              
2379             $pdl = zeroes ushort, $dimpdl->list;
2380              
2381             This is unfortunate and confusing but no good solution seems
2382             obvious that would not break existing scripts.
2383              
2384             =cut
2385              
2386             sub PDLA::new_from_specification{
2387 0     0 0   my $class = shift;
2388 0 0         my $type = ref($_[0]) eq 'PDLA::Type' ? ${shift @_}[0] : $PDLA_D;
  0            
2389 0           my $nelems = 1; my @dims;
  0            
2390 0           for (@_) {
2391 0 0         if (ref $_) {
2392 0 0         barf "Trying to use non-piddle as dimensions?" unless $_->isa('PDLA');
2393 0 0         barf "Trying to use multi-dim piddle as dimensions?"
2394             if $_->getndims > 1;
2395 0 0         warn "creating > 10 dim piddle (piddle arg)!"
2396             if $_->nelem > 10;
2397 0           for my $dim ($_->list) {$nelems *= $dim; push @dims, $dim}
  0            
  0            
2398             } else {
2399 0 0         if ($_) { # quiet warnings when $_ is the empty string
2400 0 0         barf "Dimensions must be non-negative" if $_<0;
2401 0           $nelems *= $_; push @dims, $_
  0            
2402             } else {
2403 0           $nelems *= 0; push @dims, 0;
  0            
2404             }
2405             }
2406             }
2407 0           my $pdl = $class->initialize();
2408 0           $pdl->set_datatype($type);
2409 0           $pdl->setdims([@dims]);
2410 0 0         print "Dims: ",(join ',',@dims)," DLen: ",(length $ {$pdl->get_dataref}),"\n" if $PDLA::debug;
  0            
2411 0           return $pdl;
2412             }
2413              
2414             =head2 isnull
2415              
2416             =for ref
2417              
2418             Test whether a piddle is null
2419              
2420             =for usage
2421              
2422             croak("Input piddle mustn't be null!")
2423             if $input_piddle->isnull;
2424              
2425             This function returns 1 if the piddle is null, zero if it is not. The purpose
2426             of null piddles is to "tell" any PDLA::PP methods to allocate new memory for
2427             an output piddle, but only when that PDLA::PP method is called in full-arg
2428             form. Of course, there's no reason you couldn't commandeer the special value
2429             for your own purposes, for which this test function would prove most helpful.
2430             But in general, you shouldn't need to test for a piddle's nullness.
2431              
2432             See L for more information.
2433              
2434             =head2 isempty
2435              
2436             =for ref
2437              
2438             Test whether a piddle is empty
2439              
2440             =for usage
2441              
2442             print "The piddle has zero dimension\n" if $pdl->isempty;
2443              
2444             This function returns 1 if the piddle has zero elements. This is
2445             useful in particular when using the indexing function which. In the
2446             case of no match to a specified criterion, the returned piddle has
2447             zero dimension.
2448              
2449             pdl> $a=sequence(10)
2450             pdl> $i=which($a < -1)
2451             pdl> print "I found no matches!\n" if ($i->isempty);
2452             I found no matches!
2453              
2454             Note that having zero elements is rather different from the concept
2455             of being a null piddle, see the L and
2456             L
2457             manpages for discussions of this.
2458              
2459             =cut
2460              
2461             sub PDLA::isempty {
2462 0     0 0   my $pdl=shift;
2463 0           return ($pdl->nelem == 0);
2464             }
2465              
2466             =head2 zeroes
2467              
2468             =for ref
2469              
2470             construct a zero filled piddle from dimension list or template piddle.
2471              
2472             Various forms of usage,
2473              
2474             (i) by specification or (ii) by template piddle:
2475              
2476             =for usage
2477              
2478             # usage type (i):
2479             $a = zeroes([type], $nx, $ny, $nz,...);
2480             $a = PDLA->zeroes([type], $nx, $ny, $nz,...);
2481             $a = $pdl->zeroes([type], $nx, $ny, $nz,...);
2482             # usage type (ii):
2483             $a = zeroes $b;
2484             $a = $b->zeroes
2485             zeroes inplace $a; # Equivalent to $a .= 0;
2486             $a->inplace->zeroes; # ""
2487              
2488             =for example
2489              
2490             pdl> $z = zeroes 4,3
2491             pdl> p $z
2492             [
2493             [0 0 0 0]
2494             [0 0 0 0]
2495             [0 0 0 0]
2496             ]
2497             pdl> $z = zeroes ushort, 3,2 # Create ushort array
2498             [ushort() etc. with no arg returns a PDLA::Types token]
2499              
2500             See also L
2501             for details on using piddles in the dimensions list.
2502              
2503             =cut
2504              
2505 0 0 0 0     sub zeroes { ref($_[0]) && ref($_[0]) ne 'PDLA::Type' ? PDLA::zeroes($_[0]) : PDLA->zeroes(@_) }
2506             sub PDLA::zeroes {
2507 0     0 0   my $class = shift;
2508 0 0         my $pdl = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
2509 0           $pdl.=0;
2510 0           return $pdl;
2511             }
2512              
2513             # Create convenience aliases for zeroes
2514              
2515             =head2 zeros
2516              
2517             =for ref
2518              
2519             construct a zero filled piddle (see zeroes for usage)
2520              
2521             =cut
2522              
2523             *zeros = \&zeroes;
2524             *PDLA::zeros = \&PDLA::zeroes;
2525              
2526             =head2 ones
2527              
2528             =for ref
2529              
2530             construct a one filled piddle
2531              
2532             =for usage
2533              
2534             $a = ones([type], $nx, $ny, $nz,...);
2535             etc. (see 'zeroes')
2536              
2537             =for example
2538              
2539             see zeroes() and add one
2540              
2541             See also L
2542             for details on using piddles in the dimensions list.
2543              
2544             =cut
2545              
2546 0 0 0 0     sub ones { ref($_[0]) && ref($_[0]) ne 'PDLA::Type' ? PDLA::ones($_[0]) : PDLA->ones(@_) }
2547             sub PDLA::ones {
2548 0     0 0   my $class = shift;
2549 0 0         my $pdl = scalar(@_)? $class->new_from_specification(@_) : $class->new_or_inplace;
2550 0           $pdl.=1;
2551 0           return $pdl;
2552             }
2553              
2554             =head2 reshape
2555              
2556             =for ref
2557              
2558             Change the shape (i.e. dimensions) of a piddle, preserving contents.
2559              
2560             =for usage
2561              
2562             $x->reshape(NEWDIMS); reshape($x, NEWDIMS);
2563              
2564             The data elements are preserved, obviously they will wrap
2565             differently and get truncated if the new array is shorter.
2566             If the new array is longer it will be zero-padded.
2567              
2568             ***Potential incompatibility with earlier versions of PDLA****
2569             If the list of C is empty C will just drop
2570             all dimensions of size 1 (preserving the number of elements):
2571              
2572             $a = sequence(3,4,5);
2573             $b = $a(1,3);
2574             $b->reshape();
2575             print $b->info;
2576             PDLA: Double D [5]
2577              
2578             Dimensions of size 1 will also be dropped if C is
2579             invoked with the argument -1:
2580              
2581             $b = $a->reshape(-1);
2582              
2583             As opposed to C without arguments, C
2584             preserves dataflow:
2585              
2586             $a = ones(2,1,2);
2587             $b = $a(0)->reshape(-1);
2588             $b++;
2589             print $a;
2590             [
2591             [
2592             [2 1]
2593             ]
2594             [
2595             [2 1]
2596             ]
2597             ]
2598              
2599             Note: an explicit copy of slices is generally forced - this is the
2600             only way (for now) of stopping a crash if C<$x> is a slice.
2601             Important: Physical piddles are changed inplace!
2602              
2603             =for example
2604              
2605             pdl> $x = sequence(10)
2606             pdl> reshape $x,3,4; p $x
2607             [
2608             [0 1 2]
2609             [3 4 5]
2610             [6 7 8]
2611             [9 0 0]
2612             ]
2613             pdl> reshape $x,5; p $x
2614             [0 1 2 3 4]
2615              
2616             =cut
2617              
2618             *reshape = \&PDLA::reshape;
2619             sub PDLA::reshape{
2620 0 0 0 0 0   if (@_ == 2 && $_[1] == -1) { # a slicing reshape that drops 1-dims
2621 0 0         return $_[0]->slice( map { $_==1 ? [0,0,0] : [] } $_[0]->dims);
  0            
2622             }
2623 0           my $pdl = pdl($_[0]);
2624 0           my $nelem = $pdl->nelem;
2625 0           my @dims = grep defined, @_[1..$#_];
2626 0 0         for my $dim(@dims) { barf "reshape: invalid dim size '$dim'" if $dim < 0 }
  0            
2627 0 0         @dims = grep($_ != 1, $pdl->dims) if @dims == 0; # get rid of dims of size 1
2628 0           $pdl->setdims([@dims]);
2629 0           $pdl->upd_data;
2630 0 0         if ($pdl->nelem > $nelem) {
2631 0           my $tmp=$pdl->clump(-1)->slice("$nelem:-1");
2632 0           $tmp .= 0;
2633             }
2634 0           $_[0] = $pdl;
2635 0           return $pdl;
2636             }
2637              
2638             =head2 squeeze
2639              
2640             =for ref
2641              
2642             eliminate all singleton dimensions (dims of size 1)
2643              
2644             =for example
2645              
2646             $b = $a(0,0)->squeeze;
2647              
2648             Alias for C. Removes all singleton dimensions
2649             and preserves dataflow. A more concise interface is
2650             provided by L via modifiers:
2651              
2652             use PDLA::NiceSlice;
2653             $b = $a(0,0;-); # same as $a(0,0)->squeeze
2654              
2655             =cut
2656              
2657             *squeeze = \&PDLA::squeeze;
2658 0     0 0   sub PDLA::squeeze { return $_[0]->reshape(-1) }
2659              
2660             =head2 flat
2661              
2662             =for ref
2663              
2664             flatten a piddle (alias for C<< $pdl->clump(-1) >>)
2665              
2666             =for example
2667              
2668             $srt = $pdl->flat->qsort;
2669              
2670             Useful method to make a 1D piddle from an
2671             arbitrarily sized input piddle. Data flows
2672             back and forth as usual with slicing routines.
2673             Falls through if argument already E= 1D.
2674              
2675             =cut
2676              
2677             *flat = \&PDLA::flat;
2678             sub PDLA::flat { # fall through if < 2D
2679 0 0   0 0   return my $dummy = $_[0]->getndims != 1 ? $_[0]->clump(-1) : $_[0];
2680             }
2681              
2682             =head2 convert
2683              
2684             =for ref
2685              
2686             Generic datatype conversion function
2687              
2688             =for usage
2689              
2690             $y = convert($x, $newtypenum);
2691              
2692             =for example
2693              
2694             $y = convert $x, long
2695             $y = convert $x, ushort
2696              
2697             C<$newtype> is a type B, for convenience they are
2698             returned by C etc when called without arguments.
2699              
2700             =cut
2701              
2702             # type to type conversion functions (with automatic conversion to pdl vars)
2703              
2704             sub PDLA::convert {
2705             # we don't allow inplace conversion at the moment
2706             # (not sure what needs to be changed)
2707 0 0   0 0   barf 'Usage: $y = convert($x, $newtypenum)'."\n" if $#_!=1;
2708 0           my ($pdl,$type)= @_;
2709 0 0         $pdl = pdl($pdl) unless ref $pdl; # Allow normal numbers
2710 0 0         $type = $type->enum if ref($type) eq 'PDLA::Type';
2711 0 0         barf 'Usage: $y = convert($x, $newtypenum)'."\n" unless Scalar::Util::looks_like_number($type);
2712 0 0         return $pdl if $pdl->get_datatype == $type;
2713             # make_physical-call: temporary stopgap to work around core bug
2714 0           my $conv = $pdl->flowconvert($type)->make_physical->sever;
2715 0           return $conv;
2716             }
2717              
2718             =head2 Datatype_conversions
2719              
2720             =for ref
2721              
2722             byte|short|ushort|long|longlong|float|double (shorthands to convert datatypes)
2723              
2724             =for usage
2725              
2726             $y = double $x; $y = ushort [1..10];
2727             # all of the above listed shorthands behave similarly
2728              
2729             When called with a piddle argument, they convert to the specific
2730             datatype.
2731              
2732             When called with a numeric, list, listref, or string argument they
2733             construct a new piddle. This is a convenience to avoid having to be
2734             long-winded and say C<$x = long(pdl(42))>
2735              
2736             Thus one can say:
2737              
2738             $a = float(1,2,3,4); # 1D
2739             $a = float q[1 2 3; 4 5 6]; # 2D
2740             $a = float([1,2,3],[4,5,6]); # 2D
2741             $a = float([[1,2,3],[4,5,6]]); # 2D
2742              
2743             Note the last three give identical results, and the last two are exactly
2744             equivalent - a list is automatically converted to a list reference for
2745             syntactic convenience. i.e. you can omit the outer C<[]>
2746              
2747             When called with no arguments, these functions return a special type token.
2748             This allows syntactical sugar like:
2749              
2750             $x = ones byte, 1000,1000;
2751              
2752             This example creates a large piddle directly as byte datatype in
2753             order to save memory.
2754              
2755             In order to control how undefs are handled in converting from perl lists to
2756             PDLAs, one can set the variable C<$PDLA::undefval>;
2757             see the function L for more details.
2758              
2759             =for example
2760              
2761             pdl> p $x=sqrt float [1..10]
2762             [1 1.41421 1.73205 2 2.23607 2.44949 2.64575 2.82843 3 3.16228]
2763             pdl> p byte $x
2764             [1 1 1 2 2 2 2 2 3 3]
2765              
2766             =head2 byte
2767              
2768             Convert to byte datatype
2769              
2770             =head2 short
2771              
2772             Convert to short datatype
2773              
2774             =head2 ushort
2775              
2776             Convert to ushort datatype
2777              
2778             =head2 long
2779              
2780             Convert to long datatype
2781              
2782             =head2 indx
2783              
2784             Convert to indx datatype
2785              
2786             =head2 longlong
2787              
2788             Convert to longlong datatype
2789              
2790             =head2 float
2791              
2792             Convert to float datatype
2793              
2794             =head2 double
2795              
2796             Convert to double datatype
2797              
2798             =head2 type
2799              
2800             =for ref
2801              
2802             return the type of a piddle as a blessed type object
2803              
2804             A convenience function for use with the piddle constructors, e.g.
2805              
2806             =for example
2807              
2808             $b = PDLA->zeroes($a->type,$a->dims,3);
2809             die "must be float" unless $a->type == float;
2810              
2811             See also the discussion of the C class in L.
2812             Note that the C objects have overloaded comparison and
2813             stringify operators so that you can compare and print types:
2814              
2815             $a = $a->float if $a->type < float;
2816             $t = $a->type; print "Type is $t\";
2817              
2818             =cut
2819              
2820 0     0 0   sub PDLA::type { return PDLA::Type->new($_[0]->get_datatype); }
2821              
2822             ##################### Printing ####################
2823              
2824             # New string routine
2825              
2826             $PDLA::_STRINGIZING = 0;
2827              
2828             sub PDLA::string {
2829 0     0 0   my($self,$format)=@_;
2830 0           my $to_return = eval {
2831 0 0         if($PDLA::_STRINGIZING) {
2832 0           return "ALREADY_STRINGIZING_NO_LOOPS";
2833             }
2834 0           local $PDLA::_STRINGIZING = 1;
2835 0           my $ndims = $self->getndims;
2836 0 0         if($self->nelem > $PDLA::toolongtoprint) {
2837 0           return "TOO LONG TO PRINT";
2838             }
2839 0 0         if ($ndims==0) {
2840 0 0 0       if ( $self->badflag() and $self->isbad() ) {
2841 0           return "BAD";
2842             } else {
2843 0           my @x = $self->at();
2844 0 0         return ($format ? sprintf($format, $x[0]) : "$x[0]");
2845             }
2846             }
2847 0 0         return "Null" if $self->isnull;
2848 0 0         return "Empty[".join("x",$self->dims)."]" if $self->isempty; # Empty piddle
2849 0 0         local $sep = $PDLA::use_commas ? "," : " ";
2850 0 0         local $sep2 = $PDLA::use_commas ? "," : "";
2851 0 0         if ($ndims==1) {
2852 0           return str1D($self,$format);
2853             }
2854             else{
2855 0           return strND($self,$format,0);
2856             }
2857             };
2858 0 0         if ($@) {
2859             # Remove reference to this line:
2860 0           $@ =~ s/\s*at .* line \d+\s*\.\n*/./;
2861 0           PDLA::Core::barf("Stringizing problem: $@");
2862             }
2863 0           return $to_return;
2864             }
2865              
2866             ############## Section/subsection functions ###################
2867              
2868             =head2 list
2869              
2870             =for ref
2871              
2872             Convert piddle to perl list
2873              
2874             =for usage
2875              
2876             @tmp = list $x;
2877              
2878             Obviously this is grossly inefficient for the large datasets PDLA is designed to
2879             handle. This was provided as a get out while PDLA matured. It should now be mostly
2880             superseded by superior constructs, such as PP/threading. However it is still
2881             occasionally useful and is provied for backwards compatibility.
2882              
2883             =for example
2884              
2885             for (list $x) {
2886             # Do something on each value...
2887             }
2888              
2889             If you compile PDLA with bad value support (the default), your machine's
2890             docs will also say this:
2891              
2892             =for bad
2893              
2894             list converts any bad values into the string 'BAD'.
2895              
2896             =cut
2897              
2898             # No threading, just the ordinary dims.
2899             sub PDLA::list{ # pdl -> @list
2900 0 0   0 0   barf 'Usage: list($pdl)' if $#_!=0;
2901 0           my $pdl = PDLA->topdl(shift);
2902 0 0         return () if nelem($pdl)==0;
2903 0           @{listref_c($pdl)};
  0            
2904             }
2905              
2906             =head2 unpdl
2907              
2908             =for ref
2909              
2910             Convert piddle to nested Perl array references
2911              
2912             =for usage
2913              
2914             $arrayref = unpdl $x;
2915              
2916             This function returns a reference to a Perl list-of-lists structure
2917             equivalent to the input piddle (within the limitation that while values
2918             of elements should be preserved, the detailed datatypes will not as
2919             perl itself basically has "number" data rather than byte, short, int...
2920             E.g., C<< sum($x - pdl( $x->unpdl )) >> should equal 0.
2921              
2922             Obviously this is grossly inefficient in memory and processing for the
2923             large datasets PDLA is designed to handle. Sometimes, however, you really
2924             want to move your data back to Perl, and with proper dimensionality,
2925             unlike C.
2926              
2927             =for example
2928              
2929             use JSON;
2930             my $json = encode_json unpdl $pdl;
2931              
2932             If you compile PDLA with bad value support (the default), your machine's
2933             docs will also say this:
2934              
2935             =cut
2936              
2937             =for bad
2938              
2939             unpdl converts any bad values into the string 'BAD'.
2940              
2941             =cut
2942              
2943             sub PDLA::unpdl {
2944 0 0   0 0   barf 'Usage: unpdl($pdl)' if $#_ != 0;
2945 0           my $pdl = PDLA->topdl(shift);
2946 0 0         return [] if $pdl->nelem == 0;
2947 0           return _unpdl_int($pdl);
2948             }
2949              
2950             sub _unpdl_int {
2951 0     0     my $pdl = shift;
2952 0 0         if ($pdl->ndims > 1) {
2953 0           return [ map { _unpdl_int($_) } dog $pdl ];
  0            
2954             } else {
2955 0           return listref_c($pdl);
2956             }
2957             }
2958              
2959             =head2 listindices
2960              
2961             =for ref
2962              
2963             Convert piddle indices to perl list
2964              
2965             =for usage
2966              
2967             @tmp = listindices $x;
2968              
2969             C<@tmp> now contains the values C<0..nelem($x)>.
2970              
2971             Obviously this is grossly inefficient for the large datasets PDLA is designed to
2972             handle. This was provided as a get out while PDLA matured. It should now be mostly
2973             superseded by superior constructs, such as PP/threading. However it is still
2974             occasionally useful and is provied for backwards compatibility.
2975              
2976             =for example
2977              
2978             for $i (listindices $x) {
2979             # Do something on each value...
2980             }
2981              
2982             =cut
2983              
2984             sub PDLA::listindices{ # Return list of index values for 1D pdl
2985 0 0   0 0   barf 'Usage: list($pdl)' if $#_!=0;
2986 0           my $pdl = shift;
2987 0 0         return () if nelem($pdl)==0;
2988 0 0         barf 'Not 1D' if scalar(dims($pdl)) != 1;
2989 0           return (0..nelem($pdl)-1);
2990             }
2991              
2992             =head2 set
2993              
2994             =for ref
2995              
2996             Set a single value inside a piddle
2997              
2998             =for usage
2999              
3000             set $piddle, @position, $value
3001              
3002             C<@position> is a coordinate list, of size equal to the
3003             number of dimensions in the piddle. Occasionally useful,
3004             mainly provided for backwards compatibility as superseded
3005             by use of L and assigment operator C<.=>.
3006              
3007             =for example
3008              
3009             pdl> $x = sequence 3,4
3010             pdl> set $x, 2,1,99
3011             pdl> p $x
3012             [
3013             [ 0 1 2]
3014             [ 3 4 99]
3015             [ 6 7 8]
3016             [ 9 10 11]
3017             ]
3018              
3019             =cut
3020              
3021             sub PDLA::set{ # Sets a particular single value
3022 0 0   0 0   barf 'Usage: set($pdl, $x, $y,.., $value)' if $#_<2;
3023 0           my $self = shift; my $value = pop @_;
  0            
3024 0           set_c ($self, [@_], $value);
3025 0           return $self;
3026             }
3027              
3028             =head2 at
3029              
3030             =for ref
3031              
3032             Returns a single value inside a piddle as perl scalar.
3033              
3034             =for usage
3035              
3036             $z = at($piddle, @position); $z=$piddle->at(@position);
3037              
3038             C<@position> is a coordinate list, of size equal to the
3039             number of dimensions in the piddle. Occasionally useful
3040             in a general context, quite useful too inside PDLA internals.
3041              
3042             =for example
3043              
3044             pdl> $x = sequence 3,4
3045             pdl> p $x->at(1,2)
3046             7
3047              
3048             If you compile PDLA with bad value support (the default), your machine's
3049             docs will also say this:
3050              
3051             =for bad
3052              
3053             at converts any bad values into the string 'BAD'.
3054              
3055             =cut
3056              
3057             sub PDLA::at { # Return value at ($x,$y,$z...)
3058 0 0   0 0   barf 'Usage: at($pdl, $x, $y, ...)' if $#_<0;
3059 0           my $self = shift;
3060 0           at_bad_c ($self, [@_]);
3061             }
3062              
3063             =head2 sclr
3064              
3065             =for ref
3066              
3067             return a single value from a piddle as a scalar
3068              
3069             =for example
3070              
3071             $val = $a(10)->sclr;
3072             $val = sclr inner($a,$b);
3073              
3074             The C method is useful to turn a piddle into a normal Perl
3075             scalar. Its main advantage over using C for this purpose is the fact
3076             that you do not need to worry if the piddle is 0D, 1D or higher dimensional.
3077             Using C you have to supply the correct number of zeroes, e.g.
3078              
3079             $a = sequence(10);
3080             $b = $a->slice('4');
3081             print $b->sclr; # no problem
3082             print $b->at(); # error: needs at least one zero
3083              
3084             C is generally used when a Perl scalar is required instead
3085             of a one-element piddle. If the input is a multielement piddle
3086             the first value is returned as a Perl scalar. You can optionally
3087             switch on checks to ensure that the input piddle has only one element:
3088              
3089             PDLA->sclr({Check => 'warn'}); # carp if called with multi-el pdls
3090             PDLA->sclr({Check => 'barf'}); # croak if called with multi-el pdls
3091              
3092             are the commands to switch on warnings or raise an error if
3093             a multielement piddle is passed as input. Note that these options
3094             can only be set when C is called as a class method (see
3095             example above). Use
3096              
3097             PDLA->sclr({Check=>0});
3098              
3099             to switch these checks off again (default setting);
3100             When called as a class method the resulting check mode is returned
3101             (0: no checking, 1: warn, 2: barf).
3102              
3103             =cut
3104              
3105             my $chkmode = 0; # default mode no checks
3106 117     117   77602 use PDLA::Options;
  117         322  
  117         395217  
3107             sub PDLA::sclr {
3108 0     0 0   my $this = shift;
3109 0 0         if (ref $this) { # instance method
3110 0 0 0       carp "multielement piddle in 'sclr' call"
3111             if ($chkmode == 1 && $this->nelem > 1);
3112 0 0 0       croak "multielement piddle in 'sclr' call"
3113             if ($chkmode == 2 && $this->nelem > 1);
3114 0           return sclr_c($this);
3115             } else { # class method
3116 0           my $check = (iparse({Check=>0},ifhref($_[0])))[1];
3117 0 0         if (lc($check) eq 'warn') {$chkmode = 1}
  0 0          
3118 0           elsif (lc($check) eq 'barf') {$chkmode = 2}
3119 0 0         else {$chkmode = $check != 0 ? 1 : 0}
3120 0           return $chkmode;
3121             }
3122             }
3123              
3124             =head2 cat
3125              
3126             =for ref
3127              
3128             concatenate piddles to N+1 dimensional piddle
3129              
3130             Takes a list of N piddles of same shape as argument,
3131             returns a single piddle of dimension N+1
3132              
3133             =for example
3134              
3135             pdl> $x = cat ones(3,3),zeroes(3,3),rvals(3,3); p $x
3136             [
3137             [
3138             [1 1 1]
3139             [1 1 1]
3140             [1 1 1]
3141             ]
3142             [
3143             [0 0 0]
3144             [0 0 0]
3145             [0 0 0]
3146             ]
3147             [
3148             [1 1 1]
3149             [1 0 1]
3150             [1 1 1]
3151             ]
3152             ]
3153              
3154             If you compile PDLA with bad value support (the default), your machine's
3155             docs will also say this:
3156              
3157             =for bad
3158              
3159             The output piddle is set bad if any input piddles have their bad flag set.
3160              
3161             Similar functions include L and
3162             L.
3163              
3164             =cut
3165              
3166             sub PDLA::cat {
3167 0     0 0   my $res;
3168 0           my $old_err = $@;
3169 0           $@ = '';
3170 0           eval {
3171 0           $res = $_[0]->initialize;
3172 0           $res->set_datatype($_[0]->get_datatype);
3173              
3174 0           my @resdims = $_[0]->dims;
3175 0           for my $i(0..$#_){
3176 0           my @d = $_[$i]->dims;
3177 0           for my $j(0..$#d) {
3178 0 0 0       $resdims[$j] = $d[$j] if( !defined($resdims[$j]) or $resdims[$j]==1 );
3179 0 0 0       die "mismatched dims\n" if($d[$j] != 1 and $resdims[$j] != $d[$j]);
3180             }
3181             }
3182 0           $res->setdims( [@resdims,scalar(@_) ]);
3183 0           my ($i,$t); my $s = ":,"x@resdims;
  0            
3184 0           for (@_) { $t = $res->slice($s."(".$i++.")"); $t .= $_}
  0            
  0            
3185              
3186             # propagate any bad flags
3187 0 0         for (@_) { if ( $_->badflag() ) { $res->badflag(1); last; } }
  0            
  0            
  0            
3188             };
3189 0 0         if ($@ eq '') {
3190             # Restore the old error and return
3191 0           $@ = $old_err;
3192 0           return $res;
3193             }
3194              
3195             # If we've gotten here, then there's been an error, so check things
3196             # and barf out a meaningful message.
3197              
3198 0 0 0       if ($@ =~ /PDLA::Ops::assgn|mismatched/
      0        
3199             or $@ =~ /"badflag"/
3200             or $@ =~ /"initialize"/) {
3201 0           my (@mismatched_dims, @not_a_piddle);
3202 0           my $i = 0;
3203              
3204             # non-piddles and/or dimension mismatch. The first argument is
3205             # ok unless we have the "initialize" error:
3206 0 0         if ($@ =~ /"initialize"/) {
3207             # Handle the special case that there are *no* args passed:
3208 0 0         barf("Called PDLA::cat without any arguments") unless @_;
3209              
3210 0   0       while ($i < @_ and not eval{ $_[$i]->isa('PDLA')}) {
  0            
3211 0           push (@not_a_piddle, $i);
3212 0           $i++;
3213             }
3214             }
3215              
3216             # Get the dimensions of the first actual piddle in the argument
3217             # list:
3218 0           my $first_piddle_argument = $i;
3219 0 0         my @dims = $_[$i]->dims if ref($_[$i]) =~ /PDLA/;
3220              
3221             # Figure out all the ways that the caller screwed up:
3222 0           while ($i < @_) {
3223 0           my $arg = $_[$i];
3224             # Check if not a piddle
3225 0 0         if (not eval{$arg->isa('PDLA')}) {
  0 0          
3226 0           push @not_a_piddle, $i;
3227             }
3228             # Check if different number of dimensions
3229             elsif (@dims != $arg->ndims) {
3230 0           push @mismatched_dims, $i;
3231             }
3232             # Check if size of dimensions agree
3233             else {
3234 0           DIMENSION: for (my $j = 0; $j < @dims; $j++) {
3235 0 0         if ($dims[$j] != $arg->dim($j)) {
3236 0           push @mismatched_dims, $i;
3237 0           last DIMENSION;
3238             }
3239             }
3240             }
3241 0           $i++;
3242             }
3243              
3244             # Construct a message detailing the results
3245 0           my $message = "bad arguments passed to function PDLA::cat\n";
3246 0 0         if (@mismatched_dims > 1) {
    0          
3247             # Many dimension mismatches
3248 0           $message .= "The dimensions of arguments "
3249             . join(', ', @mismatched_dims[0 .. $#mismatched_dims-1])
3250             . " and $mismatched_dims[-1] do not match the\n"
3251             . " dimensions of the first piddle argument (argument $first_piddle_argument).\n";
3252             }
3253             elsif (@mismatched_dims) {
3254             # One dimension mismatch
3255 0           $message .= "The dimensions of argument $mismatched_dims[0] do not match the\n"
3256             . " dimensions of the first piddle argument (argument $first_piddle_argument).\n";
3257             }
3258 0 0         if (@not_a_piddle > 1) {
    0          
3259             # many non-piddles
3260 0           $message .= "Arguments " . join(', ', @not_a_piddle[0 .. $#not_a_piddle-1])
3261             . " and $not_a_piddle[-1] are not piddles.\n";
3262             }
3263             elsif (@not_a_piddle) {
3264             # one non-piddle
3265 0           $message .= "Argument $not_a_piddle[0] is not a piddle.\n";
3266             }
3267              
3268             # Handle the edge case that something else happened:
3269 0 0 0       if (@not_a_piddle == 0 and @mismatched_dims == 0) {
3270 0           barf("cat: unknown error from the internals:\n$@");
3271             }
3272              
3273 0           $message .= "(Argument counting starts from zero.)";
3274 0           croak($message);
3275             }
3276             else {
3277 0           croak("cat: unknown error from the internals:\n$@");
3278             }
3279             }
3280              
3281             =head2 dog
3282              
3283             =for ref
3284              
3285             Opposite of 'cat' :). Split N dim piddle to list of N-1 dim piddles
3286              
3287             Takes a single N-dimensional piddle and splits it into a list of N-1 dimensional
3288             piddles. The breakup is done along the last dimension.
3289             Note the dataflown connection is still preserved by default,
3290             e.g.:
3291              
3292             =for example
3293              
3294             pdl> $p = ones 3,3,3
3295             pdl> ($a,$b,$c) = dog $p
3296             pdl> $b++; p $p
3297             [
3298             [
3299             [1 1 1]
3300             [1 1 1]
3301             [1 1 1]
3302             ]
3303             [
3304             [2 2 2]
3305             [2 2 2]
3306             [2 2 2]
3307             ]
3308             [
3309             [1 1 1]
3310             [1 1 1]
3311             [1 1 1]
3312             ]
3313             ]
3314              
3315             =for options
3316              
3317             Break => 1 Break dataflow connection (new copy)
3318              
3319             If you compile PDLA with bad value support (the default), your machine's
3320             docs will also say this:
3321              
3322             =for bad
3323              
3324             The output piddles are set bad if the original piddle has its bad flag set.
3325              
3326             =cut
3327              
3328             sub PDLA::dog {
3329 0 0   0 0   my $opt = pop @_ if ref($_[-1]) eq 'HASH';
3330 0           my $p = shift;
3331 0           my @res; my $s = ":,"x($p->getndims-1);
  0            
3332 0           for my $i (0..$p->getdim($p->getndims-1)-1) {
3333 0           $res[$i] = $p->slice($s."(".$i.")");
3334 0 0         $res[$i] = $res[$i]->copy if $$opt{Break};
3335 0           $i++;
3336             }
3337 0           return @res;
3338             }
3339              
3340             ###################### Misc internal routines ####################
3341              
3342             # Recursively pack an N-D array ref in format [[1,1,2],[2,2,3],[2,2,2]] etc
3343             # package vars $level and @dims must be initialised first.
3344              
3345             sub rpack {
3346 0     0     my ($ptype,$a) = @_; my ($ret,$type);
  0            
3347              
3348 0           $ret = "";
3349 0 0         if (ref($a) eq "ARRAY") {
    0          
3350              
3351 0 0         if (defined($dims[$level])) {
3352 0 0         barf 'Array is not rectangular' unless $dims[$level] == scalar(@$a);
3353             }else{
3354 0           $dims[$level] = scalar(@$a);
3355             }
3356              
3357 0           $type = ref($$a[0]);
3358 0 0         if ($type) {
3359 0           $level++;
3360 0           for(@$a) {
3361 0 0         barf 'Array is not rectangular' unless $type eq ref($_); # Equal types
3362 0           $ret .= rpack($ptype,$_);
3363             }
3364 0           $level--;
3365             } else {
3366             # These are leaf nodes
3367 0 0         $ret = pack $ptype, map {defined($_) ? $_ : $PDLA::undefval} @$a;
  0            
3368             }
3369             } elsif (ref($a) eq "PDLA") {
3370 0           barf 'Cannot make a new piddle from two or more piddles, try "cat"';
3371             } else {
3372 0           barf "Don't know how to make a PDLA object from passed argument";
3373             }
3374 0           return $ret;
3375             }
3376              
3377             sub rcopyitem { # Return a deep copy of an item - recursively
3378 0     0     my $x = shift;
3379 0           my ($y, $key, $value);
3380 0 0         if (ref(\$x) eq "SCALAR") {
    0          
    0          
    0          
    0          
3381 0           return $x;
3382             }elsif (ref($x) eq "SCALAR") {
3383 0           $y = $$x; return \$y;
  0            
3384             }elsif (ref($x) eq "ARRAY") {
3385 0           $y = [];
3386 0           for (@$x) {
3387 0           push @$y, rcopyitem($_);
3388             }
3389 0           return $y;
3390             }elsif (ref($x) eq "HASH") {
3391 0           $y={};
3392 0           while (($key,$value) = each %$x) {
3393 0           $$y{$key} = rcopyitem($value);
3394             }
3395 0           return $y;
3396             }elsif (blessed($x)) {
3397 0           return $x->copy;
3398             }else{
3399 0           barf ('Deep copy of object failed - unknown component with type '.ref($x));
3400             }
3401 0           0;}
3402              
3403             # N-D array stringifier
3404              
3405             sub strND {
3406 0     0     my($self,$format,$level)=@_;
3407             # $self->make_physical();
3408 0           my @dims = $self->dims;
3409             # print "STRND, $#dims\n";
3410              
3411 0 0         if ($#dims==1) { # Return 2D string
3412 0           return str2D($self,$format,$level);
3413             }
3414             else { # Return list of (N-1)D strings
3415 0           my $secbas = join '',map {":,"} @dims[0..$#dims-1];
  0            
3416 0           my $ret="\n"." "x$level ."["; my $j;
  0            
3417 0           for ($j=0; $j<$dims[$#dims]; $j++) {
3418 0           my $sec = $secbas . "($j)";
3419             # print "SLICE: $sec\n";
3420              
3421 0           $ret .= strND($self->slice($sec),$format, $level+1);
3422 0           chop $ret; $ret .= $sep2;
  0            
3423             }
3424 0 0         chop $ret if $PDLA::use_commas;
3425 0           $ret .= "\n" ." "x$level ."]\n";
3426 0           return $ret;
3427             }
3428             }
3429              
3430              
3431             # String 1D array in nice format
3432              
3433             sub str1D {
3434 0     0     my($self,$format)=@_;
3435 0 0         barf "Not 1D" if $self->getndims()!=1;
3436 0           my $x = listref_c($self);
3437 0           my ($ret,$dformat,$t);
3438 0           $ret = "[";
3439 0           my $dtype = $self->get_datatype();
3440 0 0         $dformat = $PDLA::floatformat if $dtype == $PDLA_F;
3441 0 0         $dformat = $PDLA::doubleformat if $dtype == $PDLA_D;
3442              
3443 0           my $badflag = $self->badflag();
3444 0           for $t (@$x) {
3445 0 0 0       if ( $badflag and $t eq "BAD" ) {
    0          
3446             # do nothing
3447             } elsif ($format) {
3448 0           $t = sprintf $format,$t;
3449             } else{ # Default
3450 0 0 0       if ($dformat && length($t)>7) { # Try smaller
3451 0           $t = sprintf $dformat,$t;
3452             }
3453             }
3454 0           $ret .= $t.$sep;
3455             }
3456              
3457 0           chop $ret; $ret.="]";
  0            
3458 0           return $ret;
3459             }
3460              
3461             # String 2D array in nice uniform format
3462              
3463             sub str2D{
3464 0     0     my($self,$format,$level)=@_;
3465             # print "STR2D:\n"; $self->printdims();
3466 0           my @dims = $self->dims();
3467 0 0         barf "Not 2D" if scalar(@dims)!=2;
3468 0           my $x = listref_c($self);
3469 0           my ($i, $f, $t, $len, $ret);
3470              
3471 0           my $dtype = $self->get_datatype();
3472 0           my $badflag = $self->badflag();
3473              
3474 0           my $findmax = 1;
3475 0 0 0       if (!defined $format || $format eq "") {
3476             # Format not given? - find max length of default
3477 0           $len=0;
3478              
3479 0 0         if ( $badflag ) {
3480 0           for (@$x) {
3481 0 0         if ( $_ eq "BAD" ) { $i = 3; }
  0            
3482 0           else { $i = length($_); }
3483 0 0         $len = $i>$len ? $i : $len;
3484             }
3485             } else {
3486 0 0         for (@$x) {$i = length($_); $len = $i>$len ? $i : $len };
  0            
  0            
3487             }
3488              
3489 0           $format = "%".$len."s";
3490              
3491 0 0         if ($len>7) { # Too long? - perhaps try smaller format
3492 0 0         if ($dtype == $PDLA_F) {
    0          
3493 0           $format = $PDLA::floatformat;
3494             } elsif ($dtype == $PDLA_D) {
3495 0           $format = $PDLA::doubleformat;
3496             } else {
3497             # Stick with default
3498 0           $findmax = 0;
3499             }
3500             }
3501             else {
3502             # Default ok
3503 0           $findmax = 0;
3504             }
3505             }
3506              
3507 0 0         if($findmax) {
3508             # Find max length of strings in final format
3509 0           $len=0;
3510              
3511 0 0         if ( $badflag ) {
3512 0           for (@$x) {
3513 0 0         if ( $_ eq "BAD" ) { $i = 3; }
  0            
3514 0           else { $i = length(sprintf $format,$_); }
3515 0 0         $len = $i>$len ? $i : $len;
3516             }
3517             } else {
3518 0           for (@$x) {
3519 0 0         $i = length(sprintf $format,$_); $len = $i>$len ? $i : $len;
  0            
3520             }
3521             }
3522             } # if: $findmax
3523              
3524 0           $ret = "\n" . " "x$level . "[\n";
3525             {
3526 0           my $level = $level+1;
  0            
3527 0           $ret .= " "x$level ."[";
3528 0           for ($i=0; $i<=$#$x; $i++) {
3529              
3530 0 0 0       if ( $badflag and $$x[$i] eq "BAD" ) {
3531 0           $f = "BAD";
3532             } else {
3533 0           $f = sprintf $format,$$x[$i];
3534             }
3535              
3536 0 0         $t = $len-length($f); $f = " "x$t .$f if $t>0;
  0            
3537 0           $ret .= $f;
3538 0 0         if (($i+1)%$dims[0]) {
3539 0           $ret.=$sep;
3540             }
3541             else{ # End of output line
3542 0           $ret.="]";
3543 0 0         if ($i==$#$x) { # very last number
3544 0           $ret.="\n";
3545             }
3546             else{
3547 0           $ret.= $sep2."\n" . " "x$level ."[";
3548             }
3549             }
3550             }
3551             }
3552 0           $ret .= " "x$level."]\n";
3553 0           return $ret;
3554             }
3555              
3556             #
3557             # Sleazy hcpy saves me time typing
3558             #
3559             sub PDLA::hcpy {
3560 0     0 0   $_[0]->hdrcpy($_[1]);
3561 0           $_[0];
3562             }
3563              
3564             ########## Docs for functions in Core.xs ##################
3565             # Pod docs for functions that are imported from Core.xs and are
3566             # not documented elsewhere. Currently this is not a complete
3567             # list. There are others.
3568              
3569             =head2 gethdr
3570              
3571             =for ref
3572              
3573             Retrieve header information from a piddle
3574              
3575             =for example
3576              
3577             $pdl=rfits('file.fits');
3578             $h=$pdl->gethdr;
3579             print "Number of pixels in the X-direction=$$h{NAXIS1}\n";
3580              
3581             The C function retrieves whatever header information is contained
3582             within a piddle. The header can be set with L and is always a
3583             hash reference or undef.
3584              
3585             C returns undef if the piddle has not yet had a header
3586             defined; compare with C and C, which are guaranteed to return a
3587             defined value.
3588              
3589             Note that gethdr() works by B: you can modify the header
3590             in-place once it has been retrieved:
3591              
3592             $a = rfits($filename);
3593             $ah = $a->gethdr();
3594             $ah->{FILENAME} = $filename;
3595              
3596             It is also important to realise that in most cases the header is not
3597             automatically copied when you copy the piddle. See L
3598             to enable automatic header copying.
3599              
3600             Here's another example: a wrapper around rcols that allows your piddle
3601             to remember the file it was read from and the columns could be easily
3602             written (here assuming that no regexp is needed, extensions are left
3603             as an exercise for the reader)
3604              
3605             sub ext_rcols {
3606             my ($file, @columns)=@_;
3607             my $header={};
3608             $$header{File}=$file;
3609             $$header{Columns}=\@columns;
3610              
3611             @piddles=rcols $file, @columns;
3612             foreach (@piddles) { $_->sethdr($header); }
3613             return @piddles;
3614             }
3615              
3616             =head2 hdr
3617              
3618             =for ref
3619              
3620             Retrieve or set header information from a piddle
3621              
3622             =for example
3623              
3624             $pdl->hdr->{CDELT1} = 1;
3625              
3626             The C function allows convenient access to the header of a
3627             piddle. Unlike C it is guaranteed to return a defined value,
3628             so you can use it in a hash dereference as in the example. If the
3629             header does not yet exist, it gets autogenerated as an empty hash.
3630              
3631             Note that this is usually -- but not always -- What You Want. If you
3632             want to use a tied L hash,
3633             for example, you should either construct it yourself and use C
3634             to put it into the piddle, or use L instead. (Note that
3635             you should be able to write out the FITS file successfully regardless
3636             of whether your PDLA has a tied FITS header object or a vanilla hash).
3637              
3638             =head2 fhdr
3639              
3640             =for ref
3641              
3642             Retrieve or set FITS header information from a piddle
3643              
3644             =for example
3645              
3646             $pdl->fhdr->{CDELT1} = 1;
3647              
3648             The C function allows convenient access to the header of a
3649             piddle. Unlike C it is guaranteed to return a defined value,
3650             so you can use it in a hash dereference as in the example. If the
3651             header does not yet exist, it gets autogenerated as a tied
3652             L hash.
3653              
3654             Astro::FITS::Header tied hashes are better at matching the behavior of
3655             FITS headers than are regular hashes. In particular, the hash keys
3656             are CAsE INsEnSItiVE, unlike normal hash keys. See
3657             L for details.
3658              
3659             If you do not have Astro::FITS::Header installed, you get back a
3660             normal hash instead of a tied object.
3661              
3662             =head2 sethdr
3663              
3664             =for ref
3665              
3666             Set header information of a piddle
3667              
3668             =for example
3669              
3670             $pdl = zeroes(100,100);
3671             $h = {NAXIS=>2, NAXIS1=>100, NAXIS=>100, COMMENT=>"Sample FITS-style header"};
3672             # add a FILENAME field to the header
3673             $$h{FILENAME} = 'file.fits';
3674             $pdl->sethdr( $h );
3675              
3676             The C function sets the header information for a piddle.
3677             You must feed in a hash ref or undef, and the header field of the PDLA is
3678             set to be a new ref to the same hash (or undefined).
3679              
3680             The hash ref requirement is a speed bump put in place since the normal
3681             use of headers is to store fits header information and the like. Of course,
3682             if you want you can hang whatever ugly old data structure you want off
3683             of the header, but that makes life more complex.
3684              
3685             Remember that the hash is not copied -- the header is made into a ref
3686             that points to the same underlying data. To get a real copy without
3687             making any assumptions about the underlying data structure, you
3688             can use one of the following:
3689              
3690             use PDLA::IO::Dumper;
3691             $pdl->sethdr( deep_copy($h) );
3692              
3693             (which is slow but general), or
3694              
3695             $pdl->sethdr( PDLA::_hdr_copy($h) )
3696              
3697             (which uses the built-in sleazy deep copier), or (if you know that all
3698             the elements happen to be scalars):
3699              
3700             { my %a = %$h;
3701             $pdl->sethdr(\%a);
3702             }
3703              
3704             which is considerably faster but just copies the top level.
3705              
3706             The C function must be given a hash reference or undef. For
3707             further information on the header, see L, L,
3708             L and L.
3709              
3710             =head2 hdrcpy
3711              
3712             =for ref
3713              
3714             switch on/off/examine automatic header copying
3715              
3716             =for example
3717              
3718             print "hdrs will be copied" if $a->hdrcpy;
3719             $a->hdrcpy(1); # switch on automatic header copying
3720             $b = $a->sumover; # and $b will inherit $a's hdr
3721             $a->hdrcpy(0); # and now make $a non-infectious again
3722              
3723             C without an argument just returns the current setting of the
3724             flag. See also "hcpy" which returns its PDLA argument (and so is useful
3725             in method-call pipelines).
3726              
3727             Normally, the optional header of a piddle is not copied automatically
3728             in pdl operations. Switching on the hdrcpy flag using the C
3729             method will enable automatic hdr copying. Note that an actual deep
3730             copy gets made, which is rather processor-inefficient -- so avoid
3731             using header copying in tight loops!
3732              
3733             Most PDLAs have the C flag cleared by default; however, some
3734             routines (notably L) set it by default
3735             where that makes more sense.
3736              
3737             The C flag is viral: if you set it for a PDLA, then derived
3738             PDLAs will get copies of the header and will also have their C
3739             flags set. For example:
3740              
3741             $a = xvals(50,50);
3742             $a->hdrcpy(1);
3743             $a->hdr->{FOO} = "bar";
3744             $b = $a++;
3745             $c = $b++;
3746             print $b->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
3747             $b->hdr->{FOO} = "baz";
3748             print $a->hdr->{FOO}, " - ", $b->hdr->{FOO}, " - ", $c->hdr->{FOO}, "\n";
3749              
3750             will print:
3751              
3752             bar - bar
3753             bar - baz - bar
3754              
3755             Performing an operation in which more than one PDLA has its hdrcpy flag
3756             causes the resulting PDLA to take the header of the first PDLA:
3757              
3758             ($a,$b) = sequence(5,2)->dog;
3759             $a->hdrcpy(1); $b->hdrcpy(1);
3760             $a->hdr->{foo} = 'a';
3761             $b->hdr->{foo} = 'b';
3762             print (($a+$b)->hdr->{foo} , ($b+$a)->hdr->{foo});
3763              
3764             will print:
3765              
3766             a b
3767              
3768             =head2 hcpy
3769              
3770             =for ref
3771              
3772             Switch on/off automatic header copying, with PDLA pass-through
3773              
3774             =for example
3775              
3776             $a = rfits('foo.fits')->hcpy(0);
3777             $a = rfits('foo.fits')->hcpy(1);
3778              
3779             C sets or clears the hdrcpy flag of a PDLA, and returns the PDLA
3780             itself. That makes it convenient for inline use in expressions.
3781              
3782             =head2 set_autopthread_targ
3783              
3784             =for ref
3785              
3786             Set the target number of processor threads (pthreads) for multi-threaded processing.
3787              
3788             =for usage
3789              
3790             set_autopthread_targ($num_pthreads);
3791              
3792             C<$num_pthreads> is the target number of pthreads the auto-pthread process will try to achieve.
3793              
3794             See L for an overview of the auto-pthread process.
3795              
3796             =for example
3797              
3798             # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
3799             # PDLAs with greater than 1M elements
3800             set_autopthread_targ(2);
3801             set_autopthread_size(1);
3802              
3803             # Execute a pdl function, processing will split into two pthreads as long as
3804             # one of the pdl-threaded dimensions is divisible by 2.
3805             $a = minimum($b);
3806              
3807             # Get the actual number of pthreads that were run.
3808             $actual_pthread = get_autopthread_actual();
3809              
3810             =cut
3811              
3812             *set_autopthread_targ = \&PDLA::set_autopthread_targ;
3813              
3814             =head2 get_autopthread_targ
3815              
3816             =for ref
3817              
3818             Get the current target number of processor threads (pthreads) for multi-threaded processing.
3819              
3820             =for usage
3821              
3822             $num_pthreads = get_autopthread_targ();
3823              
3824             C<$num_pthreads> is the target number of pthreads the auto-pthread process will try to achieve.
3825              
3826             See L for an overview of the auto-pthread process.
3827              
3828             =cut
3829              
3830             *get_autopthread_targ = \&PDLA::get_autopthread_targ;
3831              
3832             =head2 get_autopthread_actual
3833              
3834             =for ref
3835              
3836             Get the actual number of pthreads executed for the last pdl processing function.
3837              
3838             =for usage
3839              
3840             $autopthread_actual = get_autopthread_actual();
3841              
3842             C<$autopthread_actual> is the actual number of pthreads executed for the last pdl processing function.
3843              
3844             See L for an overview of the auto-pthread process.
3845              
3846             =cut
3847              
3848             *get_autopthread_actual = \&PDLA::get_autopthread_actual;
3849              
3850             =head2 set_autopthread_size
3851              
3852             =for ref
3853              
3854             Set the minimum size (in M-elements or 2^20 elements) of the largest PDLA involved in a function where auto-pthreading will
3855             be performed. For small PDLAs, it probably isn't worth starting multiple pthreads, so this function
3856             is used to define a minimum threshold where auto-pthreading won't be attempted.
3857              
3858             =for usage
3859              
3860             set_autopthread_size($size);
3861              
3862             C<$size> is the mimumum size, in M-elements or 2^20 elements (approx 1e6 elements) for the largest PDLA involved in a function.
3863              
3864             See L for an overview of the auto-pthread process.
3865              
3866             =for example
3867              
3868             # Example turning on auto-pthreading for a target of 2 pthreads and for functions involving
3869             # PDLAs with greater than 1M elements
3870             set_autopthread_targ(2);
3871             set_autopthread_size(1);
3872              
3873             # Execute a pdl function, processing will split into two pthreads as long as
3874             # one of the pdl-threaded dimensions is divisible by 2.
3875             $a = minimum($b);
3876              
3877             # Get the actual number of pthreads that were run.
3878             $actual_pthread = get_autopthread_actual();
3879              
3880             =cut
3881              
3882             *set_autopthread_size = \&PDLA::set_autopthread_size;
3883              
3884             =head2 get_autopthread_size
3885              
3886             =for ref
3887              
3888             Get the current autopthread_size setting.
3889              
3890             =for usage
3891              
3892             $autopthread_size = get_autopthread_size();
3893              
3894             C<$autopthread_size> is the mimumum size limit for auto_pthreading to occur, in M-elements or 2^20 elements (approx 1e6 elements) for the largest PDLA involved in a function
3895              
3896             See L for an overview of the auto-pthread process.
3897              
3898             =cut
3899              
3900             *get_autopthread_size = \&PDLA::get_autopthread_size;
3901              
3902             =head1 AUTHOR
3903              
3904             Copyright (C) Karl Glazebrook (kgb@aaoepp.aao.gov.au),
3905             Tuomas J. Lukka, (lukka@husc.harvard.edu) and Christian
3906             Soeller (c.soeller@auckland.ac.nz) 1997.
3907             Modified, Craig DeForest (deforest@boulder.swri.edu) 2002.
3908             All rights reserved. There is no warranty. You are allowed
3909             to redistribute this software / documentation under certain
3910             conditions. For details, see the file COPYING in the PDLA
3911             distribution. If this file is separated from the PDLA distribution,
3912             the copyright notice should be included in the file.
3913              
3914             =cut
3915              
3916             #
3917             # Easier to implement in perl than in XS...
3918             # -- CED
3919             #
3920              
3921             sub PDLA::fhdr {
3922 0     0 0   my $pdl = shift;
3923              
3924 0 0 0       return $pdl->hdr
3925             if( (defined $pdl->gethdr) ||
3926             !defined $Astro::FITS::Header::VERSION
3927             );
3928              
3929             # Avoid bug in 1.15 and earlier Astro::FITS::Header
3930 0           my @hdr = ("SIMPLE = T");
3931 0           my $hdr = new Astro::FITS::Header(Cards=>\@hdr);
3932 0           tie my %hdr, "Astro::FITS::Header", $hdr;
3933 0           $pdl->sethdr(\%hdr);
3934 0           return \%hdr;
3935             }
3936              
3937 117     117   1276 use Fcntl;
  117         1163  
  117         55397  
3938              
3939             BEGIN {
3940 117     117   10338 eval 'use File::Map 0.47 qw(:all)';
  117     117   93104  
  117         984797  
  117         795  
3941 117 50       91098 if ($@) {
  0         0  
3942 0 0       0 carp "No File::Map found, using legacy mmap (if available)\n" if $PDLA::verbose;
3943             sub sys_map;
3944             sub PROT_READ();
3945             sub PROT_WRITE();
3946             sub MAP_SHARED();
3947             sub MAP_PRIVATE();
3948             }
3949             }
3950              
3951             # Implement File::Map::sys_map bug fix. Also, might be possible
3952             # to implement without so many external (non-Core perl) modules.
3953             #
3954             # sub pdl_do_sys_map {
3955             # my (undef, $length, $protection, $flags, $fh, $offset) = @_;
3956             # my $utf8 = File::Map::_check_layers($fh);
3957             # my $fd = ($flags & MAP_ANONYMOUS) ? (-1) : fileno($fh);
3958             # $offset ||= 0;
3959             # File::Map::_mmap_impl($_[0], $length, $protection, $flags, $fd, $offset, $utf8);
3960             # return;
3961             # }
3962              
3963             sub PDLA::set_data_by_file_map {
3964 0     0 0   my ($pdl,$name,$len,$shared,$writable,$creat,$mode,$trunc) = @_;
3965 0           my $pdl_dataref = $pdl->get_dataref();
3966              
3967             # Assume we have no data to free for now
3968             # pdl_freedata($pdl);
3969              
3970 0 0 0       sysopen(my $fh, $name, ($writable && $shared ? O_RDWR : O_RDONLY) | ($creat ? O_CREAT : 0), $mode)
    0          
    0          
3971             or die "Error opening file '$name'\n";
3972              
3973 0           binmode $fh;
3974              
3975 0 0         if ($trunc) {
3976 0 0         truncate($fh,0) or die "set_data_by_mmap: truncate('$name',0) failed, $!";
3977 0 0         truncate($fh,$len) or die "set_data_by_mmap: truncate('$name',$len) failed, $!";
3978             }
3979              
3980 0 0         if ($len) {
3981              
3982             #eval {
3983             # pdl_do_sys_map( # will croak if the mapping fails
3984 0 0         if ($PDLA::debug) {
3985 0 0         printf STDERR
    0          
3986             "set_data_by_file_map: calling sys_map(%s,%d,%d,%d,%s,%d)\n",
3987             $pdl_dataref,
3988             $len,
3989             PROT_READ | ($writable ? PROT_WRITE : 0),
3990             ($shared ? MAP_SHARED : MAP_PRIVATE),
3991             $fh,
3992             0;
3993             }
3994              
3995             sys_map( # will croak if the mapping fails
3996 0 0         ${$pdl_dataref},
  0 0          
3997             $len,
3998             PROT_READ | ($writable ? PROT_WRITE : 0),
3999             ($shared ? MAP_SHARED : MAP_PRIVATE),
4000             $fh,
4001             0
4002             );
4003             #};
4004              
4005             #if ($@) {
4006             #die("Error mmapping!, '$@'\n");
4007             #}
4008              
4009 0           $pdl->upd_data;
4010              
4011 0 0         if ($PDLA::debug) {
4012 0           printf STDERR "set_data_by_file_map: length \${\$pdl_dataref} is %d.\n", length ${$pdl_dataref};
  0            
4013             }
4014 0           $pdl->set_state_and_add_deletedata_magic( length ${$pdl_dataref} );
  0            
4015              
4016             } else {
4017              
4018             # Special case: zero-length file
4019 0           $_[0] = undef;
4020             }
4021              
4022             # PDLADEBUG_f(printf("PDLA::MMap: mapped to %p\n",$pdl->data));
4023 0           close $fh ;
4024             }
4025              
4026             1;