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
Line 
1;+
2;
3; @file_comments
4; Utility function, adapted from CMPRODUCT
5;
6; @param X
7;
8; @version
9; $Id$
10;
11; @todo seb
12;-
13;
14FUNCTION cmapply_product, x
15;
16  compile_opt idl2, strictarrsubs
17;
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;+
31;
32; @file_comments
33; cmapply_redim : Utility function, used to collect collaped dimensions
34;
35; @param newarr
36;
37; @param dimapply
38;
39; @param dimkeep
40;
41; @param nkeep
42;
43; @param totcol
44;
45; @param totkeep
46;
47; @todo seb
48;
49;-
50;
51PRO cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
52;
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
76;Main function
77;+
78;
79; @file_comments
80; Applies a function to specified dimensions of an array
81;
82; Description:
83;
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.
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
94;     *     - Performs a product                 LOG_2[no. of collapsed elts.]
95;
96;     MIN   - Finds the minimum value            smaller of no. of collapsed
97;     MAX   - Finds the maximum value            or output elements
98;
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
122;   functions is not particularly optimized for speed. Users are
123;   encouraged to implement their own array if the number of output
124;   elements is large.
125;
126; @categories
127; Array
128;
129; @param OP {in}{required}{type=string}
130; The operation to perform, as a string.  May be upper or lower case.
131;
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.
135;
136; @param ARRAY {in}{required}{type=array}
137; An array of values to be operated on.
138; Must not be of type STRING (7) or STRUCTURE (8).
139;
140; @param dimapply {in}{optional}{default=1 (ie, first dimension)}{type=array}
141; An array of dimensions that are to be "collapsed", where
142; the first dimension starts with 1 (ie, same convention
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.
149;
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.
154;
155; @keyword TYPE {default=same as input type}
156; Set this to the IDL code of the desired output type (refer
157; to documentation of <proidl>SIZE</proidl>()).  Internal results will be
158; rounded to the nearest integer if the output type is an
159; integer type.
160;
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)
168;
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.
174;
175; @examples
176;
177;   First example:  Shows how CMAPPLY can be used to total the second dimension of the
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;
185;   Second example:  Input is assumed to be an 5x100 array of 1's and
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;
199;   Third example:  Shows sum over first and third dimensions in an
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;
207;   Fourth example:  A user-function (MEDIAN) is used:
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;
214;   (OUT[i,j] is the median value of IN[i,j,*])
215;
216; @history
217; Mar 1998, Written, CM
218;   Changed usage message to not bomb, 24 Mar 2000, CM
219;   Significant rewrite for *, MIN and MAX (inspired by Todd Clements
220;     <Todd_Clements\@alumni.hmc.edu>); FOR loop indices are now type
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
227;
228;  Author: Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
229;  craigm\@lheamail.gsfc.nasa.gov
230;
231; @version
232; $Id$
233;
234;-
235;
236FUNCTION cmapply, op, array, dimapply, double=dbl, type=type, $
237                  functargs=functargs, nocatch=nocatch
238;
239  compile_opt idl2, strictarrsubs
240;
241
242  if n_params() LT 2 then begin
243      message, "USAGE: XX = CMAPPLY('OP',ARRAY,2)", /info
244      message, '       where OP is +, *, AND, OR, MIN, MAX', /info
245      return, -1L
246  endif
247  if NOT keyword_set(nocatch) then $
248    on_error, 2 $
249  else $
250    on_error, 0
251
252  ;; Parameter checking
253  ;; 1) the dimensions of the array
254  sz = size(array)
255  if sz[0] EQ 0 then $
256    message, 'ERROR: ARRAY must be an array!'
257
258  ;; 2) The type of the array
259  if sz[sz[0]+1] EQ 0 OR sz[sz[0]+1] EQ 7 OR sz[sz[0]+1] EQ 8 then $
260    message, 'ERROR: Cannot apply to UNDEFINED, STRING, or STRUCTURE'
261  if n_elements(type) EQ 0 then type = sz[sz[0]+1]
262
263  ;; 3) The type of the operation
264  szop = size(op)
265  if szop[szop[0]+1] NE 7 then $
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 ]
271  dimapply = dimapply[sort(dimapply)]   ; Sort in ascending order
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
282  newarr = reform(newarr, sz[1:sz[0]], /overwrite)
283  case 1 of
284
285      ;; *** Addition
286      (newop EQ '+'): begin
287          for i = 0L, napply-1 do begin
288              newarr = total(temporary(newarr), dimapply[i]-i, double=dbl)
289          endfor
290      end
291
292      ;; *** Multiplication
293      (newop EQ '*'): begin ;; Multiplication (by summation of logarithms)
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)
297              return, (cmapply_product(newarr))[0]
298          endif
299
300          result = cmapply_product(newarr)
301          result = reform(result, sz[dimkeep+1], /overwrite)
302          return, result
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
309          for i = 0L, napply-1 do begin
310              newarr = total(temporary(newarr), dimapply[i]-i)
311              totelt = totelt * sz[dimapply[i]]
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
317      ;; Operations requiring a little more attention over how to
318      ;; iterate
319      ((newop EQ 'MAX') OR (newop EQ 'MIN')): begin
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
325
326          ;; Next task: create result array
327          result = make_array(totkeep, type=type)
328
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
333              result[0] = reform(newarr[0,*],totkeep,/overwrite)
334              case newop of
335                  'MAX': for i = 1L, totcol-1 do $
336                    result[0] = result > newarr[i,*]
337                  'MIN': for i = 1L, totcol-1 do $
338                    result[0] = result < newarr[i,*]
339              endcase
340          endif else begin
341              ;; Iterate over the number of output elements
342              case newop of
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])
345              endcase
346          endelse
347
348          result = reform(result, sz[dimkeep+1], /overwrite)
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)
363          endif
364
365          ;; Next task: create result array
366          result = make_array(totkeep, type=type)
367
368          ;; Iterate over the number of output elements
369          if n_elements(functargs) GT 0 then begin
370              for i = 0L, totkeep-1 do $
371                result[i] = call_function(functname, newarr[*,i], _EXTRA=functargs)
372          endif else begin
373              for i = 0L, totkeep-1 do $
374                result[i] = call_function(functname, newarr[*,i])
375          endelse
376
377          result = reform(result, sz[dimkeep+1], /overwrite)
378          return, result
379      end
380
381
382  endcase
383
384  newsz = size(newarr)
385  if type EQ newsz[newsz[0]+1] then return, newarr
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 $
391    return, call_function(castfns[type], round(newarr)) $
392  else $
393    return, call_function(castfns[type], newarr)
394end
Note: See TracBrowser for help on using the repository browser.