當前位置: 首頁>>代碼示例>>Java>>正文


Java ArrayRealVector類代碼示例

本文整理匯總了Java中org.apache.commons.math3.linear.ArrayRealVector的典型用法代碼示例。如果您正苦於以下問題:Java ArrayRealVector類的具體用法?Java ArrayRealVector怎麽用?Java ArrayRealVector使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ArrayRealVector類屬於org.apache.commons.math3.linear包,在下文中一共展示了ArrayRealVector類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: nextWishart

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
public RealMatrix nextWishart(double df, Cholesky invscale) {
  int d = invscale.getL().getColumnDimension();
  Array2DRowRealMatrix A = new Array2DRowRealMatrix(d,d);
  ArrayRealVector v = new ArrayRealVector(d);
  for (int i=0; i<d; i++) {
    v.setEntry(i, sqrt(nextChiSquared(df-i)));
    for (int j=0; j<i; j++) {
      v.setEntry(j, 0.0);
    }
    for (int j=i+1; j<d; j++) {
      v.setEntry(j, nextGaussian());
    }
    A.setColumnVector(i, invscale.solveLT(v));
  }
  return A.multiply(A.transpose());
}
 
開發者ID:BigBayes,項目名稱:BNPMix.java,代碼行數:17,代碼來源:Generator.java

示例2: unmarshall

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
 * Vector deserialization.
 */
public static RealVector unmarshall(byte[] bytes, boolean sparse, int dimensions) throws IOException {
    RealVector realVector = !sparse ? new ArrayRealVector(dimensions) : new OpenMapRealVector(dimensions);

    if (!sparse) {
        try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes))) {
            for (int i = 0; i < dimensions; i++) {
                realVector.setEntry(i, dis.readDouble());
            }
        }
    }
    else {
        try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes))) {
            while (true) {
                try {
                    realVector.setEntry(dis.readInt(), dis.readDouble());
                }
                catch (EOFException e) {
                    break;
                }
            }
        }
    }

    return realVector;
}
 
開發者ID:Lambda-3,項目名稱:Indra,代碼行數:29,代碼來源:BinaryCodecs.java

示例3: MixModel

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
public MixModel(MethyModel tumor, MethyModel normal, RealVector thetas, int nBetas, int MYTHREADS) throws InterruptedException {
	int nFeatures=tumor.getNaRatio().getDimension();
	this.nBetas = nBetas;
	RealVector betas = new ArrayRealVector(nBetas);
	for (int i=0; i<nBetas; i++) {
		betas.setEntry(i,i/(nBetas-1.0));
	}
	mixDens = new RealMatrix[nFeatures];
	ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);

	for(int i = 0; i < nFeatures; i++) {
		double tumorAlpha = tumor.getAlpha().getEntry(i);
		double tumorBeta = tumor.getBeta().getEntry(i);
		BetaDistribution tumorDist = new BetaDistribution(tumorAlpha,tumorBeta);
		double normalAlpha = normal.getAlpha().getEntry(i);
		double normalBeta = normal.getBeta().getEntry(i);
		BetaDistribution normalDist = new BetaDistribution(normalAlpha,normalBeta);
		Runnable worker = new CalMixDens(tumorDist,normalDist,thetas,betas,nPoints,i,mixDens);
		executor.execute(worker);
	}
	executor.shutdown();
	while (!executor.isTerminated()) {
		Thread.sleep(10000);
	}
}
 
開發者ID:jasminezhoulab,項目名稱:CancerLocator,代碼行數:26,代碼來源:MixModel.java

示例4: CrossValidationError

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
  * Compute the n-fold Cross validation error with LWR and a given Tau
  * 
  * @param tau
  * @param x
  * @param y
  * @return
  */
private Double CrossValidationError(Double tau, ArrayRealVector x,
    ArrayRealVector y) {
  int n = x.getDimension();
  double totalError = 0.0;
  for (int i = 0; i < n; ++i) {
    // CV fold for i
    double x_i = x.getEntry(i);
    double y_i = y.getEntry(i);
    ArrayRealVector Xcv = new ArrayRealVector( (ArrayRealVector)x.getSubVector(0, i), x.getSubVector(i+1, n - (i+1)) );
    ArrayRealVector Ycv = new ArrayRealVector( (ArrayRealVector)y.getSubVector(0, i), y.getSubVector(i+1, n - (i+1)) );
    Double y_predicted = LWRPredict(Xcv, Ycv, x_i, tau);
    if (null == y_predicted) {
      log.error(" cp LWR cannot predict - returning NULL");
      return null;
    }
    double predictionError = y_predicted - y_i;
    totalError += predictionError * predictionError;
  }  
  return totalError;
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:29,代碼來源:LWRCustOldAppache.java

示例5: LWRPredict

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
  * LWR prediction
  * 
  * @param X
  * @param Y
  * @param x0
  * @param tau
  * @return
  */
public Double LWRPredict(ArrayRealVector X, ArrayRealVector Y,
    double x0, final double tau) {
  ArrayRealVector X0 = new ArrayRealVector(X.getDimension(), x0);
  ArrayRealVector delta = X.subtract(X0);
  ArrayRealVector sqDists = delta.ebeMultiply(delta);
  UnivariateFunction expTau = new UnivariateFunction() {      
    @Override
    public double value(double arg0) {        
      //log.info(" cp univariate tau " + tau);
      return Math.pow(Math.E, -arg0 / (2*tau));
    }
  };
  ArrayRealVector W = sqDists.map(expTau);
  double Xt_W_X = X.dotProduct(W.ebeMultiply(X));
  if (Xt_W_X == 0.0) {
    log.error(" cp LWR cannot predict - 0 denominator returning NULL");
    log.error("Xcv is " + X.toString());
    log.error("Ycv is " + Y.toString());
    log.error("x0 is " + x0);
    return null; // <==== NOTE: a caller must be prepared for it
  }
  double theta = ( 1.0 / Xt_W_X ) * X.ebeMultiply(W).dotProduct(Y) ;  
  
  return theta * x0;    
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:35,代碼來源:LWRCustOldAppache.java

示例6: convertEnergyProfileFromServerToBroker

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
 * NOTE: subtle conversion that caused a bug - we use predictions
 * starting next time-step, but forecastCapacities are assumed
 * to be from current - so to return data to broker we need to
 * offset the record by 1
 */
protected ArrayRealVector convertEnergyProfileFromServerToBroker(
    CapacityProfile predictedEnergyProfile, int recordLength) throws Exception {
  //log.info("scaleEnergyProfile()");
  //log.info("predictedEnergyProfile" + Arrays.toString(predictedEnergyProfile.values.toArray()));
  int profileLength = predictedEnergyProfile.NUM_TIMESLOTS;
  // verify divides
  boolean divides = (recordLength / profileLength * profileLength) == recordLength; 
  if (!divides) {
    throw new Exception("How come profileLength doesn't divide recordLength");
  }
  //log.info("recordLength=" + recordLength);
  ArrayRealVector result = new ArrayRealVector(recordLength);
  
  for (int i = 0; i < recordLength; ++i) {
    result.setEntry(i, predictedEnergyProfile.getCapacity( (i + 1) % profileLength ));
    //log.info("appending " + predictedEnergyProfile.getCapacity( i % profileLength ) + " at " + i);
  }
  
  //log.info("result" + Arrays.toString(result.toArray()));
  return result;   
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:28,代碼來源:DefaultCapacityOriginator.java

示例7: smooth

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
@Override
public double[] smooth(double[] sourceX, double[] noisyY, double[] estimateX, double parameter) {
	int numDivisions = (int)Math.round(parameter);
	
	SmoothingHelper.SmoothingInput filteredInput = SmoothingHelper.filterInvalidValues(sourceX, noisyY);
	sourceX = filteredInput.getSourceX();
	noisyY = filteredInput.getSourceY();

	if(numDivisions >= sourceX.length) {
		throw new IllegalArgumentException("Cannot fit with " + numDivisions + " knots as the input data (after removing NAs) has < " + (numDivisions + 1) + " data points.");
	}

	
	double[][] sourceBasis = createBasis(numDivisions, splineDegree, sourceX);
	RealMatrix matrix = new Array2DRowRealMatrix(sourceBasis);		
	QRDecomposition decomposition = new QRDecomposition(matrix);
	RealVector coefficients = decomposition.getSolver().solve(new ArrayRealVector(noisyY));
	
	double[][] estimateBasis = createBasis((int)parameter, splineDegree, estimateX);
	RealMatrix estimateBasisMatrix = new Array2DRowRealMatrix(estimateBasis);
	
	double[] result = estimateBasisMatrix.transpose().preMultiply(coefficients).toArray();
	return result;
}
 
開發者ID:cas-bioinf,項目名稱:cy-dataseries,代碼行數:25,代碼來源:BSPlineRegressionSmoothingProvider.java

示例8: getPredictionForAbout7Days

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
@Override
public ArrayRealVector getPredictionForAbout7Days(CustomerInfo customerInfo, boolean customerPerspective, int currentTimeslot, boolean fixed) {

  // portfolioManager returns predictions from the broker's
  // perspective (producer has kwh > 0, consumer has kwh < 0)
  // so to view it from customer perspective we multiply by -1
  int sign = customerPerspective ? -1 : 1; 
  
  // TODO this is a temporary place holder - idealy this class
  // won't need the portfolioManager to get its prediction
  RealVector energy = portfolioManager.getGeneralRawUsageForCustomer(customerInfo, fixed).mapMultiply(sign);
  
  // sanity check
  if (energy.getDimension() != 7 * 24) {
    log.error("Expecting energy dimension to be 7 * 24 - unexpected behavior might happen");
  }
  
  // rotate to start from current time
  return BrokerUtils.rotateWeeklyRecordAndAppendTillEndOfDay(energy, currentTimeslot);
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:21,代碼來源:EnergyPredictionManagerService.java

示例9: optimizeTariffs

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
@Override
public TreeMap<Double, TariffSpecification> optimizeTariffs(
    HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>> tariffSubscriptions,
    HashMap<CustomerInfo, ArrayRealVector> customer2estimatedEnergy,
    List<TariffSpecification> competingTariffs, MarketManager marketManager,
    ContextManager contextManager, CostCurvesPredictor costCurvesPredictor,
    int currentTimeslot, Broker me) {

  // seed will be the best fixed-rate tariff
  TreeMap<Double, TariffSpecification> sortedTariffs =
      tariffOptimizerFixedRate.optimizeTariffs(tariffSubscriptions, 
          customer2estimatedEnergy, competingTariffs, marketManager, 
          contextManager, costCurvesPredictor, currentTimeslot, me);
  TariffSpecification fixedRateSeed = extractBestTariffSpec(sortedTariffs);
  
  TotalEnergyRecords energyRecords = sumTotalEnergy(customer2estimatedEnergy, tariffSubscriptions, currentTimeslot);
  ArrayRealVector energyUnitCosts = computeEnergyUnitCosts(costCurvesPredictor, energyRecords.getMyCustomersEnergy(), energyRecords.getCompetitorCustomersEnergy(), currentTimeslot);
  double avgMargin = computeAvgMargin(energyUnitCosts, fixedRateSeed);
  TariffSpecification touSpec = createTOUFixedMargin(energyUnitCosts, avgMargin, currentTimeslot, me);
  
  // create a result map with 1 tariff
  TreeMap<Double, TariffSpecification> eval2spec = new TreeMap<Double, TariffSpecification>();
  eval2spec.put(0.0, touSpec);
  return eval2spec;
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:26,代碼來源:TariffOptimizierTOUFixedMargin.java

示例10: computeAvgMargin

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
 * returns positive margin between selling unit-price and buying unit-cost 
 * @param energyUnitCosts
 * @param fixedRateSeed
 * @return
 */
private double computeAvgMargin(ArrayRealVector energyUnitCosts,
    TariffSpecification fixedRateSeed) {
  double totalMargin = 0;
  // next: '-' to adjust sign to broker perspective (i.e. make it positive)
  double sellingPricePerKwh = -(fixedRateSeed.getRates().get(0).getValue());
  for (int i = 0; i < energyUnitCosts.getDimension(); ++i ) {
    double buyingPricePerKwh = energyUnitCosts.getEntry(i);
    // next: '+' since buyingPricePerKwh is signed (i.e. negative)
    double margin = sellingPricePerKwh + buyingPricePerKwh; 
    totalMargin += margin; 
    log.debug("computeAvgMargin(): sellingPricePerKwh=" + sellingPricePerKwh + " buyingPricePerKwh=" + buyingPricePerKwh + "margin =" + margin + " totalMargin=" + totalMargin);
  }
  double avgMargin = totalMargin / energyUnitCosts.getDimension();
  log.debug("avgMargin=" + avgMargin);
  return avgMargin;
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:23,代碼來源:TariffOptimizierTOUFixedMargin.java

示例11: createTOUFixedMargin

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
private TariffSpecification createTOUFixedMargin(
    ArrayRealVector energyUnitCosts, double avgMargin, int currentTimeslot, Broker me) {
  
  int currentHourOfDay = (currentTimeslot - 360) % 24;
  
  TariffSpecification spec = new TariffSpecification(me, PowerType.CONSUMPTION);

  int firstHourOfPrediction = currentHourOfDay + 1;
  for (int i = 0; i < NUM_RATES; ++i) {
    // +/- confusion: energyUnitCosts contains negative values and margin is positive
    double rateValue = energyUnitCosts.getEntry(i) - avgMargin;
    int hour = (firstHourOfPrediction + i) % 24;
    log.debug("adding rate, hour=" + hour + " rate=" + rateValue);
    Rate rate = new Rate().withValue(rateValue).withDailyBegin(hour).withDailyEnd(hour);
    spec.addRate(rate);
  }
  
  return spec;     
}
 
開發者ID:LARG,項目名稱:TacTex,代碼行數:20,代碼來源:TariffOptimizierTOUFixedMargin.java

示例12: doOptimize

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/** {@inheritDoc} */
@Override
protected PointValuePair doOptimize() {
    final double[] lowerBound = getLowerBound();
    final double[] upperBound = getUpperBound();

    // Validity checks.
    setup(lowerBound, upperBound);

    isMinimize = (getGoalType() == GoalType.MINIMIZE);
    currentBest = new ArrayRealVector(getStartPoint());

    final double value = bobyqa(lowerBound, upperBound);

    return new PointValuePair(currentBest.getDataRef(),
                              isMinimize ? value : -value);
}
 
開發者ID:biocompibens,項目名稱:SME,代碼行數:18,代碼來源:BOBYQAOptimizer.java

示例13: value

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
@Override
public Pair<RealVector, RealMatrix> value(RealVector point) {

	// input
	double[] pointArray = point.toArray();

	// output
	double[] resultPoint = new double[this.distances.length];

	// compute least squares
	for (int i = 0; i < resultPoint.length; i++) {
		resultPoint[i] = 0.0;
		// calculate sum, add to overall
		for (int j = 0; j < pointArray.length; j++) {
			resultPoint[i] += (pointArray[j] - this.getPositions()[i][j]) * (pointArray[j] - this.getPositions()[i][j]);
		}
		resultPoint[i] -= (this.getDistances()[i]) * (this.getDistances()[i]);
	}

	RealMatrix jacobian = jacobian(point);
	return new Pair<RealVector, RealMatrix>(new ArrayRealVector(resultPoint), jacobian);
}
 
開發者ID:berger89,項目名稱:beacon-finder,代碼行數:23,代碼來源:TrilaterationFunction.java

示例14: bestMergedPath

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
/**
 *
 * @param forwardPath lattice of forwardPath
 * @param backwardPath lattice of backwardPath
 * @param nBestList array of arraylists (of string type) with n-best list for each entity span
 * @return best forward + best backward path
 */
public String bestMergedPath(double[][] forwardPath, double[][] backwardPath, List<String>[] nBestList) {
    int length = forwardPath.length;
    for (int i = 0; i < forwardPath.length; i++) {
        for (int j = 0; j < nBestList[i].size(); j++) {
            //System.out.println(forwardPath[i][j] + ", " + backwardPath[length - 1 - i][j] + ": " + nBestList[i].get(j));

            forwardPath[i][j] += backwardPath[length - 1 - i][j];
        }
    }
    StringBuilder bestPath = new StringBuilder();
    for (int i = 0; i < forwardPath.length; i++) {
        RealVector realVector = new ArrayRealVector(forwardPath[i]);
        int bestPathIndex = realVector.getMaxIndex();
        bestPath.append(nBestList[i].get(bestPathIndex));
        bestPath.append(CANDIDATE_DELIMITER);
    }
    return bestPath.toString();
}
 
開發者ID:yahoo,項目名稱:FEL,代碼行數:26,代碼來源:CoherentEntityLinker.java

示例15: update

import org.apache.commons.math3.linear.ArrayRealVector; //導入依賴的package包/類
@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;
}
 
開發者ID:apache,項目名稱:incubator-hivemall,代碼行數:26,代碼來源:ChangeFinder2D.java


注:本文中的org.apache.commons.math3.linear.ArrayRealVector類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。