source: trunk/SRC/Matrix/cmapply.pro @ 510

Last change on this file since 510 was 495, checked in by pinsard, 10 years ago

fix thanks to coding rules; typo; dupe empty lines; trailing blanks

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 13.0 KB
RevLine 
[2]1;+
[232]2;
[136]3; @file_comments
4; Utility function, adapted from CMPRODUCT
5;
[163]6; @param X
7;
[238]8; @version
[237]9; $Id$
[163]10;
[133]11; @todo seb
12;-
[237]13FUNCTION cmapply_product, x
[2]14;
[133]15  compile_opt idl2, strictarrsubs
[2]16;
[133]17  sz = size(x)
18  n = sz[1]
19
20  while n GT 1 do begin
21      if (n mod 2) EQ 1 then x[0,*] = x[0,*] * x[n-1,*]
22      n2 = floor(n/2)
23      x = x[0:n2-1,*] * x[n2:*,*]
24      n = n2
25  endwhile
26  return, reform(x[0,*], /overwrite)
27end
28
29;+
[237]30;
[136]31; @file_comments
[493]32; cmapply_redim : Utility function, used to collect collapsed dimensions
[136]33;
[163]34; @param newarr
35;
36; @param dimapply
37;
38; @param dimkeep
39;
40; @param nkeep
41;
42; @param totcol
43;
44; @param totkeep
45;
[237]46; @todo seb
[163]47;
[133]48;-
[237]49PRO cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
[2]50;
[133]51  compile_opt idl2, strictarrsubs
52;
53  sz = size(newarr)
54  ;; First task: rearrange dimensions so that the dimensions
55  ;; that are "kept" (ie, uncollapsed) are at the back
56  dimkeep = where(histogram(dimapply,min=1,max=sz[0]) ne 1, nkeep)
57  if nkeep EQ 0 then return
58
59  newarr = transpose(temporary(newarr), [dimapply-1, dimkeep])
60  ;; totcol is the total number of collapsed elements
61  totcol = sz[dimapply[0]]
62  for i = 1, n_elements(dimapply)-1 do totcol = totcol * sz[dimapply[i]]
63  totkeep = sz[dimkeep[0]+1]
64  for i = 1, n_elements(dimkeep)-1 do totkeep = totkeep * sz[dimkeep[i]+1]
65
66  ;; this new array has two dimensions:
67  ;;   * the first, all elements that will be collapsed
68  ;;   * the second, all dimensions that will be preserved
69  ;; (the ordering is so that all elements to be collapsed are
70  ;;  adjacent in memory)
71  newarr = reform(newarr, [totcol, totkeep], /overwrite)
72end
73
[237]74;Main function
[133]75;+
76;
[136]77; @file_comments
[133]78; Applies a function to specified dimensions of an array
79;
[136]80; Description:
[133]81;
[136]82; CMAPPLY will apply one of a few select functions to specified
83; dimensions of an array.  Unlike some IDL functions, you *do* have
84; a choice of which dimensions that are to be "collapsed" by this
85; function.  Iterative loops are avoided where possible, for
86; performance reasons.
[2]87;
88;   The possible functions are:             (and number of loop iterations:)
89;     +     - Performs a sum (as in TOTAL)       number of collapsed dimensions
90;     AND   - Finds LOGICAL "AND" (not bitwise)  same
91;     OR    - Finds LOGICAL "OR"  (not bitwise)  same
[31]92;     *     - Performs a product                 LOG_2[no. of collapsed elts.]
[2]93;
[31]94;     MIN   - Finds the minimum value            smaller of no. of collapsed
95;     MAX   - Finds the maximum value            or output elements
[2]96;
[31]97;     USER  - Applies user-defined function      no. of output elements
98;
99;   It is possible to perform user-defined operations arrays using
100;   CMAPPLY.  The OP parameter is set to 'USER:FUNCTNAME', where
101;   FUNCTNAME is the name of a user-defined function.  The user
102;   defined function should be defined such that it accepts a single
103;   parameter, a vector, and returns a single scalar value.  Here is a
104;   prototype for the function definition:
105;
106;      FUNCTION FUNCTNAME, x, KEYWORD1=key1, ...
107;         scalar = ... function of x or keywords ...
108;         RETURN, scalar
109;      END
110;
111;   The function may accept keywords.  Keyword values are passed in to
112;   CMAPPLY through the FUNCTARGS keywords parameter, and passed to
113;   the user function via the _EXTRA mechanism.  Thus, while the
114;   definition of the user function is highly constrained in the
115;   number of positional parameters, there is absolute freedom in
116;   passing keyword parameters.
117;
118;   It's worth noting however, that the implementation of user-defined
[238]119;   functions is not particularly optimized for speed. Users are
[31]120;   encouraged to implement their own array if the number of output
121;   elements is large.
122;
[238]123; @categories
[157]124; Array
[31]125;
[163]126; @param OP {in}{required}{type=string}
[136]127; The operation to perform, as a string.  May be upper or lower case.
[2]128;
[136]129; If a user-defined operation is to be passed, then OP is of
130; the form, 'USER:FUNCTNAME', where FUNCTNAME is the name of
131; the user-defined function.
[31]132;
[238]133; @param ARRAY {in}{required}{type=array}
[136]134; An array of values to be operated on.
135; Must not be of type STRING (7) or STRUCTURE (8).
[2]136;
[163]137; @param dimapply {in}{optional}{default=1 (ie, first dimension)}{type=array}
[136]138; An array of dimensions that are to be "collapsed", where
[238]139; the first dimension starts with 1 (ie, same convention
[136]140; as IDL function TOTAL).  Whereas TOTAL only allows one
141; dimension to be added, you can specify multiple dimensions
142; to CMAPPLY.  Order does not matter, since all operations
143; are associative and transitive.  NOTE: the dimensions refer
144; to the *input* array, not the output array.  IDL allows a
145; maximum of 8 dimensions.
[2]146;
[136]147; @keyword DOUBLE {default=not set}
148; Set this if you wish the internal computations to be done
149; in double precision if necessary.  If ARRAY is double
150; precision (real or complex) then DOUBLE=1 is implied.
[2]151;
[163]152; @keyword TYPE {default=same as input type}
[136]153; Set this to the IDL code of the desired output type (refer
[260]154; to documentation of <proidl>SIZE</proidl>). Internal results will be
[136]155; rounded to the nearest integer if the output type is an
156; integer type.
[2]157;
[136]158; @keyword FUNCTARGS
159; If OP is 'USER:...', then the contents of this keyword
160; are passed to the user function using the _EXTRA
161; mechanism.  This way you can pass additional data to
162; your user-supplied function, via keywords, without
163; using common blocks.
164; DEFAULT: undefined (i.e., no keywords passed by _EXTRA)
[31]165;
[136]166; @returns
167; An array of the required TYPE, whose elements are the result of
168; the requested operation.  Depending on the operation and number of
169; elements in the input array, the result may be vulnerable to
170; overflow or underflow.
[2]171;
[136]172; @examples
173;
[495]174;   First example:
175;   Shows how <pro>cmapply</pro> can be used to total the second dimension of
[260]176;   the array called IN. This is equivalent to OUT = TOTAL(IN, 2)
[2]177;
178;   IDL> IN  = INDGEN(5,5)
179;   IDL> OUT = CMAPPLY('+', IN, [2])
180;   IDL> HELP, OUT
181;   OUT             INT       = Array[5]
182;
[133]183;   Second example:  Input is assumed to be an 5x100 array of 1's and
[2]184;   0's indicating the status of 5 detectors at 100 points in time.
185;   The desired output is an array of 100 values, indicating whether
186;   all 5 detectors are on (=1) at one time.  Use the logical AND
187;   operation.
188;
189;   IDL> IN = detector_status             ; 5x100 array
190;   IDL> OUT = CMAPPLY('AND', IN, [1])    ; collapses 1st dimension
191;   IDL> HELP, OUT
192;   OUT             BYTE      = Array[100]
193;
194;   (note that MIN could also have been used in this particular case,
195;   although there would have been more loop iterations).
196;
[133]197;   Third example:  Shows sum over first and third dimensions in an
[2]198;   array with dimensions 4x4x4:
199;
200;   IDL> IN = INDGEN(4,4,4)
201;   IDL> OUT = CMAPPLY('+', IN, [1,3])
202;   IDL> PRINT, OUT
203;        408     472     536     600
204;
[133]205;   Fourth example:  A user-function (MEDIAN) is used:
[31]206;
207;   IDL> IN = RANDOMN(SEED,10,10,5)
208;   IDL> OUT = CMAPPLY('USER:MEDIAN', IN, 3)
209;   IDL> HELP, OUT
210;   OUT             FLOAT     = Array[10, 10]
211;
[114]212;   (OUT[i,j] is the median value of IN[i,j,*])
[31]213;
[238]214; @history
[232]215; Mar 1998, Written, CM
[31]216;   Changed usage message to not bomb, 24 Mar 2000, CM
[163]217;   Significant rewrite for *, MIN and MAX (inspired by Todd Clements
[136]218;     <Todd_Clements\@alumni.hmc.edu>); FOR loop indices are now type
[31]219;     LONG; copying terms are liberalized, CM, 22, Aug 2000
220;   More efficient MAX/MIN (inspired by Alex Schuster), CM, 25 Jan
221;     2002
222;   Make new MAX/MIN actually work with 3d arrays, CM, 08 Feb 2002
223;   Add user-defined functions, ON_ERROR, CM, 09 Feb 2002
224;   Correct bug in MAX/MIN initialization of RESULT, CM, 05 Dec 2002
[2]225;
[133]226;  Author: Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
[136]227;  craigm\@lheamail.gsfc.nasa.gov
[31]228;
[238]229; @version
[232]230; $Id$
[133]231;
[2]232;-
[262]233FUNCTION cmapply, op, array, dimapply, DOUBLE=dbl, TYPE=type, $
234                  FUNCTARGS=functargs, NOCATCH=nocatch
[114]235;
236  compile_opt idl2, strictarrsubs
237;
[31]238
[2]239  if n_params() LT 2 then begin
240      message, "USAGE: XX = CMAPPLY('OP',ARRAY,2)", /info
[31]241      message, '       where OP is +, *, AND, OR, MIN, MAX', /info
[2]242      return, -1L
243  endif
[31]244  if NOT keyword_set(nocatch) then $
245    on_error, 2 $
246  else $
247    on_error, 0
[2]248
249  ;; Parameter checking
250  ;; 1) the dimensions of the array
251  sz = size(array)
[114]252  if sz[0] EQ 0 then $
[2]253    message, 'ERROR: ARRAY must be an array!'
254
255  ;; 2) The type of the array
[114]256  if sz[sz[0]+1] EQ 0 OR sz[sz[0]+1] EQ 7 OR sz[sz[0]+1] EQ 8 then $
[2]257    message, 'ERROR: Cannot apply to UNDEFINED, STRING, or STRUCTURE'
[114]258  if n_elements(type) EQ 0 then type = sz[sz[0]+1]
[2]259
260  ;; 3) The type of the operation
261  szop = size(op)
[114]262  if szop[szop[0]+1] NE 7 then $
[2]263    message, 'ERROR: operation OP was not a string'
264
265  ;; 4) The dimensions to apply (default is to apply to first dim)
266  if n_params() EQ 2 then dimapply = 1
267  dimapply = [ dimapply ]
[114]268  dimapply = dimapply[sort(dimapply)]   ; Sort in ascending order
[2]269  napply = n_elements(dimapply)
270
271  ;; 5) Use double precision if requested or if needed
272  if n_elements(dbl) EQ 0 then begin
273      dbl=0
274      if type EQ 5 OR type EQ 9 then dbl=1
275  endif
276
277  newop = strupcase(op)
278  newarr = array
[114]279  newarr = reform(newarr, sz[1:sz[0]], /overwrite)
[2]280  case 1 of
281
282      ;; *** Addition
283      (newop EQ '+'): begin
[31]284          for i = 0L, napply-1 do begin
[114]285              newarr = total(temporary(newarr), dimapply[i]-i, double=dbl)
[2]286          endfor
287      end
288
289      ;; *** Multiplication
290      (newop EQ '*'): begin ;; Multiplication (by summation of logarithms)
[31]291          cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
292          if nkeep EQ 0 then begin
293              newarr = reform(newarr, n_elements(newarr), 1, /overwrite)
[114]294              return, (cmapply_product(newarr))[0]
[31]295          endif
296
297          result = cmapply_product(newarr)
[114]298          result = reform(result, sz[dimkeep+1], /overwrite)
[31]299          return, result
[2]300      end
301
302      ;; *** LOGICAL AND or OR
303      ((newop EQ 'AND') OR (newop EQ 'OR')): begin
304          newarr = temporary(newarr) NE 0
305          totelt = 1L
[31]306          for i = 0L, napply-1 do begin
[114]307              newarr = total(temporary(newarr), dimapply[i]-i)
308              totelt = totelt * sz[dimapply[i]]
[2]309          endfor
310          if newop EQ 'AND' then return, (round(newarr) EQ totelt)
311          if newop EQ 'OR'  then return, (round(newarr) NE 0)
312      end
313
[31]314      ;; Operations requiring a little more attention over how to
315      ;; iterate
[2]316      ((newop EQ 'MAX') OR (newop EQ 'MIN')): begin
[31]317          cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
318          if nkeep EQ 0 then begin
319              if newop EQ 'MAX' then return, max(newarr)
320              if newop EQ 'MIN' then return, min(newarr)
321          endif
[136]322
[31]323          ;; Next task: create result array
324          result = make_array(totkeep, type=type)
[136]325
[31]326          ;; Now either iterate over the number of output elements, or
327          ;; the number of collapsed elements, whichever is smaller.
328          if totcol LT totkeep then begin
329              ;; Iterate over the number of collapsed elements
[114]330              result[0] = reform(newarr[0,*],totkeep,/overwrite)
[136]331              case newop of
[31]332                  'MAX': for i = 1L, totcol-1 do $
[114]333                    result[0] = result > newarr[i,*]
[31]334                  'MIN': for i = 1L, totcol-1 do $
[114]335                    result[0] = result < newarr[i,*]
[2]336              endcase
[31]337          endif else begin
338              ;; Iterate over the number of output elements
[136]339              case newop of
[114]340                  'MAX': for i = 0L, totkeep-1 do result[i] = max(newarr[*,i])
341                  'MIN': for i = 0L, totkeep-1 do result[i] = min(newarr[*,i])
[31]342              endcase
343          endelse
344
[114]345          result = reform(result, sz[dimkeep+1], /overwrite)
[31]346          return, result
347      end
348
349      ;; User function
350      (strmid(newop,0,4) EQ 'USER'): begin
351          functname = strmid(newop,5)
352          if functname EQ '' then $
353            message, 'ERROR: '+newop+' is not a valid operation'
354
355          cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
356          if nkeep EQ 0 then begin
357              if n_elements(functargs) GT 0 then $
358                return, call_function(functname, newarr, _EXTRA=functargs)
359              return, call_function(functname, newarr)
[2]360          endif
[136]361
[2]362          ;; Next task: create result array
[31]363          result = make_array(totkeep, type=type)
[136]364
[31]365          ;; Iterate over the number of output elements
366          if n_elements(functargs) GT 0 then begin
367              for i = 0L, totkeep-1 do $
[114]368                result[i] = call_function(functname, newarr[*,i], _EXTRA=functargs)
[31]369          endif else begin
370              for i = 0L, totkeep-1 do $
[114]371                result[i] = call_function(functname, newarr[*,i])
[31]372          endelse
[2]373
[114]374          result = reform(result, sz[dimkeep+1], /overwrite)
[2]375          return, result
376      end
[31]377
[2]378  endcase
379
380  newsz = size(newarr)
[114]381  if type EQ newsz[newsz[0]+1] then return, newarr
[2]382
383  ;; Cast the result into the desired type, if necessary
384  castfns = ['UNDEF', 'BYTE', 'FIX', 'LONG', 'FLOAT', $
385             'DOUBLE', 'COMPLEX', 'UNDEF', 'UNDEF', 'DCOMPLEX' ]
386  if type GE 1 AND type LE 3 then $
[114]387    return, call_function(castfns[type], round(newarr)) $
[2]388  else $
[114]389    return, call_function(castfns[type], newarr)
[2]390end
Note: See TracBrowser for help on using the repository browser.