Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Storage/ILRange.cs @ 9102

Last change on this file since 9102 was 9102, checked in by gkronber, 11 years ago

#1967: ILNumerics source for experimentation

File size: 22.2 KB
Line 
1///
2///    This file is part of ILNumerics Community Edition.
3///
4///    ILNumerics Community Edition - high performance computing for applications.
5///    Copyright (C) 2006 - 2012 Haymo Kutschbach, http://ilnumerics.net
6///
7///    ILNumerics Community Edition is free software: you can redistribute it and/or modify
8///    it under the terms of the GNU General Public License version 3 as published by
9///    the Free Software Foundation.
10///
11///    ILNumerics Community Edition is distributed in the hope that it will be useful,
12///    but WITHOUT ANY WARRANTY; without even the implied warranty of
13///    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14///    GNU General Public License for more details.
15///
16///    You should have received a copy of the GNU General Public License
17///    along with ILNumerics Community Edition. See the file License.txt in the root
18///    of your distribution package. If not, see <http://www.gnu.org/licenses/>.
19///
20///    In addition this software uses the following components and/or licenses:
21///
22///    =================================================================================
23///    The Open Toolkit Library License
24///   
25///    Copyright (c) 2006 - 2009 the Open Toolkit library.
26///   
27///    Permission is hereby granted, free of charge, to any person obtaining a copy
28///    of this software and associated documentation files (the "Software"), to deal
29///    in the Software without restriction, including without limitation the rights to
30///    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
31///    the Software, and to permit persons to whom the Software is furnished to do
32///    so, subject to the following conditions:
33///
34///    The above copyright notice and this permission notice shall be included in all
35///    copies or substantial portions of the Software.
36///
37///    =================================================================================
38///   
39
40using System;
41using ILNumerics;
42using ILNumerics.Misc;
43using ILNumerics.Exceptions;
44using ILNumerics.Data;
45using System.Collections.Generic;
46using System.Linq.Expressions;
47
48namespace ILNumerics.Storage {
49
50  /// <summary>
51  /// base class for ranges, used to define subarray ranges
52    /// </summary>
53  /// <description>ILRange is used to define those parts of indices of an array,
54    /// which are to be extracted into a new subarray.
55    /// The class (and derived classes) parse indices given for each dimension and expand them into a 2-dimensional
56    /// integer array, needed for fast element traversal.
57    /// <para>The class is internally used only and not intended to be used from outside ILNumerics.</para></description>
58  internal abstract class ILRange : IDisposable {
59
60    /// <summary>
61    /// hold ranges as 2 dimensional System.Array
62    /// </summary>
63    protected ILIntList[] m_range;
64        /// <summary>
65        /// for performance reasons: give reference to internal array
66        /// </summary>
67        internal ILIntList[] RangeArray {
68            get{
69                return m_range;
70            }
71        }
72    /// <summary>
73    /// Index access for ILRange objects. Set/returns Index array for specified dimension.
74        /// </summary>
75        /// <remarks>A reference to the internal object will be returned directly! (performance)</remarks>
76    internal ILIntList this [int idx] {
77      get {
78        return m_range[idx];
79            }
80    }
81    /// <summary>
82    /// Index access for ILRange objects. returns the destIndex destination dimension for dimension specifyied by dimNr.
83    /// </summary>
84    /// <remarks>The access is readonly! No checks are made, if the requested indices exist.</remarks>
85    internal int this [int dimNr,int destIndx ] {
86      get {
87        return m_range[dimNr][destIndx];
88      }
89    }
90
91        internal void ILRanges() {}
92
93    /// <summary>
94    /// Evaluates (maps) index array on my range.
95    /// </summary>
96    /// <param name="idx">int array indexing location inside this range</param>
97        /// <param name="retIdx">(output) also return the result into array given</param>
98    /// <returns>Mapped int[] array. It can be used for direct addressing the physical storage object.</returns>
99        /// <remarks>retIdx must be at least of length m_nrDims. No check is made for this assumption!</remarks>
100    internal int[] Map(int[] idx, ref int [] retIdx) {
101            int tmpVal;
102      for (int d = 0; d < m_size.NumberOfDimensions; d++) {
103        tmpVal = m_range[d][0];
104                if (tmpVal < 0)
105                    retIdx[d] = idx[d];
106                else
107                    retIdx[d] = m_range[d][idx[d]];
108      }
109            return retIdx;
110    }
111        /// <summary>
112        /// parse single dimension specifier from string
113        /// </summary>
114        /// <param name="indices">valid index specification</param>
115        /// <param name="dimlen">number of elements in dimension to be parsed</param>
116        /// <returns>array with indices defined in 'indices'</returns>
117        /// <remarks>the indices are parsed the way needed for sequential addressing. This means:
118        /// full dimensions address the whole array. Full dimensions are transformed into negative
119        /// placeholder indices nevertheless! SetRange must handle that accordingly.</remarks>
120        internal static ILBaseArray ParseDimension(string indices, int dimlen) {
121            if (indices.Trim() == ":") {
122                return ILMath.full;
123            }
124            int pos = 0, min = 0, max = 0;
125            ILIntList list = ILIntList.Create();
126            expand(list, ref pos, indices, ref min, ref max, dimlen, 0, false);
127           
128            return list.ToTempArray();
129        }
130
131        protected ILSize m_size;
132        /// <summary>
133        /// Create trimmed size descriptor from indices in ILRange object
134    /// </summary>
135        /// <returns>new size descriptor with the neccessary size to define
136        /// an array as defined by all indices in this range</returns>
137    internal ILSize Size {
138            get {
139                return m_size;
140            }
141    }
142
143        #region private helper 
144        protected static void extractDimension(ILIntList target, ref int outLen, ILBaseArray A, int dim, ref int min, ref int max, int[] dimensions) {
145            if (object.Equals(A, null)) {
146                return;
147            }
148            using (ILScope.Enter(A)) {
149                int dimLen = dimensions[dim];
150                if (A is ILDenseArray<ILFullRange>) {
151                    // taken as ':' (i.e.: full)
152                    if (dimLen <= 0) return;
153                    min = 0;
154                    target.Add(-(dimLen - 1));
155                    max = dimLen - 1;
156                    outLen += dimLen;
157                } else if (A is ILBaseArray<ILRegularRange>) {
158                    (A as ILBaseArray<ILRegularRange>).GetValue(0).Expand(target, ref outLen, ref min, ref max, dimLen - 1);
159                } else if (A is ILDenseArray<double>) {
160                    expand(target, ref outLen, A as ILDenseArray<double>, ref min, ref max, dim);
161                } else if (A is ILBaseArray<Expression>) {
162                    if (dimensions[dim] > 0) {
163                        Expression exp = (A as ILBaseArray<Expression>).GetValue(0);
164                        int end = ILExpression.Evaluate(exp, dimLen - 1);
165                        target.Add(end);
166                        outLen++;
167                        if (end < min) min = end;
168                        if (end > max) max = end;
169                    }
170                } else if (A is ILDenseArray<float>) {
171                    expand(target, ref outLen, A as ILDenseArray<float>, ref min, ref max, dim);
172                } else if (A is ILDenseArray<string>) {
173                    if (!A.IsScalar)
174                        throw new ILArgumentException("string index specification: only one string is allowed per dimension");
175                    expand(target, ref outLen, (A as ILDenseArray<string>).GetValue(0), ref min, ref max, (dim < dimensions.Length) ? dimLen : 0, dim, true);
176                } else if (A is ILDenseArray<int>) {
177                    expand(target, ref outLen, A as ILDenseArray<int>, ref min, ref max, dim);
178                } else if (A is ILDenseArray<byte>) {
179                    expand(target, ref outLen, ILMath.find((A as ILDenseArray<byte>).C), ref min, ref max, dim);
180                } else if (A is ILDenseArray<Int64>) {
181                    expand(target, ref outLen, A as ILDenseArray<Int64>, ref min, ref max, dim);
182                } else if (A.Storage is ILCellStorage) {
183                    ILCellStorage cellStorage = A.Storage as ILCellStorage;
184                    for (int ind = 0; ind < cellStorage.Size.NumberOfElements; ind++ ) {
185                        extractDimension(target, ref outLen, cellStorage.GetScalar(ind), dim, ref min, ref max, dimensions);
186                    }
187                } else
188                    throw new ILArgumentException(String.Format("invalid type of index specification: '{0}'", A.GetType().Name));
189            }
190        }
191
192
193
194        protected static void expand(ILIntList target, ref int outLen, ILDenseArray</*HC:inArr1*/ double> A, ref int min, ref int max, int dimIdx) {
195            using (ILScope.Enter(A)) {
196                if (A.IsEmpty) {
197                    return;
198                }
199                if (!A.IsVector)
200                    throw new ILArgumentException("index specification must be vector sized. found: " + A.Size.ToString());
201                foreach (/*HC:inArr1*/ double val in A) {
202                    /*HC:NaNCheck*/
203                    if (Double.IsInfinity(val) || Double.IsNaN(val)) throw new ILArgumentException("invalid index specification, dimension idx " + dimIdx);
204                    Int32 v = (int)val;
205                    target.Add(v);
206                    if (v < min) min = v;
207                    if (v > max) max = v;
208                }
209                outLen += A.Length;
210            }
211        }
212
213#region HYCALPER AUTO GENERATED CODE
214
215
216        protected static void expand(ILIntList target, ref int outLen, ILDenseArray</*HC:*/ Int64> A, ref int min, ref int max, int dimIdx) {
217            using (ILScope.Enter(A)) {
218                if (A.IsEmpty) {
219                    return;
220                }
221                if (!A.IsVector)
222                    throw new ILArgumentException("index specification must be vector sized. found: " + A.Size.ToString());
223                foreach (/*HC:*/ Int64 val in A) {
224                    /*HC:NaNCheck*/
225                    if (Double.IsInfinity(val) || Double.IsNaN(val)) throw new ILArgumentException("invalid index specification, dimension idx " + dimIdx);
226                    Int32 v = (int)val;
227                    target.Add(v);
228                    if (v < min) min = v;
229                    if (v > max) max = v;
230                }
231                outLen += A.Length;
232            }
233        }
234
235        protected static void expand(ILIntList target, ref int outLen, ILDenseArray</*HC:*/ Int32> A, ref int min, ref int max, int dimIdx) {
236            using (ILScope.Enter(A)) {
237                if (A.IsEmpty) {
238                    return;
239                }
240                if (!A.IsVector)
241                    throw new ILArgumentException("index specification must be vector sized. found: " + A.Size.ToString());
242                foreach (/*HC:*/ Int32 val in A) {
243                    /*HC:NaNCheck*/
244                    if (Double.IsInfinity(val) || Double.IsNaN(val)) throw new ILArgumentException("invalid index specification, dimension idx " + dimIdx);
245                    Int32 v = (int)val;
246                    target.Add(v);
247                    if (v < min) min = v;
248                    if (v > max) max = v;
249                }
250                outLen += A.Length;
251            }
252        }
253
254        protected static void expand(ILIntList target, ref int outLen, ILDenseArray</*HC:*/ float> A, ref int min, ref int max, int dimIdx) {
255            using (ILScope.Enter(A)) {
256                if (A.IsEmpty) {
257                    return;
258                }
259                if (!A.IsVector)
260                    throw new ILArgumentException("index specification must be vector sized. found: " + A.Size.ToString());
261                foreach (/*HC:*/ float val in A) {
262                    /*HC:NaNCheck*/
263                    if (Double.IsInfinity(val) || Double.IsNaN(val)) throw new ILArgumentException("invalid index specification, dimension idx " + dimIdx);
264                    Int32 v = (int)val;
265                    target.Add(v);
266                    if (v < min) min = v;
267                    if (v > max) max = v;
268                }
269                outLen += A.Length;
270            }
271        }
272
273        protected static void expand(ILIntList target, ref int outLen, ILDenseArray</*HC:*/ byte> A, ref int min, ref int max, int dimIdx) {
274            using (ILScope.Enter(A)) {
275                if (A.IsEmpty) {
276                    return;
277                }
278                if (!A.IsVector)
279                    throw new ILArgumentException("index specification must be vector sized. found: " + A.Size.ToString());
280                foreach (/*HC:*/ byte val in A) {
281                    /*HC:NaNCheck*/
282                    if (Double.IsInfinity(val) || Double.IsNaN(val)) throw new ILArgumentException("invalid index specification, dimension idx " + dimIdx);
283                    Int32 v = (int)val;
284                    target.Add(v);
285                    if (v < min) min = v;
286                    if (v > max) max = v;
287                }
288                outLen += A.Length;
289            }
290        }
291
292#endregion HYCALPER AUTO GENERATED CODE
293
294        // parse SINGLE (!) dimension given by string
295        protected static void expand(ILIntList target, ref int outLen, string p, ref int min, ref int max, int dimLen, int dimIdx, bool useFullDimTag) {
296            // possible input: ":", "0:19", "20:-2:5", "1,2,3,4:2:16,end:-2:0,:"
297            if (p.Contains(";"))
298                throw new ILArgumentException("invalid string index specification: ambiguous dimension seperator ';'");
299            string[] parts = p.Split(',');
300            if (parts.Length == 0) {
301                // empty dimension?
302                return;
303            } else if (parts.Length > 1) {
304                foreach (string part in parts) {
305                    expand(target, ref outLen, part, ref min, ref max, dimLen, dimIdx, useFullDimTag);
306                }
307                return;
308            }
309            // only one range specifier
310            if (p.Trim() == ":") {
311                // full dimension
312                if (dimLen <= 0) return;
313                if (useFullDimTag) {
314                    target.Add(-(dimLen-1));
315                } else {
316                    for (int i = 0; i < dimLen; i++) {
317                        target.Add(i);
318                    }
319                }
320                outLen += dimLen;
321            } else {
322                int tmpValue, start, end, step;
323                string[] rngitems = p.Split(':');
324                switch (rngitems.Length) {
325                    case 1:
326                        // single number specified
327                        if (rngitems[0].Contains("end")) {
328                            if (rngitems[0].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
329                            if (dimLen <= 0) break;
330                            tmpValue = (dimLen-1);
331                        } else if (String.IsNullOrWhiteSpace(rngitems[0])) {
332                            break;   
333                        } else if (! int.TryParse(rngitems[0].Trim(),out tmpValue)) {
334                            throw new ILArgumentException(String.Format("invalid index for dimension {0}: ({1})", dimIdx,rngitems[0]));
335                        }
336                        if (tmpValue < min) min = tmpValue;
337                        if (tmpValue > max) max = tmpValue;
338                        target.Add (tmpValue);
339                        outLen++;
340                        break;
341                    case 2:
342                        // unstepped range specified
343                        if (rngitems[0].Contains("end")) {
344                            if (rngitems[0].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
345                            if (dimLen <= 0) break;
346                            start = dimLen - 1;
347                        } else if (!int.TryParse(rngitems[0],out start)) {
348                            throw new ILArgumentException("invalid start index for range in dimension " + dimIdx.ToString());                                       
349                        }
350                        if (rngitems[1].Contains("end")) {
351                            if (rngitems[1].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
352                            if (dimLen <= 0) break;
353                            end = dimLen - 1;
354                        } else if (!int.TryParse(rngitems[1],out end)) {
355                            throw new ILArgumentException("invalid end index for range in dimension " + dimIdx.ToString());                                       
356                        }
357                        step = (start <= end) ? 1 : 1; // -1 - make consistent with non-string spec: unspecified step is always 1!
358
359                        if (start<=end) {
360                            for (int t = start; t <= end;) {
361                                target.Add (t++);
362                            }
363                            if (start < min) min = start;
364                            if (end > max) max = end;
365                            outLen += (end-start)+1;
366                        } else {
367                            //for (int t = start; t >= end;) {
368                            //    target.Add (t--);
369                            //}
370                            //if (end < min) min = end;
371                            //if (start > max) max = start;
372                            //outLen += (start-end)+1
373
374                            // ^ this is not allowed: unspecified step will always avaluate to 1!
375                        }
376                        break;
377                    case 3:
378                        // stepped range specified
379                        if (rngitems[0].Contains("end")) {
380                            if (rngitems[0].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
381                            if (dimLen <= 0) break;
382                            start = dimLen - 1;
383                        } else if (!int.TryParse(rngitems[0],out start)) {
384                            throw new ILArgumentException("invalid start index for range in dimension " + dimIdx.ToString());                                       
385                        }
386                        if (rngitems[1].Contains("end")) {
387                            if (rngitems[1].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
388                            if (dimLen <= 0) break;
389                            step = dimLen - 1;
390                        } else if (!int.TryParse(rngitems[1],out step)) {
391                            throw new ILArgumentException("invalid step index for range in dimension " + dimIdx.ToString());                                       
392                        }
393                        if (rngitems[2].Contains("end")) {
394                            if (rngitems[2].Trim() != "end") throw new ILArgumentException("index expression evaluation is not supported for string definitions. Use non-string definitions instead!");
395                            if (dimLen <= 0) break;
396                            end = dimLen - 1;
397                        } else if (!int.TryParse(rngitems[2],out end)) {
398                            throw new ILArgumentException("invalid end index for range in dimension " + dimIdx.ToString());                                       
399                        }
400                        if (step == 0) {
401                            // empty
402                            return;
403                        }
404                        int i = start;
405                        if (start == end) {
406                            target.Add(start);
407                            outLen++;
408                            if (start < min) min = start;
409                            if (start > max) max = start;   
410                        } else if (start < end) {
411                            if (step < 0) return;
412                            for (; i <= end; i += step) {
413                                target.Add(i);
414                                outLen++;
415                      }
416                            if (start < min) min = start;
417                            if (i - step > max) max = i - step;   // cannot compare to end, since it may was not reached!
418                        } else {
419                            if (step > 0) return;
420                            for (; i >= end; i += step) {
421                                target.Add(i);
422                                outLen++;
423                      }
424                            if (start > max) max = start;
425                            if (i - step < min) min = i - step;
426                        }
427                        break;
428                    default:
429                        throw new ILArgumentException("invalid index for dimension " + dimIdx.ToString());
430                }
431            }
432        }
433        #endregion
434
435        #region IDisposable Members
436
437        public void Dispose() {
438            if (m_range != null) {
439                foreach (ILIntList list in m_range) {
440                    if (list != null) {
441                        list.Dispose();
442                    }
443                }
444            }
445            m_range = null;
446        }
447
448        #endregion
449    }
450}
Note: See TracBrowser for help on using the repository browser.