/// /// This file is part of ILNumerics Community Edition. /// /// ILNumerics Community Edition - high performance computing for applications. /// Copyright (C) 2006 - 2012 Haymo Kutschbach, http://ilnumerics.net /// /// ILNumerics Community Edition is free software: you can redistribute it and/or modify /// it under the terms of the GNU General Public License version 3 as published by /// the Free Software Foundation. /// /// ILNumerics Community Edition is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with ILNumerics Community Edition. See the file License.txt in the root /// of your distribution package. If not, see . /// /// In addition this software uses the following components and/or licenses: /// /// ================================================================================= /// The Open Toolkit Library License /// /// Copyright (c) 2006 - 2009 the Open Toolkit library. /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights to /// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of /// the Software, and to permit persons to whom the Software is furnished to do /// so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// ================================================================================= /// using System; using System.Collections.Generic; using System.Linq; using System.Text; using ILNumerics.Storage; namespace ILNumerics { /// /// The class implements additional functionality needed for cells /// public class ILBaseCell : ILDenseArray { #region constructors internal ILBaseCell(ILCellStorage cellStorage, bool tempArr) : base(cellStorage, tempArr) { } #endregion constructors #region properties /// /// Transposed version of this ILCell /// /// This property is an alias for 'Shifted(1). /// public new ILRetCell T { get { return new ILRetCell((ILCellStorage)Storage.ShiftDimensions(1)); } } /// /// Access to the more specialized version (ILCellStorage) of this storage /// internal new ILCellStorage Storage { get { return (m_storage as ILCellStorage); } set { // e.g. Storage.Detach() may return itself (if no detaching is // required). So we must check for that equalty here! if (!object.Equals(value, m_storage)) { m_storage.Dispose(); m_storage = value; } } } /// /// Clone of this cell /// /// /// Clones of all arrays in ILNumerics.Server are done in a very fast, lazy way. This means, /// at the time the clone is made, no relevant memory is copied. Elements of both arrays rather point to the same /// underlying System.Array. A reference counting mechanism ensures the detaching of thoses arrays on write access. /// Cells profit from the same efficient clone creation process. However, since a cell may store an arbitrarily deep /// hirarchy of other cells and arrays, in order to clone a cell, the cells elements have to be cloned as well - in an /// recursive manner. Clones play an important role for ILNumerics cells. They are used to implement value semantics for cell /// elements. I.e.: the cloned cell returned cannot not be used to alter elements of the original cell in any way. public new ILRetCell C { get { return new ILRetCell((ILCellStorage)Storage.Clone()); } } #endregion #region public interface /// /// Concatenate this cell /// /// Cell to concatenate this cell with /// Dimension index along which to concatenate the cells. /// New cell with concatenation of all elements of both cells /// The array returned will be a copy of both cells involved. /// If is larger than /// the number of dimensions of one of the arrays its value will be used in modulus. /// The resulting cell has the size of both input cells, laid beside one /// another along the dimension. public ILRetCell Concat(ILInCell A, int dim) { using (ILScope.Enter(A)) return new ILRetCell((ILCellStorage)Storage.Concat(A.Storage, dim)); } /// /// Retrieve a single array of a known type from a cell position /// /// Element type of the array /// Position of the array within this cell /// Lazy, shallow clone of the array found at the given position public ILRetArray GetArray(params ILBaseArray[] indices) { using (ILScope.Enter(indices)) return new ILRetArray(Storage.GetDenseStorage(indices)); } /// /// Retrieve a single element from the given position /// /// Position of the element to retrieve, must evaluate to a scalar position /// A clone of the scalar element found /// /// The method returns a lazy, shallow clone of the content of the cell element specified by . /// However, the return type (ILBaseArray) is not strongly typed and may contain any element. According to the /// true element stored in the cell, this might be an array of arbitrary type, null or even another cell. Moreover, handling /// ILBaseArray directly is not recommended for ILNumerics, since this would hinder the memory management from proper /// functioning. Therefore: The use of this method is not recommended and left to ILNumerics experts - for very /// specific and rare situations. /// internal ILBaseArray GetBaseArray(params ILBaseArray[] indices) { using (ILScope.Enter(indices)) return Storage.GetScalar(indices); } /// /// Retrieve a subcell of this cell /// /// Subcell definition, arbitrary size /// A cell with a lazy, shallow clone of the elements of this cell, addressed by /// The cell returned will have the size and shape specified by . public ILRetCell GetCell(params ILBaseArray[] indices) { using (ILScope.Enter(indices)) { ILCellStorage retStorage = (ILCellStorage)Storage.Subarray(indices); if (retStorage.Size.NumberOfElements == 1) { ILCellStorage retInner = retStorage.GetValueTyped(0) as ILCellStorage; if (retInner == null) throw new Exceptions.ILArgumentException("no cell found at the specified position"); return new ILRetCell(retInner); } else { throw new Exceptions.ILArgumentException("index specification must resolve to a scalar element location"); } } } /// /// Enumerator returning elements as scalar cells /// /// Enumerator /// This method enables the use of cells in foreach loops. /// The iterator is returned, if arrays are directly used in foreach statements. The iterator /// is compatible with ILNumerics memory management. /// ILDenseStorage<T> A = ILMath.rand(5,4,6); /// foreach (double element in A) { /// // all elements are scalar double values /// String.Format("Element: {0} ",element); /// // Note: 'element' cannot be used to alter the collection! /// } /// public new IEnumerator GetEnumerator() { int len = Size.NumberOfElements; for (int i = 0; i < len; i++) { //yield return GetBaseArray(i); yield return new ILRetCell((ILCellStorage)Storage.Subarray(i)); } } /// /// Retrieve single element from this cell /// /// Position of the element /// Lazy, shallow clone of the element to retrieve or null, if there is no element at this place public new object GetValue(params int[] idx) { return Storage.GetValue(idx); } /// /// Retrieve a typed single element from within the cell, supports deep indexing /// /// Expected type of the value to be returned /// Location of the single element addressed /// A clone of the single element addressed by /// The element returned will have the type given by . It is an error to specify /// a different type as the true type of the element specified. An exception is thrown if both types differ. public T GetValue(params int[] indices) { return Storage.GetValue(indices); } /// /// Test if an element of the cell is an array of the given element type /// /// The array element type to check the cell element against /// Position of the cell element to be tested /// true if the element found at the given position is an array of the element type , false otherwise /// The method is helpful in order to investigate the contents of a cell array. If you are not sure about the /// types of elements in the cell, this function can be used to make sure, elements are of the expected type before retrieving them as such. /// In most situations, elements of a cell are stored arrays of a distinct element type. That element type is given to IsTypeOf as /// typeparameter . That means, in order to find out, if the first cell element stores an array of int (ILArray<int>), /// one may use cell.IsTypeOf<int>(0) /// In order to test, if a cell element is of type ILCell, one can provide the type ILCell as type parameter: /// cell.IsTypeOf<ILCell>(0). Note the different semantic when checking for cell elements of type cell. Here we do not test for the /// element type but for the array type itself, ie. ILCell. The reason of this is: the type of elements of ILCell is /// an implementation detail and therefore hidden to the user. /// /// /// In the following example a ILCell of size 3x2 is created. It stores several array types, among which other cells are stored as elements of the outer cell. /// ILCell cell = ILMath.cell(new ILSize(3, 2) /// , "first element" /// , 2.0 /// , ILMath.cell(Math.PI, 100f) /// , ILMath.create<short>(1, 2, 3, 4, 5, 6) /// , new double[] {-1.4, -1.5, -1.6}); /// /// The cell is now: /// ILCell [3,2] /// <String> first element <Int16> [2,3,4,5,6] /// <Double> 2 ILCell [1,3] /// ILCell [2,1] (null) /// /// We test the element type of every element in the cell: /// /// Console.Out.WriteLine("cell[0,0] is of type 'string': {0}", cell.IsTypeOf<string>(0)); /// Console.Out.WriteLine("cell[0,0] is of type 'double': {0}", cell.IsTypeOf<double>(0)); /// /// Console.Out.WriteLine("cell[1,0] is of type 'double': {0}", cell.IsTypeOf<double>(1)); /// Console.Out.WriteLine("cell[2,0] is of type 'ILCell': {0}", cell.IsTypeOf<ILCell>(2)); /// /// Console.Out.WriteLine("cell[0,1] is of type 'short': {0}", cell.IsTypeOf<short>(0, 1)); /// Console.Out.WriteLine("cell[1,1] is of type 'ILCell': {0}", cell.IsTypeOf<ILCell>(1, 1)); /// Console.Out.WriteLine("cell[2,1] is of type 'double': {0}", cell.IsTypeOf<double>(2, 1)); /// /// This gives the following output: /// /// cell[0,0] is element type 'string': True /// cell[0,0] is element type 'double': False /// cell[1,0] is element type 'double': True /// cell[2,0] is element type 'ILCell': True /// cell[0,1] is element type 'short': True /// cell[1,1] is element type 'ILCell': True /// cell[2,1] is element type 'double': False // element is null, IsTypeOf<> never gives true /// public bool IsTypeOf(params ILBaseArray[] position) { using (ILScope.Enter(position)) return Storage.IsTypeOf(position); } /// /// Create reshaped copy of this cell /// /// New size of the cell /// Reshaped copy of the cell /// The current instance will not be changed! A new cell is created, having /// the elements of this cell and a shape as determined by . /// /// If the number of elements in /// do not match the number of elements in this cell. public new ILRetCell Reshape(ILSize size) { ILCell ret = C; ret.Storage.Reshape(size); return ret; } /// /// Create reshaped copy of this cell /// /// New size of the cell /// Reshaped copy of the cell /// The current instance will not be changed! A new cell is created, having /// the elements of this cell and a shape as determined by . /// /// If the number of elements in /// do not match the number of elements in this cell. public new ILRetCell Reshape(params int[] size) { return Reshape(new ILSize(size)); } /// /// Create replication of this cell /// /// Size descriptor /// If the number of elements in is /// less than the number of dimensions in this cell, the trailing dimensions will /// be set to 1 (singleton dimensions). On the other hand, if the number specified /// is larger then the number of dimension stored inside the storge the resulting /// storage will get its number of dimensions extended accordingly. /// Array created by multiple replications of this array along /// arbitrary dimensions according to public new ILRetCell Repmat(params int[] dims) { return new ILRetCell((ILCellStorage)Storage.Repmat(dims)); } /// /// Dimension shifted cell from this cell /// /// Number of dimensions to shift /// Shifted version of this cell /// The shift is done 'to the left': /// ILCell A = cell(2,4);
/// ILCell B = A.Shifted(1);
/// // B is now: ILCell [4,2]
/// //
/// ILCell C = cell(2,4,3);
/// ILCell D = C.Shifted(1);
/// // D is now: ILCell [4,3,2]
///
/// The dimensions are shifted circulary to the left. This /// can be imagined as removing the first dimensions from the beginning of the list of /// dimensions and "append" them to the end in a ringbuffer style. /// For dimension shifts of '1', you may consider using the /// property for readability. /// must be positive. It is taken modulus the number of dimensions. ///
public new ILRetCell Shifted(int shift) { return new ILRetCell((ILCellStorage)Storage.ShiftDimensions(shift)); } /// /// Subarray access. Get/set regular subarray. /// /// Address range /// Reference cell array with subarray addressed by indices. /// Query access: for N-dimensional cell arrays missing trailing dimensions indices will be choosen to be 0. Therefore you /// may ommit those trailing dimensions in indices. /// The indexer may be used for querying or altering single/any elements /// in this cell. indices may contains index specifications for one to any /// dimension. The cell array returned will have the size specified by indices. /// Values returned will be reference cells. All elements contained will be 'deep references' created by /// recursively walking downwards the elements and replacing them by references to itself. Therefore altering the /// values returned will not alter the original elements. /// The indexer may also be used for removing parts of the cell. Therefore null must be assigned to the range specified by indices (using the set-access). indices /// must contain exactly one dimension specification other than 'full' in this case. This may be any vector-sized numeric ILArray of any /// numeric type. If indices apply to fewer dimensions than the number of dimensions existing, the upper dimensions will be /// merged and the array will be reshaped before applying the removal to it. /// /// /// ILCell C = new ILCell(4,10); /// C[":",2] = null; // >- will remove the third column (index: 2) from the cell. /// C[full,vec(2,5)] = null; >- will remove columns 3...6 /// C[1,1] = null; >- will produce an error. Only one dimension can be specified not full! /// /// The general behavior of this access methods is full compatible with the corresponding Matlab/Octave/Scilab access: a(:) = []. /// public new ILRetCell Subarray(params ILBaseArray[] indices) { using (ILScope.Enter(indices)) { ILCellStorage elements = (ILCellStorage)Storage.Subarray(indices); return new ILRetCell(elements); } } #endregion } }