Exemple #1
0
        /// <summary>
        /// Creates a ShortLookupTable to implement the rescale.
        /// The table may have either a SHORT or BYTE input. </summary>
        /// <param name="nElems">    Number of elements the table is to have.
        ///                  This will generally be 256 for byte and
        ///                  65536 for short. </param>
        private ShortLookupTable CreateShortLut(float[] scale, float[] off, int nBands, int nElems)
        {
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: short[][] lutData = new short[scale.Length][nElems];
            short[][] lutData = RectangularArrays.ReturnRectangularShortArray(scale.Length, nElems);

            for (int band = 0; band < scale.Length; band++)
            {
                float   bandScale   = scale[band];
                float   bandOff     = off[band];
                short[] bandLutData = lutData[band];
                for (int i = 0; i < nElems; i++)
                {
                    int val = (int)(i * bandScale + bandOff);
                    if ((val & 0xffff0000) != 0)
                    {
                        if (val < 0)
                        {
                            val = 0;
                        }
                        else
                        {
                            val = 65535;
                        }
                    }
                    bandLutData[i] = (short)val;
                }
            }

            return(new ShortLookupTable(0, lutData));
        }
        /// <param name="intervals"> {xValues[1]-xValues[0], xValues[2]-xValues[1],...} </param>
        /// <param name="solnMatrix"> Sensitivity of second derivatives (x 0.5) </param>
        /// <returns> Array of i coefficient matrices \frac{\partial a^i_j}{\partial y_k} </returns>
        protected internal virtual DoubleMatrix[] getCommonSensitivityCoeffs(double[] intervals, double[][] solnMatrix)
        {
            int nDataPts = intervals.Length + 1;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][][] res = new double[nDataPts - 1][4][nDataPts];
            double[][][] res = RectangularArrays.ReturnRectangularDoubleArray(nDataPts - 1, 4, nDataPts);
            for (int i = 0; i < nDataPts - 1; ++i)
            {
                res[i][3][i]     = 1.0;
                res[i][2][i + 1] = 1.0 / intervals[i];
                res[i][2][i]     = -1.0 / intervals[i];
                for (int k = 0; k < nDataPts; ++k)
                {
                    res[i][0][k]  = solnMatrix[i + 1][k] / 6.0 / intervals[i] - solnMatrix[i][k] / 6.0 / intervals[i];
                    res[i][1][k]  = 0.5 * solnMatrix[i][k];
                    res[i][2][k] += -intervals[i] * solnMatrix[i][k] / 2.0 - intervals[i] * solnMatrix[i + 1][k] / 6.0 + intervals[i] * solnMatrix[i][k] / 6.0;
                }
            }

            DoubleMatrix[] resMat = new DoubleMatrix[nDataPts - 1];
            for (int i = 0; i < nDataPts - 1; ++i)
            {
                resMat[i] = DoubleMatrix.copyOf(res[i]);
            }
            return(resMat);
        }
        /// <param name="values"> Y values of data </param>
        /// <param name="intervals"> (xValues_{i+1} - xValues_{i}) </param>
        /// <param name="slopes"> (yValues_{i+1} - yValues_{i})/(xValues_{i+1} - xValues_{i}) </param>
        /// <param name="slopeSensitivity"> Derivative values of slope with respect to yValues </param>
        /// <param name="firstWithSensitivity"> First derivative values at xValues_i and their yValues dependencies </param>
        /// <returns> Coefficient matrix and its node dependencies </returns>
        public virtual DoubleMatrix[] solveWithSensitivity(double[] values, double[] intervals, double[] slopes, double[][] slopeSensitivity, DoubleArray[] firstWithSensitivity)
        {
            int nData = values.Length;

            double[]       first = firstWithSensitivity[0].toArray();
            DoubleMatrix[] res   = new DoubleMatrix[nData];

            double[][] coef = solve(values, intervals, slopes, first);
            res[0] = DoubleMatrix.copyOf(coef);

            for (int i = 0; i < nData - 1; ++i)
            {
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] coefSense = new double[4][nData];
                double[][] coefSense = RectangularArrays.ReturnRectangularDoubleArray(4, nData);
                Arrays.fill(coefSense[3], 0.0);
                coefSense[3][i] = 1.0;
                for (int k = 0; k < nData; ++k)
                {
                    coefSense[0][k] = -(2.0 * slopeSensitivity[i][k] - firstWithSensitivity[i + 2].get(k) - firstWithSensitivity[i + 1].get(k)) / intervals[i] / intervals[i];
                    coefSense[1][k] = (3.0 * slopeSensitivity[i][k] - firstWithSensitivity[i + 2].get(k) - 2.0 * firstWithSensitivity[i + 1].get(k)) / intervals[i];
                    coefSense[2][k] = firstWithSensitivity[i + 1].get(k);
                }
                res[i + 1] = DoubleMatrix.copyOf(coefSense);
            }

            return(res);
        }
Exemple #4
0
        private DoubleMatrix getAMatrix(double[][] funcMatrix, double[] invSigmaSqr)
        {
            int m = funcMatrix.Length;
            int n = funcMatrix[0].Length;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] a = new double[m][m];
            double[][] a = RectangularArrays.ReturnRectangularDoubleArray(m, m);
            for (int i = 0; i < m; i++)
            {
                double sum = 0;
                for (int k = 0; k < n; k++)
                {
                    sum += FunctionUtils.square(funcMatrix[i][k]) * invSigmaSqr[k];
                }
                a[i][i] = sum;
                for (int j = i + 1; j < m; j++)
                {
                    sum = 0;
                    for (int k = 0; k < n; k++)
                    {
                        sum += funcMatrix[i][k] * funcMatrix[j][k] * invSigmaSqr[k];
                    }
                    a[i][j] = sum;
                    a[j][i] = sum;
                }
            }

            return(DoubleMatrix.copyOf(a));
        }
Exemple #5
0
 /// <summary>
 /// Computu the product of the matrix (m x n) and its transpose (n x m)
 /// </summary>
 /// <returns> matrix of size (m x m) </returns>
 public virtual InsightsMatrix computeAAT()
 {
     if (!_valid)
     {
         throw new Exception("[InsightsMatrix][computeAAT] invalid matrix");
     }
     //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
     //ORIGINAL LINE: final double[][] data = new double[_m][_m];
     //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
     //ORIGINAL LINE: double[][] data = new double[_m][_m];
     double[][] data = RectangularArrays.ReturnRectangularDoubleArray(_m, _m);
     for (int i = 0; i < _m; ++i)
     {
         //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
         //ORIGINAL LINE: final double[] rowI = _data[i];
         double[] rowI = _data[i];
         for (int j = 0; j < _m; ++j)
         {
             //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
             //ORIGINAL LINE: final double[] rowJ = _data[j];
             double[] rowJ = _data[j];
             double   temp = 0;
             for (int k = 0; k < _n; ++k)
             {
                 temp += rowI[k] * rowJ[k];
             }
             data[i][j] = temp;
         }
     }
     return(new InsightsMatrix(data, false));
 }
        //-------------------------------------------------------------------------
        public override DoubleMatrix calculateJacobian(DoubleArray x)
        {
            ArgChecker.notNull(x, "x");
            ArgChecker.isTrue(x.size() == LengthOfDomain, "Incorrect length of x. Is {} but should be {}", x.size(), LengthOfDomain);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] jac = new double[LengthOfRange][LengthOfDomain];
            double[][] jac = RectangularArrays.ReturnRectangularDoubleArray(LengthOfRange, LengthOfDomain);

            int posInput = 0;
            int pos1     = 0;
            int pos2     = 0;

            for (int i = 0; i < nPartitions; i++)
            {
                int          nRows  = yPartition[i];
                int          nCols  = xPartition[i];
                DoubleArray  sub    = x.subArray(posInput, posInput + nCols);
                DoubleMatrix subJac = functions[i].calculateJacobian(sub);
                if (nCols > 0)
                {
                    for (int r = 0; r < nRows; r++)
                    {
                        Array.Copy(subJac.toArrayUnsafe()[r], 0, jac[pos1++], pos2, nCols);
                    }
                    pos2 += nCols;
                }
                else
                {
                    pos1 += nRows;
                }
                posInput += nCols;
            }
            return(DoubleMatrix.copyOf(jac));
        }
Exemple #7
0
        // vidi konstruktore za MLayer
        //    public MatrixBackPropLayer(int inputSize, int outputSize, TransferFunction transferFunction) {
        //        inputs = new double[inputSize];
        //        outputs = new double[outputSize];
        //        weights = new double[outputSize][inputSize];
        //
        //        this.transferFunction = transferFunction;
        //    }



        public MatrixMlpLayer(Layer sourceLayer, MatrixLayer previousLayer, TransferFunction transferFunction)
        {
            this.sourceLayer   = sourceLayer;
            this.previousLayer = previousLayer;
            if (!(previousLayer is MatrixInputLayer))
            {
                ((MatrixMlpLayer)previousLayer).NextLayer = this;
            }
            this.transferFunction = transferFunction;

            this.neuronsCount = sourceLayer.NeuronsCount;
            //          if (sourceLayer.getNeuronAt(neuronsCount-1) instanceof BiasNeuron) this.neuronsCount = this.neuronsCount -1;

            this.inputsCount = previousLayer.Outputs.Length;

            outputs = new double[neuronsCount];
            //          biases = new double[neuronsCount];
            //          deltaBiases = new double[neuronsCount];
            inputs   = new double[inputsCount];
            netInput = new double[neuronsCount];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: weights = new double[neuronsCount][inputsCount];
            weights = RectangularArrays.ReturnRectangularDoubleArray(neuronsCount, inputsCount);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: deltaWeights = new double[neuronsCount][inputsCount];
            deltaWeights = RectangularArrays.ReturnRectangularDoubleArray(neuronsCount, inputsCount);

            errors = new double[neuronsCount];

            copyNeuronsToMatrices();
        }
Exemple #8
0
 public Matrix(double[] vector)
 {
     numberOfRows    = 1;
     numberOfColumns = vector.Length;
     content         = RectangularArrays.ReturnRectangularDoubleArray(numberOfRows, numberOfColumns);
     content[0]      = vector;
 }
        public virtual double?[] getRoots(RealPolynomialFunction1D function)
        {
            ArgChecker.notNull(function, "function");
            double[] coeffs = function.Coefficients;
            int      l      = coeffs.Length - 1;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] hessianDeref = new double[l][l];
            double[][] hessianDeref = RectangularArrays.ReturnRectangularDoubleArray(l, l);
            for (int i = 0; i < l; i++)
            {
                hessianDeref[0][i] = -coeffs[l - i - 1] / coeffs[l];
                for (int j = 1; j < l; j++)
                {
                    hessianDeref[j][i] = 0;
                    if (i != l - 1)
                    {
                        hessianDeref[i + 1][i] = 1;
                    }
                }
            }
            RealMatrix hessian = new Array2DRowRealMatrix(hessianDeref);

            double[]  d      = (new EigenDecomposition(hessian)).RealEigenvalues;
            double?[] result = new double?[d.Length];
            for (int i = 0; i < d.Length; i++)
            {
                result[i] = d[i];
            }
            return(result);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("synthetic-access") @Override public com.opengamma.strata.collect.array.DoubleMatrix apply(final com.opengamma.strata.collect.array.DoubleArray a)
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
            public override DoubleMatrix apply(DoubleArray a)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int n = X.size();
                int n = X.size();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int m = a.size();
                int m = a.size();

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final double[][] res = new double[n][m];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] res = new double[n][m];
                double[][] res = RectangularArrays.ReturnRectangularDoubleArray(n, m);
                for (int i = 0; i < n; i++)
                {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final com.opengamma.strata.collect.array.DoubleArray temp = PARAM_GRAD.evaluate(X.get(i), a);
                    DoubleArray temp = PARAM_GRAD.evaluate(X.get(i), a);
                    ArgChecker.isTrue(m == temp.size());
                    for (int j = 0; j < m; j++)
                    {
                        res[i][j] = temp.get(j);
                    }
                }
                return(DoubleMatrix.copyOf(res));
            }
Exemple #11
0
        public Matrix(int nRows, int nColumns)
        {
            numberOfRows    = nRows;
            numberOfColumns = nColumns;

            content = RectangularArrays.ReturnRectangularDoubleArray(numberOfRows, numberOfColumns);
        }
        //-------------------------------------------------------------------------
        private double[] computesFittingParameters()
        {
            double[] param = new double[3];     // Implementation note: called a,b,c in the note.
            // Computes derivatives at cut-off.
            double[] vD = new double[6];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] vD2 = new double[2][2];
            double[][] vD2 = RectangularArrays.ReturnRectangularDoubleArray(2, 2);
            volatilityK = sabrFunction.volatilityAdjoint2(forward, cutOffStrike, timeToExpiry, sabrData, vD, vD2);
            Pair <ValueDerivatives, double[][]> pa2 = BlackFormulaRepository.priceAdjoint2(forward, cutOffStrike, timeToExpiry, volatilityK, true);

            double[]   bsD  = pa2.First.Derivatives.toArrayUnsafe();
            double[][] bsD2 = pa2.Second;
            priceK[0] = pa2.First.Value;
            priceK[1] = bsD[1] + bsD[3] * vD[1];
            priceK[2] = bsD2[1][1] + bsD2[1][2] * vD[1] + (bsD2[2][1] + bsD2[2][2] * vD[1]) * vD[1] + bsD[3] * vD2[1][1];
            if (Math.Abs(priceK[0]) < SMALL_PRICE && Math.Abs(priceK[1]) < SMALL_PRICE && Math.Abs(priceK[2]) < SMALL_PRICE)
            {
                // Implementation note: If value and its derivatives is too small, then parameters are such that the extrapolated price is "very small".
                return(new double[] { -100.0, 0, 0 });
            }
            System.Func <double, double> toSolveC = getCFunction(priceK, cutOffStrike, mu);
            BracketRoot            bracketer      = new BracketRoot();
            double                 accuracy       = 1.0E-5;
            RidderSingleRootFinder rootFinder     = new RidderSingleRootFinder(accuracy);

            double[] range = bracketer.getBracketedPoints(toSolveC, -1.0, 1.0);
            param[2] = rootFinder.getRoot(toSolveC, range[0], range[1]).Value;
            param[1] = -2 * param[2] / cutOffStrike - (priceK[1] / priceK[0] * cutOffStrike + mu) * cutOffStrike;
            param[0] = Math.Log(priceK[0] / Math.Pow(cutOffStrike, -mu)) - param[1] / cutOffStrike - param[2] / (cutOffStrike * cutOffStrike);
            return(param);
        }
Exemple #13
0
        public LogLikelihoodFunction(DataIndexer indexer)
        {
            // get data from indexer.
            if (indexer is OnePassRealValueDataIndexer)
            {
                this.values = indexer.Values;
            }
            else
            {
                this.values = null;
            }

            this.contexts           = indexer.Contexts;
            this.outcomeList        = indexer.OutcomeList;
            this.numTimesEventsSeen = indexer.NumTimesEventsSeen;

            this.outcomeLabels = indexer.OutcomeLabels;
            this.predLabels    = indexer.PredLabels;

            this.numOutcomes     = indexer.OutcomeLabels.Length;
            this.numFeatures     = indexer.PredLabels.Length;
            this.numContexts     = this.contexts.Length;
            this.domainDimension = numOutcomes * numFeatures;
            this.probModel       = RectangularArrays.ReturnRectangularDoubleArray(numContexts, numOutcomes);
            this.gradient        = null;
        }
Exemple #14
0
        internal virtual void ForwardDCT(int[][] input, int[][] output)
        {
            double[][] temp = RectangularArrays.ReturnRectangularDoubleArray(n, n);
            double     temp1;
            int        i, j, k;

            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    temp[i][j] = 0.0;
                    for (k = 0; k < n; k++)
                    {
                        temp[i][j] += (input[i][k] - 128) * ct[k][j];
                    }
                }
            }

            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    temp1 = 0.0;
                    for (k = 0; k < n; k++)
                    {
                        temp1 += c[i][k] * temp[k][j];
                    }
                    output[i][j] = (int)Math.Round(temp1);
                }
            }
        }
Exemple #15
0
        //*******************************************************************************************
        // Difference methods
        //*******************************************************************************************

        /// <summary>
        /// get the k^th order difference matrix, D,  which acts on a vector, x, of length m to produce the k^th order
        /// difference vector. The first k rows of D are set to zero - because of this D_1 * D_1 != D_2<para>
        /// For example, for x = {x1,x2,....xn}, D_1 * x = {0, x2-x1, x3-x2,...., xn - x(n-1)} and
        /// D_2 * x = {0,0, x3-2*x2+x1,....,xn-2*x(n-1)+x(n-2)} etc
        /// </para>
        /// </summary>
        /// <param name="m"> Length of the vector </param>
        /// <param name="k"> Difference order. Require m > k </param>
        /// <returns> The k^th order difference matrix  </returns>
        public static DoubleMatrix getDifferenceMatrix(int m, int k)
        {
            ArgChecker.notNegativeOrZero(m, "m");
            ArgChecker.notNegative(k, "k");
            ArgChecker.isTrue(k < m, "Difference order too high, require m > k, but have: m = {} and k = {}", m, k);
            if (k == 0)
            {
                return(DoubleMatrix.identity(m));
            }
            int[] coeff = new int[k + 1];
            int   sign  = 1;

            for (int i = k; i >= 0; i--)
            {
                coeff[i] = (int)(sign * binomialCoefficient(k, i));
                sign     = -sign;
            }

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] data = new double[m][m];
            double[][] data = RectangularArrays.ReturnRectangularDoubleArray(m, m);
            for (int i = k; i < m; i++)
            {
                for (int j = 0; j < k + 1; j++)
                {
                    data[i][j + i - k] = coeff[j];
                }
            }
            return(DoubleMatrix.ofUnsafe(data));
        }
        internal DataFileVariables()
        {
            afk = new int[256];
            afm = new int[257];
            afn = new int[257];
            agc = new bool[256];
            agd = new bool[16];
            age = new int[256];
            agf = new int[4096];
            agg = new int[16];
            agh = new sbyte[18002];
            agi = new sbyte[18002];
//ORIGINAL LINE: agj = new sbyte[6][258];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            agj = RectangularArrays.ReturnRectangularSbyteArray(6, 258);
//ORIGINAL LINE: agk = new int[6][258];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            agk = RectangularArrays.ReturnRectangularIntArray(6, 258);
//ORIGINAL LINE: agl = new int[6][258];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            agl = RectangularArrays.ReturnRectangularIntArray(6, 258);
//ORIGINAL LINE: agm = new int[6][258];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            agm = RectangularArrays.ReturnRectangularIntArray(6, 258);
            agn = new int[6];
        }
        public virtual BufferedImage processImage(BufferedImage image)
        {
            originalImage = image;
            width         = originalImage.Width;
            height        = originalImage.Height;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: visited = new bool[width][height];
            visited = RectangularArrays.ReturnRectangularBoolArray(width, height);

            int name = 1;

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    int color = (new Color(originalImage.getRGB(i, j))).Red;
                    if (color == 255)
                    {
                        visited[i][j] = true;
                    }
                    else
                    {
                        if (name > 3000)
                        {
                            return(originalImage);
                        }
                        BFS(i, j, name + "");
                        name++;
                    }
                }
            }

            return(originalImage);
        }
        /// <summary>
        /// Gamma is in the  form gamma^i_{j,k} =\partial^2y_j/\partial x_i \partial x_k, where i is the
        /// index of the matrix in the stack (3rd index of the tensor), and j,k are the individual
        /// matrix indices. We would like it in the form H^i_{j,k} =\partial^2y_i/\partial x_j \partial x_k,
        /// so that each matrix is a Hessian (for the dependent variable y_i), hence the reshaping below.
        /// </summary>
        /// <param name="gamma">  the rank 3 tensor </param>
        /// <returns> the reshaped rank 3 tensor </returns>
        private DoubleMatrix[] reshapeTensor(DoubleMatrix[] gamma)
        {
            int m = gamma.Length;
            int n = gamma[0].rowCount();

            ArgChecker.isTrue(gamma[0].columnCount() == m, "tenor wrong size. Seond index is {}, should be {}", gamma[0].columnCount(), m);
            DoubleMatrix[] res = new DoubleMatrix[n];
            for (int i = 0; i < n; i++)
            {
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] temp = new double[m][m];
                double[][] temp = RectangularArrays.ReturnRectangularDoubleArray(m, m);
                for (int j = 0; j < m; j++)
                {
                    DoubleMatrix gammaJ = gamma[j];
                    for (int k = j; k < m; k++)
                    {
                        temp[j][k] = gammaJ.get(i, k);
                    }
                }
                for (int j = 0; j < m; j++)
                {
                    for (int k = 0; k < j; k++)
                    {
                        temp[j][k] = temp[k][j];
                    }
                }
                res[i] = DoubleMatrix.copyOf(temp);
            }
            return(res);
        }
Exemple #19
0
        public override LeastSquaresRegressionResult regress(double[][] x, double[][] weights, double[] y, bool useIntercept)
        {
            if (weights == null)
            {
                throw new System.ArgumentException("Cannot perform GLS regression without an array of weights");
            }
            checkData(x, weights, y);
            double[][] dep   = addInterceptVariable(x, useIntercept);
            double[]   indep = new double[y.Length];
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] wArray = new double[y.Length][y.Length];
            double[][] wArray = RectangularArrays.ReturnRectangularDoubleArray(y.Length, y.Length);
            for (int i = 0; i < y.Length; i++)
            {
                indep[i] = y[i];
                for (int j = 0; j < y.Length; j++)
                {
                    wArray[i][j] = weights[i][j];
                }
            }
            DoubleMatrix matrix      = DoubleMatrix.copyOf(dep);
            DoubleArray  vector      = DoubleArray.copyOf(indep);
            DoubleMatrix w           = DoubleMatrix.copyOf(wArray);
            DoubleMatrix transpose   = ALGEBRA.getTranspose(matrix);
            DoubleMatrix betasVector = (DoubleMatrix)ALGEBRA.multiply(ALGEBRA.multiply(ALGEBRA.multiply(ALGEBRA.getInverse(ALGEBRA.multiply(transpose, ALGEBRA.multiply(w, matrix))), transpose), w), vector);

            double[] yModel = base.writeArrayAsVector(((DoubleMatrix)ALGEBRA.multiply(matrix, betasVector)).toArray());
            double[] betas  = base.writeArrayAsVector(betasVector.toArray());
            return(getResultWithStatistics(x, y, betas, yModel, useIntercept));
        }
        public override DoubleMatrix apply(TridiagonalMatrix x)
        {
            ArgChecker.notNull(x, "x");
            double[] a = x.DiagonalData;
            double[] b = x.UpperSubDiagonalData;
            double[] c = x.LowerSubDiagonalData;
            int      n = a.Length;
            int      i, j, k;

            double[] theta = new double[n + 1];
            double[] phi   = new double[n];

            theta[0] = 1.0;
            theta[1] = a[0];
            for (i = 2; i <= n; i++)
            {
                theta[i] = a[i - 1] * theta[i - 1] - b[i - 2] * c[i - 2] * theta[i - 2];
            }

            if (theta[n] == 0.0)
            {
                throw new MathException("Zero determinant. Cannot invert the matrix");
            }

            phi[n - 1] = 1.0;
            phi[n - 2] = a[n - 1];
            for (i = n - 3; i >= 0; i--)
            {
                phi[i] = a[i + 1] * phi[i + 1] - b[i + 1] * c[i + 1] * phi[i + 2];
            }

            double product;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] res = new double[n][n];
            double[][] res = RectangularArrays.ReturnRectangularDoubleArray(n, n);

            for (j = 0; j < n; j++)
            {
                for (i = 0; i <= j; i++)
                {
                    product = 1.0;
                    for (k = i; k < j; k++)
                    {
                        product *= b[k];
                    }
                    res[i][j] = ((i + j) % 2 == 0 ? 1 : -1) * product * theta[i] * phi[j] / theta[n];
                }
                for (i = j + 1; i < n; i++)
                {
                    product = 1.0;
                    for (k = j; k < i; k++)
                    {
                        product *= c[k];
                    }
                    res[i][j] = ((i + j) % 2 == 0 ? 1 : -1) * product * theta[j] * phi[i] / theta[n];
                }
            }
            return(DoubleMatrix.copyOf(res));
        }
Exemple #21
0
        public Config(int pegs, int colors)
        {
            this.pegs   = pegs;
            this.colors = colors;

            this.combinations = (int)Math.Pow(colors, pegs);

            grades = pegs * (pegs + 3) / 2;
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: id2array = new int[grades][2];
            id2array = RectangularArrays.ReturnRectangularIntArray(grades, 2);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: array2id = new int[pegs + 1][pegs + 1];
            array2id = RectangularArrays.ReturnRectangularIntArray(pegs + 1, pegs + 1);
            int currentID = 0;

            for (int i = 0; i <= pegs; i++)
            {
                for (int z = 0; z <= pegs - i; z++)
                {
                    if (i == pegs - 1 && z == 1)
                    {
                        continue;
                    }
                    array2id[i][z]      = currentID;
                    id2array[currentID] = new int[] { i, z };
                    currentID++;
                }
            }
        }
Exemple #22
0
        public virtual double[][] multiply(double[][] m1, double[][] m2)
        {
            int m1rows = m1.Length;
            int m1cols = m1[0].Length;
            int m2rows = m2.Length;
            int m2cols = m2[0].Length;

            if (m1cols != m2rows)
            {
                throw new System.ArgumentException("matrices don't match: " + m1cols + " != " + m2rows);
            }
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] result = new double[m1rows][m2cols];
            double[][] result = RectangularArrays.ReturnRectangularDoubleArray(m1rows, m2cols);

            // multiply
            for (int i = 0; i < m1rows; i++)
            {
                for (int j = 0; j < m2cols; j++)
                {
                    for (int k = 0; k < m1cols; k++)
                    {
                        result[i][j] += m1[i][k] * m2[k][j];
                    }
                }
            }
            return(result);
        }
Exemple #23
0
        private DoubleMatrix getDiffMatrix(int m, int k)
        {
            ArgChecker.isTrue(k < m, "difference order too high");

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] data = new double[m][m];
            double[][] data = RectangularArrays.ReturnRectangularDoubleArray(m, m);
            if (m == 0)
            {
                return(DoubleMatrix.copyOf(data));
            }

            int[] coeff = new int[k + 1];

            int sign = 1;

            for (int i = k; i >= 0; i--)
            {
                coeff[i] = (int)(sign * binomialCoefficient(k, i));
                sign    *= -1;
            }

            for (int i = k; i < m; i++)
            {
                for (int j = 0; j < k + 1; j++)
                {
                    data[i][j + i - k] = coeff[j];
                }
            }
            DoubleMatrix d = DoubleMatrix.copyOf(data);

            DoubleMatrix dt = _algebra.getTranspose(d);

            return((DoubleMatrix)_algebra.multiply(dt, d));
        }
Exemple #24
0
        /// <summary>
        /// Constructor for ArimaParams
        /// </summary>
        /// <param name="p"> ARIMA parameter, the order (number of time lags) of the autoregressive model </param>
        /// <param name="d"> ARIMA parameter, the degree of differencing </param>
        /// <param name="q"> ARIMA parameter, the order of the moving-average model </param>
        /// <param name="P"> ARIMA parameter, autoregressive term for the seasonal part </param>
        /// <param name="D"> ARIMA parameter, differencing term for the seasonal part </param>
        /// <param name="Q"> ARIMA parameter, moving average term for the seasonal part </param>
        /// <param name="m"> ARIMA parameter, the number of periods in each season </param>
        public ArimaParams(int p, int d, int q, int P, int D, int Q, int m)
        {
            this.p = p;
            this.d = d;
            this.q = q;
            this.P = P;
            this.D = D;
            this.Q = Q;
            this.m = m;

            // dependent states
            this._opAR = NewOperatorAR;
            this._opMA = NewOperatorMA;
            _opAR.initializeParams(false);
            _opMA.initializeParams(false);
            this._dp = _opAR.Degree;
            this._dq = _opMA.Degree;
            this._np = _opAR.numParams();
            this._nq = _opMA.numParams();
            //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            //ORIGINAL LINE: this._init_seasonal = (D > 0 && m > 0) ? new double[D][m] : null;
            this._init_seasonal = (D > 0 && m > 0) ? RectangularArrays.ReturnRectangularDoubleArray(D, m) : null;
            //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
            //ORIGINAL LINE: this._init_non_seasonal = (d > 0) ? new double[d][1] : null;
            this._init_non_seasonal      = (d > 0) ? RectangularArrays.ReturnRectangularDoubleArray(d, 1) : null;
            this._diff_seasonal          = (D > 0 && m > 0) ? new double[D][] : null;
            this._diff_non_seasonal      = (d > 0) ? new double[d][] : null;
            this._integrate_seasonal     = (D > 0 && m > 0) ? new double[D][] : null;
            this._integrate_non_seasonal = (d > 0) ? new double[d][] : null;
        }
            internal static DoubleMatrix getRightMatrix(double[] oneOverDeltaX, bool leftNatural, bool rightNatural)
            {
                int n = oneOverDeltaX.Length + 1;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] res = new double[n][n];
                double[][] res = RectangularArrays.ReturnRectangularDoubleArray(n, n);
                for (int i = 1; i < n - 1; i++)
                {
                    res[i][i - 1] = oneOverDeltaX[i - 1];
                    res[i][i]     = -oneOverDeltaX[i] - oneOverDeltaX[i - 1];
                    res[i][i + 1] = oneOverDeltaX[i];
                }
                if (!leftNatural)
                {
                    res[0][0] = oneOverDeltaX[0];
                    res[0][1] = -oneOverDeltaX[0];
                }

                if (!rightNatural)
                {
                    res[n - 1][n - 1] = -oneOverDeltaX[n - 2];
                    res[n - 2][n - 2] = oneOverDeltaX[n - 2];
                }
                return(DoubleMatrix.copyOf(res));
            }
Exemple #26
0
 public Connect4IA() : base()
 {
     //JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
     //ORIGINAL LINE: this.grid = new int[GRID_SIZE][GRID_SIZE];
     this.grid = RectangularArrays.RectangularIntArray(GRID_SIZE, GRID_SIZE);
     NewGame();
 }
        public FractionHSLData(BufferedImage img)
        {
            if (img != null)
            {
                width  = img.Width;
                height = img.Height;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: hueValues = new double[height][width];
                hueValues = RectangularArrays.ReturnRectangularDoubleArray(height, width);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: saturationValues = new double[height][width];
                saturationValues = RectangularArrays.ReturnRectangularDoubleArray(height, width);
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: lightnessValues = new double[height][width];
                lightnessValues    = RectangularArrays.ReturnRectangularDoubleArray(height, width);
                flattenedHSLValues = new double[width * height * 3];
                flattenedHueValues = new double[width * height];

                populateHSLArrays(new ImageJ2SE(img));
            }
            else     //no input image specified so default all values
            {
                width              = 0;
                height             = 0;
                hueValues          = null;
                saturationValues   = null;
                lightnessValues    = null;
                flattenedHSLValues = null;
                flattenedHueValues = null;
            }
        }
Exemple #28
0
        protected internal virtual double[][] addInterceptVariable(double[][] x, bool useIntercept)
        {
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: double[][] result = useIntercept ? new double[x.Length][x[0].Length + 1] : new double[x.Length][x[0].Length];
            double[][] result = useIntercept ? RectangularArrays.ReturnRectangularDoubleArray(x.Length, x[0].Length + 1) : RectangularArrays.ReturnRectangularDoubleArray(x.Length, x[0].Length);
            for (int i = 0; i < x.Length; i++)
            {
                if (useIntercept)
                {
                    result[i][0] = 1.0;
                    for (int j = 1; j < x[0].Length + 1; j++)
                    {
                        result[i][j] = x[i][j - 1];
                    }
                }
                else
                {
                    for (int j = 0; j < x[0].Length; j++)
                    {
                        result[i][j] = x[i][j];
                    }
                }
            }
            return(result);
        }
Exemple #29
0
        private readonly short[][] costs; // array is backward IDs first since get is called using the same backward ID consecutively. maybe doesn't matter.

        private ConnectionCosts()
        {
            short[][] costs = null;

            using (Stream @is = BinaryDictionary.GetTypeResource(GetType(), FILENAME_SUFFIX))
            {
                DataInput @in = new InputStreamDataInput(@is);
                CodecUtil.CheckHeader(@in, HEADER, VERSION, VERSION);
                int forwardSize  = @in.ReadVInt32();
                int backwardSize = @in.ReadVInt32();
                costs = RectangularArrays.ReturnRectangularArray <short>(backwardSize, forwardSize);
                int accum = 0;
                for (int j = 0; j < costs.Length; j++)
                {
                    short[] a = costs[j];
                    for (int i = 0; i < a.Length; i++)
                    {
                        int raw = @in.ReadVInt32();
                        accum += ((int)((uint)raw) >> 1) ^ -(raw & 1);
                        a[i]   = (short)accum;
                    }
                }
            }

            this.costs = costs;
        }
Exemple #30
0
        protected internal virtual void createKernel()
        {
            int size   = radius * 2 + 1;
            int center = radius;

//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: kernel = new double [size][size];
            kernel = RectangularArrays.ReturnRectangularDoubleArray(size, size);

            for (int i = 0; i < kernel.Length; i++)
            {
                for (int j = 0; j < kernel[0].Length; j++)
                {
                    int distanceX = Math.Abs(center - i);
                    int distanceY = Math.Abs(center - j);
                    kernel [i][j] = gaussianFormula(distanceX, distanceY);
                }
            }

            double noralizationValue = getNormalizationValue(kernel);

            for (int i = 0; i < kernel.Length; i++)
            {
                for (int j = 0; j < kernel[0].Length; j++)
                {
                    kernel[i][j] = kernel[i][j] * noralizationValue;
                }
            }
        }