Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Array/ILLogical.cs @ 12005

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

#1967: ILNumerics source for experimentation

File size: 21.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.Storage;
45using ILNumerics.Native;
46using System.Text;
47
48namespace ILNumerics {
49    /// <summary>
50    /// Boolean array for high performance relational operations on arbitrary arrays
51    /// </summary>
52    /// <remarks>
53    /// Logical arrays are derived from <c><![CDATA[ILArray<byte>]]></c>. It consumes
54    /// 1 byte per element and is the output parameter of all relational comparisons
55    /// as well as the input parameter for all functions consuming <c><![CDATA[ILArray<byte>]]></c>.
56    /// The difference between arrays and logical arrays is: the logical array
57    /// stores a integer value with the number of nonzero elements as additional information.
58    /// Therefore functions like 'find' are able to determine the lenght of output array to
59    /// be created omitting the need of multiple walks through the array. Therefore ILLogicalArrays
60    /// consume (a little) more time while construction but are much more performand on functions like
61    /// 'find'.
62    /// </remarks>
63    [Serializable]
64    public sealed class ILLogical : ILBaseLogical {
65       
66        private static readonly bool s_isTempArray = false;
67
68        #region constructors
69        /// <summary>
70        /// constructor - create logical array of type <c>Byte</c> of specified size
71        /// </summary>
72        /// <param name="size">
73        /// Variable length int array specifying the number and size of dimensions to
74        /// be created.
75        /// </param>
76        /// <remarks>
77        /// The size parameter may not be null or an empty array! An Exception will be
78        /// thrown in this case. The dimensions will be trimmed before processing
79        /// (removing trailing non singleton dimensions).
80        /// Depending on the requested size an ILArray &lt; byte &gt; of the specified dimensions
81        /// will be created. The type of storage will be <c>bool</c>.
82        /// </remarks>
83        internal ILLogical(params int[] size)
84            : base(new ILLogicalStorage(new ILSize(size)), s_isTempArray) {
85            NumberNonZero = sumElements();
86        }
87        /// <summary>
88        /// constructor - create logical array of type <c>Byte</c> of specified size
89        /// </summary>
90        /// <param name="size">
91        /// dimension object
92        /// </param>
93        /// <remarks>
94        /// The size parameter may not be null. An Exception will be
95        /// thrown in this case. The dimensions will be trimmed before processing
96        /// (removing trailing singleton dimensions).
97        /// Depending on the requested size an logical array of the specified dimensions
98        /// will be created. The element type is be <c>bool</c>.
99        /// </remarks>
100        internal ILLogical(ILSize size)
101            : base(new ILLogicalStorage(size), s_isTempArray) {
102            NumberNonZero = sumElements();
103        }
104        /// <summary>
105        /// Constructor creating logical array from dense storage
106        /// </summary>
107        /// <param name="A">input array, the storage of this ILArray will directly be used for
108        /// storage of the new logical array</param>
109        internal ILLogical(ILLogicalStorage A)
110            : base(A, s_isTempArray) {
111            NumberNonZero = sumElements();
112        }
113        /// <summary>
114        /// Constructor creating logical array from (dense) storage
115        /// </summary>
116        /// <param name="A">input array, the storage of this ILArray will directly be used for
117        /// storage of the new logical array</param>
118        /// <param name="numberNonZero">number of nonzero elements in A. Must be positive or 0.</param>
119        /// <remarks> Providing this parameter prevents the constructor from having to count the
120        /// 'true' elements in A.</remarks>
121        internal ILLogical(ILLogicalStorage A, long numberNonZero)
122            : base(A, s_isTempArray) {
123            if (numberNonZero < 0)
124                throw new ILNumerics.Exceptions.ILArgumentException("invalid number of non-zero-elements given!");
125            NumberNonZero = numberNonZero;
126        }
127        /// <summary>
128        /// constructor - create logical array of specified size
129        /// from data array
130        /// </summary>
131        /// <param name="size">
132        /// Variable length int array specifying the number and size of dimensions to
133        /// be created.
134        /// </param>
135        /// <param name="data"> byte array matching the size of the dimensions
136        /// specified. The data will directly be used as storage! No copy will be made!</param>
137        /// <remarks>
138        /// The size parameter may not be null or an empty array! An Exception will be
139        /// thrown in this case. The dimensions will be trimmed before processing
140        /// (removing trailing non singleton dimensions).
141        /// Depending on the requested size an logical array of the specified size
142        /// will be created. The type of storage will be <c>byte</c>.
143        /// </remarks>
144        internal ILLogical(byte[] data, params int[] size)
145            : base(new ILLogicalStorage(data, new ILSize(size)), s_isTempArray) {
146            NumberNonZero = sumElements();
147        }
148        /// <summary>
149        /// Constructor creating logical array, provide predefined storage
150        /// </summary>
151        /// <param name="data">predefined storage elements. The array will directly be used
152        /// as underlying storage. No copy will be made! </param>
153        /// <param name="dimension">Dimensions specification.</param>
154        internal ILLogical(byte[] data, ILSize dimension)
155            : base(new ILLogicalStorage(data, dimension), s_isTempArray) {
156           NumberNonZero = sumElements();
157        }
158        /// <summary>
159        /// Constructor creating logical array, predefined storage (fast version)
160        /// </summary>
161        /// <param name="data">predefined storage elements. The array will directly be used
162        /// as underlying storage. No copy will be made! </param>
163        /// <param name="dimension">Dimensions specification.</param>
164        /// <param name="nonZeroCount">number of nonzero elements in <paramref name="data"/>.
165        /// Providing this parameter prevents from counting the 'true' elements (again). </param>
166        internal ILLogical(byte[] data, ILSize dimension, long nonZeroCount)
167            : base(new ILLogicalStorage(data, dimension), s_isTempArray) {
168            if (nonZeroCount < 0)
169                throw new ILNumerics.Exceptions.ILArgumentException("invalid number of non-zero-elements given!");
170            NumberNonZero = nonZeroCount;
171        }
172        #endregion
173
174        #region operator overloading
175        #region constructional operators
176        /// <summary>
177        /// Implicitly convert boolean scalar to logical array of size 1x1 (scalar).
178        /// </summary>
179        /// <param name="val">Boolean scalar</param>
180        /// <returns>New logical array of size 1x1 holding the only element of type Byte
181        /// with value of val.</returns>
182        public static implicit operator ILLogical(bool val) {
183            ILLogical ret = new ILLogical(new byte[1] { val ? (byte)1 : (byte)0 }, 1, 1);
184            return ret;
185        }
186        /// <summary>
187        /// Implicitly convert logical array to bool
188        /// </summary>
189        /// <param name="A">logical array</param>
190        /// <returns>true if <b>all</b> elements of A are non-zero, false otherwise
191        /// </returns>
192        /// <remarks> If A is null or empty, the function returns false. Otherwise allall returns true,
193        /// if all elements of A are non-zero and returns false, if A contains any zero elements.</remarks>
194        public static implicit operator bool(ILLogical A) {
195            // this operator is implicit for convenience reasons:
196            // if(tmp[0]!=-10.0) { ... is only possible this way
197            if (object.Equals(A, null) || A.IsEmpty)
198                return false;
199            if (A.IsScalar)
200                return A.GetValue(0, 0) == 1;
201            return ILMath.allall(A).GetValue(0) == 1;
202        }
203        /// <summary>
204        /// Implicitly convert integer scalar to logical array of size 1x1 (scalar).
205        /// </summary>
206        /// <param name="val">Scalar value</param>
207        /// <returns>New logical array of size 1x1 holding the only element of type Byte
208        /// with value of val.</returns>
209        public static implicit operator ILLogical(int val) {
210            ILLogical ret = new ILLogical(new Byte[1] {
211                                 val != 0 ? (byte)1:(byte)0 }, 1, 1);
212            return ret;
213        }
214        /// <summary>
215        /// Implicitly cast one dimensional System.Array to ILNumerics array (vector)
216        /// </summary>
217        /// <param name="A">1-dimensional system array, arbitrary type</param>
218        /// <returns>ILNumerics array of same element type as elements of A.
219        /// Row vector. If A is null: empty array.</returns>
220        /// <remarks>The System.Array A will directly be used for the new ILNumerics array!
221        /// No copy will be done! Make sure, not to reference A after this conversion!</remarks>
222        public static implicit operator ILLogical(byte[] A) {
223            if (A == null) {
224                ILLogicalStorage dS = new ILLogicalStorage(new byte[0], ILSize.Empty00);
225                return new ILLogical(dS);
226            }
227            return new ILLogical(A, 1, A.Length);
228        }
229        /// <summary>
230        /// Implicitly convert n-dim. System.Array to ILNumerics array
231        /// </summary>
232        /// <param name="A">Arbitrarily sized System.Array</param>
233        /// <returns>If A is null: empty array. Else: new ILNumerics array of the same size as A</returns>
234        /// <remarks>The inner type of input array <paramref name="A"/> must match the requested type
235        /// <typeparamref name="ElementType"/>. The resulting ILArray will reflect all dimensions of
236        /// A. Elements of A will get copied to elements of output array (shallow copy).</remarks>
237        /// <exception cref="ILNumerics.Exceptions.ILCastException"> if type of input does not match
238        /// ElementType</exception>
239        public static implicit operator ILLogical(Array elements) {
240            if (elements == null || elements.Length == 0) {
241                return new ILLogical(ILSize.Empty00);
242            }
243            if (elements.GetType().GetElementType() != typeof(byte))
244                throw new ILCastException("inner type of System.Array must match");
245            int[] dims = new int[elements.Rank];
246            byte[] retArr = ILMemoryPool.Pool.New<byte>(elements.Length);
247            int posArr = 0;
248            for (int i = 0; i < dims.Length; i++) {
249                dims[i] = elements.GetLength(dims.Length - i - 1);
250            }
251            foreach (byte item in elements)
252                retArr[posArr++] = item;
253            return new ILLogical(retArr, dims);
254        }
255        /// <summary>
256        /// Implicitly cast two dimensional System.Array to ILNumerics array
257        /// </summary>
258        /// <param name="A">2D System.Array</param>
259        /// <returns>If A is null: empty array. ILNumerics array of same size and type as A otherwise.</returns>
260        public static implicit operator ILLogical(byte[,] A) {
261            if (A == null || A.Length == 0) {
262                return new ILLogical(ILSize.Empty00);
263            }
264            int[] dims = new int[2];
265            byte[] retArr = ILMemoryPool.Pool.New<byte>(A.Length);
266            int posArr = 0;
267            for (int i = 0; i < 2; i++) {
268                dims[i] = A.GetLength(dims.Length - i - 1);
269            }
270            foreach (byte item in A)
271                retArr[posArr++] = item;
272            return new ILLogical(retArr, dims);
273        }
274        /// <summary>
275        /// Implicitly cast three dimensional System.Array to ILNumerics array
276        /// </summary>
277        /// <param name="A">3-dimensional System.Array</param>
278        /// <returns>If A is null: empty array. ILNumerics array of same size and type as A otherwise.</returns>
279        public static implicit operator ILLogical(byte[, ,] A) {
280            if (A == null || A.Length == 0) {
281                return new ILLogical(ILSize.Empty00);
282            }
283            int[] dims = new int[3];
284            byte[] retArr = ILMemoryPool.Pool.New<byte>(A.Length);
285            int posArr = 0;
286            for (int i = 0; i < 3; i++) {
287                dims[i] = A.GetLength(dims.Length - i - 1);
288            }
289            foreach (byte item in A)
290                retArr[posArr++] = item;
291            return new ILLogical(retArr, dims);
292        }
293        #endregion
294
295        #region operational operators
296        /// <summary>
297        /// Invert values of array elements
298        /// </summary>
299        /// <param name="in1">Input array</param>
300        /// <returns>New solid logical array, inverted element values</returns>
301        public static ILRetLogical operator !(ILLogical in1) {
302            if (object.Equals(in1, null))
303                throw new ILArgumentException("operator -(): parameter must not be null!");
304            return (in1 != (byte)1);
305        }
306        #endregion
307
308        #region conversional operators
309        public static implicit operator ILLogical(ILRetLogical A) {
310            if (object.Equals(A, null))
311                return null;
312            ILLogicalStorage aStorage = (ILLogicalStorage)A.GiveStorageAwayOrClone();
313            ILLogical ret = new ILLogical(aStorage, aStorage.NumberNonZero);
314            ILScope.Context.RegisterArray(ret);
315            return ret;
316        }
317        public static implicit operator ILLogical(ILInLogical A) {
318            if (object.Equals(A, null))
319                return null;
320            ILLogicalStorage storage = A.Storage;
321            ILLogical ret = new ILLogical(
322                    new ILLogicalStorage(storage.GetDataArray(), storage.Size));
323            ILScope.Context.RegisterArray(ret);
324            return ret;
325        }
326        public static implicit operator ILLogical(ILArray<byte> A) {
327            if (object.Equals(A, null))
328                return null;
329            ILLogical ret = new ILLogical(
330                new ILLogicalStorage(A.Storage.GetDataArray(), A.Size));
331            ILScope.Context.RegisterArray(ret);
332            return ret;
333        }
334        public static implicit operator ILLogical(ILInArray<byte> A) {
335            if (object.Equals(A, null))
336                return null;
337            ILLogical ret = new ILLogical(
338                new ILLogicalStorage(A.Storage.GetDataArray(), A.Size));
339            ILScope.Context.RegisterArray(ret);
340            return ret;
341        }
342
343        public static implicit operator ILArray<byte>(ILLogical A) {
344            if (object.Equals(A, null))
345                return null;
346            ILArray<byte> ret = new ILArray<byte>(
347                new ILDenseStorage<byte>(A.Storage.GetDataArray(), A.Size));
348            ILScope.Context.RegisterArray(ret);
349            return ret;
350        }
351        public static implicit operator ILInArray<byte>(ILLogical A) {
352            if (object.Equals(A,null))
353                return null;
354            ILInArray<byte> ret = new ILInArray<byte>(
355                new ILDenseStorage<byte>(A.Storage.GetDataArray(), A.Size));
356            return ret;
357        }
358        #endregion
359
360        #endregion operator overloads
361
362        #region index access + mutability
363        /// <summary>
364        /// Subarray access
365        /// </summary>
366        /// <param name="range">Range specification</param>
367        /// <returns>Reference pointing to the elements of this array specified by range. If used for removal:
368        /// the array will be changed to a referencing array having the parts requested removed and reshaped accordingly.</returns>
369        /// <remarks>Query access: for N-dimensional arrays trailing dimensions will be choosen to be 0. Therefore you
370        /// may ommit those trailing dimensions in range.
371        /// <para>The indexer may be used for querying or altering single/any elements
372        /// in this array. <c>range</c> may contains index specifications for one ... any
373        /// dimension. The array returned will have the size specified by range.</para>
374        /// <para>The indexer may also be used for removing parts of the array. Therefore an empty array
375        /// (of the same type) or 'null' must be assigned to the range specified by <c>range</c> using the set-access. <c>range</c>
376        /// must contain exactly one dimension specification other than null. This may be any vector-sized numeric ILArray of any
377        /// type. If <c>range</c> applies
378        /// to less dimensions than dimensions existing in the array, the upper dimensions will be
379        /// merged and the array will be reshaped before applying the removal to it.</para>
380        /// <para>In case of removal the ILArray returned will be a reference array.</para></remarks>
381        public ILRetLogical this[params ILBaseArray[] dims] {
382            get {
383                return new ILRetLogical((ILLogicalStorage)Storage.Subarray(dims));
384            }
385            set {
386                SetRange(value,dims);
387                NumberNonZero = sumElements();
388            }
389        }
390        /// <summary>
391        /// Set single value to element at index specified
392        /// </summary>
393        /// <param name="value">New value</param>
394        /// <param name="idx">Index of element to be altered</param>
395        public void SetValue(byte value, params int[] idx) {
396            Storage.SetValueTyped(value, idx);
397        }
398        /// <summary>
399        /// Alter a range of this array
400        /// </summary>
401        /// <param name="value">Array with new values</param>
402        /// <param name="range">Range specification</param>
403        public void SetRange(ILInLogical value, params ILBaseArray[] range) {
404            using (ILScope.Enter(value))
405            using (ILScope.Enter(range)) {
406                if (object.Equals(value, null)) {
407                    Storage.IndexSubrange(null, range);
408                } else {
409                    Storage.IndexSubrange(value.Storage, range);
410                }
411            }
412        }
413        /// <summary>
414        /// Replace the elements of this array with another array's elements, preventing memory leaks
415        /// </summary>
416        /// <param name="value">New array</param>
417        public ILRetLogical a {
418            set { Assign(value); }
419            get { return this.C; }
420        }
421        /// <summary>
422        /// Replaces storage of this array with new array elements, registers this array for out-of-scope disposal
423        /// </summary>
424        /// <param name="value">New array</param>
425        public void Assign(ILRetLogical value) {
426            if (!IsDisposed)
427                Storage.Dispose();
428            m_storage = value.GiveStorageAwayOrClone();
429            //ILScope.Context.RegisterArray(this); 
430        }
431        #endregion
432
433        #region memory management
434        internal override bool EnterScope() {
435            return false;
436        }
437        #endregion
438
439    }
440}
Note: See TracBrowser for help on using the repository browser.