Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Array/ILInLogical.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: 19.3 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 <![CDATA[ILArray<byte>]]>. 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 <![CDATA[ILArray<byte>]]>.
56    /// The difference between <![CDATA[ILArray<byte>]]> and logical arrays is, the logical array
57    /// storing 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 ILInLogical : ILBaseLogical {
65
66        private static readonly bool s_isTempArray = true;
67
68        #region constructors
69        /// <summary>
70        /// constructor - create logical array 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        /// </remarks>
81        internal ILInLogical(params int[] size)
82            : base(new ILLogicalStorage(new ILSize(size)), s_isTempArray) {
83            NumberNonZero = sumElements();
84        }
85        /// <summary>
86        /// constructor - create logical array of specified size
87        /// </summary>
88        /// <param name="size">
89        /// dimension object
90        /// </param>
91        /// <remarks>
92        /// The size parameter may not be null. An exception will be
93        /// thrown in this case. The dimensions will be trimmed before processing
94        /// (removing trailing singleton dimensions).
95        /// </remarks>
96        internal ILInLogical(ILSize size)
97            : base(new ILLogicalStorage(size), s_isTempArray) {
98            NumberNonZero = sumElements();
99        }
100        /// <summary>
101        /// Constructor creating logical array from dense storage
102        /// </summary>
103        /// <param name="A">input array, the storage of this ILArray will directly be used for
104        /// storage of the new logical array</param>
105        internal ILInLogical(ILLogicalStorage A)
106            : base(A, s_isTempArray) {
107            NumberNonZero = sumElements();
108        }
109        /// <summary>
110        /// Constructor creating logical array from (dense) storage
111        /// </summary>
112        /// <param name="A">input array storage, the storage will directly be used for
113        /// storage of the new logical array</param>
114        /// <param name="numberNonZero">number of nonzero elements in A. Must be positive or 0.</param>
115        /// <remarks> Providing this parameter prevents the constructor from having to count the
116        /// 'true' elements in A.</remarks>
117        internal ILInLogical(ILLogicalStorage A, long numberNonZero)
118            : base(A, s_isTempArray) {
119            if (numberNonZero < 0)
120                throw new ILNumerics.Exceptions.ILArgumentException("invalid number of non-zero-elements given!");
121            NumberNonZero = numberNonZero;
122        }
123        /// <summary>
124        /// constructor - create logical array of specified size
125        /// from data array
126        /// </summary>
127        /// <param name="size">
128        /// Variable length int array specifying the number and size of dimensions to
129        /// be created.
130        /// </param>
131        /// <param name="data"> byte array matching the size of the dimensions
132        /// specified. The data will directly be used as storage! No copy will be made!</param>
133        /// <remarks>
134        /// The size parameter may not be null or an empty array! An Exception will be
135        /// thrown in this case. The dimensions will be trimmed before processing
136        /// (removing trailing non singleton dimensions).
137        /// </remarks>
138        internal ILInLogical(byte[] data, params int[] size)
139            : base(new ILLogicalStorage(data, new ILSize(size)), s_isTempArray) {
140            NumberNonZero = sumElements();
141        }
142        /// <summary>
143        /// Constructor creating logical array, provide predefined storage
144        /// </summary>
145        /// <param name="data">predefined storage elements. The array will directly be used
146        /// as underlying storage. No copy will be made! </param>
147        /// <param name="dimension">Dimensions specification.</param>
148        internal ILInLogical(byte[] data, ILSize dimension)
149            : base(new ILLogicalStorage(data, dimension), s_isTempArray) {
150           NumberNonZero = sumElements();
151        }
152        /// <summary>
153        /// Constructor creating logical array, predefined storage (fast version)
154        /// </summary>
155        /// <param name="data">predefined storage elements. The array will directly be used
156        /// as underlying storage. No copy will be made! </param>
157        /// <param name="dimension">Dimensions specification.</param>
158        /// <param name="nonZeroCount">number of nonzero elements in <paramref name="data"/>.
159        /// Providing this parameter prevents from counting the 'true' elements (again). </param>
160        internal ILInLogical(byte[] data, ILSize dimension, long nonZeroCount)
161            : base(new ILLogicalStorage(data, dimension), s_isTempArray) {
162            if (nonZeroCount < 0)
163                throw new ILNumerics.Exceptions.ILArgumentException("invalid number of non-zero-elements given!");
164            NumberNonZero = nonZeroCount;
165        }
166        #endregion
167
168        #region operator overloading
169
170        #region operational operators
171        /// <summary>
172        /// Invert values of array elements
173        /// </summary>
174        /// <param name="A">Input array</param>
175        /// <returns>New logical array, having the element values of A inverted</returns>
176        public static ILRetLogical operator !(ILInLogical A) {
177            if (object.Equals(A, null))
178                throw new ILArgumentException("operator !: array must not be null");
179            return (A != (byte)1);
180        }
181        #endregion
182
183        #region conversional operators
184        public static implicit operator ILInLogical(ILArray<byte> a) {
185            if (object.Equals(a, null))
186                return null;
187            ILInLogical ret = new ILInLogical(new ILLogicalStorage(
188                a.Storage.GetDataArray(), a.Size));
189            if (Settings.AllowInArrayAssignments)
190                ILScope.Context.RegisterArray(ret);
191            return ret;
192        }
193        public static implicit operator ILInLogical(ILInArray<byte> a) {
194            if (object.Equals(a, null))
195                return null;
196            ILInLogical ret = new ILInLogical(new ILLogicalStorage(
197                a.Storage.GetDataArray(), a.Size));
198            if (Settings.AllowInArrayAssignments)
199                ILScope.Context.RegisterArray(ret);
200            return ret;
201        }
202        public static implicit operator ILArray<byte>(ILInLogical a) {
203            if (object.Equals(a, null))
204                return null;
205            ILArray<byte> ret = new ILArray<byte>(
206                new ILDenseStorage<byte>(a.Storage.GetDataArray(), a.Size));
207            ILScope.Context.RegisterArray(ret);
208            return ret;
209        }
210        public static implicit operator ILInArray<byte>(ILInLogical a) {
211            if (object.Equals(a, null))
212                return null;
213            ILInArray<byte> ret = new ILInArray<byte>(
214                new ILDenseStorage<byte>(a.Storage.GetDataArray(), a.Size));
215            if (Settings.AllowInArrayAssignments)
216                ILScope.Context.RegisterArray(ret);
217            return ret;
218        }
219        public static implicit operator ILInLogical(ILRetLogical a) {
220            if (object.Equals(a,null))
221                return null;
222            ILLogicalStorage storage = (ILLogicalStorage)a.GiveStorageAwayOrClone();
223            ILInLogical ret = new ILInLogical(storage, storage.NumberNonZero);
224            if (Settings.AllowInArrayAssignments)
225                ILScope.Context.RegisterArray(ret);
226            return ret;
227        }
228        public static implicit operator ILInLogical(ILLogical a) {
229            if (object.Equals(a, null))
230                return null;
231            ILInLogical ret = new ILInLogical(new ILLogicalStorage(a.Storage.GetDataArray(), a.Size));
232            if (Settings.AllowInArrayAssignments)
233                ILScope.Context.RegisterArray(ret);
234            return ret;
235        }
236        #endregion
237
238        #region constructional operators
239        /// <summary>
240        /// Implicitly convert logical array to bool
241        /// </summary>
242        /// <param name="A">logical array</param>
243        /// <returns>true if <b>all</b> elements of A are non-zero, false otherwise
244        /// </returns>
245        /// <remarks>If A is null or empty, the function returns false. Otherwise allall returns true,
246        /// if all elements of A are non-zero and returns false, if A contains any zero elements.</remarks>
247        public static implicit operator bool(ILInLogical A) {
248            // this operator is implicit for convenience reasons:
249            // if(tmp[0]!=-10.0) { ... is only possible this way
250            if (object.Equals(A, null) || A.IsEmpty)
251                return false;
252            if (A.IsScalar)
253                return A.GetValue(0, 0) == 1;
254            if (Settings.LogicalArrayToBoolConversion == LogicalConversionMode.ImplicitAllAll) {
255                if (A.Size.NumberOfElements > 0) {
256                    return ILMath.allall(A).GetValue(0) == 1;
257                } else {
258                    return false;
259                }
260            } else { // if (Settings.LogicalArrayToBoolConversion == LogicalConversionMode.NonScalarThrowsException) {
261                if (!A.IsScalar) {
262                    throw new ILArgumentException("error while attempting to convert logical of size " + A.Size.ToString() + " to boolean");
263                } else {
264                    return A.GetValue(0) == 1;
265                }
266            }
267        }
268
269        /// <summary>
270        /// Implicitly convert scalar byte to logical array of size 1x1 (scalar).
271        /// </summary>
272        /// <param name="val">Byte scalar</param>
273        /// <returns>New logical array of size 1x1 holding the only element of type <c>byte</c>
274        /// with value of val.</returns>
275        public static implicit operator ILInLogical(bool val) {
276            ILInLogical ret = new ILInLogical(new byte[1] { val ? (byte)1 : (byte)0 }, 1, 1);
277            return ret;
278        }
279
280        /// <summary>
281        /// Implicitly convert integer scalar to logical array of size 1x1 (scalar).
282        /// </summary>
283        /// <param name="val">Scalar value</param>
284        /// <returns>New logical array of size 1x1 holding the only element of type Byte
285        /// with value of val.</returns>
286        public static implicit operator ILInLogical(int val) {
287            ILInLogical ret = new ILInLogical(new Byte[1] {
288                                 val != 0 ? (byte)1:(byte)0 }, 1, 1);
289            return ret;
290        }
291        /// <summary>
292        /// implicitly cast one dimensional System.Array to ILNumerics array (vector)
293        /// </summary>
294        /// <param name="A">1 dimensional system array, arbitrary type</param>
295        /// <returns>ILNumerics array of same element type as elements of A.
296        /// Row vector. If A is null: empty array.</returns>
297        /// <remarks>The System.Array A will directly be used for the new ILNumerics array!
298        /// No copy will be done! Make sure, not to reference A after this conversion!</remarks>
299        public static implicit operator ILInLogical(byte[] A) {
300            if (A == null) {
301                ILLogicalStorage dS = new ILLogicalStorage(new byte[0], ILSize.Empty00);
302                return new ILInLogical(dS);
303            }
304            ILInLogical ret = new ILInLogical(A, 1, A.Length);
305            if (Settings.AllowInArrayAssignments)
306                ILScope.Context.RegisterArray(ret);
307            return ret;
308        }
309        /// <summary>
310        /// Implicitly convert n-dim. System.Array to ILNumerics array
311        /// </summary>
312        /// <param name="A">Arbitrarily sized System.Array</param>
313        /// <returns>If A is null: empty array. Else: new ILNumerics array of the same size as A</returns>
314        /// <remarks>The inner type of input array <paramref name="A"/> must match the requested type
315        /// <typeparamref name="ElementType"/>. The resulting ILArray will reflect all dimensions of
316        /// A. Elements of A will get copied to elements of output array (shallow copy).</remarks>
317        /// <exception cref="ILNumerics.Exceptions.ILCastException">If type of input does not match
318        /// ElementType</exception>
319        public static implicit operator ILInLogical(Array elements) {
320            if (elements == null || elements.Length == 0) {
321                return new ILInLogical(ILSize.Empty00);
322            }
323            if (elements.GetType().GetElementType() != typeof(byte))
324                throw new ILCastException("inner type of System.Array must match");
325            int[] dims = new int[elements.Rank];
326            byte[] retArr = ILMemoryPool.Pool.New<byte>(elements.Length);
327            int posArr = 0;
328            for (int i = 0; i < dims.Length; i++) {
329                dims[i] = elements.GetLength(dims.Length - i - 1);
330            }
331            foreach (byte item in elements)
332                retArr[posArr++] = item;
333            ILInLogical ret = new ILInLogical(retArr, dims);
334            if (Settings.AllowInArrayAssignments)
335                ILScope.Context.RegisterArray(ret);
336            return ret;
337        }
338        /// <summary>
339        /// Implicitly cast two dimensional System.Array to ILNumerics array
340        /// </summary>
341        /// <param name="A">2-dimensional System.Array</param>
342        /// <returns>If A is null: empty array. ILNumerics array of same size and type as A otherwise.</returns>
343        public static implicit operator ILInLogical(byte[,] A) {
344            if (A == null || A.Length == 0) {
345                return new ILInLogical(ILSize.Empty00);
346            }
347            int[] dims = new int[2];
348            byte[] retArr = ILMemoryPool.Pool.New<byte>(A.Length);
349            int posArr = 0;
350            for (int i = 0; i < 2; i++) {
351                dims[i] = A.GetLength(dims.Length - i - 1);
352            }
353            foreach (byte item in A)
354                retArr[posArr++] = item;
355            ILInLogical ret = new ILInLogical(retArr, dims);
356            if (Settings.AllowInArrayAssignments)
357                ILScope.Context.RegisterArray(ret);
358            return ret;
359        }
360        /// <summary>
361        /// Implicitly cast three dimensional System.Array to ILNumerics array
362        /// </summary>
363        /// <param name="A">3-dimensional System.Array</param>
364        /// <returns>If A is null: empty array. ILNumerics array of same size and type as A otherwise.</returns>
365        public static implicit operator ILInLogical(byte[, ,] A) {
366            if (A == null || A.Length == 0) {
367                return new ILInLogical(ILSize.Empty00);
368            }
369            int[] dims = new int[3];
370            byte[] retArr = ILMemoryPool.Pool.New<byte>(A.Length);
371            int posArr = 0;
372            for (int i = 0; i < 3; i++) {
373                dims[i] = A.GetLength(dims.Length - i - 1);
374            }
375            foreach (byte item in A)
376                retArr[posArr++] = item;
377            ILInLogical ret = new ILInLogical(retArr, dims);
378            if (Settings.AllowInArrayAssignments)
379                ILScope.Context.RegisterArray(ret);
380            return ret;
381        }
382        #endregion
383        #endregion
384
385        #region index access + mutability
386        /// <summary>
387        /// Subarray access (readonly)
388        /// </summary>
389        /// <param name="range">Range specification</param>
390        /// <returns>Logical array with the elements specified by range</returns>
391        /// <remarks>Query access: for N-dimensional arrays trailing dimensions will be choosen to be 0. Therefore you
392        /// may ommit those trailing dimensions in range.
393        /// <para>The indexer may be used for querying any elements
394        /// in this array. <c>range</c> may contains index specifications for one ... to any
395        /// dimension. The array returned will have the size specified by range.</para>
396        /// </remarks>
397        public ILRetLogical this[params ILBaseArray[] dims] {
398            get {
399                return new ILRetLogical((ILLogicalStorage)Storage.Subarray(dims));
400            }
401        }
402        #endregion
403
404    }
405}
Note: See TracBrowser for help on using the repository browser.