Ejemplo n.º 1
0
        public void Model(ILArray <double> x, ILArray <double> u, ILMatFile wt, ILMatFile env, double DT, out double Omega, out double Ct, out double Cp)
        {
            // Parameters

            var R   = (double)wt.GetArray <double>("wt_rotor_radius");
            var I   = (double)wt.GetArray <double>("wt_rotor_inertia");
            var Rho = (double)env.GetArray <double>("env_rho");

            // Definitons etc.

            Omega = x.GetValue(0);
            var Ve   = x.GetValue(1);
            var Beta = u.GetValue(0);
            var Tg   = u.GetValue(1);

            // Algorithm

            var Lambda = Omega * R / Ve;

            _eInterpolCp.Interpolate(Beta, Lambda, wt.GetArray <double>("wt_cp_table"), wt.GetArray <double>("wt_cp_beta"), wt.GetArray <double>("wt_cp_tsr"), out Cp);
            _eInterpolCt.Interpolate(Beta, Lambda, wt.GetArray <double>("wt_ct_table"), wt.GetArray <double>("wt_ct_beta"), wt.GetArray <double>("wt_ct_tsr"), out Ct);

            var Tr = 0.5 * Rho * ILMath.pi * Math.Pow(R, 2) * Math.Pow(Ve, 3) * Cp / Omega;

            Omega = Omega + DT * (Tr - Tg) / I; //Integration method: Forward Euler
        }
Ejemplo n.º 2
0
        /// <summary>Bilinear Interpolation</summary>
        /// <param name="X">Vector representing possible X lookups into Z.</param>
        /// <param name="Y">Vector representing possible Y lookups into Z.</param>
        /// <param name="Z">The table values: Z = f(X,Y).
        /// Must be a 2D matrix with X.Count Columns and Y.Count Rows.</param>
        ///
        /// <param name="XI">X component of point to interpolate.</param>
        /// <param name="YI">Y component of point to interpolate.</param>
        /// <returns>Scalar value ZI interpolated at XI,YI: ZI ~= f(XI,YI).</returns>
        public static ILArray <double> linearInterp2D(ILArray <double> X, ILArray <double> Y, ILArray <double> Z, double xi, double yi)
        {
            // 1. Input checking
            if (X.m_dimensions.NumberOfElements != Z.m_dimensions[1] || Y.m_dimensions.NumberOfElements != Z.m_dimensions[0])
            {
                throw new ILDimensionMismatchException("Sizes of X and Y must correspond to Z.Cols and Z.Rows respectively.");
            }

            if (X.m_data.Length < 2)
            {
                throw new ILArgumentSizeException("There must be at least 2 data points to perform interpolation.");
            }

            // 2. Declarations
            double[] x  = X.m_data;
            double[] y  = Y.m_data;
            double[] zi = new double[1];

            double xLeft, xRight, yTop, yBottom;
            double zBottomLeft, zBottomRight, zTopRight, zTopLeft;
            int    xLeftIdx, xRightIdx, yTopIdx, yBottomIdx;

            // 3. Locate grid square
            xRight  = smallestElementGreaterThan(xi, x, out xRightIdx);
            xLeft   = greatestElementLessThan(xi, x, out xLeftIdx);
            yTop    = smallestElementGreaterThan(yi, y, out yTopIdx);
            yBottom = greatestElementLessThan(yi, y, out yBottomIdx);

            if (xLeftIdx < 0 || xRightIdx < 0 || yTopIdx < 0 || yBottomIdx < 0)
            {
                zi[0] = double.NaN;
                goto Finish;
            }

            zBottomLeft  = Z.GetValue(yBottomIdx, xLeftIdx);
            zBottomRight = Z.GetValue(yBottomIdx, xRightIdx);
            zTopRight    = Z.GetValue(yTopIdx, xRightIdx);
            zTopLeft     = Z.GetValue(yTopIdx, xLeftIdx);

            // 4. Perform bilinear interpolation calculation
            double t = (xi - xLeft) / (xRight - xLeft);
            double u = (yi - yBottom) / (yTop - yBottom);

            if (double.IsNaN(t))
            {
                t = 1;
            }
            if (double.IsNaN(u))
            {
                u = 1;
            }

            zi[0] = (1 - t) * (1 - u) * zBottomLeft + t * (1 - u) * zBottomRight + t * u * zTopRight + (1 - t) * u * zTopLeft;

Finish:
            return(new ILArray <double>(zi));
        }
Ejemplo n.º 3
0
            /// <summary>
            /// Calculates the normals.
            /// </summary>
            /// <param name="vertices">vertex array of the shape</param>
            /// <param name="shapeIndices">The shape mapping indices.</param>
            /// <param name="shapeIndicesIndex">Index of the shape indices.</param>
            public static void CalculateNormals(
                VertexType[] vertices
                , ILArray <int> shapeIndices
                , Dictionary <int, List <int> > shapeIndicesIndex)
            {
#if MEASURE_NORMAL_CALCULATION
                DateTime start = DateTime.Now;
#endif
                System.Diagnostics.Debug.Assert(vertices != null && vertices.Length > 0 && vertices[0].StoresNormals);
                // first calculate the normal for all vertices
                ILPoint3Df[] snormals = new ILPoint3Df[shapeIndices.Dimensions[1]];
                for (int shapeCol = 0; shapeCol < snormals.Length; shapeCol++)
                {
                    // crossproduct of vertex: (#1 - #0) x (#2 - #0)
                    int        vi0   = shapeIndices.GetValue(0, shapeCol);
                    int        vi1   = shapeIndices.GetValue(1, shapeCol);
                    int        vi2   = shapeIndices.GetValue(2, shapeCol);
                    ILPoint3Df cross = ILPoint3Df.crossN(
                        vertices[vi1].Position - vertices[vi0].Position,
                        vertices[vi1].Position - vertices[vi2].Position);
                    snormals[shapeCol] = cross;
                }
#if MEASURE_NORMAL_CALCULATION
                TimeSpan crossDone    = DateTime.Now - start;
                DateTime startSorting = DateTime.Now;
                System.Diagnostics.Debug.WriteLine("Normals Calculation: cross products in " + crossDone.TotalMilliseconds.ToString() + "ms");
#endif
                // find all facettes using this vertex
                for (int i = 0; i < vertices.Length; i++)
                {
                    if (!shapeIndicesIndex.ContainsKey(i))
                    {
                        continue;
                    }
                    ILPoint3Df normal = new ILPoint3Df();
                    foreach (int shapeIdx in shapeIndicesIndex[i])
                    {
                        normal += snormals[shapeIdx];
                    }
                    // or should we let OpenGL normalize the normals...?
                    vertices[i].Normal = ILPoint3Df.normalize(normal);

                    //System.Diagnostics.Debug.Assert(
                    //    Math.Abs(Math.Sqrt(
                    //    vertices[0].Normal.X * vertices[0].Normal.X +
                    //    vertices[0].Normal.Y * vertices[0].Normal.Y +
                    //    vertices[0].Normal.Z * vertices[0].Normal.Z) - 1.0) < (double)MachineParameterFloat.eps);
                }
#if MEASURE_NORMAL_CALCULATION
                TimeSpan sortDone = DateTime.Now - startSorting;
                System.Diagnostics.Debug.WriteLine("Normals Calculation: sorting done in " + sortDone.TotalMilliseconds.ToString() + "ms");
#endif
            }
Ejemplo n.º 4
0
        /// <summary>
        /// convert numerical ILArray to single precision floating point precision
        /// </summary>
        /// <param name="X">numeric input array</param>
        /// <returns><![CDATA[ILArray<float>]]> of same size as X having all elements converted to
        /// single precision floating point format.</returns>
        /// <remarks>All overloads of this function will return a solid physical copy
        /// of the input array X.</remarks>
        public static ILArray <float> single(/*!HC:inCls1*/ ILArray <double> X)
        {
            int nrX = X.m_dimensions.NumberOfElements;

            float []        retArr = new float [nrX];
            ILArray <float> ret    = new ILArray <float> (retArr, X.m_dimensions);

            if (X.IsReference)
            {
                for (int i = 0; i < nrX; i++)
                {
                    retArr[i] = (float)X.GetValue(i);
                }
            }
            else
            {
                unsafe
                {
                    fixed(float *outArr = ret.m_data)
                    fixed(/*!HC:inArr1*/ double *inArr = X.m_data)
                    {
                        float *lastElementAfter       = outArr + nrX;
                        float *outArrP                = outArr;
                        /*!HC:inArr1*/ double *inArrP = inArr;

                        while (outArrP < lastElementAfter)
                        {
                            *outArrP++ = (float)*inArrP++;
                        }
                    }
                }
            }
            return(ret);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Polynomial curve fitting of degree n
        /// </summary>
        /// <param name="x">Vector of X values</param>
        /// <param name="y">Vector of Y values</param>
        /// <param name="n">Degress of polynomial to fit</param>
        /// <returns>Vector of polynomial coefficients [p1, p2, .., pn+1], fit is p(x) = p1*x^n + p2*x^(n-1) + ...</returns>
        public static ILArray <double> polyfit(ILArray <double> x, ILArray <double> y, int n)
        {
            // Create Vandermonde matrix [[x0^n, x0^(n-1), ..., 1], [x1^n, x1^(n-1), ..., 1], ...]
            if (!x.IsVector || !y.IsVector)
            {
                throw new ILArgumentException("x and y must be vectors");
            }
            if (x.Length != y.Length)
            {
                throw new ILArgumentException("x and y must have the same length");
            }
            int m = x.Length;
            ILArray <double> V = new ILArray <double>(m, n + 1);

            for (int i = 0; i < m; ++i)
            {
                double vElement = 1;
                double currentX = x.GetValue(i);
                for (int j = n; j >= 0; --j)
                {
                    V[i, j]   = vElement;
                    vElement *= currentX;
                }
            }
            ILArray <double> coefficients = ILMath.linsolve(V, y);

            return(coefficients);
        }
Ejemplo n.º 6
0
        public static bool isequalwithequalnans(/*HC:*/ ILArray <complex> A, /*HC:*/ ILArray <complex> 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 (complex a in A.Values)
            {
                complex b = B.GetValue(pos++);
                if (complex.IsNaN(a) && complex.IsNaN(b))
                {
                    continue;
                }
                if (complex.IsInfinity(a) && complex.IsInfinity(b))
                {
                    continue;
                }
                if (b != a)
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// update composite shape
        /// </summary>
        /// <param name="X">x coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Y">y coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="Z">z coordinates, vector of length <see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/></param>
        /// <param name="mapping">Mapping of shapes, composes shapes out of vertices. Matrix having
        /// <see cref="ILNumerics.Drawing.Shapes.ILShape&lt;T>.VerticesPerShape"/> rows.
        /// Every element in a column specifies the index of a vertex according to its position in X,Y,Z.
        /// The <see cref="ILNumerics.Drawing.Shapes.ILShape&lt;T>.VerticesPerShape"/> elements in a column therefore
        /// compose a single shape. Vertices may get used arbitrary times (or not at all). All elements must be
        /// positive integer values in range 0...[<see cref="ILNumerics.Drawing.Shapes.ILShape.VertexCount"/>-1].</param>
        /// <remarks>All vertices of the shape are updated with the data specified in X,Y and Z. Neither the colors or any
        /// other data of vertices are changed. The shape is invalidated for reconfiguration at next redraw. </remarks>
        public void Update(ILBaseArray X, ILBaseArray Y, ILBaseArray Z, ILBaseArray mapping)
        {
            if (!X.IsVector || !Y.IsVector || !Z.IsVector || X.Length != Y.Length || Y.Length != Z.Length)
            {
                throw new ILArgumentException("numeric vectors of same length expected for: X, Y and Z");
            }
            if (mapping == null || mapping.IsEmpty || !mapping.IsMatrix || !mapping.IsNumeric || mapping.Dimensions[0] != VerticesPerShape)
            {
                throw new ILArgumentException("mapping must be a numeric matrix, " + VerticesPerShape.ToString() + " rows, each column specifies indices for the vertices of a single shape.");
            }
            if (mapping is ILArray <int> )
            {
                m_shapeIndices = (mapping as ILArray <int>).C;
            }
            else
            {
                m_shapeIndices = ILMath.toint32(mapping);
            }
            ILArray <float> fX = ILMath.tosingle(X);
            ILArray <float> fY = ILMath.tosingle(Y);
            ILArray <float> fZ = ILMath.tosingle(Z);

            for (int i = 0; i < m_vertices.Length; i++)
            {
                m_vertices[i].XPosition = fX.GetValue(i);
                m_vertices[i].YPosition = fY.GetValue(i);
                m_vertices[i].ZPosition = fZ.GetValue(i);
            }
            Invalidate();
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Determine if matrix A is upper triangular matrix
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a upper 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 istriup(ILArray <byte> A)
        {
            if (object.Equals(A, null))
            {
                throw new ILArgumentException("istriup: A must not be null!");
            }
            if (A.IsScalar)
            {
                return(true);
            }
            if (A.IsEmpty)
            {
                return(false);
            }
            if (!A.IsMatrix)
            {
                throw new ILArgumentException("istriup: A must be matrix or scalar!");
            }
            int m = A.Dimensions[0];
            int n = A.Dimensions[1];

            for (int c = 0; c < n; c++)
            {
                for (int r = c + 1; r < m; r++)
                {
                    if (A.GetValue(r, c) != 0.0)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 10
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);
        }
Ejemplo n.º 11
0
        protected static string num2str(ILArray <double> ilArray)
        {
            if (ilArray == null)
            {
                return(null);
            }
            string serializedILArray = string.Empty;//string.Format("{0}", ilArray.Dimensions);

            serializedILArray += "[";
            for (var i = 0; i < ilArray.Size[0]; i++)
            {
                if (i > 0)
                {
                    serializedILArray += "; ";
                }
                for (var j = 0; j < ilArray.Size[1]; j++)
                {
                    if (j > 0)
                    {
                        serializedILArray += ", ";
                    }
                    serializedILArray += ilArray.GetValue(i, j).ToString();
                }
            }
            serializedILArray += "]";
            return(serializedILArray);
        }
Ejemplo n.º 12
0
        private void createVertices(int detail)
        {
            //ILArray<float> vertData = Computation.CreateVertices(
            //            m_center,m_radius,horRes,vertRes, out m_shapeIndices);
            ILArray <float> vertData = Computation.CreateVerticesTri(
                detail, out m_shapeIndices);

            Resize(vertData.Dimensions[1]);
            for (int r = 0, pos = 0; r < VertexCount; r++)
            {
                m_vertices[pos].XPosition = vertData.GetValue(0, r) + m_center.X;
                m_vertices[pos].YPosition = vertData.GetValue(1, r) + m_center.Y;
                m_vertices[pos].ZPosition = vertData.GetValue(2, r) + m_center.Z;
                m_vertices[pos].Color     = m_fillColor;
                m_vertices[pos++].Alpha   = m_fillColor.A;
            }
        }
Ejemplo n.º 13
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; 
 }
Ejemplo n.º 14
0
            public static ILArray <int> configureVertices(
                ILArray <float> xVals, ILArray <float> yVals,
                ILArray <float> zVals, ILColormap cmap, C4fN3fV3f[] Vertices, byte opacity)
            {
                int   i = 0, x, y, y0 = zVals.Dimensions[0] - 1;
                float minZ, maxZ;

                if (!zVals.GetLimits(out minZ, out maxZ, false))
                {
                    minZ = maxZ = 1.0f;
                }
                x = 0;
                y = 0;
                ILArray <float> colors = (tosingle((zVals - minZ) / (maxZ - minZ)))[":"] * (cmap.Length - 1);

                colors[isnan(colors)] = 0;
                bool useXvals          = (xVals != null && !xVals.IsEmpty);
                bool useYvals          = (yVals != null && !yVals.IsEmpty);

                foreach (float a in zVals.Values)
                {
                    C4fN3fV3f v = Vertices[i];
                    v.Position = new ILPoint3Df(
                        (useXvals)? xVals.GetValue(y, x): x
                        , (useYvals)? yVals.GetValue(y, x): y0 - y
                        , a);
                    byte r, g, b;
                    cmap.Map(colors.GetValue(i), out r, out g, out b);
                    v.Color       = Color.FromArgb(255, r, g, b);
                    v.Alpha       = opacity;
                    Vertices[i++] = v;
                    // set next position
                    if (++y >= zVals.Dimensions[0])
                    {
                        x++;
                        y = 0;
                    }
                }

                // create quad indices
                int numQuad = (zVals.Dimensions[0] - 1) * (zVals.Dimensions[1] - 1);

                x = 0; y = 0;
                ILArray <double> ret  = zeros(4, numQuad);
                ILArray <double> mult = counter(0.0, 1.0, zVals.Dimensions.ToIntArray());

                mult = mult["0:" + (zVals.Dimensions[0] - 2), "0:" + (zVals.Dimensions[1] - 2)];
                mult = mult[":"].T;

                ret["0;:"] = mult;
                ret["3;:"] = mult + 1;
                mult       = mult + zVals.Dimensions.SequentialIndexDistance(1);
                ret["2;:"] = mult + 1;
                ret["1;:"] = mult;
                return(toint32(ret));
            }
Ejemplo n.º 15
0
        public Bars(Plot2D plot2D, ILArray <double> barStart, ILArray <double> barEnd, ILArray <double> barPosition, ILArray <double> barThickness, BarType barType)
        {
            this.plot2D = plot2D;
            int n = barStart.Length;

            rectangles = new List <Path>();
            Geometry geometry;
            Path     rectangle;
            Rect     bounds          = new Rect();
            Rect     rectangleBounds = new Rect();

            for (int i = 0; i < n; ++i)
            {
                rectangle = new Path();
                rectangles.Add(rectangle);
                if (barType == BarType.Horizontal)
                {
                    rectangleBounds = new Rect(new Point(barStart.GetValue(i), barPosition.GetValue(i) + barThickness.GetValue(i) / 2),
                                               new Point(barEnd.GetValue(i), barPosition.GetValue(i) - barThickness.GetValue(i) / 2));
                }
                else
                {
                    rectangleBounds = new Rect(new Point(barPosition.GetValue(i) + barThickness.GetValue(i) / 2, barStart.GetValue(i)),
                                               new Point(barPosition.GetValue(i) - barThickness.GetValue(i) / 2, barEnd.GetValue(i)));
                }
                geometry                  = new RectangleGeometry(rectangleBounds);
                rectangle.Data            = geometry;
                geometry.Transform        = plot2D.GraphToCanvas;
                rectangle.Fill            = (Brush)(this.GetValue(FillProperty));
                rectangle.StrokeThickness = (double)(this.GetValue(StrokeThicknessProperty));
                rectangle.Stroke          = (Brush)(this.GetValue(StrokeProperty));
                if (i == 0)
                {
                    bounds = rectangleBounds;
                }
                else
                {
                    bounds.Union(rectangleBounds);
                }
            }
            Bounds = bounds;
            SetBindings();
        }
Ejemplo n.º 16
0
        //P_ref is a vector of power refenreces for tehe wind turbine with dimension 1xN
        //v_nac is a vector of wind speed at each wind turbine with dimension 1xN
        //P_demand is a scale of the wind farm power demand.
        //parm is a struct of wind turbine parameters e.g. NREL5MW
        public static void DistributePower(ILArray <double> v_nac, double P_demand, ILArray <double> Power, WindTurbineParameters parm, out ILArray <double> P_ref, out ILArray <double> P_a)
        {
            double           rho;
            ILArray <double> R;
            ILArray <double> rated;
            int N;
            ILArray <double> Cp;
            double           P_avail;

            rho   = parm.rho;               //air density for each wind turbine(probably the same for all)
            R     = parm.radius.C;          //rotor radius for each wind turbine(NREL.r=63m)
            rated = parm.rated.C;           //Rated power for each wind turbine(NREL.Prated=5MW)
            N     = parm.N;                 //Number of turbines in windfarm
            Cp    = parm.Cp.C;              // Max cp of the turbines for each wind turbine(NREL.Cp.max=0.45)

            P_a   = ILMath.zeros(N, 1);
            P_ref = ILMath.zeros(N, 1);

            // Compute available power at each turbine
            for (var i = 0; i <= N - 1; i++)
            {
                //P_a=A*pi*r*r*Cp*v*v*v
                P_a[i] = Math.Min(rated.GetValue(i), (ILMath.pi / 2) * rho * Math.Pow(R.GetValue(i), 2) * Math.Pow(v_nac.GetValue(i), 3) * Cp.GetValue(i));
            }

            //Compute total available power
            P_avail = (double)ILMath.sum(P_a);

            //Distribute power according to availibility
            for (var i = 0; i <= N - 1; i++)
            {
                if (P_demand < P_avail)
                {
                    P_ref[i] = Math.Max(0, Math.Min(rated.GetValue(i), P_demand * P_a.GetValue(i) / P_avail));
                }
                else
                {
                    P_ref[i] = P_a.GetValue(i);
                }
            }
        }
        //P_ref is a vector of power refenreces for tehe wind turbine with dimension 1xN
        //v_nac is a vector of wind speed at each wind turbine with dimension 1xN
        //P_demand is a scale of the wind farm power demand.
        //parm is a struct of wind turbine parameters e.g. NREL5MW
        public static void DistributePower(ILArray<double> v_nac, double P_demand, ILArray<double> Power, WindTurbineParameters parm, out ILArray<double> P_ref, out ILArray<double> P_a)
        {
            double rho;
            ILArray<double> R;
            ILArray<double> rated;
            int N;
            ILArray<double> Cp;
            double P_avail;

            rho = parm.rho;                 //air density for each wind turbine(probably the same for all)
            R = parm.radius.C;              //rotor radius for each wind turbine(NREL.r=63m)
            rated = parm.rated.C;           //Rated power for each wind turbine(NREL.Prated=5MW)
            N = parm.N;                     //Number of turbines in windfarm
            Cp = parm.Cp.C;                 // Max cp of the turbines for each wind turbine(NREL.Cp.max=0.45)

            P_a = ILMath.zeros(N, 1);
            P_ref = ILMath.zeros(N, 1);

            // Compute available power at each turbine
            for (var i = 0; i <= N - 1; i++)
            {
                //P_a=A*pi*r*r*Cp*v*v*v
                P_a[i] = Math.Min(rated.GetValue(i), (ILMath.pi / 2) * rho * Math.Pow(R.GetValue(i), 2) * Math.Pow(v_nac.GetValue(i), 3) * Cp.GetValue(i));
            }

            //Compute total available power
            P_avail = (double)ILMath.sum(P_a);

            //Distribute power according to availibility
            for (var i = 0; i <= N - 1; i++)
            {
                if (P_demand < P_avail)
                {
                    P_ref[i] = Math.Max(0, Math.Min(rated.GetValue(i), P_demand * P_a.GetValue(i) / P_avail));
                }
                else
                {
                    P_ref[i] = P_a.GetValue(i);
                }
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// copy upper triangle from PHYSICAL array A
 /// </summary>
 /// <typeparam name="T">arbitrary inner type </typeparam>
 /// <param name="A">PHYSICAL ILArray</param>
 /// <param name="m">number of rows</param>
 /// <param name="n">number of columns</param>
 /// <returns>newly created physical array with the upper triangle of A</returns>
 /// <remarks>no checks are made for m,n fit inside A!</remarks>
 internal static ILArray <T> copyUpperTriangle <T>(ILArray <T> A, int m, int n)
 {
     T[] arr = ILMemoryPool.Pool.New <T>(m * n);
     for (int r = 0; r < m; r++)
     {
         for (int c = r; c < n; c++)
         {
             arr[r + c * m] = A.GetValue(r, c);
         }
     }
     return(new ILArray <T> (arr, m, n));
 }
Ejemplo n.º 19
0
 /// <summary>
 /// draws a fringe around the render output in fringe color
 /// </summary>
 /// <param name="m_renderer"></param>
 /// <param name="m_rendererQueue"></param>
 /// <param name="dest"></param>
 /// <param name="textOrientation"></param>
 /// <param name="m_color"></param>
 private void drawFringed(IILTextRenderer m_renderer, object m_rendererQueue, Point dest, TextOrientation textOrientation, Color m_color)
 {
     m_renderer.ColorOverride = m_fringeColor;
     for (int i = 0; i < m_fringeOffsets.Dimensions[0]; i++)
     {
         m_renderer.Draw(m_renderQueue
                         , new Point(dest.X + m_fringeOffsets.GetValue(i, 0), dest.Y + m_fringeOffsets.GetValue(i, 1))
                         , TextOrientation.Horizontal, m_fringeColor);
     }
     m_renderer.ColorOverride = Color.Empty;
     m_renderer.Draw(m_renderQueue, dest, TextOrientation.Horizontal, m_color);
 }
Ejemplo n.º 20
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 <complex> 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++)
            {
                if (A.GetValue(c, c).imag != 0.0)
                {
                    return(false);
                }
                for (int r = c + 1; r < n; r++)
                {
                    complex val1 = A.GetValue(r, c); complex val2 = A.GetValue(c, r); if (val1.real != val2.real || val1.imag + val2.imag != 0.0)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Convert vector to grid matrix ILArray[nrow,ncol]
        /// </summary>
        /// <typeparam name="T">type</typeparam>
        /// <param name="vector">vector storing serial value</param>
        /// <param name="novalue">no data value</param>
        /// <returns></returns>
        public ILArray <T> ToILMatrix <T>(ILArray <T> vector, T novalue)
        {
            ILArray <T> matrix = ILMath.zeros <T>(RowCount, ColumnCount);

            //matrix = novalue;
            for (int i = 0; i < ActiveCellCount; i++)
            {
                int[] loc = Topology.ActiveCell[i];
                matrix[RowCount - loc[0] - 1, loc[1]] = vector.GetValue(i);
            }

            return(matrix);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// convert real array to complex array
        /// </summary>
        /// <param name="X">complex input array</param>
        /// <returns>real part of complex array</returns>
        /// <remarks> the newly created array will have a imaginary part of zero.</remarks>
        public static ILArray <complex> real2complex(/*!HC:inCls1*/ ILArray <double> X)
        {
            int nrX = X.m_dimensions.NumberOfElements;

            complex []        retArr = new complex [nrX];
            ILArray <complex> ret    = new ILArray <complex> (retArr, X.m_dimensions);

            for (int i = 0; i < nrX; i++)
            {
                retArr[i] = new  complex((double)X.GetValue(i), (double)0.0);
            }
            return(ret);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// real part of complex array
        /// </summary>
        /// <param name="X">complex input array</param>
        /// <returns>real part of complex array</returns>
        public static ILArray <fcomplex> real2fcomplex(ILArray <float> X)
        {
            int nrX = X.m_dimensions.NumberOfElements;

            fcomplex []        retArr = new fcomplex [nrX];
            ILArray <fcomplex> ret    = new ILArray <fcomplex> (retArr, X.m_dimensions);

            for (int i = 0; i < nrX; i++)
            {
                retArr[i] = new  fcomplex((float)X.GetValue(i), (float)0.0);
            }
            return(ret);
        }
Ejemplo n.º 24
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);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// create complex array out of real and imaginary part
        /// </summary>
        /// <param name="real">real array for real part</param>
        /// <param name="imag">real array for imaginary part</param>
        /// <returns>complex array having the real- and part imaginary parts constructed out of
        /// real and imag.</returns>
        /// <remarks>real and imag must be the same length. Eather one may be a row- or a column vector.
        /// The array returned will be the same size as real.</remarks>
        public static ILArray <fcomplex> real2fcomplex(/*!HC:inCls1*/ ILArray <double> real, /*!HC:inCls1*/ ILArray <double> imag)
        {
            int nrX = real.m_dimensions.NumberOfElements;

            fcomplex []        retArr = new fcomplex [nrX];
            ILArray <fcomplex> ret    = new ILArray <fcomplex> (retArr, real.m_dimensions);

            for (int i = 0; i < nrX; i++)
            {
                retArr[i] = new  fcomplex((float)real.GetValue(i), (float)imag.GetValue(i));
            }
            return(ret);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// copy lower triangle from PHYSICAL array A, set diagonal to val
 /// </summary>
 /// <typeparam name="T">arbitrary inner type </typeparam>
 /// <param name="A">PHYSICAL ILArray</param>
 /// <param name="m">number of rows</param>
 /// <param name="n">number of columns</param>
 /// <param name="val">value for diagonal entries</param>
 /// <returns>newly created physical array with the lower triangle of A</returns>
 /// <remarks>no checks are made for m,n fit inside A!</remarks>
 private static ILArray <T> copyLowerTriangle <T>(ILArray <T> A, int m, int n, T val)
 {
     T[] arr = ILMemoryPool.Pool.New <T>(m * n);
     for (int r = 0; r < m; r++)
     {
         for (int c = r + 1; c-- > 0;)
         {
             arr[r + m * c] = A.GetValue(r, c);
         }
         arr[r + m * r] = val;
     }
     return(new ILArray <T> (arr, m, n));
 }
Ejemplo n.º 27
0
// DO NOT EDIT INSIDE THIS REGION !! CHANGES WILL BE LOST !!
        /// <summary>
        /// imaginary part of complex array elements
        /// </summary>
        /// <param name="X">complex input array</param>
        /// <returns>imaginary part of complex array</returns>
        public static ILArray <float> imag(ILArray <fcomplex> X)
        {
            int nrX = X.m_dimensions.NumberOfElements;

            float []        retArr = new  float [nrX];
            ILArray <float> ret    = new  ILArray <float> (retArr, X.m_dimensions);

            for (int i = 0; i < nrX; i++)
            {
                retArr[i] = X.GetValue(i).imag;
            }
            return(ret);
        }
Ejemplo n.º 28
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(/*!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; c++)
            {
                /*!HC:testReal*/  //
                for (int r = c + 1; r < n; r++)
                {
                    /*!HC:compareComplx*/
                    if (A.GetValue(r, c) != A.GetValue(c, r))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 29
0
        private string[] generateStringsRandom(int count, int maxLen)
        {
            string []     ret  = new string[count];
            ILArray <int> r    = ILMath.toint32(ILMath.rand(maxLen, count) * 26) + (int)'a';
            ILArray <int> lens = ILMath.toint32(ILMath.rand(1, count) * (maxLen - 1));

            for (int i = 0; i < count; i++)
            {
                ILArray <double> rang  = ILMath.vector(0, lens.GetValue(i));
                ILArray <char>   chars = ILMath.tochar(r[rang, i]);
                ret[i] = new String(chars.Detach().m_data);
            }
            return(ret);
        }
Ejemplo 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;
        }
Ejemplo n.º 31
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);
        }
Ejemplo n.º 32
0
        public void Model(ILArray<double> x, ILArray<double> u, ILMatFile wt, ILMatFile env, double DT, out double Omega, out double Ct, out double Cp)
        {
            // Parameters

            var R = (double)wt.GetArray<double>("wt_rotor_radius");
            var I = (double)wt.GetArray<double>("wt_rotor_inertia");
            var Rho = (double)env.GetArray<double>("env_rho");

            // Definitons etc.

            Omega = x.GetValue(0);
            var Ve = x.GetValue(1);
            var Beta = u.GetValue(0);
            var Tg = u.GetValue(1);

            // Algorithm

            var Lambda = Omega * R / Ve;
            _eInterpolCp.Interpolate(Beta, Lambda, wt.GetArray<double>("wt_cp_table"), wt.GetArray<double>("wt_cp_beta"), wt.GetArray<double>("wt_cp_tsr"), out Cp);
            _eInterpolCt.Interpolate(Beta, Lambda, wt.GetArray<double>("wt_ct_table"), wt.GetArray<double>("wt_ct_beta"), wt.GetArray<double>("wt_ct_tsr"), out Ct);

            var Tr = 0.5 * Rho * ILMath.pi * Math.Pow(R, 2) * Math.Pow(Ve, 3) * Cp / Omega;
            Omega = Omega + DT * (Tr - Tg) / I; //Integration method: Forward Euler
        }
Ejemplo n.º 33
0
        protected void createQuads(ILBaseArray data)
        {
            if (data == null || data.Length == 0)
            {
                Clear();
                m_quads = new ILQuad[0];
            }
            else
            {
                Clear();
                m_quads = new ILQuad[data.Length];
                ILColorEnumerator colors = new ILColorEnumerator();
                ILArray <float>   fData  = null;
                if (data is ILArray <float> )
                {
                    fData = (ILArray <float>)data;
                }
                else
                {
                    fData = ILMath.tosingle(data);
                }
                for (int i = 0; i < m_quads.Length; i++)
                {
                    m_quads[i] = new ILQuad(m_panel);
                    m_quads[i].Border.Visible = true;
                    m_quads[i].FillColor      = colors.NextColor();
                    ILPoint3Df pos = new ILPoint3Df();
                    pos.X = i - m_barWidth / 2;
                    pos.Y = 0;
                    pos.Z = -0.5f;
                    m_quads[i].Vertices[0].Position = pos;
                    pos.X += m_barWidth;
                    m_quads[i].Vertices[1].Position = pos;
                    pos.Y += fData.GetValue(i);
                    m_quads[i].Vertices[2].Position = pos;
                    pos.X -= m_barWidth;
                    m_quads[i].Vertices[3].Position = pos;
                    // label the bar
                    m_quads[i].Label.Text   = i.ToString();
                    m_quads[i].Label.Anchor = new PointF(.5f, -1);

                    // bars will be transparent, oldest fading to OpacityOldest
                    m_quads[i].Opacity = (byte)(m_oldestOpacity + i * (255 - m_oldestOpacity) / m_quads.Length);
                    // add the bar to the scene graph node (base)
                    Add(m_quads[i]);
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// copy lower triangle from PHYSICAL array A, set diagonal to val, permuted version
        /// </summary>
        /// <typeparam name="T">arbitrary inner type </typeparam>
        /// <param name="A">PHYSICAL ILArray</param>
        /// <param name="m">number of rows</param>
        /// <param name="n">number of columns</param>
        /// <param name="perm">mapping for rows, must be converted fom LAPACK version to single indices </param>
        /// <param name="val">value for diagonal entries</param>
        /// <returns>newly created physical array with the lower triangle of A</returns>
        /// <remarks>no checks are made for m,n fit inside A!</remarks>
        private static ILArray <T> copyLowerTrianglePerm <T>(ILArray <T> A, int m, int n, T val, int[] perm)
        {
            T[] arr = ILMemoryPool.Pool.New <T>(m * n);
            int trueRow;

            for (int r = 0; r < perm.Length; r++)
            {
                trueRow = perm[r];
                for (int c = 0; c < trueRow; c++)
                {
                    arr[r + c * m] = A.GetValue(trueRow, c);
                }
                arr[r + m * trueRow] = val;
            }
            return(new ILArray <T> (arr, m, n));
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Polynomial curve fitting of degree n
 /// </summary>
 /// <param name="x">Vector of X values</param>
 /// <param name="y">Vector of Y values</param>
 /// <param name="n">Degress of polynomial to fit</param>
 /// <returns>Vector of polynomial coefficients [p1, p2, .., pn+1], fit is p(x) = p1*x^n + p2*x^(n-1) + ...</returns>
 public static ILArray<double> polyfit(ILArray<double> x, ILArray<double> y, int n)
 {
     // Create Vandermonde matrix [[x0^n, x0^(n-1), ..., 1], [x1^n, x1^(n-1), ..., 1], ...]
     if (!x.IsVector || !y.IsVector)
         throw new ILArgumentException("x and y must be vectors");
     if (x.Length != y.Length)
         throw new ILArgumentException("x and y must have the same length");
     int m = x.Length;
     ILArray<double> V = new ILArray<double>(m, n + 1);
     for (int i = 0; i < m; ++i)
     {
         double vElement = 1;
         double currentX = x.GetValue(i);
         for (int j = n; j >= 0; --j)
         {
             V[i, j] = vElement;
             vElement *= currentX;
         }
     }
     ILArray<double> coefficients = ILMath.linsolve(V, y);
     return coefficients;
 }
Ejemplo n.º 36
0
 /// <summary>
 /// convert numerical ILArray to single precision floating point precision
 /// </summary>
 /// <param name="X">numeric input array</param>
 /// <returns><![CDATA[ILArray<float>]]> of same size as X having all elements converted to 
 /// single precision floating point format.</returns>
 /// <remarks>All overloads of this function will return a solid physical copy 
 /// of the input array X.</remarks>
 public static ILArray<float> single (/*!HC:inCls1*/ ILArray<double> X) {
     int nrX = X.m_dimensions.NumberOfElements; 
     float [] retArr = new float [nrX]; 
     ILArray<float> ret = new ILArray<float> (retArr,X.m_dimensions); 
     if (X.IsReference) {
         for (int i= 0; i < nrX; i++) {
             retArr[i] = (float) X.GetValue(i); 
         }
     } else {
         unsafe {
             fixed (float * outArr = ret.m_data)
             fixed (/*!HC:inArr1*/ double * inArr = X.m_data) {
                 float* lastElementAfter = outArr + nrX;
                 float* outArrP = outArr; 
                 /*!HC:inArr1*/ double * inArrP = inArr; 
                 while (outArrP < lastElementAfter){
                     *outArrP++ = (float)*inArrP++; 
                 }
             }
         }
     }
     return ret; 
 }
Ejemplo n.º 37
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<complex> 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++) {
                 if (A.GetValue(c,c).imag != 0.0) return false;
                for (int r = c+1; r < n; r++){
                    complex val1 = A.GetValue(r,c); complex val2 = A.GetValue(c,r); if (val1.real != val2.real || val1.imag + val2.imag != 0.0) return false;
			    }       
			}
            return true; 
        }
Ejemplo n.º 38
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(/*!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; c++) {
                /*!HC:testReal*/  //
                for (int r = c+1; r < n; r++){
                    /*!HC:compareComplx*/
                    if (A.GetValue(r,c) != A.GetValue(c,r)) return false; 
			    }       
			}
            return true; 
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Find nonzero elements in X
        /// </summary>
        /// <param name="X">input array to be evaluated</param>
        /// <param name="limit">number of elements to search for. If this value is <![CDATA[< 0]]> the function 
        /// will return at most 'limit' nonzero elements from the end of the array ordered by ascending index.
        /// Set to 0 to search full array.</param>
        /// <param name="C">If not null, the function will return the row indices of nonzero elements 
        /// as main return value. C will therefore hold the column indices of those elements. If X
        /// has more than 2 dimensions, the column indices will go along the 2nd dimension.</param>
        /// <param name="V">if not null on entrance, V will hold a copy of the values of nonzero elements returned.</param>
        /// <returns>Vector containing (sequential) indices of nonzero elements in X. If C was 
        /// not null, return value will contain row indices of nonzero elements. </returns>
        /// <remarks>The return type of the index vectors is always 'double'. The return type 
        /// of the element vector 'V' depends on the type of input array X. V and C may be null on 
        /// entrance, indicating their information is not needed. If V is not null (f.e. 'empty()') C must be 
        /// not null also. Any initial data of V or C will be lost.</remarks>
        public static ILArray<double> find( ILArray<byte> X, int limit,
                      ref ILArray<double> C, ref  ILArray<byte> V) {
            double[] retArray;
            bool create_row_columns = !Object.Equals(C, null);
            bool return_values = !Object.Equals(V, null); 
            ILArray<double> ret = null;
            ILDimension inDim = X.Dimensions;
            if (inDim.NumberOfElements == 1) {
                #region SCALAR
                // scalar -> return copy
                if (X.GetValue(0,0) != 0)
                {
                    retArray = new double[1] { 0 };
                    if (create_row_columns) {
                        C = new ILArray<double>(0.0); 
                    }
                    if (return_values) {
                        V = new  ILArray<byte> (new  byte [1]{X.GetValue(0, 0)}); 
                    }
                    return new ILArray<double>(retArray, 1, 1);
                } else {
                    if (create_row_columns) {
                        C = ILArray<double>.empty(0,0);
                    }
                    if (return_values) {
                        V =  ILArray<byte> .empty(0,0);
                    }
                    return ILArray<double>.empty(0,0);
                }
                #endregion SCALAR
            }
            double[] indices;
            int nrElements = inDim.NumberOfElements;
            if (X is ILLogicalArray) nrElements = ((ILLogicalArray)X).NumberTrues;
            if (limit != 0) {
                int lim = Math.Abs ( limit );
                if (lim < nrElements)
                    nrElements = lim;
            }
            indices = ILMemoryPool.Pool.New<double>(nrElements); // init return array with most elements for non logical inarray -> shorten afterwards 
            int foundIdx = 0;

            #region physical
            // physical -> pointer arithmetic
            if (limit >= 0) {
                unsafe {
                    fixed (double* pIndices = indices)
                    fixed ( byte * pX = X.m_data) {
                        byte * lastElement = pX + inDim.NumberOfElements;
                        byte * tmpIn = pX;
                        double* pI = pIndices;
                        double* pFoundLast = pI + indices.Length;
                        while (tmpIn < lastElement && pI < pFoundLast) {
                            if (*tmpIn != 0)
                                *pI++ = (double) ( tmpIn - pX );
                            tmpIn++;
                        }
                        foundIdx = (int) ( pI - pIndices );
                    }
                }
            } else {
                // search backwards 
                unsafe {
                    fixed (double* pIndices = indices)
                    fixed ( byte * pX = X.m_data) {
                        byte * lastElementX = pX; 
                        byte * tmpIn = pX + inDim.NumberOfElements;
                        double* pI = pIndices + indices.Length;
                        while (tmpIn > lastElementX && pI > pIndices) {
                            tmpIn--;
                            if (*tmpIn != 0)
                                *(--pI) = (double) ( tmpIn - pX );
                        }
                        foundIdx = (int) ( pIndices + indices.Length - pI );
                    }
                }
            }
            #endregion

            if (foundIdx == 0) {
                // return empty array
                return ILArray<double>.empty(0,0);
            }
            // transform to row / columns; extract values if needed
            int leadDimLen = inDim[0]; 
            if (create_row_columns) {
                #region RETURN ROWS / COLUMNS /VALUES
                C = new ILArray<double> ( ILMemoryPool.Pool.New<double>(foundIdx), foundIdx, 1 );
                ret = new ILArray<double> ( ILMemoryPool.Pool.New<double>(foundIdx), foundIdx, 1 );
                if (return_values) {
                    V = new  ILArray<byte> ( ILMemoryPool.Pool.New<  byte >(foundIdx), foundIdx, 1 );
                    // copy values, transform to row/columns
                    unsafe {
                        fixed (double* pIndices = indices,
                               pRows = ret.m_data, pCols = C.m_data)
                        fixed ( byte * pValues = V.m_data, pInput = X.m_data) {
                            double* pI = (limit >= 0) ? 
                                    pIndices : (pIndices + indices.Length - foundIdx);
                            double* pLastIndex = pIndices + foundIdx;
                            double* pR = pRows;
                            double* pC = pCols;
                            byte * pV = pValues;
                            byte * pX = pInput;

                            while (pI < pLastIndex) {
                                *pR++ = *( pI ) % leadDimLen;
                                *pC++ = (int) *( pI ) / leadDimLen;
                                *pV++ = *( pInput + (int) *pI++ );
                            }

                        }
                    }
                } else {
                    // just return row / columns 
                    unsafe {
                        fixed (double* pIndices = indices,
                               pRows = ret.m_data, pCols = C.m_data)
                        fixed ( byte * pInput = X.m_data) {
                            double* pI = (limit >= 0) ? 
                                    pIndices : (pIndices + indices.Length - foundIdx);
                            double* pLastIndex = pIndices + foundIdx;
                            double* pR = pRows;
                            double* pC = pCols;
                            while (pI < pLastIndex) {
                                *pR++ = *(pI) % leadDimLen; 
                                *pC++ = (int)(*(pI++) / leadDimLen); 
                            }
                        }
                    }
                }
                #endregion RETURN ROWS / COLUMNS 
            } else {
                #region RETURN INDICES ONLY 
                if (foundIdx != indices.Length) {
                    ret = new ILArray<double> ( ILMemoryPool.Pool.New<double>(foundIdx), foundIdx, 1 );
                    unsafe {
                        fixed (double* pIndices = indices, pRows = ret.m_data){
                            double* pI = (limit >= 0) ? 
                                    pIndices : (pIndices + indices.Length - foundIdx);
                            double* pLastIndex = pIndices + foundIdx;
                            double* pR = pRows;
                            while (pI < pLastIndex) {
                                *pR++ = *pI++;
                            }
                        }
                    }
                } else {
                    ret = new ILArray<double> (indices, foundIdx, 1);
                }
                #endregion RETURN INDICES ONLY
            }
            return ret; 
        }
Ejemplo n.º 40
0
 /// <summary>
 /// QR decomposition, returning Q and R, optionally economical sized
 /// </summary>
 /// <param name="A">general input matrix A of size [m x n]</param>
 /// <param name="R">output parameter. Upper triangular matrix R as 
 /// result of decomposition. Size [m x n] or [min(m,n) x n] (see remarks). </param>
 /// <param name="economySize">if true, the size of Q and R will 
 /// be [m x m] and [m x n] respectively. However, if m &lt; n, 
 /// the economySize parameter has no effect. </param>
 /// <returns>Orthonormal real / unitary complex matrix Q as result 
 /// of decomposition. Size [m x m] or [m x min(m,n)], depending 
 /// on <paramref name="economySize"/> (see remarks below)</returns>
 /// <remarks>The function returns Q and R such that the equation 
 /// <para>A = Q * R</para> holds with roundoff errors. ('*' 
 /// denotes matrix multiplication.) 
 /// <para>Q and R will be solid ILArray's.</para></remarks>
 public static  ILArray<complex> qr(
                         ILArray<complex> A, 
                         ref  ILArray<complex> R, bool economySize) {
     if (Object.Equals(R,null)) {
         return qr(A); 
     }
     int m = A.Dimensions[0]; 
     int n = A.Dimensions[1]; 
     if (m < n && economySize) return qr(A,ref R, false); 
     ILArray<complex> ret;
     if (m == 0 || n == 0) { 
         R = new  ILArray<complex> (new  complex [0],m,n); 
         return  ILArray<complex> .empty(A.Dimensions);  
     }
     int minMN = (m<n)?m:n;
     int info = 0; 
     complex [] tau = new  complex [minMN];  
     complex [] QArr;
     if (m >= n) {
         ret = new  ILArray<complex> (
                             new  complex [(economySize)? minMN * m : m * m],
                             m,(economySize)? minMN: m); 
     } else {
         // economySize is always false ... !
         // a temporary array is needed for extraction of the compact lapack Q (?geqrf)
         ret = new  ILArray<complex> (
                             new  complex [m * n],m,n); 
     }
     QArr = ret.m_data;
     for (int i = m*n; i-->0;) {
         QArr[i] = A.GetValue(i); 
     }
     Lapack.zgeqrf (m,n,QArr,m,tau,ref info);
     if (info != 0) {
         throw new ILArgumentException("qr: error inside lapack library (?geqrf). info=" + info.ToString());
     }
     // extract R, Q
     if (economySize) {
         R = copyUpperTriangle(QArr,m,n,minMN); 
         Lapack.zungqr (m,minMN,tau.Length,QArr,m,tau,ref info); 
     } else {
         R = copyUpperTriangle(QArr,m,n,m); 
         Lapack.zungqr (m,m,tau.Length,QArr,m,tau,ref info); 
         if (m < n) 
             ret = ret[":;0:" + (m-1)]; 
     }
     if (info != 0) 
         throw new ILArgumentException("qr: error in lapack library (???gqr). info=" + info.ToString());
     return ret; 
 }
Ejemplo n.º 41
0
 /// <summary>
 /// elementwise logical 'and' operator 
 /// </summary>
 /// <param name="A">input array A</param>
 /// <param name="B">input array B</param>
 /// <returns>logical array of same size as A and B, elements with result of logical 'and'.</returns>
 /// <remarks>A and B must have the same size or either one may be scalar. If one of A or B is empty, 
 /// an empty array of the same inner element type is returned.</remarks>
 public static ILLogicalArray and( ILArray<byte> A,  ILArray<byte> B) {
     if (A == null || B == null) 
         throw new ILArgumentException ("ILMath.and: A and B must be matrices and cannot be null!");
     if (!A.Dimensions.IsSameShape(B.Dimensions)) 
         throw new ILArgumentException("input arrays must have the same size"); 
     if (A.IsEmpty || B.IsEmpty) 
         return ILLogicalArray.empty(A.Dimensions); 
     if (A.IsScalar) {
         if (A.GetValue(0) != 0) return B != 0.0; 
         byte[] ret = ILMemoryPool.Pool.New<byte>(B.Dimensions.NumberOfElements); 
         return new ILLogicalArray(ret, B.Dimensions,0); 
     } else if (B.IsScalar) {
         if (B.GetValue(0) != 0) return A != 0.0; 
         byte[] ret = ILMemoryPool.Pool.New<byte>(A.Dimensions.NumberOfElements); 
         return new ILLogicalArray(ret, A.Dimensions,0);
     }
     oplogical_bytebyte helper = new  oplogical_bytebyte ();
     return  LogicalBinaryByteOperator (A, B, helper.and);
 }
Ejemplo n.º 42
0
// DO NOT EDIT INSIDE THIS REGION !! CHANGES WILL BE LOST !! 
        /// <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< UInt64 > X) {
            if (outputType  ==  NumericType.UInt64 )
                return X; 
            ILBaseArray ret = null; 
            switch (outputType) {
                case NumericType.Double:
                    unsafe {
                        double [] retA = ILMemoryPool.Pool.New<double>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            fixed (double * pretA = retA) {
                                int c = 0; 
                                double * pStart = pretA; 
                                double * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (double) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (double * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                double * pStartR = pretA; 
                                double * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (double) *(pWalkX++); 
                                }
                            }
                        }
                        ret = new ILArray<double> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.Single:
                    unsafe {
                        float [] retA = ILMemoryPool.Pool.New<float>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (float * pretA = retA) {
                                float * pStart = pretA; 
                                float * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (float) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (float * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                float * pStartR = pretA; 
                                float * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (float) *(pWalkX++); 
                                }
                            }
                        }
                        ret = new ILArray<float> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.Complex:
                    unsafe {
                        complex [] retA = ILMemoryPool.Pool.New<complex>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (complex * pretA = retA) {
                                complex * pStart = pretA; 
                                complex * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (complex * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                complex * pStartR = pretA; 
                                complex * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (complex) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<complex> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.FComplex:
                    unsafe {
                        fcomplex [] retA = ILMemoryPool.Pool.New<fcomplex>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (fcomplex * pretA = retA) {
                                fcomplex * pStart = pretA; 
                                fcomplex * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (fcomplex) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (fcomplex * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                fcomplex * pStartR = pretA; 
                                fcomplex * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (fcomplex) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<fcomplex> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.Byte:
                    unsafe {
                        byte [] retA = ILMemoryPool.Pool.New<byte>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (byte * pretA = retA) {
                                byte * pStart = pretA; 
                                byte * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (byte) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (byte * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                byte * pStartR = pretA; 
                                byte * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (byte) *(pWalkX++); 
                                }
                            }
                        }
                        ret = new ILArray<byte> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.Char:
                    unsafe {
                        char [] retA = ILMemoryPool.Pool.New<char>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (char * pretA = retA) {
                                char * pStart = pretA; 
                                char * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (char) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (char * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                char * pStartR = pretA; 
                                char * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (char) *(pWalkX++); 
                                }
                            }
                        }
                        ret = new ILArray<char> (retA,X.Dimensions); 
                    }
                    return ret; 
                case NumericType.Int16:
                    unsafe {
                        Int16 [] retA = ILMemoryPool.Pool.New<Int16>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (Int16 * pretA = retA) {
                                Int16 * pStart = pretA; 
                                Int16 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (Int16) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (Int16 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                Int16 * pStartR = pretA; 
                                Int16 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (short) *(pWalkX++); 
                                }
                            }
                        }
                        ret = new ILArray<Int16> (retA,X.Dimensions); 
                    }
                    return ret; 
                 case NumericType.Int32:
                    unsafe {
                        Int32 [] retA = ILMemoryPool.Pool.New<Int32>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (Int32 * pretA = retA) {
                                Int32 * pStart = pretA; 
                                Int32 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (Int32) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (Int32 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                Int32 * pStartR = pretA; 
                                Int32 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (Int32) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<Int32> (retA,X.Dimensions); 
                    }
                    return ret; 
                 case NumericType.Int64:
                    unsafe {
                        Int64 [] retA = ILMemoryPool.Pool.New<Int64>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (Int64 * pretA = retA) {
                                Int64 * pStart = pretA; 
                                Int64 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (Int64) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (Int64 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                Int64 * pStartR = pretA; 
                                Int64 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (Int64) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<Int64> (retA,X.Dimensions); 
                    }
                    return ret; 
                 case NumericType.UInt16:
                    unsafe {
                        UInt16 [] retA = ILMemoryPool.Pool.New<UInt16>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (UInt16 * pretA = retA) {
                                UInt16 * pStart = pretA; 
                                UInt16 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (UInt16) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (UInt16 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                UInt16 * pStartR = pretA; 
                                UInt16 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (UInt16) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<UInt16> (retA,X.Dimensions); 
                    }
                    return ret; 
                 case NumericType.UInt32:
                    unsafe {
                        UInt32 [] retA = ILMemoryPool.Pool.New<UInt32>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (UInt32 * pretA = retA) {
                                UInt32 * pStart = pretA; 
                                UInt32 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (UInt32) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (UInt32 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                UInt32 * pStartR = pretA; 
                                UInt32 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (UInt32) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<UInt32> (retA,X.Dimensions); 
                    }
                    return ret; 
                 case NumericType.UInt64:
                    unsafe {
                        UInt64 [] retA = ILMemoryPool.Pool.New<UInt64>(X.Dimensions.NumberOfElements);
                        if (X.IsReference) {
                            int c = 0; 
                            fixed (UInt64 * pretA = retA) {
                                UInt64 * pStart = pretA; 
                                UInt64 * pEnd = pretA + retA.Length; 
                                while (pStart < pEnd) {
                                    *(pStart++) = (UInt64) X.GetValue(c++);
                                }
                            }
                        } else {
                            fixed (UInt64 * pretA = retA)
                            fixed ( UInt64 * pX = X.m_data) {
                                UInt64 * pStartR = pretA; 
                                UInt64 * pEndR = pretA + X.m_data.Length;
                                UInt64 * pWalkX = pX; 
                                while (pStartR < pEndR) {
                                    *(pStartR++) = (UInt64) (*(pWalkX++)); 
                                }
                            }
                        }
                        ret = new ILArray<UInt64> (retA,X.Dimensions); 
                    }
                    return ret; 
            }
            return ret; 
        }
Ejemplo n.º 43
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; 
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Elementwise logical 'not equal' operator
 /// </summary>
 /// <param name="A">input array 1</param>
 /// <param name="B">input array 2</param>
 /// <returns>Logical array having '1' for elements in A not equal elements in B, '0' else</returns>
 /// <remarks><para>On empty input - empty array will be returned.</para>
 /// <para>A and / or B may be scalar. The scalar value will operate on all elements of the other arrays in this case.</para>
 /// <para>If neither of A or B is scalar or empty, the dimensions of both arrays must match.</para></remarks>
 /// <exception cref="ILNumerics.Exceptions.ILDimensionMismatchException">if neither of A or B is scalar and the size of both arrays does not match</exception>
 public static ILLogicalArray neq (ILArray<String> A, ILArray<String> B) {
     if (object.Equals(A,null)) 
         throw new ILArgumentException("neq: input argurment A must not be null!");
     if (object.Equals(B,null)) 
         throw new ILArgumentException("neq: input argurment B must not be null!");
     if (!A.Dimensions.IsSameShape(B.Dimensions)) 
         throw new ILArgumentException("input arrays must have the same size"); 
     if (A.IsEmpty || B.IsEmpty)
         return ILLogicalArray.empty(A.Dimensions); 
     ILLogicalArray ret = null; 
     string scalarValue; 
     ILDimension retDim = null; 
     byte[] retArr = null; 
     if (A.IsScalar) {
         if (B.IsScalar) {
             retDim = new ILDimension(1,1); 
             ret = new ILLogicalArray(new byte[1]{(A.GetValue(0) != B.GetValue(0))?(byte)1:(byte)0},1,1); 
         } else {
             retDim = B.Dimensions; 
             int len = B.Dimensions.NumberOfElements; 
             retArr = new byte[len]; 
             scalarValue = A.GetValue(0); 
             for (int i = 0; i < len; i++) {
                 if (scalarValue != B.GetValue(i)) {
                     retArr[i] = 1; 
                 }
             }
         }
     } else {
         retDim = A.Dimensions; 
         if (B.IsScalar) {
             int len = A.Dimensions.NumberOfElements; 
             retArr = new byte[len]; 
             scalarValue = B.GetValue(0); 
             for (int i = 0; i < len; i++) {
                 if (scalarValue != A.GetValue(i))
                     retArr[i] = 1; 
             }
         } else {
             if (!A.Dimensions.IsSameSize(B.Dimensions))
                 throw new ILDimensionMismatchException("neq: size of arrays must match!");
             int len = A.Dimensions.NumberOfElements; 
             retArr = new byte[len]; 
             for (int i = 0; i < len; i++) {
                 if (A.GetValue(i) != B.GetValue(i))
                     retArr[i] = 1; 
             }
         }
     }
     return new ILLogicalArray(retArr,retDim); 
 }
Ejemplo n.º 45
0
 /// <summary>
 /// QR decomposition with pivoting, possibly economical sized
 /// </summary>
 /// <param name="A">general input matrix A of size [m x n]</param>
 /// <param name="R">output parameter. Upper triangular matrix R as 
 /// result of decomposition. Size [m x n] or [min(m,n) x n] depending 
 /// on <paramref name="economySize"/> (see remarks). </param>
 /// <param name="economySize"><para>if true, <list type="bullet">
 /// <item>the size of Q and R will be [m x m] and [m x n] respectively. 
 /// However, if m &lt; n, the economySize parameter has no effect on 
 /// those sizes.</item>
 /// <item>the output parameter E will be returned as row permutation 
 /// vector rather than as permutation matrix</item></list></para>
 /// <para>if false, this function acts exactly as its overload 
 /// <see cref="ILNumerics.BuiltInFunctions.ILMath.qr(ILArray&lt;double&gt;,ref ILArray&lt;double&gt;,ref ILArray&lt;double&gt;)"/></para>
 /// </param>
 /// <param name="E">permutation matrix from pivoting. Size [m x m]. 
 /// If this is not null, the permutation matrix/ vector E will be returned.
 /// <para>E is of size [n x n], if <paramref name="economySize"/> is 
 /// true, a row vector of length n otherwise</para></param>
 /// <returns>Orthonormal / unitary matrix Q as result of decomposition. 
 /// Size [m x m] or [m x min(m,n)], depending on <paramref name="economySize"/> 
 /// (see remarks below)</returns>
 /// <remarks><para> If <paramref name="economySize"/> is false, the function 
 /// returns Q, R and E such that the equation A * E = Q * R holds except 
 /// roundoff errors. </para>
 /// <para>If <paramref name="economySize"/> is true, E will be a permutation 
 /// vector and the equation A[null,E] == Q * R holds (except roundoff).</para>
 /// <para>E reflects the pivoting of A done inside LAPACK in order to give R 
 /// increasingly diagonal elements.</para>
 /// <para>Q, R and E will be solid ILArray's.</para></remarks>
 public static  ILArray<fcomplex> qr(
                         ILArray<fcomplex> A, 
                         ref  ILArray<fcomplex> R, 
                         ref  ILArray<fcomplex> E, 
                         bool economySize) {
     if (Object.Equals(R,null)) {
         return qr(A); 
     }
     int m = A.Dimensions[0]; 
     int n = A.Dimensions[1]; 
     if (m < n && economySize) return qr(A,ref R, false); 
     ILArray<fcomplex> ret;
     if (m == 0 || n == 0) { 
         R = new  ILArray<fcomplex> (new  fcomplex [0],m,n); 
         E = new  ILArray<fcomplex> (new  fcomplex [0],1,0); 
         return  ILArray<fcomplex> .empty(A.Dimensions);  
     }
     // prepare IPVT
     if (object.Equals(E,null)) 
         return qr(A,ref R,economySize); 
     if (!economySize) {
         E = new  ILArray<fcomplex> (new  fcomplex [n * n],n,n);  
     } else {
         E = new  ILArray<fcomplex> (new  fcomplex [n],1,n);  
     }
     int [] ipvt = new int[n];
     int minMN = (m<n)?m:n;
     int info = 0; 
     fcomplex [] tau = new  fcomplex [minMN];  
     fcomplex [] QArr;
     if (m >= n) {
         ret = new  ILArray<fcomplex> (
                             new  fcomplex [(economySize)? minMN * m : m * m],
                             m,(economySize)? minMN: m); 
     } else {
         // economySize is always false ... !
         // a temporary array is needed for extraction of the compact lapack Q (?geqrf)
         ret = new  ILArray<fcomplex> (
                             new  fcomplex [m * n],m,n); 
     }
     QArr = ret.m_data;
     for (int i = m*n; i-->0;) {
         QArr[i] = A.GetValue(i); 
     }
     Lapack.cgeqp3 (m,n,QArr,m,ipvt,tau,ref info);
     if (info != 0) {
         throw new ILArgumentException("qr: error inside lapack library (?geqrf). info=" + info.ToString());
     }
     // extract R, Q
     if (economySize) {
         R = copyUpperTriangle(QArr,m,n,minMN); 
         Lapack.cungqr (m,minMN,tau.Length,QArr,m,tau,ref info);
         // transform E into out typed vector
         for (int i = 0; i < n; i++) {
              E.m_data[i] = ipvt[i] - 1; 
         }
     } else {
         R = copyUpperTriangle(QArr,m,n,m); 
         Lapack.cungqr (m,m,tau.Length,QArr,m,tau,ref info); 
         if (m < n) 
             ret = ret[":;0:" + (m-1)]; 
         // transform E into matrix
         for (int i = 0; i < n; i++) {
              E.m_data[(ipvt[i]-1) + n * i] =  new fcomplex(1.0f,0.0f) ; 
         }
     }
     if (info != 0) 
         throw new ILArgumentException("qr: error in lapack library (???gqr). info=" + info.ToString());
     return ret; 
 }
Ejemplo n.º 46
0
// DO NOT EDIT INSIDE THIS REGION !! CHANGES WILL BE LOST !! 

        public static bool isequalwithequalnans(/*HC:*/ ILArray<fcomplex> A,/*HC:*/ ILArray<fcomplex> 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 ( fcomplex a in A.Values) {
                fcomplex b = B.GetValue(pos++); 
                if ( fcomplex .IsNaN(a) &&  fcomplex .IsNaN(b)) continue; 
                if ( fcomplex .IsInfinity(a) &&  fcomplex .IsInfinity(b)) continue; 
                if (b != a) return false; 
            }
            return true;
        }
Ejemplo n.º 47
0
        /// <summary> sum two arrays elementwise</summary>
        /// <param name="A">input 1</param>
        /// <param name="B">input 2</param>
        /// <returns> Array with elementwise sum of A and B </returns>
        /// <remarks><para>On empty input - empty array will be returned.</para>
        /// <para>A and / or B may be scalar. The scalar value will operate on all elements of the other arrays in this case.</para>
        /// <para>If neither of A or B is scalar or empty, the dimensions of both arrays must match.</para></remarks>
        public static  ILArray<byte>  max ( ILArray<byte> A,  ILArray<byte> B) {
            if (A.IsEmpty) {
                return  ILArray<byte> .empty(A.Dimensions); 
            }
            if (B.IsEmpty) {
                return  ILArray<byte> .empty(B.Dimensions);
            }
            if (A.IsScalar) {
                if (B.IsScalar) {
                    return new ILArray<byte> (new byte[1]{(A.GetValue(0) > B.GetValue(0))?A.GetValue(0):B.GetValue(0)});
                } else {
                    #region scalar + array  
                    ILDimension inDim = B.Dimensions;

                    byte [] retArr =
                        ILMemoryPool.Pool.New< byte > (inDim.NumberOfElements);

                    byte scalarValue = A.m_data[0]; 
                    
                    unsafe {
                        fixed ( byte * pOutArr = retArr)
                        fixed ( byte * pInArr = B.m_data) {
                            byte * lastElement = pOutArr + retArr.Length;
                            byte * tmpOut = pOutArr;
                            byte * tmpIn = pInArr;
                            while (tmpOut < lastElement) //HC03
                                { *tmpOut++ = (scalarValue > *tmpIn)? scalarValue: *tmpIn; tmpIn++; }
                        }       
                    }

                    return new  ILArray<byte> ( retArr, inDim );
                    #endregion scalar + array
                }
            } else {
                if (B.IsScalar) {
                    #region array + scalar
                    ILDimension inDim = A.Dimensions;

                    byte [] retArr = 
                        ILMemoryPool.Pool.New< byte > (A.m_data.Length);

                    byte scalarValue = B.m_data[0]; 

                    unsafe {
                        fixed ( byte * pOutArr = retArr)
                        fixed ( byte * pInArr = A.m_data) {
                            byte * lastElement = pOutArr + retArr.Length;
                            byte * tmpOut = pOutArr;
                            byte * tmpIn = pInArr;
                            while (tmpOut < lastElement) { //HC06
                                { *tmpOut++ = (scalarValue > *tmpIn)? scalarValue: *tmpIn; tmpIn++; }
                            }
                        }
                    }

                    return new  ILArray<byte> ( retArr, inDim );
                    #endregion array + scalar
                } else {
                    #region array + array
                    ILDimension inDim = A.Dimensions;
                    if (!inDim.IsSameSize ( B.Dimensions ))
                        throw new ILDimensionMismatchException ();

                    byte [] retSystemArr =
                        ILMemoryPool.Pool.New< byte > (inDim.NumberOfElements);

                    unsafe {
                        fixed ( byte * pOutArr = retSystemArr)
                        fixed ( byte * inA1 = A.m_data) 
                        fixed ( byte * inA2 = B.m_data) {
                            byte * pInA1 = inA1; 
                            byte * pInA2 = inA2;
                            byte * poutarr = pOutArr;
                            byte * outEnd = poutarr + retSystemArr.Length;
                            while (poutarr < outEnd) {  //HC11
                                if (*pInA1> *pInA2) { *poutarr++ = *pInA1++; pInA2++;} else {*poutarr++ = *pInA2++; pInA1++;}
                            }
                        }
                    }

                    return new  ILArray<byte> ( retSystemArr, inDim );
                    #endregion array + array
                }
            }
        }
Ejemplo n.º 48
0
 /// <summary>
 /// Create complex array from real and imaginary parts. 
 /// </summary>
 /// <param name="real">Array with real part elements.</param>
 /// <param name="imag">Array with imaginary part elements.</param>
 /// <returns>Complex array constructed out of real and imaginary parts given.</returns>
 /// <exception cref="ILNumerics.Exceptions.ILArgumentException">If the size of both arguments is not the same.</exception>
 public static ILArray<complex> ccomplex(ILArray<double> real, ILArray<double> imag) {
     if (!real.Dimensions.IsSameSize(imag.Dimensions)) 
         throw new ILArgumentException("complex: input arrays must have the same size!");
     ILArray<complex> ret = ILMath.tocomplex(real);
     int nelem = real.Dimensions.NumberOfElements; 
     // here 'ret' is assumed to be physical (NOT reference storage!)
     for (int i = 0; i < nelem; i++) {
         ret.m_data[i].imag = imag.GetValue(i); 
     }
     return ret; 
 }
Ejemplo n.º 49
0
 /// <summary>
 /// Create complex array from real and imaginary parts. 
 /// </summary>
 /// <param name="real">Array with real part elements.</param>
 /// <param name="imag">Array with imaginary part elements.</param>
 /// <returns>Complex array constructed out of real and imaginary parts supplied.</returns>
 /// <exception cref="ILNumerics.Exceptions.ILArgumentException">If the size of both arguments is not the same.</exception>
 public static ILArray<fcomplex> ccomplex(ILArray<float> real, ILArray<float> imag) {
     if (!real.Dimensions.IsSameSize(imag.Dimensions)) 
         throw new ILArgumentException("fcomplex: input arrays must have the same size!");
     ILArray<fcomplex> ret = ILMath.tofcomplex(real);
     int nelem = real.Dimensions.NumberOfElements; 
     int baseIdxRet; 
     for (int i = 0; i < nelem; i++) {
         baseIdxRet = real.getBaseIndex(i); 
         ret.m_data[baseIdxRet].imag = imag.GetValue(i); 
     }
     return ret; 
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Determine if matrix A is upper triangular matrix
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a upper 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 istriup( ILArray<byte> A) {
            if (object.Equals(A,null))
                throw new ILArgumentException ("istriup: A must not be null!"); 
            if (A.IsScalar) {   return true;    }
            if (A.IsEmpty)  {   return false;   }
            if (!A.IsMatrix)
                throw new ILArgumentException ("istriup: A must be matrix or scalar!"); 
            int m = A.Dimensions[0]; 
            int n = A.Dimensions[1]; 
            for (int c = 0; c < n; c++) {
                for (int r = c+1; r < m; r++){
                    if (A.GetValue(r,c) !=  0.0 ) return false; 
			    }       
			}
            return true; 
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Determine if matrix A is lower Hessenberg matrix 
        /// </summary>
        /// <param name="A">Matrix or scalar A of numeric inner type</param>
        /// <returns>true if A is a lower Hessenberg matrix, false otherwise</returns>
        /// <exception cref="ILNumerics.Exceptions.ILArgumentException">if A was null</exception>
        public static bool ishesslow( ILArray<byte> A) {
            if (object.Equals(A,null))
                throw new ILArgumentException ("ishesslow: A must not be null!"); 
            if (A.IsScalar) {   return true;    }
            if (A.IsEmpty)  {   return false;   }
            if (!A.IsMatrix)    return false; 
            int m = A.Dimensions[0]; 
            int n = A.Dimensions[1]; 
            if (m != n)         return false; 
            for (int c = 2; c < n; c++) {
                for (int r = 0; r < c-1; r++){
                    if (A.GetValue(r,c) !=  0.0 ) return false; 
			    }       
			}
            return true; 
        }
Ejemplo n.º 52
0
 /// <summary>
 /// elementwise logical 'or' operator 
 /// </summary>
 /// <param name="A">input array A</param>
 /// <param name="B">input array B</param>
 /// <returns>logical array of same size as A and B, elements with result of logical 'or'.</returns>
 /// <remarks>A and B must have the same size or either one may be scalar.</remarks>
 public static ILLogicalArray or( ILArray<byte> A,  ILArray<byte> B) {
     if (A == null || B == null) 
         throw new ILArgumentException ("ILMath.and: A and B must be matrices and cannot be null!");
     if (!A.Dimensions.IsSameShape(B.Dimensions)) 
         throw new ILArgumentException("input arrays must have the same size"); 
     if (A.IsEmpty || B.IsEmpty) 
         return ILLogicalArray.empty(A.Dimensions); 
     if (A.IsScalar) {
         if (A.GetValue(0) == 0) return B != 0.0; 
         return tological(ones(B.Dimensions));  
     } else if (B.IsScalar) {
         if (B.GetValue(0) == 0) return A != 0.0; 
         return tological(ones(A.Dimensions));  
     }
     oplogical_bytebyte helper = new  oplogical_bytebyte ();
     return  LogicalBinaryByteOperator (A, B, helper.or);
 }
Ejemplo n.º 53
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; 
        }
Ejemplo n.º 54
0
        /// <summary>
		/// Sum elements of A along dimension specified.
		/// </summary>
		/// <param name="A">N-dimensional array</param>
		/// <param name="leadDim">index of dimension to operate along</param>
		/// <returns>array, same size as A, but having the 'leadDim's dimension 
		/// reduced to the length 1 with the sum of all
		/// elements along that dimension.</returns>
        public static  ILArray<UInt16>  sum ( ILArray<UInt16> A, int leadDim) {
            if (leadDim >= A.Dimensions.NumberOfDimensions)
                throw new ILArgumentException("dimension parameter out of range!");
            if (A.IsEmpty)       
                return  ILArray<UInt16> .empty(A.Dimensions); 
            if (A.IsScalar) {
               
                return new  ILArray<UInt16> (new  UInt16 []{A.GetValue(0)},1,1);
            }
            ILDimension inDim = A.Dimensions; 
			int[] newDims = inDim.ToIntArray();
           
            if (inDim[leadDim] == 1) return ( ILArray<UInt16> )A.Clone();
			int newLength;
			 UInt16 [] retDblArr;
			// build ILDimension
			newLength = inDim.NumberOfElements / newDims[leadDim];
			newDims[leadDim] = 1;
			retDblArr = ILMemoryPool.Pool.New< UInt16 >(newLength);
            ILDimension newDimension = new ILDimension(newDims); 
            int incOut = newDimension.SequentialIndexDistance(leadDim); 
            int leadDimLen = inDim[leadDim];
            int posCounter; 
			int nrHigherDims = inDim.NumberOfElements / leadDimLen;
            if (A.IsReference) {
#region Reference storage
				// ========================  REFERENCE double Storage ===========
				if (A.IsMatrix) {
#region Matrix
					////////////////////////////   MATRIX   ///////////////////////
					unsafe {
						ILIndexOffset idxOffset = A.m_indexOffset;
						int secDim = (leadDim + 1) % 2;
						fixed (int* leadDimStart = idxOffset[leadDim],
								secDimStart = idxOffset[secDim]) {
							fixed ( UInt16 * pOutArr = retDblArr)
						    fixed ( UInt16 * pInArr = A.m_data) {
								 UInt16 * tmpOut = pOutArr;
								 UInt16 * lastElementOut = tmpOut + retDblArr.Length;
								 UInt16 * tmpIn = pInArr;
								int* secDimEnd = secDimStart + idxOffset[secDim].Length - 1;
								int* secDimIdx = secDimStart; 
								int* leadDimIdx = leadDimStart;
								int* leadDimEnd = leadDimStart + leadDimLen - 1;
								// start at first element
								while (secDimIdx <= secDimEnd) {
									tmpIn = pInArr + *secDimIdx++; 
									leadDimIdx = leadDimStart;
                                    *tmpOut = 0;
									while (leadDimIdx <= leadDimEnd) {
                                        UInt16 inVal = *(tmpIn + *leadDimIdx++); 
                                        /**/
										 *tmpOut +=  (UInt16) (inVal)  ;
									}
                                    
                                    /**/
                                    tmpOut++;
								}
							}
						}
					} 
#endregion
				} else {
					/////////////////////////////   ARBITRARY DIMENSIONS //////////
#region arbitrary size
					unsafe {
						ILIndexOffset idxOffset = A.m_indexOffset;
						int[] curPosition = new int[A.Dimensions.NumberOfDimensions];
						fixed (int* leadDimStart = idxOffset[leadDim]) {
							fixed ( UInt16 * pOutArr = retDblArr)
							fixed ( UInt16 * pInArr = A.m_data) {
								 UInt16 * tmpOut = pOutArr;
								 UInt16 * lastElementOut = tmpOut + retDblArr.Length - 1;
								 UInt16 * tmpIn = pInArr + A.m_indexOffset.Map(0);
								int* leadDimIdx = leadDimStart;
								int* leadDimEnd = leadDimStart + leadDimLen;
								int dimLen = curPosition.Length;
								int d, curD;
								// start at first element
                                posCounter = retDblArr.Length; 
								while (posCounter-->0) {
									leadDimIdx = leadDimStart;
                                    *tmpOut = 0;
									while (leadDimIdx < leadDimEnd){
                                        UInt16 inVal = *(tmpIn + *leadDimIdx++); 
                                        /**/
										 *tmpOut +=  (UInt16) (inVal)  ;
									 
                                    /**/
                                    }
                                    tmpOut += incOut;
                                    if (tmpOut > lastElementOut)
                                        tmpOut -= (retDblArr.Length - 1);
									// increment higher dimensions 
									d = 1;
									while (d < dimLen) {
										curD = (d + leadDim) % dimLen;
										curPosition[curD]++;
										if (curPosition[curD] < idxOffset[curD].Length) {
											break;
										}
										curPosition[curD] = 0;
										d++;
									}
                                    tmpIn = pInArr + A.m_indexOffset.IndexFromArray(curPosition); 
								}
							}
						}
					}
#endregion
				}
				// ==============================================================
#endregion
			} else {
				// physical -> pointer arithmetic
                if (leadDim == 0) {
#region physical along 1st leading dimension
                    unsafe {
                        fixed ( UInt16 * pOutArr = retDblArr)
                        fixed ( UInt16 * pInArr = A.m_data) {
                            UInt16 * lastElement;
                            UInt16 * tmpOut = pOutArr;
                            UInt16 * tmpIn = pInArr;
                            for (int h = nrHigherDims; h-- > 0; ) {
								lastElement = tmpIn + leadDimLen;
                                *tmpOut = 0;
                                while (tmpIn < lastElement) {
                                    UInt16 inVal = *(tmpIn++); 
                                    /**/
                                    *tmpOut +=  (UInt16) (inVal)  ;
                                }
							    
                                /**/
                                tmpOut++;
                            }
                        }
					}
#endregion
				} else {
#region physical along abitrary dimension
					// sum along abitrary dimension 
                    unsafe {
                        fixed ( UInt16 * pOutArr = retDblArr)
                        fixed ( UInt16 * pInArr = A.m_data) {
                            UInt16 * lastElementOut = newLength + pOutArr -1;
                            int inLength = inDim.NumberOfElements -1; 
                            UInt16 * lastElementIn = pInArr + inLength; 
                            int inc = inDim.SequentialIndexDistance(leadDim); 
                            UInt16 * tmpOut = pOutArr;
                            int outLength = newLength - 1;
                            UInt16 * leadEnd; 
                            UInt16 * tmpIn = pInArr;
                            for (int h = nrHigherDims; h--> 0; ) {
								leadEnd = tmpIn + leadDimLen * inc;
                                *tmpOut = 0;
                                while (tmpIn < leadEnd) {
                                    UInt16 inVal = *(tmpIn); 
                                    tmpIn += inc; 
                                    /**/
                                    *tmpOut +=  (UInt16) (inVal)  ;
                                }
								 
                                /**/
                                tmpOut  += inc;
                                if (tmpOut > lastElementOut)
                                    tmpOut = pOutArr + ((tmpOut - pOutArr) - outLength);
                                if (tmpIn > lastElementIn)
                                    tmpIn = pInArr + ((tmpIn - pInArr) - inLength); 
                            }
                        }
					}
#endregion
				}
			}
			return new  ILArray<UInt16> (retDblArr, newDims);;
        }
Ejemplo n.º 55
0
        /// <summary>
        /// map all elements in A into final colors
        /// </summary>
        /// <param name="A">array with elements to map</param>
        /// <returns>colors as ILArray, the i-th row represents the color for the i-th element of A as RGB tripel.</returns>
        public ILArray<float> Map (ILArray<float> A) {
            ILArray<float> ret = new ILArray<float>(A.Dimensions.NumberOfElements,3); 
            float min, max;
            if (!A.GetLimits(out min, out max) || min == max) {
                // special case: all constant: eturn middle of colormap
                return ILMath.repmat(m_map[m_map.Length / 2, null], ret.Dimensions[0], 1);
            }

            float dist = (m_map.Dimensions[0]-1) / (A.MaxValue - min);
            for (int i = 0; i < ret.Dimensions[0]; i++) {
                double index = (double)(A.GetValue(i)-min)*dist;
                if (index >= m_map.Dimensions[0] - 1) {
                    ret[i, null] = m_map["end;:"];
                    continue;
                } else if (index < 0) {
                    ret[i, null] = m_map["0;:"];
                    continue;
                }
                int find = (int)Math.Floor(index); 
                if (find == index) { 
                    ret[i,null] = m_map[find,null];
                    continue; 
                }
                // interpolate
                index = index - find; 
                float r1 = m_map.GetValue(find,0);
                float g1 = m_map.GetValue(find,1); 
                float b1 = m_map.GetValue(find,2); 
                r1 = (float)(index*(m_map.GetValue(find+1,0)-r1)+r1); 
                g1 = (float)(index*(m_map.GetValue(find+1,1)-g1)+g1); 
                b1 = (float)(index*(m_map.GetValue(find+1,2)-b1)+b1); 
                ret.SetValue(r1,i,0); 
                ret.SetValue(g1,i,1); 
                ret.SetValue(b1,i,2); 
            }
            return ret; 
        }
Ejemplo n.º 56
0
        /// <summary> sum two arrays elementwise</summary>
        /// <param name="A">input 1</param>
        /// <param name="B">input 2</param>
        /// <returns> Array with elementwise sum of A and B </returns>
        /// <remarks><para>On empty input - empty array will be returned.</para>
        /// <para>A and / or B may be scalar. The scalar value will operate on all elements of the 
        /// other array in this case.</para>
        /// <para>If neither of A or B is scalar or empty, the dimensions of both arrays must match.
        /// </para></remarks>
        public static  ILArray<UInt16>  subtract ( ILArray<UInt16> A,  ILArray<UInt16> B) {
            if (A.IsEmpty && B.IsEmpty ) {
                if (!A.Dimensions.IsSameShape(B.Dimensions))
                    throw new ILDimensionMismatchException(); 
                return  ILArray<UInt16> .empty(A.Dimensions); 
            }
            if (A.IsScalar) {
                if (B.IsScalar) {
                   
                    return new  ILArray<UInt16> (new  UInt16 [1]{ saturateUInt16 (A.GetValue(0)  - (double) B.GetValue(0))}, A.Dimensions);
                } else {
                    if (B.IsEmpty) {
                        return  ILArray<UInt16> .empty(B.Dimensions); 
                    }
                    #region scalar + array  
                    ILDimension inDim = B.Dimensions;
                    //  UInt16 [] retArr = new  UInt16 [inDim.NumberOfElements];
                    UInt16 [] retArr = ILMemoryPool.Pool.New< UInt16 > (inDim.NumberOfElements);
                    double scalarValue = A.GetValue(0); 
                    UInt16 tmpValue2; 
                    int leadDim = 0,leadDimLen = inDim [0];
                    if (B.IsReference) {
                        #region Reference storage
                        // walk along the longest dimension (for performance reasons)
                        ILIndexOffset idxOffset = B.m_indexOffset;
                        int incOut = inDim.SequentialIndexDistance ( leadDim );
                        System.Diagnostics.Debug.Assert(!B.IsVector,"Reference arrays of vector size should not exist!"); 
                        for (int i = 1; i < inDim.NumberOfDimensions; i++) {
                            if (leadDimLen < inDim [i]) {
                                leadDimLen = inDim [i];
                                leadDim = i;
                                incOut = inDim.SequentialIndexDistance ( leadDim );
                            }
                        }
                        if (B.IsMatrix) {
                            #region Matrix
                            ////////////////////////////   MATRIX   ////////////////////
                            int secDim = ( leadDim + 1 ) % 2;
                            unsafe {
                                fixed (int* leadDimStart = idxOffset [leadDim],secDimStart = idxOffset [secDim])
                                fixed ( UInt16 * pOutArr = retArr)
                                fixed ( UInt16 * pInArr = B.m_data) {
                                        UInt16 * tmpOut = pOutArr;
                                        UInt16 * tmpIn = pInArr;
                                        UInt16 * tmpOutEnd = pOutArr + inDim.NumberOfElements - 1;
                                        int* secDimEnd = secDimStart + idxOffset [secDim].Length;
                                        int* secDimIdx = secDimStart;
                                        int* leadDimIdx = leadDimStart;
                                        int* leadDimEnd = leadDimStart + leadDimLen;
                                        while (secDimIdx < secDimEnd) {
                                            if (tmpOut > tmpOutEnd)
                                                tmpOut = pOutArr + ( tmpOut - tmpOutEnd);
                                            tmpIn = pInArr + *secDimIdx++;
                                            leadDimIdx = leadDimStart;
                                            while (leadDimIdx < leadDimEnd) {
                                               
                                                *tmpOut =  saturateUInt16 (scalarValue  - (double) (*( tmpIn + *leadDimIdx++ )));
                                                tmpOut += incOut;
                                            }
                                        }
                                }
                            }
                            #endregion
                        } else {
                            #region arbitrary size
                            unsafe {
                                int [] curPosition = new int [B.Dimensions.NumberOfDimensions];
                                fixed (int* leadDimStart = idxOffset [leadDim]) {
                                    fixed ( UInt16 * pOutArr = retArr)
                                    fixed ( UInt16 * pInArr = B.m_data) {
                                        UInt16 * tmpOut = pOutArr;
                                        UInt16 * tmpOutEnd = tmpOut + retArr.Length;
                                        // init lesezeiger: add alle Dimensionen mit 0 (auer leadDim)
                                        UInt16 * tmpIn = pInArr + B.getBaseIndex (0,0);
                                        tmpIn -= idxOffset [leadDim, 0];
                                        int* leadDimIdx = leadDimStart;
                                        int* leadDimEnd = leadDimStart + leadDimLen;
                                        int dimLen = curPosition.Length;
                                        int d, curD;
                                        // start at first element
                                        while (tmpOut < tmpOutEnd) {
                                            leadDimIdx = leadDimStart;
                                            while (leadDimIdx < leadDimEnd) {
                                               
                                                *tmpOut =  saturateUInt16 (scalarValue  - (double) (*(tmpIn + *leadDimIdx++)));
                                                tmpOut += incOut;
                                            }
                                            if (tmpOut > tmpOutEnd)
                                                tmpOut = pOutArr + ( tmpOutEnd - tmpOut );

                                            // increment higher dimensions 
                                            d = 1;
                                            while (d < dimLen) {
                                                curD = ( d + leadDim ) % dimLen;
                                                tmpIn -= idxOffset [curD, curPosition [curD]];
                                                curPosition [curD]++;
                                                if (curPosition [curD] < idxOffset [curD].Length) {
                                                    tmpIn += idxOffset [curD, curPosition [curD]];
                                                    break;
                                                }
                                                curPosition [curD] = 0;
                                                tmpIn += idxOffset [curD, 0];
                                                d++;
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion
                    } else {
                        // physical -> pointer arithmetic
                        #region physical storage
                        unsafe {
                            fixed ( UInt16 * pOutArr = retArr)
                            fixed ( UInt16 * pInArr = B.m_data) {
                                UInt16 * lastElement = pOutArr + retArr.Length;
                                UInt16 * tmpOut = pOutArr;
                                UInt16 * tmpIn = pInArr;
                                while (tmpOut < lastElement) //HC03
                                    
                                	*tmpOut++ =  saturateUInt16 (scalarValue  - (double) (*tmpIn++));
                            }       
                        }
                        #endregion
                    }
                    return new  ILArray<UInt16> ( retArr, inDim );
                    #endregion scalar + array
                }
            } else {
                if (B.IsScalar) {
                    if (A.IsEmpty) {
                        return  ILArray<UInt16> .empty(A.Dimensions);  
                    }
                    #region array + scalar
                    ILDimension inDim = A.Dimensions;
                    //  UInt16 [] retArr = new  UInt16 [inDim.NumberOfElements];
                    UInt16 [] retArr = ILMemoryPool.Pool.New< UInt16 > (inDim.NumberOfElements);
                    double scalarValue = B.GetValue(0); 
                    UInt16 tmpValue1;
                    int leadDim = 0,leadDimLen = inDim [0];
                    if (A.IsReference) {
                        #region Reference storage
                        // walk along the longest dimension (for performance reasons)
                        ILIndexOffset idxOffset = A.m_indexOffset;
                        int incOut = inDim.SequentialIndexDistance ( leadDim );
                        System.Diagnostics.Debug.Assert(!A.IsVector,"Reference arrays of vector size should not exist!"); 
                        for (int i = 1; i < inDim.NumberOfDimensions; i++) {
                            if (leadDimLen < inDim [i]) {
                                leadDimLen = inDim [i];
                                leadDim = i;
                                incOut = inDim.SequentialIndexDistance ( leadDim );
                            }
                        }
                        if (A.IsMatrix) {
                            #region Matrix
                            ////////////////////////////   MATRIX   ////////////////////
                            int secDim = ( leadDim + 1 ) % 2;
                            unsafe {
                                fixed (int* leadDimStart = idxOffset [leadDim],secDimStart = idxOffset [secDim])
                                fixed ( UInt16 * pOutArr = retArr)
                                fixed ( UInt16 * pInArr = A.m_data) {
                                        UInt16 * tmpOut = pOutArr;
                                        UInt16 * tmpIn = pInArr;
                                        UInt16 * tmpOutEnd = pOutArr + inDim.NumberOfElements - 1;
                                        int* secDimEnd = secDimStart + idxOffset [secDim].Length;
                                        int* secDimIdx = secDimStart;
                                        int* leadDimIdx = leadDimStart;
                                        int* leadDimEnd = leadDimStart + leadDimLen;
                                        while (secDimIdx < secDimEnd) {
                                            if (tmpOut > tmpOutEnd)
                                                tmpOut = pOutArr + ( tmpOut - tmpOutEnd);
                                            tmpIn = pInArr + *secDimIdx++;
                                            leadDimIdx = leadDimStart;
                                            while (leadDimIdx < leadDimEnd) { //HC04
                                                
                                                *tmpOut =  saturateUInt16 (*( tmpIn + *leadDimIdx++ )  - (double) scalarValue);
                                                tmpOut += incOut;
                                            }
                                        }
                                }
                            }
                            #endregion
                        } else {
                            #region arbitrary size
                            unsafe {
                                int [] curPosition = new int [A.Dimensions.NumberOfDimensions];
                                fixed (int* leadDimStart = idxOffset [leadDim]) {
                                    fixed ( UInt16 * pOutArr = retArr)
                                    fixed ( UInt16 * pInArr = A.m_data) {
                                        UInt16 * tmpOut = pOutArr;
                                        UInt16 * tmpOutEnd = tmpOut + retArr.Length;
                                        // init readpointer: add all Dimensions with 0 (except leadDim)
                                        UInt16 * tmpIn = pInArr + A.getBaseIndex (0,0);
                                        tmpIn -= idxOffset [leadDim, 0];
                                        int* leadDimIdx = leadDimStart;
                                        int* leadDimEnd = leadDimStart + leadDimLen;
                                        int dimLen = curPosition.Length;
                                        int d, curD;
                                        // start at first element
                                        while (tmpOut < tmpOutEnd) {
                                            leadDimIdx = leadDimStart;
                                            while (leadDimIdx < leadDimEnd) {   //HC05
                                                
                                                *tmpOut =  saturateUInt16 (*(tmpIn + *leadDimIdx++)  - (double) scalarValue);
                                                tmpOut += incOut;
                                            }
                                            if (tmpOut > tmpOutEnd)
                                                tmpOut = pOutArr + ( tmpOutEnd - tmpOut );

                                            // increment higher dimensions 
                                            d = 1;
                                            while (d < dimLen) {
                                                curD = ( d + leadDim ) % dimLen;
                                                tmpIn -= idxOffset [curD, curPosition [curD]];
                                                curPosition [curD]++;
                                                if (curPosition [curD] < idxOffset [curD].Length) {
                                                    tmpIn += idxOffset [curD, curPosition [curD]];
                                                    break;
                                                }
                                                curPosition [curD] = 0;
                                                tmpIn += idxOffset [curD, 0];
                                                d++;
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion
                    } else {
                        // physical -> pointer arithmetic
                        #region physical storage
                        unsafe {
                            fixed ( UInt16 * pOutArr = retArr)
                            fixed ( UInt16 * pInArr = A.m_data) {
                                UInt16 * lastElement = pOutArr + retArr.Length;
                                UInt16 * tmpOut = pOutArr;
                                UInt16 * tmpIn = pInArr;
                                while (tmpOut < lastElement) { //HC06
                                    
                                    *tmpOut++ =  saturateUInt16 (*tmpIn++  - (double) scalarValue);
                                }
                            }
                        }
                        #endregion
                        //tmpValue1 = 0; 
                    }
                    return new  ILArray<UInt16> ( retArr, inDim );
                    #endregion array + scalar
                } else {
                    #region array + array
                    ILDimension inDim = A.Dimensions;
                    if (!inDim.IsSameShape ( B.Dimensions ))
                        throw new ILDimensionMismatchException ();
                    UInt16 [] retSystemArr;
                    UInt16 tmpValue1; 
                    UInt16 tmpValue2; 
                    // retSystemArr = new  UInt16 [inDim.NumberOfElements];
                    retSystemArr = ILMemoryPool.Pool.New< UInt16 > (inDim.NumberOfElements);
                    
                    int leadDim = 0, leadDimLen = inDim [0];
                    // this will most probably be not very fast, but .... :|
                    // walk along the longest dimension (for performance reasons)
                    for (int i = 1; i < inDim.NumberOfDimensions; i++) {
                        if (leadDimLen < inDim [i]) {
                            leadDimLen = inDim [i];
                            leadDim = i;
                        }
                    }
                    unsafe {
                        fixed ( UInt16 * pOutArr = retSystemArr)
                        fixed ( UInt16 * inA1 = A.m_data) 
                        fixed ( UInt16 * inA2 = B.m_data) {
                            UInt16 * pInA1 = inA1; 
                            UInt16 * pInA2 = inA2;
                            int c = 0; 
                            UInt16 * poutarr = pOutArr;
                            UInt16 * outEnd = poutarr + retSystemArr.Length;
                            if (A.IsReference) { 
                                if (!B.IsReference) {
                                    while (poutarr < outEnd) {  //HC07
                                        
                                        *poutarr++ =  saturateUInt16 ( *(pInA1 + A.getBaseIndex(c++))  - (double) (*pInA2++));
                                    }
                                } else {
                                    // optimization for matrix 
                                    if (inDim.NumberOfDimensions < 3) {
                                        fixed (int * pA1idx0 = A.m_indexOffset[0])
                                        fixed (int * pA1idx1 = A.m_indexOffset[1])
                                        fixed (int * pA2idx0 = B.m_indexOffset[0])
                                        fixed (int * pA2idx1 = B.m_indexOffset[1]) {
                                            int r = 0, rLen = A.m_dimensions[0];
                                            int        cLen = A.m_dimensions[1]; 
                                            while (poutarr < outEnd) {   //HC08
                                               
                                                *poutarr++ =  saturateUInt16  ( *(pInA1 + (*(pA1idx0 + r)) + (*(pA1idx1 + c))) - (double)  (*(pInA2+ (*(pA2idx0 + r)) + (*(pA2idx1 + c)))));
                                                if (++r == rLen) {
                                                    r = 0; 
                                                    c++; 
                                                }
                                            }
                                        }
                                    } else {
                                         while (poutarr < outEnd) {  //HC09
                                             
                                             *poutarr++ =  saturateUInt16 ( *(pInA1 + A.getBaseIndex(c)) - (double)  (*(pInA2+B.getBaseIndex(c++))));
                                        }
                                   }
                                   // tmpValue1 = 0; tmpValue2 = 0; 
                                }
                            } else {
                                if (B.IsReference) {
                                    while (poutarr < outEnd) {  //HC10
                                         
                                        *poutarr++ =  saturateUInt16  ( *pInA1++  - (double)  (*(pInA2 + B.getBaseIndex(c++))));
                                    }
                                } else {
                                    while (poutarr < outEnd) {  //HC11
                                         
                                        *poutarr++ =  saturateUInt16 ( *pInA1++ /*HC:*/ - (double)  (*pInA2++));
                                    }
                                }
                            }
                        }
                    }
                    return new  ILArray<UInt16> ( retSystemArr, inDim );
                    #endregion array + array
                }
            }
        }
Ejemplo n.º 57
0
 /// <summary>
 /// elementwise logical 'or' operator 
 /// </summary>
 /// <param name="A">input array A</param>
 /// <param name="B">input array B</param>
 /// <returns>logical array of same size as A and B, elements with result of logical 'or'.</returns>
 /// <remarks>A and B must have the same size or either one may be scalar.</remarks>
 public static ILLogicalArray or(/*!HC:inCls1*/ ILArray<double> A, /*!HC:inCls2*/ ILArray<double> B) {
     if (A == null || B == null) 
         throw new ILArgumentException ("ILMath.and: A and B must be matrices and cannot be null!");
     if (!A.Dimensions.IsSameShape(B.Dimensions)) 
         throw new ILArgumentException("input arrays must have the same size"); 
     if (A.IsEmpty || B.IsEmpty) 
         return ILLogicalArray.empty(A.Dimensions); 
     if (A.IsScalar) {
         if (A.GetValue(0) == 0) return B != 0.0; 
         return tological(ones(B.Dimensions));  
     } else if (B.IsScalar) {
         if (B.GetValue(0) == 0) return A != 0.0; 
         return tological(ones(A.Dimensions));  
     }
     /*!HC:ClsName*/ oplogical_doubledouble helper = new /*!HC:ClsName*/ oplogical_doubledouble ();
     return /*!HC:logicalbinaryop*/ LogicalBinaryDoubleOperator (A, B, helper.or);
 }
Ejemplo n.º 58
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; 
        }
Ejemplo n.º 59
0
 private static ILLogicalArray  LogicalBinaryByteOperator (
     ILArray<byte> A,
     ILArray<byte> B,
     ILLogicalFunctionByteByte operation) {
     ILDimension inDim = A.m_dimensions;
     if (!inDim.IsSameSize ( B.m_dimensions ))
         throw new ILDimensionMismatchException ();
     byte [] retSystemArr;
     // build ILDimension
     int newLength = inDim.NumberOfElements;
     retSystemArr = new byte [newLength];
     int leadDim = 0;
     int leadDimLen = inDim [0];
     if (A.IsReference || B.IsReference) {
         // this will most probably be not very fast, but .... :|
         #region Reference storage
         // walk along the longest dimension (for performance reasons)
         for (int i = 1; i < inDim.NumberOfDimensions; i++) {
             if (leadDimLen < inDim [i]) {
                 leadDimLen = inDim [i];
                 leadDim = i;
             }
         }
         unsafe {
             fixed (byte* pOutArr = retSystemArr) {
                 int c = 0; 
                 byte* poutarr = pOutArr;
                 byte* outEnd = poutarr + newLength;
                 while (poutarr < outEnd) {
                     *poutarr++ = operation ( A.GetValue(c), B.GetValue(c++) );
                 }
             }
         }
         // ==============================================================
         #endregion
     } else {
         // physical -> pointer arithmetic
         #region physical storage
         unsafe {
             fixed ( byte * pInArr1 = A.m_data)
             fixed ( byte * pInArr2 = B.m_data)
             fixed (byte* pOutArr = retSystemArr) {
                 byte* poutarr = pOutArr;
                 byte* poutend = poutarr + newLength;
                 byte * pIn1 = pInArr1;
                 byte * pIn2 = pInArr2;
                 while (poutarr < poutend)
                     *poutarr++ = operation ( *pIn1++, *pIn2++ );
             }
         }
         #endregion
     }
     return new ILLogicalArray ( retSystemArr, inDim.ToIntArray () );
 }
Ejemplo n.º 60
0
 public Bars(Plot2D plot2D, ILArray<double> barStart, ILArray<double> barEnd, ILArray<double> barPosition, ILArray<double> barThickness, BarType barType)
 {
     this.plot2D = plot2D;
     int n = barStart.Length;
     rectangles = new List<Path>();
     Geometry geometry;
     Path rectangle;
     Rect bounds = new Rect();
     Rect rectangleBounds = new Rect();
     for (int i = 0; i < n; ++i)
     {
         rectangle = new Path();
         rectangles.Add(rectangle);
         if (barType == BarType.Horizontal)
         {
             rectangleBounds = new Rect(new Point(barStart.GetValue(i), barPosition.GetValue(i) + barThickness.GetValue(i) / 2),
                 new Point(barEnd.GetValue(i), barPosition.GetValue(i) - barThickness.GetValue(i) / 2));
         }
         else
         {
             rectangleBounds = new Rect(new Point(barPosition.GetValue(i) + barThickness.GetValue(i) / 2, barStart.GetValue(i)),
                 new Point(barPosition.GetValue(i) - barThickness.GetValue(i) / 2, barEnd.GetValue(i)));
         }
         geometry = new RectangleGeometry(rectangleBounds);
         rectangle.Data = geometry;
         geometry.Transform = plot2D.GraphToCanvas;
         rectangle.Fill = (Brush)(this.GetValue(FillProperty));
         rectangle.StrokeThickness = (double)(this.GetValue(StrokeThicknessProperty));
         rectangle.Stroke = (Brush)(this.GetValue(StrokeProperty));
         if (i == 0) bounds = rectangleBounds;
         else
         {
             bounds.Union(rectangleBounds);
         }
     }
     Bounds = bounds;
     SetBindings();
 }