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
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;-
13FUNCTION cmapply_product, x
14;
15  compile_opt idl2, strictarrsubs
16;
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;+
30;
31; @file_comments
32; cmapply_redim : Utility function, used to collect collapsed dimensions
33;
34; @param newarr
35;
36; @param dimapply
37;
38; @param dimkeep
39;
40; @param nkeep
41;
42; @param totcol
43;
44; @param totkeep
45;
46; @todo seb
47;
48;-
49PRO cmapply_redim, newarr, dimapply, dimkeep, nkeep, totcol, totkeep
50;
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
74;Main function
75;+
76;
77; @file_comments
78; Applies a function to specified dimensions of an array
79;
80; Description:
81;
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.
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
92;     *     - Performs a product                 LOG_2[no. of collapsed elts.]
93;
94;     MIN   - Finds the minimum value            smaller of no. of collapsed
95;     MAX   - Finds the maximum value            or output elements
96;
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
119;   functions is not particularly optimized for speed. Users are
120;   encouraged to implement their own array if the number of output
121;   elements is large.
122;
123; @categories
124; Array
125;
126; @param OP {in}{required}{type=string}
127; The operation to perform, as a string.  May be upper or lower case.
128;
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.
132;
133; @param ARRAY {in}{required}{type=array}
134; An array of values to be operated on.
135; Must not be of type STRING (7) or STRUCTURE (8).
136;
137; @param dimapply {in}{optional}{default=1 (ie, first dimension)}{type=array}
138; An array of dimensions that are to be "collapsed", where
139; the first dimension starts with 1 (ie, same convention
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.
146;
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.
151;
152; @keyword TYPE {default=same as input type}
153; Set this to the IDL code of the desired output type (refer
154; to documentation of <proidl>SIZE</proidl>). Internal results will be
155; rounded to the nearest integer if the output type is an
156; integer type.
157;
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)
165;
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.
171;
172; @examples
173;
174;   First example:
175;   Shows how <pro>cmapply</pro> can be used to total the second dimension of
176;   the array called IN. This is equivalent to OUT = TOTAL(IN, 2)
177;
178;   IDL> IN  = INDGEN(5,5)
179;   IDL> OUT = CMAPPLY('+', IN, [2])
180;   IDL> HELP, OUT
181;   OUT             INT       = Array[5]
182;
183;   Second example:  Input is assumed to be an 5x100 array of 1's and
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;
197;   Third example:  Shows sum over first and third dimensions in an
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;
205;   Fourth example:  A user-function (MEDIAN) is used:
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;
212;   (OUT[i,j] is the median value of IN[i,j,*])
213;
214; @history
215; Mar 1998, Written, CM
216;   Changed usage message to not bomb, 24 Mar 2000, CM
217;   Significant rewrite for *, MIN and MAX (inspired by Todd Clements
218;     <Todd_Clements\@alumni.hmc.edu>); FOR loop indices are now type
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
225;
226;  Author: Craig B. Markwardt, NASA/GSFC Code 662, Greenbelt, MD 20770
227;  craigm\@lheamail.gsfc.nasa.gov
228;
229; @version
230; $Id$
231;
232;-
233FUNCTION cmapply, op, array, dimapply, DOUBLE=dbl, TYPE=type, $
234                  FUNCTARGS=functargs, NOCATCH=nocatch
235;
236  compile_opt idl2, strictarrsubs
237;
238
239  if n_params() LT 2 then begin
240      message, "USAGE: XX = CMAPPLY('OP',ARRAY,2)", /info
241      message, '       where OP is +, *, AND, OR, MIN, MAX', /info
242      return, -1L
243  endif
244  if NOT keyword_set(nocatch) then $
245    on_error, 2 $
246  else $
247    on_error, 0
248
249  ;; Parameter checking
250  ;; 1) the dimensions of the array
251  sz = size(array)
252  if sz[0] EQ 0 then $
253    message, 'ERROR: ARRAY must be an array!'
254
255  ;; 2) The type of the array
256  if sz[sz[0]+1] EQ 0 OR sz[sz[0]+1] EQ 7 OR sz[sz[0]+1] EQ 8 then $
257    message, 'ERROR: Cannot apply to UNDEFINED, STRING, or STRUCTURE'
258  if n_elements(type) EQ 0 then type = sz[sz[0]+1]
259
260  ;; 3) The type of the operation
261  szop = size(op)
262  if szop[szop[0]+1] NE 7 then $
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 ]
268  dimapply = dimapply[sort(dimapply)]   ; Sort in ascending order
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
279  newarr = reform(newarr, sz[1:sz[0]], /overwrite)
280  case 1 of
281
282      ;; *** Addition
283      (newop EQ '+'): begin
284          for i = 0L, napply-1 do begin
285              newarr = total(temporary(newarr), dimapply[i]-i, double=dbl)
286          endfor
287      end
288
289      ;; *** Multiplication
290      (newop EQ '*'): begin ;; Multiplication (by summation of logarithms)
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)
294              return, (cmapply_product(newarr))[0]
295          endif
296
297          result = cmapply_product(newarr)
298          result = reform(result, sz[dimkeep+1], /overwrite)
299          return, result
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
306          for i = 0L, napply-1 do begin
307              newarr = total(temporary(newarr), dimapply[i]-i)
308              totelt = totelt * sz[dimapply[i]]
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
314      ;; Operations requiring a little more attention over how to
315      ;; iterate
316      ((newop EQ 'MAX') OR (newop EQ 'MIN')): begin
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
322
323          ;; Next task: create result array
324          result = make_array(totkeep, type=type)
325
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
330              result[0] = reform(newarr[0,*],totkeep,/overwrite)
331              case newop of
332                  'MAX': for i = 1L, totcol-1 do $
333                    result[0] = result > newarr[i,*]
334                  'MIN': for i = 1L, totcol-1 do $
335                    result[0] = result < newarr[i,*]
336              endcase
337          endif else begin
338              ;; Iterate over the number of output elements
339              case newop of
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])
342              endcase
343          endelse
344
345          result = reform(result, sz[dimkeep+1], /overwrite)
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)
360          endif
361
362          ;; Next task: create result array
363          result = make_array(totkeep, type=type)
364
365          ;; Iterate over the number of output elements
366          if n_elements(functargs) GT 0 then begin
367              for i = 0L, totkeep-1 do $
368                result[i] = call_function(functname, newarr[*,i], _EXTRA=functargs)
369          endif else begin
370              for i = 0L, totkeep-1 do $
371                result[i] = call_function(functname, newarr[*,i])
372          endelse
373
374          result = reform(result, sz[dimkeep+1], /overwrite)
375          return, result
376      end
377
378  endcase
379
380  newsz = size(newarr)
381  if type EQ newsz[newsz[0]+1] then return, newarr
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 $
387    return, call_function(castfns[type], round(newarr)) $
388  else $
389    return, call_function(castfns[type], newarr)
390end
Note: See TracBrowser for help on using the repository browser.