Exemplo n.º 1
0
 public Vector(double[] vector, double label, int id)
     : base()
 {
     this.values = vector.ToArray();
     this.label = label;
     this.Id = id;
 }
Exemplo n.º 2
0
 /// <summary>
 /// Create surface data of a sphere
 /// </summary>
 /// <param name="n">number of facettes per angle</param>
 /// <param name="X">[output] X coords</param>
 /// <param name="Y">[output] Y coords</param>
 /// <param name="Z">[output] Z coords</param>
 public static void sphere(int n, out ILArray<double> X,out ILArray<double> Y,out ILArray<double> Z) {
     ILArray<double> phi = repmat(linspace(-pi,pi,n).T,1,n);
     ILArray<double> rho = repmat(linspace(0,pi,n),n,1); 
     Y = sin(phi) * sin(rho); 
     X = cos(phi) * sin(rho);
     Z = cos(rho); 
 }
Exemplo n.º 3
0
 // The special constructor is used to deserialize values.
 public Vector(SerializationInfo info, StreamingContext context)
 {
     label = (double)info.GetValue("label", typeof(double));
     valuesMDF = (ILArray<double>)info.GetValue("valuesMDF", typeof(ILArray<double>));
     values = (ILArray<double>)info.GetValue("values", typeof(ILArray<double>));
     id = (int)info.GetValue("id", typeof(int));
 }
Exemplo n.º 4
0
        // Wake Code - Matlab
        // Rasmus Christensen
        // Control and Automation, Aalborg University

        // N_turb = number of turbines.
        // X_turb = x-position of turbine.
        // Y_turb = y-position of turbine.
        #endregion
        internal static void ROTATE_corrd(out ILArray<double> out_x, out ILArray<double> out_y, ILArray<double> xTurb, ILArray<double> yTurb, double rotA)
        {
            #region "Used variables declaration"
            ILArray<double> x_out;
            ILArray<double> y_out;
            int i;
            #endregion

            x_out = zeros(1, length(xTurb)); // Initialization x-coordinates
            y_out = zeros(1, length(yTurb)); // Initialization y-coordinates
    
            rotA = rotA * pi / 180; // Conversion to radians

            for (i = 1; i <= length(xTurb); i++)
            {
                x_out._(i, '=', xTurb._(i) * cos(rotA) - xTurb._(i) * sin(rotA));
                y_out._(i, '=', xTurb._(i) * sin(rotA) + yTurb._(i) * cos(rotA));
            }

            if (min_(x_out) < 0) // Moves the x-points if these are negative.
            {
                x_out = x_out + 500 + abs(min_(x_out));
            }

            if (min_(y_out) < 0) // Moves the y-points if these are negative.
            {
                y_out = y_out + 500 + abs(min_(y_out));
            }
    
	        out_x = x_out;
	        out_y = y_out;
        }
Exemplo n.º 5
0
 private static void load(string windMatFilePath, out ILArray<double> wind)
 {
     using (var WindMatFile = new ILMatFile(windMatFilePath))
     {
         wind = WindMatFile.GetArray<double>("wind");
     }
 }
Exemplo n.º 6
0
        // Wake Code - Matlab
        // Rasmus Christensen
        // Control and Automation, Aalborg University
        #endregion
        internal static void WT_order(out ILArray<double> xOrder, out ILArray<double> yOrder, ILArray<double> xTurb, ILArray<double> yTurb)
        {
            #region "Used variables declaration"
            ILArray<double> sorted;
            ILArray<double> turbineOrder;
            int sortCtr;
            int i;
            int j;
            #endregion

            sorted = sortrows(__[ xTurb.T, yTurb.T ], 1);
            turbineOrder = zeros(length(sorted), 2);
            sortCtr = 0;
            for (i = 1; i <= length(sorted); i++)
            {
                for (j = i + 1; j <= length(sorted); j++)
                {
                    if (sorted._(i, 1) == sorted._(j, 1))
                    {
                        sortCtr = sortCtr + 1;
                    }
                }
                turbineOrder[_(i, ':', i + sortCtr), _(':')] = sortrows(sorted[_(i, ':', i + sortCtr), _(':')], 2);
                sortCtr = 0;
            }
            xOrder = turbineOrder[_(':'), _(1)];
            yOrder = turbineOrder[_(':'), _(2)];
        }
Exemplo n.º 7
0
 public ClusterX(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     child = (Node)info.GetValue("child", typeof(Node));
     covarianceMatrixMDF = (ILArray<double>)info.GetValue("covarianceMatrixMDF", typeof(ILArray<double>));
     label = (double)info.GetValue("label", typeof(double));
 }
Exemplo n.º 8
0
        private void TestBucketSortArrayMatrixRow() {
            try {
                ILArray<string> A = new ILArray<string>(3,4); 
                A[0,0] = "abc"; 
                A[0,1] = "rtu"; 
                A[0,2] = "sfkw"; 
                A[0,3] = "lsdkfi"; 
                A[1,0] = "iowejkc"; 
                A[1,1] = "cjks"; 
                A[1,2] = "wokys"; 
                A[1,3] = "suem,"; 
                A[2,0] = "fgj"; 
                A[2,1] = "JKSF"; 
                A[2,2] = "SEs"; 
                A[2,3] = "SEFsr"; 
                ILArray<double> ind; 
                ILArray<string> res = ILMath.sort(A,out ind,0,false); 
                if (!res.Equals(A[ind]))
                    throw new Exception("invalid indices/values detected");
                ILArray<Int16> indI = ILMath.toint16(ILMath.counter(0.0,1.0,A.Dimensions.ToIntArray())); 
                res = ILMath.sort(A,ref indI, 0, true, new ILASCIIKeyMapper()); 
                if (!res.Equals(A[indI]))
                    throw new Exception("invalid indices/values detected");

                Success(" elapsed: " + m_stopwatch.ElapsedMilliseconds + " ms"); 
            } catch (Exception e) {
                Error(0, e.Message); 
            }
        }
Exemplo n.º 9
0
        public static ILArray<double> cross(ILArray<double> A, ILArray<double> B, int dim)
        {
            // Input checking
            if (!A.m_dimensions.IsSameShape(B.m_dimensions))
                throw new ILDimensionMismatchException("Inputs must have the same size and shape.");

            ILDimension outDims = A.m_dimensions;
            double[] outArray = ILMemoryPool.Pool.New<double>(outDims.NumberOfElements);

            if (dim >= outDims.NumberOfDimensions || dim < 0)
                throw new Exception("Specified dim is out of bounds of the array!");

            if (outDims[dim] != 3)
                throw new Exception("Must have length 3 in the dimension where the cross product is taken.");

            // Cross Product
            int SID = outDims.SequentialIndexDistance(dim);
            int crosses = outDims.NumberOfElements / 3;
            int SID2 = 2 * SID;

            for (int i = 0; i < crosses; i++)
            {
                outArray[i] = A.m_data[SID + i] * B.m_data[SID2 + i] - A.m_data[SID2 + i] * B.m_data[SID + i];
                outArray[SID + i] = A.m_data[SID2 + i] * B.m_data[i] - A.m_data[i] * B.m_data[SID2 + i];
                outArray[SID2 + i] = A.m_data[i] * B.m_data[SID + i] - A.m_data[SID + i] * B.m_data[i];
            }

            return new ILArray<double>(outArray, outDims);
        }
private static void forwBackwGenCheck(IILFFT fft, ILArray<fcomplex> A, ILArray<fcomplex> Result, int dim, float mult) { 
ILArray<fcomplex> B = fft.FFTForward1D(A, dim);
if (ILMath.sumall(ILMath.abs(Result - B))/A.Dimensions.NumberOfElements / A.Dimensions[dim] > (double)ILMath.MachineParameterFloat.eps * mult)
    throw new Exception("invalid value");
B = fft.FFTBackward1D(B, dim);
if (ILMath.sumall(ILMath.abs(A - B))/A.Dimensions.NumberOfElements / A.Dimensions[dim] > (double)ILMath.MachineParameterFloat.eps * mult)
    throw new Exception("invalid value");}
Exemplo n.º 11
0
 /// <summary>
 /// convert sequential index into subscript indices
 /// </summary>
 /// <param name="A">input array</param>
 /// <param name="seqindex">sequential index</param>
 /// <returns>subscript indices</returns>
 /// <remarks><para>the length of the value returned will be the number of dimensions of A</para>
 /// <para>if A is null or empty array, the return value will be of length 0</para>
 /// </remarks>
 /// <exception cref="System.IndexOutOfRangeException">if seqindex is &lt; 0 or &gt; numel(A)</exception>
 public static int[] ind2sub(ILArray<complex>   A, int seqindex) {  
     if (object.Equals(A,null) || A.IsEmpty)
         return new int[0]; 
     int [] ret = new int[A.Dimensions.NumberOfDimensions]; 
     A.GetValueSeq(seqindex,ref ret); 
     return ret; 
 }
Exemplo n.º 12
0
 /// <summary>
 /// trace of matrix
 /// </summary>
 /// <param name="A">input matrix, size [m x n]</param>
 /// <returns>scalar of same type as A with the sum of diagonal elements of A.</returns>
 public static /*!HC:inCls1*/ ILArray<double> trace (/*!HC:inCls1*/ ILArray<double> A) {
     if (A.IsEmpty) 
         return /*!HC:inCls1*/ ILArray<double> .empty(A.Dimensions); 
     if (A.IsVector || A.IsScalar) 
         return A[0]; 
     return sum(diag(A));
 }
Exemplo n.º 13
0
// DO NOT EDIT INSIDE THIS REGION !! CHANGES WILL BE LOST !! 
        /// <summary>
        /// trace of matrix
        /// </summary>
        /// <param name="A">input matrix, size [m x n]</param>
        /// <returns>scalar of same type as A with the sum of diagonal elements of A.</returns>
        public static  ILArray<complex> trace ( ILArray<complex> A) {
            if (A.IsEmpty) 
                return  ILArray<complex> .empty(A.Dimensions); 
            if (A.IsVector || A.IsScalar) 
                return A[0]; 
            return sum(diag(A));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sinus of array elements 
        /// </summary>
        /// <param name="A">input array</param>
        /// <returns>Sinus of elements from input array</returns>
        /// <remarks><para>If the input array is empty, an empty array will be returned.</para>
        /// <para>The array returned will be a dense array.</para></remarks>
        public static /*!HC:outCls*/ ILArray<double> /*!HC:HCfuncname*/ sin (/*!HC:inCls1*/ ILArray<double> A) {
            if (A.IsEmpty)
                return /*!HC:outCls*/ ILArray<double> .empty(A.Dimensions); 
            ILDimension inDim = A.Dimensions;
            /*!HC:outArr*/ double [] retDblArr;
            // build ILDimension    
            int newLength = inDim.NumberOfElements;
            //retDblArr = new /*!HC:outArr*/ double [newLength];
            retDblArr = ILMemoryPool.Pool.New</*!HC:outArr*/ double > (newLength); 
            int leadDimLen = inDim [0];

            // physical -> pointer arithmetic
            unsafe
            {
                fixed (/*!HC:outArr*/ double * pOutArr = retDblArr)
                fixed (/*!HC:inArr1*/ double * pInArr = A.m_data) {
                    /*!HC:outArr*/ double * lastElement = pOutArr + retDblArr.Length;
                    /*!HC:outArr*/ double * tmpOut = pOutArr;
                    /*!HC:inArr1*/ double * tmpIn = pInArr;
                    while (tmpOut < lastElement) { // HC02
                        /*!HC:HCCompute02*/
                        *tmpOut++ = /*!HC:HCoperation*/ Math.Sin ( *tmpIn++ ) /*!HC:HCpostOp*/ ;
                    }
                }
            }

            return new /*!HC:outCls*/ ILArray<double> ( retDblArr, inDim );
        }
Exemplo n.º 15
0
 // The special constructor is used to deserialize values.
 public Cluster(SerializationInfo info, StreamingContext context)
 {
     clusterPair = (ClusterPair)info.GetValue("clusterPair", typeof(ClusterPair));
     items = (List<Vector>)info.GetValue("items", typeof(List<Vector>));
     mean = (Vector)info.GetValue("mean", typeof(Vector));
     meanMDF = (ILArray<double>)info.GetValue("meanMDF", typeof(ILArray<double>));
     parent = (Node)info.GetValue("parent", typeof(Node));
 }
Exemplo n.º 16
0
 /// <summary>
 /// imaginary part of complex array elements
 /// </summary>
 /// <param name="X">complex input array</param>
 /// <returns>imaginary part of complex array</returns>
 public static /*!HC:outCls1*/ ILArray<double> imag (/*!HC:inCls1*/ ILArray<complex> X) {
     int nrX = X.m_dimensions.NumberOfElements; 
     /*!HC:outArr1*/ double [] retArr = new /*!HC:outArr1*/ double [nrX]; 
     /*!HC:outCls1*/ ILArray<double> ret = new /*!HC:outCls1*/ ILArray<double> (retArr,X.m_dimensions); 
     for (int i= 0; i < nrX; i++) {
         retArr[i] = X.GetValue(i).imag; 
     }
     return ret; 
 }
Exemplo n.º 17
0
        public void Test_Serialize() {
            int errorCode = 0;
            try {
                double[] data = new double[1000 * 1000 * 10];
                String filename = "ILDoubleArray_SerializeTest1.ils";
                for (int i = 0; i < data.Length; i++)
                    data[i] = (double)i;
                ILArray<double> A = new ILArray<double>(data, 1000,1000,10);

                FileStream fs = new FileStream(filename, FileMode.Create);
                Info("Serializing to file: (please wait...)");
                A.Serialize(fs); 
                fs.Close();
                FileInfo fi = new FileInfo(filename);
                Info("Serialized to file: [1000 x 1000 x 10] => " + ((int)(fi.Length/1024)) + "kB");
                
                // create reference storage from smaler range -> should Detach()  
                errorCode = 1;
                filename = "ILDoubleArray_SerializeTest2.ils";
                fs = new FileStream(filename, FileMode.Create);
                ILArray<double> AR1 = (ILArray<double>)A[0,"0:600;30:400;0:end"];
                AR1.Serialize(fs);
                fs.Close();
                fi = new FileInfo(filename);
                Info("Serialized to file: [600 x 360 x 10] => " + ((int)(fi.Length / 1024)) + "kB");

                // if reference storage saved effective memory - keep it as reference
                errorCode = 2;
                filename = "ILDoubleArray_SerializeTest3.ils";
                fs = new FileStream(filename, FileMode.Create);
                ILArray<double> AR2 = (ILArray<double>)A[0,"0:end,0:end;0:end,0:end;0:end"];
                AR2.Serialize(fs);
                fs.Close();
                fi = new FileInfo(filename);
                Info("Serialized to file: [2000 x 2000 x 20] => " + ((int)(fi.Length / 1024)) + "kB");


                // test if small reference would NOT store full data array
                errorCode = 4;
                filename = "ILDoubleArray_SerializeTest4.ils";
                fs = new FileStream(filename, FileMode.Create);
                ILArray<double> AR3 = (ILArray<double>)A["3;3;1"];
                AR3.Serialize(fs);
                fs.Close();
                fi = new FileInfo(filename);
                Info("Serialized to file: [1 x 1] => " + ((int)(fi.Length / 1024)) + "kB");
                if (fi.Length > 1024 * 2)
                    throw new Exception("Small reference storages should get detached before serializing!");
                errorCode = 5;

                Success("Test_serialize successfull");
            } catch (SerializationException e) {
                Error("Test_serialize failed on ErrorCode: "+ errorCode +"due: " + e.Message);
            } catch (Exception e) {
                Error("Test_serialize failed on ErrorCode: " + errorCode + "due: " + e.Message);
            }
        }
Exemplo n.º 18
0
        /// <summary>Unique and sorted elements of a vector.</summary>
        /// <param name="X">Elements from which to extract unique values (treated as a vector).</param>
        /// <param name="whereResultInX">Indices (same size as retValue) such that x[whereResultInX] = retValue.</param>
        /// <param name="whereXInResult">Indices (same size as x) such that retValue[whereXInResult] = x.</param>
        /// <returns>Sorted row vector with size less than or equal to x where no 2 elements have the same value.</returns>
        public static ILArray<double> unique(ILArray<double> X, out ILArray<double> whereResultInX, out ILArray<double> whereXInResult)
        {
            // 1. Handle empty and singleton cases
            if (X.IsEmpty)
            {
                whereResultInX = new ILArray<double>();
                whereXInResult = new ILArray<double>();
                return new ILArray<double>();
            }

            if (X.IsScalar)
            {
                whereResultInX = new ILArray<double>(new double[] { 0 });
                whereXInResult = new ILArray<double>(new double[] { 0 });
                return X.C;
            }

            // 2. Sort
            double[] x = (double[])X.m_data.Clone();
            int[] oldXInd = ILMemoryPool.Pool.New<int>(x.Length);

            for (int i = 0; i < x.Length; i++)
                oldXInd[i] = i;

            Array.Sort(x, oldXInd);

            // 3. Declarations
            int unqCount = 1;
            for (int i = 1; i < x.Length; i++)
                if (x[i - 1] != x[i])
                    unqCount++;

            double[] unq = ILMemoryPool.Pool.New<double>(unqCount);
            double[] wxnr = ILMemoryPool.Pool.New<double>(x.Length);
            double[] wrnx = ILMemoryPool.Pool.New<double>(unqCount);

            // 4. Unique
            unq[0] = x[0];
            wxnr[oldXInd[0]] = 0;
            wrnx[0] = oldXInd[0];

            for (int i = 1, j = 1; i < x.Length; i++)
            {
                if (x[i - 1] != x[i])
                {
                    unq[j] = x[i];
                    wrnx[j] = oldXInd[i];
                    j++;
                }
                wxnr[oldXInd[i]] = j - 1;
            }

            whereResultInX = new ILArray<double>(wrnx);
            whereXInResult = new ILArray<double>(wxnr);
            return new ILArray<double>(unq);
        }
Exemplo n.º 19
0
        /// <summary>
        /// multiply and fold array elements along first non singleton dimension
        /// </summary>
        /// <param name="inArray">N-dimensional double array</param>
        /// <returns>array having the first non singleton dimension 
		/// reduced to the length 1 with the result of the products of 
		/// corresponding elements of inArray in that dimension.
		/// The result will have the same number of dimensions as 
		/// inArray, but the first non singleton dimension having the 
		/// size 1.</returns>
		public static ILArray<double> prod(ILArray<double> inArray) {
            int[] newDims = inArray.Dimensions.ToIntArray();
            int nsDim = 0;
            while (nsDim < newDims.Length && newDims[nsDim] < 2)
                nsDim++;
            if (nsDim == newDims.Length)
                // scalar -> return copy
                return (ILArray<double>)inArray.Clone();
            return prod(inArray, nsDim);
        }
Exemplo n.º 20
0
private static void forwBackwGenCheck(IILFFT fft, ILArray<double> A, ILArray<complex> Result, int dim, double mult) { 
ILArray<complex> B = fft.FFTForward1D(A, dim);
if (ILMath.sumall(ILMath.abs(Result - B))/A.Dimensions.NumberOfElements / A.Dimensions[dim] > ILMath.MachineParameterDouble.eps * mult)
    throw new Exception("invalid value");
ILArray<double> ResultR = fft.FFTBackwSym1D(B,dim);
if (ILMath.sumall(ILMath.abs(ResultR - A))/A.Dimensions.NumberOfElements / A.Dimensions[dim] > ILMath.MachineParameterDouble.eps * mult)
   throw new Exception("invalid value");
B = fft.FFTBackward1D(B, dim);
if (ILMath.sumall(ILMath.abs(ILMath.tocomplex(A) - B))/A.Dimensions.NumberOfElements / A.Dimensions[dim] > ILMath.MachineParameterDouble.eps * mult)
    throw new Exception("invalid value");}
Exemplo n.º 21
0
        //private void wakeCalculation(ILArray<double> Ct, int i, ILCell wind, out ILArray<double> v_nac)
        public static void Calculate(ILArray<double> Ct, int i, ILMatFile wind, out ILArray<double> v_nac)
        {
            //% v_nac = WAKECALCULATION(Ct,i,wind)
            //This function calculates the wake
            //Currently it is a very very simplified wake calculation. It just serves as
            //a placeholder for a correct wake calculation that will come later

            ILArray<double> scaling = ILMath.linspace(0.5, 0.9, Ct.Length);
            v_nac = scaling * wind.GetArray<double>("wind").GetValue(i - 1, 1);
        }
Exemplo n.º 22
0
 /// <summary>
 /// real part of complex array
 /// </summary>
 /// <param name="X">complex input array</param>
 /// <returns>real part of complex array</returns>
 public static /*!HC:outCls1*/ ILArray<double> real (/*!HC:inCls1*/ ILArray<complex> X) {
     int nrX = X.m_dimensions.NumberOfElements; 
     /*!HC:outArr1*/ double [] retArr = new /*!HC:outArr1*/ double [nrX]; 
     /*!HC:outCls1*/ ILArray<double> ret = new /*!HC:outCls1*/ ILArray<double> (retArr,X.m_dimensions); 
     ILIterator</*!HC:inArr1*/ complex > it = X.CreateIterator(ILIteratorPositions.ILEnd,0); 
     for (int i= 0; i < nrX; i++) {
         retArr[i] = it.Increment().real; 
     }
     return ret; 
 }
Exemplo n.º 23
0
        /// <summary>
        /// Multidimensional scaling/PCoA: transform distances to points in a coordinate system.
        /// </summary>
        /// <param name="input">A matrix of pairwise distances. Zero indicates identical objects.</param>
        /// <returns>A matrix, the columns of which are coordinates in the nth dimension. 
        /// The rows are in the same order as the input.</returns>
        public static ILArray<double> Scale(ILArray<double> input)
        {
            int n = input.Length;

            ILArray<double> p = ILMath.eye<double>(n, n) - ILMath.repmat(1.0 / n, n, n);

            ILArray<double> a = -.5 * ILMath.multiplyElem(input, input);
            ILArray<double> b = ILMath.multiply(p, a, p);

            ILArray<complex> V = ILMath.empty<complex>();
            ILArray<complex> E = ILMath.eig((b + b.T) / 2, V);

            ILArray<int> i = ILMath.empty<int>();
            ILArray<double> e = ILMath.sort(ILMath.diag(ILMath.real(E)), i);

            e = ILMath.flipud(e);
            i = ILMath.toint32(ILMath.flipud(ILMath.todouble(i)));

            ILArray<int> keep = ILMath.empty<int>();
            for (int j = 0; j < e.Length; j++)
            {
                if (e[j] > 0.000000001)
                {
                    keep.SetValue(j, keep.Length);
                }
            }

            ILArray<double> Y;
            if (ILMath.isempty(keep))
            {
                Y = ILMath.zeros(n, 1);
            }
            else
            {
                Y = ILMath.zeros<double>(V.S[0], keep.Length);
                for (int j = 0; j < keep.Length; j++)
                {
                    Y[ILMath.full, j] = ILMath.todouble(-V[ILMath.full, i[keep[j]]]) ;
                }
                Y = ILMath.multiply(Y, ILMath.diag(ILMath.sqrt(e[keep])));
            }

            ILArray<int> maxind = ILMath.empty<int>();
            ILMath.max(ILMath.abs(Y), maxind, 0);
            int d = Y.S[1];
            ILArray<int> indices = maxind + ILMath.toint32(ILMath.array<int>(SteppedRange(0,n, (d-1)*n)));
            ILArray<double> colsign = ILMath.sign(Y[indices]);
            for (int j = 0; j < Y.S[1]; j++)
            {
                Y[ILMath.full, j] = Y[ILMath.full, j] * colsign[j];
            }

            return Y;
        }
Exemplo n.º 24
0
 public static ILBaseArray convert(object type, ILArray<Double> X)
 {
     if (type.GetType() == typeof(IronPython.Runtime.Types.PythonType))
     {
         if (((IronPython.Runtime.Types.PythonType)type).__clrtype__() == typeof(Int32))
         {
             return convert(NumericType.Int32, X);
         }
         else return X;
     }
     else return X;
 }
Exemplo n.º 25
0
 /// <summary>
 /// convert arbitrary numeric array to arbitrary numeric type
 /// </summary>
 /// <param name="X">input array</param>
 /// <param name="outputType">type description for return type</param>
 /// <returns>converted array</returns>
 /// <remarks> The newly created array will be converted to the type requested. 
 /// <para>Important note: if X matches the type requested, NO COPY will be made for it and the SAME array will be returned!</para></remarks>
 public static ILBaseArray convert(NumericType outputType,  ILArray</*!HC:inType1*/ double > X) {
     if (outputType  == /*!HC:inTypeName*/ NumericType.Double )
         return X; 
     ILBaseArray ret = null; 
     switch (outputType) {
         case NumericType.Double:
             unsafe {
                 double [] retA = ILMemoryPool.Pool.New<double>(X.Dimensions.NumberOfElements);
                 fixed (double * pretA = retA)
                 fixed (/*!HC:inType1*/ double * pX = X.m_data) {
                     double * pStartR = pretA; 
                     double * pEndR = pretA + X.m_data.Length;
                     /*!HC:inType1*/ double * pWalkX = pX; 
                     while (pStartR < pEndR) {
                         *(pStartR++) = (double) *(pWalkX++); 
                     }
                 }
                 ret = new ILArray<double> (retA,X.Dimensions); 
             }
             return ret; 
         case NumericType.Complex:
             unsafe {
                 complex [] retA = ILMemoryPool.Pool.New<complex>(X.Dimensions.NumberOfElements);
                 fixed (complex * pretA = retA)
                 fixed (/*!HC:inType1*/ double * pX = X.m_data) {
                     complex * pStartR = pretA; 
                     complex * pEndR = pretA + X.m_data.Length;
                     /*!HC:inType1*/ double * pWalkX = pX; 
                     while (pStartR < pEndR) {
                         *(pStartR++) = (complex) (*(pWalkX++)); 
                     }
                 }
                 ret = new ILArray<complex> (retA,X.Dimensions); 
             }
             return ret; 
         case NumericType.Byte:
             unsafe {
                 byte [] retA = ILMemoryPool.Pool.New<byte>(X.Dimensions.NumberOfElements);
                 fixed (byte * pretA = retA)
                 fixed (/*!HC:inType1*/ double * pX = X.m_data) {
                     byte * pStartR = pretA; 
                     byte * pEndR = pretA + X.m_data.Length;
                     /*!HC:inType1*/ double * pWalkX = pX; 
                     while (pStartR < pEndR) {
                         *(pStartR++) = (byte) *(pWalkX++); 
                     }
                 }
                 ret = new ILArray<byte> (retA,X.Dimensions); 
             }
             return ret; 
     }
     return ret; 
 }
Exemplo n.º 26
0
        public static ILArray<double> cumsum(ILArray<double> X)
        {
            double[] outArray = ILMemoryPool.Pool.New<double>(X.m_dimensions.NumberOfElements);
            double tally = 0;

            for (int i = 0; i < outArray.Length; i++)
            {
                tally += X.m_data[i];
                outArray[i] = tally;
            }

            return new ILArray<double>(outArray, X.m_dimensions);
        }
Exemplo n.º 27
0
        internal static void turbinesCalculations(out double dTurb, out int nTurb, out double kWake, out ILArray<double> x, out int gridX, out int gridY, out ILArray<double> yOrder, out double dy, out ILArray<int> xTurbC, out ILArray<int> yTurbC, WindTurbineParameters parm, SimParm simParm)
        {
            #region "Used variables declaration"
            ILArray<double> data;
            double rotA;
            int gridRes;
            int endSize;
            ILArray<double> y;
            ILArray<double> xCoor;
            ILArray<double> yCoor;
            ILArray<double> xTurb;
            ILArray<double> yTurb;
            ILArray<double> xOrder;
            int ppp;
            ILArray<double> xGrid;
            ILArray<double> yGrid;
            #endregion

            data = parm.wf.C;
            dTurb = 2 * parm.radius._(1);
            nTurb = parm.N;
            rotA = parm.rotA;
            kWake = parm.kWake;
            gridRes = simParm.gridRes; // Grid Resolution, the lower the number, the higher the amount of points computed.
            endSize = simParm.grid;

            //if (Ct < 0) // !ILMath.isreal(Ct) | 
            {
                //disp('Ct is negative or complex');
            }

            x = _c(1.0, gridRes, endSize);// x-grid.
            y = _c(1.0, gridRes, endSize);// y-grid.
            gridX = length(x); // Number of grid points.
            gridY = length(y); // Number of grid points.

            xCoor = data[_(':'), _(1)]; // Coordiante of turbine, x-position
            yCoor = data[_(':'), _(2)]; // Coordinate of turbine, y-position

            ROTATE_corrd(out xTurb, out yTurb, xCoor, yCoor, rotA); // Rotated (and scaled) coordinates
            WT_order(out xOrder, out yOrder, xTurb, yTurb); // Ordered turbines. 

            ppp = 2; // This parameter is also a bit weird.. But it changes the grid.
            DOMAIN_pt(out xGrid, out _double, gridX, dTurb, xOrder, ppp); // 
            ppp = 5;
            DOMAIN_pt(out yGrid, out dy, gridY, dTurb, yOrder, ppp);

            Turb_centr_coord(out xTurbC, nTurb, gridX, xGrid, xOrder, gridRes); // Determines the grid point closest to the turbine.
            Turb_centr_coord(out yTurbC, nTurb, gridY, yGrid, yOrder, gridRes); // Determines the grid point closest to the turbine. 
        }
Exemplo n.º 28
0
        /// <summary>
        /// Create new ILArray&lt;double&gt;, setting initial element values to one.
        /// </summary>
        /// <returns>Physical ILArray&lt;double&gt; with all elements set to one.</returns>
        public static ILArray<double> ones(params int[] dimensions) {
	        ILDimension dim = new ILDimension(dimensions);
	        double[] data = ILMemoryPool.Pool.New<double>(dim.NumberOfElements);
	        ILArray<double> ret = new ILArray<double>(data, dimensions);
	        return set(ret, 1.0); 
	        {/* unsafe {
		        fixed(double* pData = data) {
			        double* ende = pData + data.Length; 
			        double* curr = pData; 
			        while (curr < ende) 
				        *curr++ = 1.0; 
	        }*/
	        }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Determine if matrix A is lower triangular matrix
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a lower triangular matrix, false otherwise</returns>
        /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if A was not a matrix or if A was null</exception>
        public static bool istrilow(/*!HC:inCls1*/ ILArray<double> A) {
            if (object.Equals(A,null))
                throw new ILArgumentException ("istrilow: A must not be null!"); 
            if (A.IsScalar) {   return true;    }
            if (A.IsEmpty)  {   return false;   }
            if (!A.IsMatrix)
                throw new ILArgumentException ("istrilow: A must be a matrix!"); 
            int n = A.Dimensions[1]; 
            for (int c = 1; c < n; c++) {
                for (int r = 0; r < c; r++){
                    if (A.GetValue(r,c) != /*!HC:zerosVal*/ 0.0 ) return false; 
			    }       
			}
            return true; 
        }
Exemplo n.º 30
0
/*!HC:TYPELIST:
<hycalper>
<type>
    <source>
        inCls1
    </source>
    <destination><![CDATA[ILArray<complex>]]></destination>
    <destination><![CDATA[ILArray<float>]]></destination>
    <destination><![CDATA[ILArray<fcomplex>]]></destination>
</type>
<type>
    <source>
        inCls2
    </source>
    <destination><![CDATA[ILArray<complex>]]></destination>
    <destination><![CDATA[ILArray<float>]]></destination>
    <destination><![CDATA[ILArray<fcomplex>]]></destination>
</type>
<type>
    <source>
        inArr1
    </source>
    <destination>complex</destination>
    <destination>float</destination>
    <destination>fcomplex</destination>
</type>
</hycalper>
*/
        public static bool isequalwithequalnans(/*HC:inCls1*/ ILArray<double> A,/*HC:inCls2*/ ILArray<double> B) {
            if (object.Equals(A,null) || object.Equals(B,null)) {
                return !(object.Equals(A,null) ^ object.Equals(B,null)); 
            }
            if (A.IsEmpty && B.IsEmpty) return true; 
            if (!A.Dimensions.IsSameSize(B.Dimensions)) return false; 
            int pos = 0; 
            foreach (/*!HC:inArr1*/ double a in A.Values) {
                /*!HC:inArr1*/ double b = B.GetValue(pos++); 
                if (/*!HC:inArr1*/ double .IsNaN(a) && /*!HC:inArr1*/ double .IsNaN(b)) continue; 
                if (/*!HC:inArr1*/ double .IsInfinity(a) && /*!HC:inArr1*/ double .IsInfinity(b)) continue; 
                if (b != a) return false; 
            }
            return true;
        }
Exemplo n.º 31
0
            /// <summary>
            /// Creates the index of the shape indices.
            /// </summary>
            /// <param name="shapeIndices">The shape indices.</param>
            /// <returns>index of shape indices</returns>
            /// <remarks>The index of shape indices is used for fast facette lookup while (auto) creating
            /// the normal vectors for the vertices. Therefore, the index of every vertex used in the shape
            /// serves as index for a list of those facettes, where that vertex occures.
            /// <para>TODO: may be replaced by a custom data structure in order to decrease memory requirements?</para></remarks>
            public static Dictionary <int, List <int> > CreateShapeIndicesIndex(ILArray <int> shapeIndices)
            {
                Dictionary <int, List <int> > ret = new Dictionary <int, List <int> >();
                int shapeCount   = shapeIndices.Dimensions[1];
                int vertPerShape = shapeIndices.Dimensions[0];
                int curShapeIdx  = 0;
                int curRowIdx    = 0;

                foreach (int i in shapeIndices.Values)
                {
                    if (!ret.ContainsKey(i))
                    {
                        ret.Add(i, new List <int>());
                    }
                    ret[i].Add(curShapeIdx);
                    curRowIdx++;
                    if (curRowIdx >= vertPerShape)
                    {
                        curRowIdx = 0;
                        curShapeIdx++;
                    }
                }
                return(ret);
            }
Exemplo n.º 32
0
        public void Test_LDA_Performance1000x2000_100()
        {
            int errorCode = 0;

            try {
                LDA lda                 = new LDA();
                ILArray <double> X      = ILMath.horzcat(ILMath.randn(1000, 2000) * 2.0, ILMath.randn(1000, 2000) * -2.0);
                ILLogicalArray   labels = ILMath.tological(ILMath.horzcat(ILMath.ones(1, 2000), ILMath.zeros(1, 2000)));
                labels = labels.Concat(ILMath.tological(ILMath.zeros(1, 2000).Concat(ILMath.ones(1, 2000), 1)), 0);
                ILPerformer    timer = new ILPerformer();
                LDA.Hyperplane C;
                int            rep = 1;
                timer.Tic();
                for (int i = 0; i < rep; i++)
                {
                    C = lda.TrainLDA(X, labels, 0.4);
                }
                timer.Toc();
                Info("Test_LDA_Performance: data: 1000x4000 run " + rep.ToString() + " times in: " + timer.Duration + "ms");
                Success();
            }catch (Exception e) {
                Error(errorCode, e.Message);
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Sinus of array elements
        /// </summary>
        /// <param name="A">input array</param>
        /// <returns>Sinus of elements from input array</returns>
        /// <remarks><para>If the input array is empty, an empty array will be returned.</para>
        /// <para>The array returned will be a dense array.</para></remarks>
        public static /*!HC:outCls*/ ILArray <double> /*!HC:HCfuncname*/ sin(/*!HC:inCls1*/ ILArray <double> A)
        {
            if (A.IsEmpty)
            {
                return /*!HC:outCls*/ (ILArray <double> .empty(A.Dimensions));
            }
            ILDimension inDim = A.Dimensions;

            /*!HC:outArr*/ double [] retDblArr;
            // build ILDimension
            int newLength = inDim.NumberOfElements;

            //retDblArr = new /*!HC:outArr*/ double [newLength];
            retDblArr = ILMemoryPool.Pool.New </*!HC:outArr*/ double> (newLength);
            int leadDimLen = inDim [0];

            // physical -> pointer arithmetic
            unsafe
            {
                fixed(/*!HC:outArr*/ double *pOutArr = retDblArr)
                fixed(/*!HC:inArr1*/ double *pInArr = A.m_data)
                {
                    /*!HC:outArr*/ double *lastElement = pOutArr + retDblArr.Length;
                    /*!HC:outArr*/ double *tmpOut      = pOutArr;
                    /*!HC:inArr1*/ double *tmpIn       = pInArr;

                    while (tmpOut < lastElement)   // HC02
                    /*!HC:HCCompute02*/
                    {
                        *tmpOut++ = /*!HC:HCoperation*/ Math.Sin(*tmpIn++) /*!HC:HCpostOp*/;
                    }
                }
            }

            return(new /*!HC:outCls*/ ILArray <double> (retDblArr, inDim));
        }
Exemplo n.º 34
0
        /// <summary>
        /// Determine if matrix A is upper Hessenberg matrix
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a upper Hessenberg matrix, false otherwise</returns>
        /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if A was null</exception>
        public static bool ishessup(/*!HC:inCls1*/ ILArray <double> A)
        {
            if (object.Equals(A, null))
            {
                throw new ILArgumentException("ishessup: A must not be null!");
            }
            if (A.IsScalar)
            {
                return(true);
            }
            if (A.IsEmpty)
            {
                return(false);
            }
            if (!A.IsMatrix)
            {
                return(false);
            }
            int n = A.Dimensions[1];

            if (n != A.Dimensions[0])
            {
                return(false);
            }
            for (int c = 0; c < n - 2; c++)
            {
                for (int r = c + 2; r < n; r++)
                {
                    if (A.GetValue(r, c) != /*!HC:zerosVal*/ 0.0)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Determine if matrix A is Hermitian matrix
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a Hermitian matrix, false otherwise</returns>
        /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if A was null</exception>
        public static bool ishermitian(ILArray <byte> A)
        {
            if (object.Equals(A, null))
            {
                throw new ILArgumentException("ishessup: A must not be null!");
            }
            if (A.IsScalar)
            {
                return(true);
            }
            if (A.IsEmpty)
            {
                return(false);
            }
            if (!A.IsMatrix)
            {
                return(false);
            }
            int n = A.Dimensions[1];

            if (n != A.Dimensions[0])
            {
                return(false);
            }
            for (int c = 0; c < n; c++)
            {
                for (int r = c + 1; r < n; r++)
                {
                    if (A.GetValue(r, c) != A.GetValue(c, r))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemplo n.º 36
0
// DO NOT EDIT INSIDE THIS REGION !! CHANGES WILL BE LOST !!
        /// <summary>Cosine of array elements</summary>
        /// <param name="A">input array</param>
        /// <returns>Cosine of array elements</returns>
        /// <remarks><para>If the input array is empty, an empty array will be returned.</para>
        /// <para>The array returned will be a dense array.</para></remarks>
        public static ILArray <complex> cos(ILArray <complex> A)
        {
            if (A.IsEmpty)
            {
                return(ILArray <complex> .empty(A.Dimensions));
            }
            ILDimension inDim = A.Dimensions;

            complex [] retDblArr;
            // build ILDimension
            int newLength = inDim.NumberOfElements;

            //retDblArr = new  complex [newLength];
            retDblArr = ILMemoryPool.Pool.New <complex> (newLength);
            int leadDimLen = inDim [0];

            // physical -> pointer arithmetic
            unsafe
            {
                fixed(complex *pOutArr = retDblArr)
                fixed(complex * pInArr = A.m_data)
                {
                    complex *lastElement = pOutArr + retDblArr.Length;
                    complex *tmpOut      = pOutArr;
                    complex *tmpIn       = pInArr;

                    while (tmpOut < lastElement)   // HC02

                    {
                        *tmpOut++ = complex.Cos(*tmpIn++);
                    }
                }
            }

            return(new  ILArray <complex> (retDblArr, inDim));
        }
Exemplo n.º 37
0
        /// <summary>
        /// Rank of matrix inArray
        /// </summary>
        /// <param name="inArray">Matrix</param>
        /// <param name="tolerance">tolerance used to decide, if a singular value is
        /// treated as zero</param>
        /// <returns>rank of matrix inArray</returns>
        /// <remarks>The rank is the number of singular values greater than
        /// tolerance. If tolerance is smaller than zero, the following equation is used as
        /// default: \\
        /// tol = length(inArray) * norm(inArray) * Double.epsilon \\
        /// with
        /// <list type="bullet">
        /// <item>length(inArray) - the longest dimension of inArray</item>
        /// <item>norm(inArray) beeing the largest singular value of inArray, </item>
        /// <item>Double.epsilon - the smallest number greater than zero</item>
        /// </list>
        /// </remarks>
        public static ILArray <double> rank(ILArray <double> inArray, double tolerance)
        {
            if (inArray.Dimensions.NumberOfDimensions > 2)
            {
                throw new ILArgumentSizeException("rank: the input array must be matrix or vector!");
            }
            ILArray <double> ret = svd(inArray);

            if (tolerance < 0)
            {
                tolerance = inArray.Dimensions.Longest * max(ret).GetValue(0) * System.Double.Epsilon;
            }
            // count vector elements: ret must (and will) be physical vector returned from svd
            double count = 0.0;

            foreach (double d in  ret.Values)
            {
                if (d > tolerance)
                {
                    count++;
                }
            }
            return(new ILArray <double>(count));
        }
Exemplo n.º 38
0
            public static ILArray <float> CreateData(int rX, int rY)
            {
                Bitmap          heightmap = Resource1.saltlake;
                int             x         = Math.Min(heightmap.Size.Width, rX);
                int             y         = Math.Min(heightmap.Size.Height, rY);
                ILArray <float> ret       = new ILArray <float>(rX, rY);

                for (int c = 0; c < x; c++)
                {
                    for (int r = 0; r < y; r++)
                    {
                        Color val = heightmap.GetPixel(c, r);
                        ret.SetValue(val.GetBrightness(), r, c);
                    }
                }
                float maxVal = (float)maxall(abs(ret));

                if (maxVal != 0)
                {
                    ret /= maxVal;
                }
                ret *= 50;
                return(ret); // ["0:2:end;0:2:end"];
            }
Exemplo n.º 39
0
        public static ILArray <double> cross(ILArray <double> A, ILArray <double> B, int dim)
        {
            // Input checking
            if (!A.m_dimensions.IsSameShape(B.m_dimensions))
            {
                throw new ILDimensionMismatchException("Inputs must have the same size and shape.");
            }

            ILDimension outDims = A.m_dimensions;

            double[] outArray = ILMemoryPool.Pool.New <double>(outDims.NumberOfElements);

            if (dim >= outDims.NumberOfDimensions || dim < 0)
            {
                throw new Exception("Specified dim is out of bounds of the array!");
            }

            if (outDims[dim] != 3)
            {
                throw new Exception("Must have length 3 in the dimension where the cross product is taken.");
            }

            // Cross Product
            int SID     = outDims.SequentialIndexDistance(dim);
            int crosses = outDims.NumberOfElements / 3;
            int SID2    = 2 * SID;

            for (int i = 0; i < crosses; i++)
            {
                outArray[i]        = A.m_data[SID + i] * B.m_data[SID2 + i] - A.m_data[SID2 + i] * B.m_data[SID + i];
                outArray[SID + i]  = A.m_data[SID2 + i] * B.m_data[i] - A.m_data[i] * B.m_data[SID2 + i];
                outArray[SID2 + i] = A.m_data[i] * B.m_data[SID + i] - A.m_data[SID + i] * B.m_data[i];
            }

            return(new ILArray <double>(outArray, outDims));
        }
Exemplo n.º 40
0
        /// <summary>Locate infinite value elements</summary>
        /// <param name="A">input array</param>
        /// <returns>Logical array with 1 if the corresponding elements of input array is infinite, 0 else.</returns>
        /// <remarks><para>If the input array is empty, an empty array will be returned.</para>
        /// <para>The array returned will be a dense array.</para></remarks>
        public static ILLogicalArray  isinf(ILArray <complex> A)
        {
            if (A.IsEmpty)
            {
                return(ILLogicalArray.empty(A.Dimensions));
            }
            ILDimension inDim = A.Dimensions;

            byte [] retDblArr;
            // build ILDimension
            int newLength = inDim.NumberOfElements;

            //retDblArr = new  byte [newLength];
            retDblArr = ILMemoryPool.Pool.New <byte> (newLength);
            int leadDimLen = inDim [0];

            // physical -> pointer arithmetic
            unsafe
            {
                fixed(byte *pOutArr = retDblArr)
                fixed(complex * pInArr = A.m_data)
                {
                    byte *   lastElement = pOutArr + retDblArr.Length;
                    byte *   tmpOut      = pOutArr;
                    complex *tmpIn       = pInArr;

                    while (tmpOut < lastElement)   // HC02

                    {
                        *tmpOut++ = complex.IsInfinity(*tmpIn++)  ?(byte)1:(byte)0;
                    }
                }
            }

            return(new  ILLogicalArray(retDblArr, inDim));
        }
Exemplo n.º 41
0
        public void ILArrayToFile(ILArray <double> ilarray, int dimensionX, int dimensionY)
        {
            double[,] array = this.GetTwoDimensionalArray(ilarray, dimensionX, dimensionY);

            StringBuilder sb = new StringBuilder();

            sb.Append("{");

            for (int i = 0; i < dimensionX; i++)
            {
                sb.Append("{");

                for (int j = 0; j < dimensionY; j++)
                {
                    sb.Append(array[i, j].ToString());

                    if (j < dimensionY - 1)
                    {
                        sb.Append(",");
                    }
                }

                sb.Append("}");

                if (i < dimensionX - 1)
                {
                    sb.Append(",");
                }

                sb.Append("\r\n");
            }

            sb.Append("}");

            File.WriteAllText(@"D:/TestMatrix.txt", sb.ToString());
        }
Exemplo n.º 42
0
            // code to create the weight
            // Basically only a circle is created and corresponding indices for the quad mappings
            internal static ILCell CreatePendulaWeight()
            {
                // weigth midpoint
                maxAlpha *= 0.999999;
                double a1   = Math.Sin(DateTime.Now.TimeOfDay.TotalMilliseconds / 1000) * maxAlpha;
                double xPos = pLength * Math.Sin(a1);
                double yPos = pLength * Math.Cos(a1);


                // create circle for weight
                ILArray <double> alpha = linspace(0, 2 * pi, vLen);
                ILArray <double> coord = vertcat(
                    cos(alpha) + xPos,
                    pLength - sin(alpha) - yPos,
                    zeros(1, vLen));

                // create mapping for weight edges (quads)
                ILArray <double> maps = counter(0.0, 1.0, 1, vLen - 1);

                maps = vertcat(maps, maps + 1, maps + vLen + 1, maps + vLen);

                // wrap all arrays into an ILCell
                return(new ILCell(new ILBaseArray[] { coord, maps }, 1, 2));
            }
Exemplo n.º 43
0
        /// <summary>Arctangent of array elements </summary>
        /// <param name="A">input array</param>
        /// <returns>Arctangent of array elements</returns>
        /// <remarks><para>If the input array is empty, an empty array will be returned.</para>
        /// <para>The array returned will be a dense array.</para></remarks>
        public static ILArray <double> atan(ILArray <double> A)
        {
            if (A.IsEmpty)
            {
                return(ILArray <double> .empty(A.Dimensions));
            }
            ILDimension inDim = A.Dimensions;

            double [] retDblArr;
            // build ILDimension
            int newLength = inDim.NumberOfElements;

            //retDblArr = new  double [newLength];
            retDblArr = ILMemoryPool.Pool.New <double> (newLength);
            int leadDimLen = inDim [0];

            // physical -> pointer arithmetic
            unsafe
            {
                fixed(double *pOutArr = retDblArr)
                fixed(double *pInArr = A.m_data)
                {
                    double *lastElement = pOutArr + retDblArr.Length;
                    double *tmpOut      = pOutArr;
                    double *tmpIn       = pInArr;

                    while (tmpOut < lastElement)   // HC02

                    {
                        *tmpOut++ = Math.Atan(*tmpIn++);
                    }
                }
            }

            return(new  ILArray <double> (retDblArr, inDim));
        }
Exemplo n.º 44
0
        private void SetExampleScene(ILPanel panel)
        {
            ILScene scene = new ILScene();

            try {
                ILLabel.DefaultFont = new System.Drawing.Font("Helvetica", 8);
                //ilPanel1.Driver = RendererTypes.GDI;

                #region upper left plot
                // prepare some data
                ILArray <float> P = 1,
                                x = ILMath.linspace <float>(-2, 2, 40),
                                y = ILMath.linspace <float>(2, -2, 40);

                ILArray <float> F = ILMath.meshgrid(x, y, P);
                // a simple RBF
                ILArray <float> Z = ILMath.exp(-(1.2f * F * F + P * P));
                // surface expects a single matrix
                Z[":;:;2"] = F; Z[":;:;1"] = P;

                // add a plot cube
                var pc = scene.Add(new ILPlotCube {
                    // shrink viewport to upper left quadrant
                    ScreenRect = new RectangleF(0.05f, 0, 0.4f, 0.5f),
                    // 3D rotation
                    TwoDMode = false,
                    Children =
                    {
                        // add surface
                        new ILSurface(Z)
                        {
                            // disable mouse hover marking
                            Fill      = { Markable = false },
                            Wireframe ={ Markable                 = false },
                            // make it shiny
                            UseLighting = true,
                            Children    = { new ILColorbar() }
                        },
                        //ILLinePlot.CreateXPlots(Z["1:10;:;0"], markers: new List<MarkerStyle>() {
                        //    MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.None,MarkerStyle.Circle, MarkerStyle.Cross, MarkerStyle.Plus, MarkerStyle.TriangleDown }),
                        //new ILLegend("hi","n","ku","zs","le", "blalblalblalblalb\\color{red} hier gehts rot")
                    },
                    Rotation = Matrix4.Rotation(new Vector3(1.1f, -0.4f, -0.69f), 1.3f)
                });

                #endregion

                #region top right plot
                // create a gear shape
                var gear = new ILGear(toothCount: 30, inR: 0.5f, outR: 0.9f)
                {
                    Fill = { Markable = false, Color = Color.DarkGreen }
                };
                // group with right clipping plane
                var clipgroup = new ILGroup()
                {
                    Clipping = new ILClipParams()
                    {
                        Plane0 = new Vector4(1, 0, 0, 0)
                    },
                    Children =
                    {
                        // a camera holding the (right) clipped gear
                        new ILCamera()
                        {
                            // shrink viewport to upper top quadrant
                            ScreenRect = new RectangleF(0.5f, 0, 0.5f, 0.5f),
                            // populate interactive changes back to the global scene
                            IsGlobal = true,
                            // adds the gear to the camera
                            Children ={ gear                },
                            Position = new Vector3(0, 0, -15)
                        }
                    }
                };
                // setup the scene
                var gearGroup = scene.Add(new ILGroup {
                    clipgroup, clipgroup // <- second time: group is cloned
                });

                gearGroup.First <ILCamera>().Parent.Clipping = new ILClipParams()
                {
                    Plane0 = new Vector4(-1, 0, 0, 0)
                };
                // make the left side transparent green
                gearGroup.First <ILTriangles>().Color = Color.FromArgb(100, Color.Green);

                // synchronize both cameras; source: left side
                gearGroup.First <ILCamera>().PropertyChanged += (s, arg) => {
                    gearGroup.Find <ILCamera>().ElementAt(1).CopyFrom(s as ILCamera, false);
                };
                #endregion

                #region left bottom plot
                // start value
                int nrBalls = 10; bool addBalls = true;
                var balls = new ILPoints("balls")
                {
                    Positions = ILMath.tosingle(ILMath.randn(3, nrBalls)),
                    Colors    = ILMath.tosingle(ILMath.rand(3, nrBalls)),
                    Color     = null,
                    Markable  = false
                };
                var leftBottomCam = scene.Add(new ILCamera {
                    ScreenRect = new RectangleF(0, 0.5f, 0.5f, 0.5f),
                    Projection = Projection.Perspective,
                    Children   = { balls }
                });
                // funny label
                string harmony    = @"\color{red}H\color{blue}a\color{green}r\color{yellow}m\color{magenta}o\color{cyan}n\color{black}y\reset
";
                var    ballsLabel = scene.Add(new ILLabel(tag: "harmony")
                {
                    Text     = harmony,
                    Fringe   = { Color = Color.FromArgb(240, 240, 240) },
                    Position = new Vector3(-0.75f, -0.25f, 0)
                });
                long   oldFPS          = 1;
                PointF currentMousePos = new PointF();
                // setup the swarm. Start with a few balls, increase number
                // until framerate drops below 60 fps.
                ILArray <float> velocity = ILMath.tosingle(ILMath.randn(3, nrBalls));
                EventHandler <ILRenderEventArgs> updateBallsRenderFrame = (s, arg) => {
                    // transform viewport coords into 3d scene coords
                    Vector3 mousePos = new Vector3(currentMousePos.X * 2 - 1,
                                                   currentMousePos.Y * -2 + 1, 0);
                    // framerate dropped? -> stop adding balls
                    if (panel.FPS < oldFPS && panel.FPS < 60)
                    {
                        addBalls = false;
                    }
                    oldFPS = panel.FPS;
                    Computation.UpdateBalls(mousePos, balls, velocity, addBalls);
                    // balls buffers have been changed -> must call configure() to publish
                    balls.Configure();
                    // update balls label
                    ballsLabel.Text = harmony + "(" + balls.Positions.DataCount.ToString() + " balls)";
                };

                // saving the mouse position in MouseMove is easier for
                // transforming the coordinates into the viewport
                leftBottomCam.MouseMove += (s, arg) => {
                    // save the mouse position
                    currentMousePos = arg.LocationF;
                };
                panel.BeginRenderFrame += updateBallsRenderFrame;
                m_cleanUpExample        = () => {
                    leftBottomCam.MouseMove -= (s, arg) => {
                        // save the mouse position
                        currentMousePos = arg.LocationF;
                    };
                    panel.BeginRenderFrame -= updateBallsRenderFrame;
                };
                #endregion

                panel.Scene = scene;
            } catch (Exception exc) {
                System.Diagnostics.Trace.WriteLine("ILPanel_Load Error:");
                System.Diagnostics.Trace.WriteLine("====================");
                System.Diagnostics.Trace.WriteLine(exc.ToString());
                MessageBox.Show(exc.ToString());
            }
        }
Exemplo n.º 45
0
        private ILArray <double> calculateDispersion(double[,] matrix)
        {
            ILArray <double> tmp = matrix;

            return(((double[, ])MachineLearning.Learning.Regression.FeatureSubsetSelection.toSystemMatrix <double>((ILMath.multiply(tmp, tmp.T)))).PseudoInverse());
        }
Exemplo n.º 46
0
 protected static ILArray <double> sum(ILArray <double> ilArray)
 {
     return(ILMath.sum(ilArray));
 }
Exemplo n.º 47
0
        protected static double sum_(ILArray <double> ilArray)
        {
            ILArray <double> result = sum(ilArray);

            return(result._Scalar());
        }
Exemplo n.º 48
0
 protected static ILArray <double> reshape(ILArray <double> ilArray, int dim1, int dim2)
 {
     return(ILMath.reshape(ilArray, dim1, dim2));
 }
Exemplo n.º 49
0
 protected static ILArray <double> mean(ILArray <double> ilArray)
 {
     return(ILMath.mean(ilArray));
 }
Exemplo n.º 50
0
 protected static ILArray <double> transpose(ILArray <double> ilArray)
 {
     return(ilArray.T);
 }
Exemplo n.º 51
0
 protected static ILArray <double> max(ILArray <double> ilArray, double value)
 {
     return(ILMath.max(ilArray, value));
 }
Exemplo n.º 52
0
 /// <summary>
 /// Matrix multiplication
 /// </summary>
 /// <param name="star">'*'</param>
 protected static ILArray <double> _m(ILArray <double> ilArray1, char star, ILArray <double> ilArray2)
 {
     return(ILMath.multiply(ilArray1, ilArray2));
 }
Exemplo n.º 53
0
 /// <summary>
 /// Matrix division (matrix equation A * X = B solving)
 /// </summary>
 /// <param name="star">'\'</param>
 protected static ILArray <double> _s(ILArray <double> ilArray1, char backslash, ILArray <double> ilArray2)
 {
     return(ILMath.linsolve(ilArray1, ilArray2));
 }
Exemplo n.º 54
0
 protected static ILArray <int> _int(ILArray <double> ilArray)
 {
     return(ILMath.toint32(ilArray));
 }
Exemplo n.º 55
0
 protected static ILArray <double> _dbl(ILArray <int> ilArray)
 {
     return(ILMath.todouble(ilArray));
 }
Exemplo n.º 56
0
        //protected static bool isempty<T>(ILArray<T> ilArray)
        //{
        //    return ILMath.isempty(ilArray);
        //}

        protected static bool isempty(ILArray <double> ilArray)
        {
            return(ILMath.isempty(ilArray));
        }
Exemplo n.º 57
0
        private double calcVarianceForRunIL(double[] run, ILArray <double> dispersion)
        {
            ILArray <double> vector = run;

            return((double)ILMath.multiply(ILMath.multiply(vector.T, dispersion), vector));
        }
Exemplo n.º 58
0
 protected static ILArray <double> inv(ILArray <double> ilArray)
 {
     return(ILMath.pinv(ilArray));
 }
Exemplo n.º 59
0
        public bool compute(int _sampleSize, int _k)
        {
            if (options.Count == 0)
            {
                return(false);
            }

            // set number of possible levels for each VariableFeature
            numberOfLevels = new Dictionary <NumericOption, int>();
            foreach (NumericOption numOption in options)
            {
                optionToIndex.Add(numOption, optionToIndex.Count);

                List <double> allValuesOfOption = numOption.getAllValues();
                optionToValues.Add(numOption, allValuesOfOption);

                int posLevels = allValuesOfOption.Count;

                if (!rescale || posLevels <= 4) // include all levels if # <= 4
                {
                    numberOfLevels.Add(numOption, posLevels);
                }
                else
                {
                    numberOfLevels.Add(numOption, Convert.ToInt32(4 + Math.Round(Math.Sqrt(posLevels) / 2.0))); // rescale
                }
            }

            // get full factorial design
            double[,] fullFactorial = getFullFactorial(numberOfLevels);

            fullFactorial = filterByNonBooleanconstraints(fullFactorial);

            // create initial random design
            Random rnd = new Random(1);
            Dictionary <int, int> usedCandidates = new Dictionary <int, int>();

            matrix = new double[_sampleSize, options.Count];

            // chose initial candidates from full factorial
            do
            {
                if (usedCandidates.Count >= _sampleSize)
                {
                    break;
                }

                int candidate = rnd.Next(0, fullFactorial.GetLength(0));

                if (!usedCandidates.Values.Contains(candidate))
                {
                    int tmp = usedCandidates.Count;
                    setRowOfMatrixTo(matrix, tmp, fullFactorial, candidate);
                    usedCandidates.Add(tmp, candidate);
                }
            } while (true);

            // Calculate dispersion matrix
            ILArray <double> dispersion = calculateDispersion(matrix);

            // start of k-Exchange algorithm
            bool couplesWithPositiveDelta = true;


            while (couplesWithPositiveDelta)
            {
                Dictionary <int, double> variances = new Dictionary <int, double>();
                for (int i = 0; i < matrix.GetLength(0); i++)
                {
                    variances.Add(i, calcVarianceForRunIL(getRowFromMatrix(matrix, i), dispersion));
                }

                couplesWithPositiveDelta = false;

                foreach (KeyValuePair <int, double> v in variances.OrderByDescending(p => p.Value).Take(_k))
                {
                    // Get deltas for exchange
                    Dictionary <int, double> deltaF = getAllDeltas(usedCandidates[v.Key], fullFactorial);

                    // Get rid of duplicates
                    deltaF = deltaF.Where(c => !usedCandidates.Values.Contains(c.Key)).ToDictionary(dict => dict.Key, dict => dict.Value);

                    // Get exchange candidates
                    KeyValuePair <int, double> eF = deltaF.OrderByDescending(p => p.Value).First();

                    if (eF.Value > epsilon)
                    {
                        setRowOfMatrixTo(matrix, v.Key, fullFactorial, eF.Key);
                        usedCandidates[v.Key]    = eF.Key;
                        dispersion               = calculateDispersion(matrix);
                        couplesWithPositiveDelta = true;
                    }
                }
            }

            // map configuration to valid values that can be passed to the software
            Dictionary <Tuple <NumericOption, int>, double> values = new Dictionary <Tuple <NumericOption, int>, double>();

            foreach (NumericOption opt in options)
            {
                int    maxVal = numberOfLevels[opt] - 1;
                double delta  = opt.Max_value - opt.Min_value;

                for (int i = 0; i <= maxVal; i++)
                {
                    double value = opt.Min_value + (i / (double)maxVal) * delta;
                    value = opt.nearestValidValue(value);
                    values.Add(Tuple.Create(opt, i), value);
                }
            }

            List <Dictionary <NumericOption, double> > configs = new List <Dictionary <NumericOption, double> >();

            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                Dictionary <NumericOption, double> run = new Dictionary <NumericOption, double>();

                int j = 0;
                foreach (NumericOption vf in options)
                {
                    run.Add(vf, values[Tuple.Create(vf, Convert.ToInt32(matrix[i, j]))]);
                    j++;
                }

                configs.Add(run);
            }

            this.selectedConfigurations = configs;

            return(true);
        }
Exemplo n.º 60
0
        protected static double max_(ILArray <double> ilArray)
        {
            ILArray <double> result = MatlabCode.max(ilArray);

            return(result._Scalar());
        }