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

Last change on this file since 238 was 238, checked in by pinsard, 17 years ago

improvements/corrections of some *.pro headers

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