org.apache.commons.math3.linear.ArrayRealVector Java Examples

The following examples show how to use org.apache.commons.math3.linear.ArrayRealVector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionMeasurementMatrixMismatch() {
    
    // A and H matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // no control input
    RealMatrix B = null;
    // H = [ 1 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and measurement matrix should not be compatible");
}
 
Example #2
Source File: ChangeFinder2D.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
@Override
public void update(@Nonnull final Object arg, @Nonnull final double[] outScores)
        throws HiveException {
    ArrayRealVector x = parseX(arg);

    // [Stage#1] Outlier Detection        
    xRing.add(x).toArray(xSeries, false /* LIFO */);
    int k1 = xRing.size() - 1;
    RealVector x_hat = sdar1.update(xSeries, k1);

    double scoreX = (k1 == 0.d) ? 0.d : loss(x, x_hat, lossFunc1);
    // smoothing
    double y = ChangeFinderUDF.smoothing(outlierScores.add(scoreX));

    // [Stage#2] Change-point Detection
    yRing.add(y).toArray(ySeries, false /* LIFO */);
    int k2 = yRing.size() - 1;
    double y_hat = sdar2.update(ySeries, k2);

    double lossY = (k2 == 0.d) ? 0.d : loss(y, y_hat, lossFunc1);
    double scoreY = ChangeFinderUDF.smoothing(changepointScores.add(lossY));

    outScores[0] = scoreX;
    outScores[1] = scoreY;
}
 
Example #3
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionControlMatrixMismatch() {
    
    // A and B matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // B = [ 1 1 ]
    RealMatrix B = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // H = [ 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and control matrix should not be compatible");
}
 
Example #4
Source File: MovingAverage.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Override
public void addToWindow(Datum newDatum) {
    if (window.size() == 0) {
        // We don't know what weight to use for the first datum, so we wait
        // until we have the second one to actually process it.
        window.add(new DatumWithInfo(newDatum, 0));
    } else {
        long weight = newDatum.getTime(timeColumn) - getLatestDatum().getTime(timeColumn);
        if (window.size() == 1) {
            windowSum = new ArrayRealVector(newDatum.metrics()
                    .getDimension());
            // Remove and re-add first datum with the correct weight
            Datum first = window.remove().getDatum();
            // Assume same weight for first as for second
            addDatumWithWeight(first, weight);
        }

        addDatumWithWeight(newDatum, weight);
    }
}
 
Example #5
Source File: DiagnosticsUtils.java    From macrobase with Apache License 2.0 6 votes vote down vote up
public static List<Datum> createGridFixedSize(double[][] boundaries, int pointsPerDimension) {
    int dimension = boundaries.length;
    double delta[] = new double[dimension];
    for (int d = 0; d < dimension; d++) {
        delta[d] = (boundaries[d][1] - boundaries[d][0]) / (pointsPerDimension - 1.);
    }

    List<RealVector> gridPointVectors = new ArrayList<>(dimension);

    for (int d = 0; d < dimension; d++) {
        double[] array = new double[pointsPerDimension];
        for (int i = 0; i < pointsPerDimension; i++) {
            array[i] = boundaries[d][0] + i * delta[d];
        }
        gridPointVectors.add(new ArrayRealVector(array));
    }

    return convertToGrid(gridPointVectors);
}
 
Example #6
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionMeasurementMatrixMismatch() {
    
    // A and H matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // no control input
    RealMatrix B = null;
    // H = [ 1 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and measurement matrix should not be compatible");
}
 
Example #7
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionControlMatrixMismatch() {
    
    // A and B matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // B = [ 1 1 ]
    RealMatrix B = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // H = [ 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and control matrix should not be compatible");
}
 
Example #8
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionMeasurementMatrixMismatch() {
    
    // A and H matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // no control input
    RealMatrix B = null;
    // H = [ 1 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and measurement matrix should not be compatible");
}
 
Example #9
Source File: ZScoreTest.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleTest() {
    ZScore z = new ZScore(new MacroBaseConf());

    List<Datum> data = new ArrayList<>();
    for (int i = 0; i < 100; ++i) {
        double[] sample = new double[1];
        sample[0] = i;
        data.add(new Datum(new ArrayList<>(), new ArrayRealVector(sample)));
    }

    z.train(data);
    assertEquals(1.714816, z.score(data.get(0)), 1e-5);
    assertEquals(1.714816, z.score(data.get(data.size() - 1)), 1e-5);
    assertEquals(0.017321, z.score(data.get(50)), 1e-5);
}
 
Example #10
Source File: KalmanFilterTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test(expected=MatrixDimensionMismatchException.class)
public void testTransitionMeasurementMatrixMismatch() {
    
    // A and H matrix do not match in dimensions
    
    // A = [ 1 ]
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // no control input
    RealMatrix B = null;
    // H = [ 1 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d, 1d });
    // Q = [ 0 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { 0 });
    // R = [ 0 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { 0 });

    ProcessModel pm
        = new DefaultProcessModel(A, B, Q,
                                  new ArrayRealVector(new double[] { 0 }), null);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    new KalmanFilter(pm, mm);
    Assert.fail("transition and measurement matrix should not be compatible");
}
 
Example #11
Source File: IterativeCGTupleFitter.java    From OSPREY3 with GNU General Public License v2.0 6 votes vote down vote up
RealVector calcRHS(){//Calculate right-hand side vector of normal equations
    double atb[] = new double[numTup];
    //apply A^T to true vals
    for(int s=0; s<numSamp; s++){
        double curTarget = getCurTarget(s);
        if(!Double.isNaN(curTarget)){//restraint active for sample
            ArrayList<Integer> sampTup = tupIndMat.calcSampleTuples(samples.get(s));
            for(int t : sampTup)
                atb[t] += curTarget;
        }
    }
    
    //damping.  Slightly penalizes changes from curCoeffs
    if(curCoeffs!=null){
        for(int t=0; t<numTup; t++)
            atb[t] += damperLambda * curCoeffs.getEntry(t);
    }
    
    Atb = new ArrayRealVector(atb);
    return Atb;
}
 
Example #12
Source File: FFTTest.java    From macrobase with Apache License 2.0 6 votes vote down vote up
@Test
public void testFFTTransformNotPowTwo() throws Exception {
    double[] test_input =  {2.24120611573000,2.12215703941000,1.75273899872000,1.33988834232000,0.944127790619000,0.740475575456000,0.688064246951000,0.647745146434000,0.684477804740000,0.905214502349000,1.11429962551000,1.35319232934000,1.54059522739000,1.78246688712000,2.17183901182000,2.55432971168000,2.92949308220000,3.20230988502000,3.42596923011000,3.61949923094000,3.78276832765000,3.87181704262000,3.86482056309000,3.68006472992000};
    double[] expected_return = {50.959560447139005,0.0, -19.18116056949066,5.501342136595359,8.4180172341819,-16.05988961755714,9.257726525809472,-1.4007288223010215,-0.1263026558020457,0.9511833120557635,-2.268687435900532,-4.543228417029076,3.591125444534933,-4.629703914058681,3.0904615384885172,0.19497138213139342,-0.8950633278720002,0.5702785586589999,-0.27121650007953746,-2.7675753532010674,3.000682832479642,-1.8870566655000403,2.099339190479186,1.1612853788078912,-0.6983260301759526,0.0877513770137655,0.5448230754788493,-2.1055528083622272,2.9350600615635263,-0.5720388054824936,1.222418443454704,1.6052800572847277,-0.6787603980789996,0.0,1.2224184434547087,-1.6052800572847288,2.935060061563525,0.5720388054824976,0.5448230754788472,2.105552808362229,-0.6983260301759526,-0.08775137701376556,2.099339190479185,-1.1612853788078894,3.00068283247964,1.8870566655000391,-0.27121650007953546,2.7675753532010647,-0.8950633278720002,-0.5702785586589999,3.0904615384885172,-0.19497138213139342,3.5911254445349354,4.629703914058684,-2.2686874359005333,4.543228417029075,-0.12630265580204597,-0.9511833120557633,9.25772652580947,1.4007288223010232,8.418017234181896,16.059889617557136,-19.181160569490658,-5.501342136595361};
    List<Datum> data = new ArrayList<>();
    Datum d = new Datum(new ArrayList<>(), new ArrayRealVector(test_input));
    data.add(d);

    FFT fft = new FFT(new MacroBaseConf());
    fft.consume(data);
    List<Datum> transformed = fft.getStream().drain();
    for (Datum td: transformed){
        double[] val = td.metrics().toArray();
        assertEquals(64,val.length);
        assertArrayEquals(expected_return, val, 1e-5);
    }
}
 
Example #13
Source File: CSVIngester.java    From macrobase with Apache License 2.0 6 votes vote down vote up
private Datum parseRecord(CSVRecord record) throws NumberFormatException {
    int vecPos = 0;

    RealVector metricVec = new ArrayRealVector(metrics.size());
    for (String metric : metrics) {
        metricVec.setEntry(vecPos, Double.parseDouble(record.get(metric)));
        vecPos += 1;
    }

    List<Integer> attrList = new ArrayList<>(attributes.size());
    for (String attr : attributes) {
        int pos = schema.get(attr);
        attrList.add(conf.getEncoder().getIntegerEncoding(pos + 1, record.get(pos)));
    }

    return new Datum(
            attrList,
            metricVec
    );
}
 
Example #14
Source File: AnnoyVectorSpace.java    From Indra with MIT License 5 votes vote down vote up
@Override
public Map<String, RealVector> getNearestVectors(AnalyzedTerm term, int topk, Filter filter) {
    Collection<Integer> nearest = getNearestIds(term, topk, filter);

    Map<String, RealVector> results = new HashMap<>();
    for (Integer id : nearest) {
        double[] dv = index.getItemVector(id);

        RealVector vector = new ArrayRealVector(dv);
        results.put(idToWord[id], vector);
    }

    return results;
}
 
Example #15
Source File: GCCorrector.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * As described above, calculate medians of each GC bin and convolve with an exponential kernel.
 *
 * @param coveragesByGC list of coverages for each GC bin
 * @return multiplicative correction factors for each GC bin
 */
private double[] calculateCorrectionFactors(final List<List<Double>> coveragesByGC) {
    final RealVector medians = new ArrayRealVector(coveragesByGC.stream().mapToDouble(GCCorrector::medianOrDefault).toArray());
    return IntStream.range(0, NUMBER_OF_GC_BINS).mapToDouble(bin -> {
        final RealVector weights = new ArrayRealVector(IntStream.range(0, NUMBER_OF_GC_BINS)
                .mapToDouble(n -> coveragesByGC.get(n).size() * Math.exp(-Math.abs(bin - n) * correlationDecayRatePerBin)).toArray());
        return weights.dotProduct(medians) / weights.getL1Norm();
    }).map(x -> 1/x).toArray();
}
 
Example #16
Source File: MonteCarloConditionalExpectationRegression.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Return the solution x of XTX x = XT y for a given y.
 * @TODO Performance upon repeated call can be optimized by caching XTX.
 *
 * @param dependents The sample vector of the random variable y.
 * @return The solution x of XTX x = XT y.
 */
public double[] getLinearRegressionParameters(final RandomVariable dependents) {

	final RandomVariable[] basisFunctions = basisFunctionsEstimator.getBasisFunctions();

	synchronized (solverLock) {
		if(solver == null) {
			// Build XTX - the symmetric matrix consisting of the scalar products of the basis functions.
			final double[][] XTX = new double[basisFunctions.length][basisFunctions.length];
			for(int i=0; i<basisFunctions.length; i++) {
				for(int j=i; j<basisFunctions.length; j++) {
					XTX[i][j] = basisFunctions[i].mult(basisFunctions[j]).getAverage();	// Scalar product
					XTX[j][i] = XTX[i][j];												// Symmetric matrix
				}
			}

			solver = new SingularValueDecomposition(new Array2DRowRealMatrix(XTX, false)).getSolver();
		}
	}

	// Build XTy - the projection of the dependents random variable on the basis functions.
	final double[] XTy = new double[basisFunctions.length];
	for(int i=0; i<basisFunctions.length; i++) {
		XTy[i] = dependents.mult(basisFunctions[i]).getAverage();				// Scalar product
	}

	// Solve X^T X x = X^T y - which gives us the regression coefficients x = linearRegressionParameters
	final double[] linearRegressionParameters = solver.solve(new ArrayRealVector(XTy)).toArray();

	return linearRegressionParameters;
}
 
Example #17
Source File: XDataFrameLeastSquares.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the Y vector for this regression model
 * @return  the Y vector for regression model
 */
RealVector createY() {
    final int rowCount = frame.rows().count();
    final int colIndex = frame.cols().ordinalOf(regressand);
    final RealVector y = new ArrayRealVector(rowCount);
    for (int i = 0; i < rowCount; ++i) {
        y.setEntry(i, frame.data().getDouble(i, colIndex));
    }
    return y;
}
 
Example #18
Source File: LearnReadOrientationModelEngine.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given the posterior distributions over the artifact states (ie responsibilities) under the current estimates for the prior,
 * update the prior weights such that they maximize the lower bound on the marginal likelihood P(Data).
 * We do so by maximizing the expectation of the complete data likelihood with respect to the posterior
 * for the artifact states from the E-step
 */
private double[] takeMstep(final double[] pseudocounts) {
    // First we compute the effective counts of each state, N_k in the docs. We do this separately over alt and ref sites
    final double[] effectiveAltCountsFromDesignMatrix = MathUtils.sumArrayFunction(0, altDesignMatrix.size(), n -> altResponsibilities.getRow(n));
    double[] effectiveAltCountsFromHistograms = new double[F1R2FilterConstants.NUM_STATES];

    for (Histogram<Integer> histogram : altDepthOneHistograms){
        final Triple<String, Nucleotide, ReadOrientation> triplet = F1R2FilterUtils.labelToTriplet(histogram.getValueLabel());
        final Nucleotide altAllele = triplet.getMiddle();
        final ReadOrientation orientation = triplet.getRight();


        final double[] effectiveAltCountsFromHistogram = MathUtils.sumArrayFunction(0, maxDepth,
                i -> MathArrays.scale(histogram.get(i + 1).getValue(), responsibilitiesOfAltDepth1Sites.get(createKey(i+1, altAllele, orientation))));
        effectiveAltCountsFromHistograms = MathArrays.ebeAdd(effectiveAltCountsFromHistograms, effectiveAltCountsFromHistogram);
    }

    final double[] effectiveAltCounts = MathArrays.ebeAdd(effectiveAltCountsFromDesignMatrix, effectiveAltCountsFromHistograms);

    // TODO: at some depth, the responsibilities must be 1 for z = HOM_REF and 0 for everything else, we could probably save some time there
    // Over ref sites, we have a histogram of sites over different depths. At each depth we simply multiply the responsibilities by the number of sites,
    // and sum them over all of depths. Because we cut off the depth histogram at {@code MAX_COVERAGE}, we underestimate the ref effective counts by design
    final double[] effectiveRefCounts = MathUtils.sumArrayFunction(0, maxDepth,
            i -> MathArrays.scale(refHistogram.get(i + 1).getValue(), refResponsibilities.getRow(i)));

    effectiveCounts = new ArrayRealVector(MathArrays.ebeAdd(effectiveAltCounts, effectiveRefCounts));
    return MathUtils.normalizeSumToOne(effectiveCounts.add(new ArrayRealVector(pseudocounts)).toArray());
}
 
Example #19
Source File: KalmanFlattenedMatrixFilterTest.java    From macrobase with Apache License 2.0 5 votes vote down vote up
@Test
public void reduceToVectorKalmanFilterTest() throws Exception {
    MacroBaseConf conf = new MacroBaseConf()
            .set(MacroBaseConf.RANDOM_SEED, 4)
            .set(MacroBaseConf.DATA_LOADER_TYPE, "CSV_LOADER")
            .set(MacroBaseConf.CSV_COMPRESSION, CSVIngester.Compression.GZIP)
            .set(MacroBaseConf.CSV_INPUT_FILE, "src/test/resources/data/2gaussians-500points.csv.gz")
            .set(MacroBaseConf.METRICS, "XX, YY")
            .set(MacroBaseConf.ATTRIBUTES, "");
    List<Datum> data = Drainer.drainIngest(conf);
    assertEquals(500, data.size());

    KalmanVectorFilter f = new KalmanVectorFilter(new ArrayRealVector(2), 1e-6, 1);

    RealMatrix shapeMatrix = new BlockRealMatrix(2, 1);
    KalmanFlattenedMatrixFilter mf = new KalmanFlattenedMatrixFilter(shapeMatrix, 1e-6, 1);

    List<Datum> oneCluster = data.subList(201, 500);
    List<RealVector> vectorFiltered = oneCluster.stream().map(d -> f.step(d.metrics(), 1)).collect(Collectors.toList());
    List<RealMatrix> matrixFiltered = oneCluster.stream()
            .map(d -> mf.step(AlgebraUtils.reshapeMatrixByColumns(d.metrics(), shapeMatrix), 1))
            .collect(Collectors.toList());

    for (int i = 0; i < 10; i++) {
        int ri = conf.getRandom().nextInt(300);
        assertEquals(vectorFiltered.get(ri), AlgebraUtils.flattenMatrixByColumns(matrixFiltered.get(ri)));
    }
}
 
Example #20
Source File: BatchMixtureModel.java    From macrobase with Apache License 2.0 5 votes vote down vote up
public static List<RealVector> initializeClustersFromFile(String filename, int K) throws FileNotFoundException {
    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new FileReader(filename));
    RealVector[] centers = gson.fromJson(reader, ArrayRealVector[].class);
    List<RealVector> vectors = Arrays.asList(centers);
    if(vectors.size() > K) {
        return vectors.subList(0, K);
    } else {
        return vectors;
    }
}
 
Example #21
Source File: KDTree.java    From macrobase with Apache License 2.0 5 votes vote down vote up
/**
 * Estimates min and max difference absolute vectors from point to region
 * @param queryDatum target point
 * @return minVec, maxVec
 */
// TODO: Make this method faster.
public RealVector[] getMinMaxDistanceVectors(Datum queryDatum) {
    double[] minDifferences = new double[k];
    double[] maxDifferences = new double[k];

    RealVector metrics = queryDatum.metrics();
    for (int i=0; i<k; i++) {
        double deltaLo = metrics.getEntry(i) - this.boundaries[i][0];
        double deltaHi = this.boundaries[i][1] - metrics.getEntry(i);
        // point is outside
        double minD = Math.abs(deltaLo);
        double maxD = Math.abs(deltaHi);
        if (minD < maxD) {
            minDifferences[i] = minD;
            maxDifferences[i] = maxD;
        } else {
            minDifferences[i] = maxD;
            maxDifferences[i] = minD;
        }

        if (deltaLo > 0 && deltaHi > 0) {
            // Point is inside so only add to max distance.
            minDifferences[i] = 0;
        }
    }

    RealVector[] rtn = new RealVector[2];
    rtn[0] = new ArrayRealVector(minDifferences);
    rtn[1] = new ArrayRealVector(maxDifferences);
    return rtn;
}
 
Example #22
Source File: AbstractMultipleLinearRegression.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads new y sample data, overriding any previous data.
 *
 * @param y the array representing the y sample
 * @throws NullArgumentException if y is null
 * @throws NoDataException if y is empty
 */
protected void newYSampleData(double[] y) {
    if (y == null) {
        throw new NullArgumentException();
    }
    if (y.length == 0) {
        throw new NoDataException();
    }
    this.yVector = new ArrayRealVector(y);
}
 
Example #23
Source File: AbstractMultipleLinearRegression.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads new y sample data, overriding any previous data.
 *
 * @param y the array representing the y sample
 * @throws NullArgumentException if y is null
 * @throws NoDataException if y is empty
 */
protected void newYSampleData(double[] y) {
    if (y == null) {
        throw new NullArgumentException();
    }
    if (y.length == 0) {
        throw new NoDataException();
    }
    this.yVector = new ArrayRealVector(y);
}
 
Example #24
Source File: ContextualDatum.java    From macrobase with Apache License 2.0 5 votes vote down vote up
public RealVector getContextualDoubleAttributes() {
    if (contextualDoubleAttributes != null) {
        return contextualDoubleAttributes;
    } else {
        return new ArrayRealVector(0);
    }
}
 
Example #25
Source File: LinalgUtil.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Solve a linear matrix equation, or system of linear scalar equations.
 *
 * @param a Coefficient matrix.
 * @param b Ordinate or “dependent variable” values.
 * @return Solution to the system a x = b. Returned shape is identical to b.
 */
public static Array solve(Array a, Array b) {
    Array r = Array.factory(DataType.DOUBLE, b.getShape());
    double[][] aa = (double[][]) ArrayUtil.copyToNDJavaArray_Double(a);
    RealMatrix coefficients = new Array2DRowRealMatrix(aa, false);
    DecompositionSolver solver = new LUDecomposition(coefficients).getSolver();
    double[] bb = (double[]) ArrayUtil.copyToNDJavaArray_Double(b);
    RealVector constants = new ArrayRealVector(bb, false);
    RealVector solution = solver.solve(constants);
    for (int i = 0; i < r.getSize(); i++) {
        r.setDouble(i, solution.getEntry(i));
    }

    return r;
}
 
Example #26
Source File: AbstractMultipleLinearRegression.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads new y sample data, overriding any previous data.
 *
 * @param y the array representing the y sample
 * @throws NullArgumentException if y is null
 * @throws NoDataException if y is empty
 */
protected void newYSampleData(double[] y) {
    if (y == null) {
        throw new NullArgumentException();
    }
    if (y.length == 0) {
        throw new NoDataException();
    }
    this.yVector = new ArrayRealVector(y);
}
 
Example #27
Source File: AbstractMultipleLinearRegression.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Loads new y sample data, overriding any previous data.
 *
 * @param y the array representing the y sample
 * @throws NullArgumentException if y is null
 * @throws NoDataException if y is empty
 */
protected void newYSampleData(double[] y) {
    if (y == null) {
        throw new NullArgumentException();
    }
    if (y.length == 0) {
        throw new NoDataException();
    }
    this.yVector = new ArrayRealVector(y);
}
 
Example #28
Source File: AbstractEvaluation.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public RealVector getSigma(double covarianceSingularityThreshold) {
    final RealMatrix cov = this.getCovariances(covarianceSingularityThreshold);
    final int nC = cov.getColumnDimension();
    final RealVector sig = new ArrayRealVector(nC);
    for (int i = 0; i < nC; ++i) {
        sig.setEntry(i, FastMath.sqrt(cov.getEntry(i,i)));
    }
    return sig;
}
 
Example #29
Source File: Math_13_AbstractLeastSquaresOptimizer_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Update the residuals array and cost function value.
 * @throws DimensionMismatchException if the dimension does not match the
 * problem dimension.
 * @throws org.apache.commons.math3.exception.TooManyEvaluationsException
 * if the maximal number of evaluations is exceeded.
 * @deprecated As of 3.1. Please use {@link #computeResiduals(double[])},
 * {@link #computeObjectiveValue(double[])}, {@link #computeCost(double[])}
 * and {@link #setCost(double)} instead.
 */
@Deprecated
protected void updateResidualsAndCost() {
    objective = computeObjectiveValue(point);
    final double[] res = computeResiduals(objective);

    // Compute cost.
    cost = computeCost(res);

    // Compute weighted residuals.
    final ArrayRealVector residuals = new ArrayRealVector(res);
    weightedResiduals = weightMatrixSqrt.operate(residuals).toArray();
}
 
Example #30
Source File: AbstractLeastSquaresOptimizer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Update the residuals array and cost function value.
 * @throws DimensionMismatchException if the dimension does not match the
 * problem dimension.
 * @throws org.apache.commons.math3.exception.TooManyEvaluationsException
 * if the maximal number of evaluations is exceeded.
 * @deprecated As of 3.1. Please use {@link #computeResiduals(double[])},
 * {@link #computeObjectiveValue(double[])}, {@link #computeCost(double[])}
 * and {@link #setCost(double)} instead.
 */
@Deprecated
protected void updateResidualsAndCost() {
    objective = computeObjectiveValue(point);
    final double[] res = computeResiduals(objective);

    // Compute cost.
    cost = computeCost(res);

    // Compute weighted residuals.
    final ArrayRealVector residuals = new ArrayRealVector(res);
    weightedResiduals = weightMatrixSqrt.operate(residuals).toArray();
}