Example usage for java.lang Double isNaN

List of usage examples for java.lang Double isNaN

Introduction

In this page you can find the example usage for java.lang Double isNaN.

Prototype

public static boolean isNaN(double v) 

Source Link

Document

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

Usage

From source file:ch.epfl.lsir.xin.algorithm.core.ItemBasedCF.java

/**
 * This function calculates the similarity matrix for items
 * *///from w ww  . j av a2  s  .  c  o m
public void similarityMatrixCalculation() {
    for (int i = 0; i < this.ratingMatrix.getColumn(); i++) {
        for (int j = i; j < this.ratingMatrix.getColumn(); j++) {
            if (i == j) //the similarity with herself is 1 
            {
                this.similarityMatrix[i][j] = 1;
            } else {
                ArrayList<Double> commonRatings1 = new ArrayList<Double>();
                ArrayList<Double> commonRatings2 = new ArrayList<Double>();
                //find common ratings for the two items
                for (int i1 = 0; i1 < this.ratingMatrix.getRow(); i1++) {
                    if (this.ratingMatrix.getRatingMatrix().get(i1).get(i) != null
                            && this.ratingMatrix.getRatingMatrix().get(i1).get(j) != null) {
                        commonRatings1.add(this.ratingMatrix.getRatingMatrix().get(i1).get(i));
                        commonRatings2.add(this.ratingMatrix.getRatingMatrix().get(i1).get(j));
                    }
                }
                double similarity = Double.NaN;
                if (this.similarityCalculation.equals("pcc")) {
                    similarity = SimilarityCalculator.getSimilarityPCC(commonRatings1, commonRatings2,
                            this.config.getInt("SHRINKAGE"));
                } else if (this.similarityCalculation.equals("cosine")) {
                    similarity = SimilarityCalculator.getSimilarityCosine(commonRatings1, commonRatings2,
                            this.config.getInt("SHRINKAGE"));
                } else {
                    logger.append("Cannot determine which similarity calculation method is used for. \n");
                    return;
                }

                if (Double.isNaN(similarity)) {
                    similarity = 0;
                }
                this.similarityMatrix[i][j] = similarity;
                this.similarityMatrix[j][i] = similarity;
            }
        }
    }
}

From source file:edu.cmu.tetrad.data.CovarianceMatrix.java

/**
 * Constructs a new covariance matrix from the given data set.
 *
 * @throws IllegalArgumentException if this is not a continuous data set.
 *//*  w w w . java 2  s  . co m*/
public CovarianceMatrix(DataSet dataSet) {
    if (!dataSet.isContinuous()) {
        throw new IllegalArgumentException("Not a continuous data set.");
    }

    this.matrix = new TetradMatrix(dataSet.getNumColumns(), dataSet.getNumColumns());

    this.variables = Collections.unmodifiableList(dataSet.getVariables());
    this.sampleSize = dataSet.getNumRows();

    if (dataSet instanceof BoxDataSet) {

        DataBox box = ((BoxDataSet) dataSet).getDataBox().copy();

        if (box instanceof VerticalDoubleDataBox) {
            if (!dataSet.getVariables().equals(variables))
                throw new IllegalArgumentException();

            vectors = ((VerticalDoubleDataBox) box).getVariableVectors();

            //                final TetradMatrix doubleData = dataSet.getDoubleData();

            //                DataUtils.remean(doubleData, means);
        }

    }

    if (vectors == null) {
        final TetradMatrix doubleData = dataSet.getDoubleData().copy();
        TetradVector means = DataUtils.means(doubleData);
        DataUtils.demean(doubleData, means);

        final RealMatrix realMatrix = doubleData.getRealMatrix();

        vectors = new double[variables.size()][];

        for (int i = 0; i < variables.size(); i++) {
            vectors[i] = realMatrix.getColumnVector(i).toArray();
        }
    }

    TetradVector means = DataUtils.means(vectors);

    int NTHREADS = Runtime.getRuntime().availableProcessors() * 10;
    int _chunk = variables.size() / NTHREADS + 1;
    int minChunk = 100;
    final int chunk = _chunk < minChunk ? minChunk : _chunk;

    class VarianceTask extends RecursiveTask<Boolean> {
        private int chunk;
        private int from;
        private int to;

        public VarianceTask(int chunk, int from, int to) {
            this.chunk = chunk;
            this.from = from;
            this.to = to;
        }

        @Override
        protected Boolean compute() {
            if (to - from <= chunk) {
                for (int i = from; i < to; i++) {
                    double d = 0.0D;

                    int count = 0;

                    double[] v1 = vectors[i];

                    for (int k = 0; k < sampleSize; ++k) {
                        if (Double.isNaN(v1[k])) {
                            continue;
                        }

                        d += v1[k] * v1[k];
                        count++;
                    }

                    double v = d;
                    v /= (count - 1);

                    matrix.set(i, i, v);

                    if (v == 0) {
                        System.out.println("Zero variance! " + variables.get(i));
                    }
                }

                return true;
            } else {
                int mid = (to + from) / 2;

                VarianceTask left = new VarianceTask(chunk, from, mid);
                VarianceTask right = new VarianceTask(chunk, mid, to);

                left.fork();
                right.compute();
                left.join();

                return true;
            }
        }
    }

    class RestOfThemTask extends RecursiveTask<Boolean> {
        private int chunk;
        private int from;
        private int to;

        public RestOfThemTask(int chunk, int from, int to) {
            this.chunk = chunk;
            this.from = from;
            this.to = to;
        }

        @Override
        protected Boolean compute() {
            if (to - from <= chunk) {
                for (int i = from; i < to; i++) {
                    for (int j = 0; j < i; j++) {

                        double d = 0.0D;

                        double[] v1 = vectors[i];
                        double[] v2 = vectors[j];
                        int count = 0;

                        for (int k = 0; k < sampleSize; k++) {
                            if (Double.isNaN(v1[k]))
                                continue;
                            if (Double.isNaN(v2[k]))
                                continue;

                            d += v1[k] * v2[k];
                            count++;
                        }

                        double v = d;
                        v /= (count - 1);

                        matrix.set(i, j, v);
                        matrix.set(j, i, v);
                    }
                }

                return true;
            } else {
                int mid = (to + from) / 2;

                RestOfThemTask left = new RestOfThemTask(chunk, from, mid);
                RestOfThemTask right = new RestOfThemTask(chunk, mid, to);

                left.fork();
                right.compute();
                left.join();

                return true;
            }
        }
    }

    VarianceTask task = new VarianceTask(chunk, 0, variables.size());
    ForkJoinPoolInstance.getInstance().getPool().invoke(task);

    RestOfThemTask task2 = new RestOfThemTask(chunk, 0, variables.size());
    ForkJoinPoolInstance.getInstance().getPool().invoke(task2);

    DataUtils.demean(vectors, means);

    this.variables = Collections.unmodifiableList(dataSet.getVariables());
    this.sampleSize = dataSet.getNumRows();
}

From source file:geogebra.kernel.AlgoSurdText.java

private int[] PSLQ(double[] x, double AccuracyFactor, int bound) {

    int n = x.length;
    int[] coeffs = new int[n];

    double normX;
    double[] ss;/*from  ww w  . java 2s.  c om*/
    double[][] H, P, newH;
    int[][] D, E, A, B, newAorB;
    double[][][] G;
    int[][][] R;
    double gamma, deltaSq;

    for (int i = 0; i < n; i++) {
        coeffs[i] = 0;
    }

    if (n <= 1)
        return coeffs;

    for (int i = 0; i < n; i++) {
        if (Double.isNaN(x[i]))
            return coeffs;
    }

    //normalize x
    normX = 0;
    for (int i = 0; i < n; i++) {
        normX += x[i] * x[i];
    }
    normX = Math.sqrt(normX);
    for (int i = 0; i < n; i++) {
        x[i] = x[i] / normX;
    }

    //partial sums of squares
    ss = new double[n];
    ss[n - 1] = x[n - 1] * x[n - 1];
    for (int i = n - 2; i >= 0; i--) {
        ss[i] = ss[i + 1] + x[i] * x[i];
    }
    for (int i = 0; i < n; i++) {
        ss[i] = Math.sqrt(ss[i]);
    }

    //pre-calculate ss[j]*ss[j+1]
    double[] Pss = new double[n - 1];
    for (int i = 0; i < n - 1; i++) {
        Pss[i] = ss[i] * ss[i + 1];
    }

    //initialize Matrix H (lower trapezoidal
    H = new double[n][n - 1];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            H[i][j] = -x[i] * x[j] / Pss[j];
        }

        if (i < n - 1)
            H[i][i] = ss[i + 1] / ss[i];

        for (int j = i + 1; j < n - 1; j++) {
            H[i][j] = 0;
        }
    }

    //test property of H: the n-1 columns are orthogonal
    /*
    for (int i =0 ; i<n-1; i++) {
       for (int j=0; j<n-1; j++) {
    double sum = 0;
    for (int k=0; k<n; k++) {
       sum += H[k][i]*H[k][j];
    }
    System.out.println(sum);
       }
    }*/

    //matrix P = In - x.x
    P = new double[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            P[i][j] = -x[i] * x[j];
    for (int i = 0; i < n; i++)
        P[i][i] += 1;

    //debug: |P|^2=|H|^2 = n-1
    Application.debug("Frobenius Norm Squares: \n" + "|P|^2 = " + frobNormSq(P, n, n) + "|H|^2 = "
            + frobNormSq(H, n, n - 1));

    //initialize matrices R
    R = new int[n - 1][n][n];
    for (int j = 0; j < n - 1; j++) {
        for (int i = 0; i < n; i++)
            for (int k = 0; k < n; k++)
                R[j][i][k] = 0;
        for (int i = 0; i < n; i++)
            R[j][i][i] = 1;
        R[j][j][j] = 0;
        R[j][j][j + 1] = 1;
        R[j][j + 1][j] = 1;
        R[j][j + 1][j + 1] = 0;
    }

    gamma = 1.5;
    deltaSq = 3.0 / 4 - (1.0 / gamma) / gamma;

    //initialize A, B = I_n
    A = new int[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            A[i][j] = 0;
    for (int i = 0; i < n; i++)
        A[i][i] = 1;
    B = new int[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            B[i][j] = 0;
    for (int i = 0; i < n; i++)
        B[i][i] = 1;

    //iteration
    int itCount = 0;
    double itBound = 2.0 * gamma / deltaSq * n * n * (n + 1) * Math.log(Math.sqrt(bound * bound * n) * n * n)
            / Math.log(2);
    Application.debug("itBound = " + itBound);
    while (itCount < itBound) {

        //0. test if we have found a relation in a column of B
        double[] xB = new double[n];
        for (int i = 0; i < n; i++) {
            xB[i] = 0;
            for (int k = 0; k < n; k++)
                xB[i] += x[k] * B[k][i];
            if (Kernel.isEqual(xB[i], 0, AccuracyFactor)) {
                for (int k = 0; k < n; k++)
                    coeffs[k] = B[k][i];
                return coeffs;
            }
        }

        //0.5. calculate D, E
        //matrix D
        D = new int[n][n];
        double[][] D0 = new double[n][n]; //testing
        for (int i = 0; i < n; i++) {
            //define backwards. the 0's and 1's should be defined first.
            for (int j = n - 1; j >= i + 1; j--) {
                D[i][j] = 0;
                D0[i][j] = 0;
            }
            D[i][i] = 1;
            D0[i][i] = 1;

            for (int j = i - 1; j >= 0; j--) {
                double sum = 0;
                double sum0 = 0;
                for (int k = j + 1; k <= i; k++) {
                    sum += D[i][k] * H[k][j];
                    sum0 += D0[i][k] * H[k][j];
                }

                D[i][j] = (int) Math.floor(-1.0 / H[j][j] * sum + 0.5);
                D0[i][j] = -1.0 / H[j][j] * sum0;
            }

        }

        //matrix E = D^{-1}
        E = new int[n][n];
        for (int i = 0; i < n; i++) {
            //define backwards. the 0's and 1's should be defined first.
            for (int j = n - 1; j >= i + 1; j--) {
                E[i][j] = 0;
            }
            E[i][i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                int sum = 0;
                for (int k = j + 1; k <= i; k++)
                    sum += E[i][k] * D[k][j];

                E[i][j] = -sum;
            }

        }

        //1. replace H by DH
        newH = new double[n][n - 1];
        double[][] newH0 = new double[n][n - 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                newH[i][j] = 0;
                newH0[i][j] = 0;
                for (int k = 0; k < n; k++) {
                    newH[i][j] += D[i][k] * H[k][j];
                    newH0[i][j] += D0[i][k] * H[k][j];
                }

            }
        }

        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - 1; j++)
                H[i][j] = newH[i][j];

        //2. find j to maximize gamma^j |h_jj|
        double gammaPow = 1;
        double temp;
        double max = 0;
        int index = 0;

        for (int j = 0; j < n - 1; j++) {
            gammaPow *= gamma;
            temp = gammaPow * Math.abs(H[j][j]);
            if (max < temp) {
                max = temp;
                index = j;
            }
        }

        //2.5 calculate matrices G[0], G[1],... G[n-2]
        G = new double[n - 1][n - 1][n - 1];
        for (int i = 0; i < n - 1; i++)
            for (int k = 0; k < n - 1; k++)
                G[n - 2][i][k] = 0;
        for (int i = 0; i < n - 1; i++)
            G[n - 2][i][i] = 1;

        for (int j = 0; j < n - 2; j++) {
            double a = H[j][j];
            double b = H[j + 1][j];
            double c = H[j + 1][j + 1];
            double d = Math.sqrt(b * b + c * c);
            for (int i = 0; i < n - 2; i++)
                for (int k = 0; k < n - 2; k++)
                    G[j][i][k] = 0;
            for (int i = 0; i < j; i++)
                G[j][i][i] = 1;
            for (int i = j + 2; i < n - 1; i++)
                G[j][i][i] = 1;
            G[j][j][j] = b / d;
            G[j][j][j + 1] = -c / d;
            G[j][j + 1][j] = -G[j][j][j + 1]; // =c/d
            G[j][j + 1][j + 1] = G[j][j][j]; // = b/d
        }

        //3. replace H by R_jHG_j, A by R_jDA, B by BER_j
        newH = new double[n][n - 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - 1; j++) {
                newH[i][j] = 0;
                for (int k = 0; k < n; k++)
                    for (int l = 0; l < n - 1; l++)
                        newH[i][j] += R[index][i][k] * H[k][l] * G[index][l][j];
            }
        }
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n - 1; j++)
                H[i][j] = newH[i][j];

        newAorB = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                newAorB[i][j] = 0;
                for (int k = 0; k < n; k++)
                    for (int l = 0; l < n; l++)
                        newAorB[i][j] += R[index][i][k] * D[k][l] * A[l][j];
            }
        }
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                A[i][j] = newAorB[i][j];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                newAorB[i][j] = 0;
                for (int k = 0; k < n; k++)
                    for (int l = 0; l < n; l++)
                        newAorB[i][j] += B[i][k] * E[k][l] * R[index][l][j];
            }
        }
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                B[i][j] = newAorB[i][j];

        itCount++;
    }

    return coeffs;
}

From source file:com.cloudera.knittingboar.sgd.iterativereduce.POLRWorkerNode.java

/**
 * The IR::Compute method - this is where we do the next batch of records for
 * SGD//w  w  w  . j  a  v a  2  s. c  o m
 */
@Override
public ParameterVectorGradientUpdatable compute() {

    Text value = new Text();
    long batch_vec_factory_time = 0;

    boolean result = true;
    //boolean processBatch = false;

    /*    if (this.LocalPassCount > this.GlobalPassCount) {
          // we need to sit this one out
          System.out.println("Worker " + this.internalID
              + " is ahead of global pass count [" + this.LocalPassCount + ":"
              + this.GlobalPassCount + "] ");
          processBatch = true;
        }
                
        if (this.LocalPassCount >= this.NumberPasses) {
          // learning is done, terminate
          System.out.println("Worker " + this.internalID + " is done ["
              + this.LocalPassCount + ":" + this.GlobalPassCount + "] ");
          processBatch = false;
        }    
                
        if (processBatch) {
     */

    //    if (this.lineParser.hasMoreRecords()) {
    //for (int x = 0; x < this.BatchSize; x++) {
    while (this.lineParser.hasMoreRecords()) {

        try {
            result = this.lineParser.next(value);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        if (result) {

            long startTime = System.currentTimeMillis();

            Vector v = new RandomAccessSparseVector(this.FeatureVectorSize);
            int actual = -1;
            try {

                actual = this.VectorFactory.processLine(value.toString(), v);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            long endTime = System.currentTimeMillis();

            batch_vec_factory_time += (endTime - startTime);

            // calc stats ---------

            double mu = Math.min(k + 1, 200);
            double ll = this.polr.logLikelihood(actual, v);

            metrics.AvgLogLikelihood = metrics.AvgLogLikelihood + (ll - metrics.AvgLogLikelihood) / mu;

            if (Double.isNaN(metrics.AvgLogLikelihood)) {
                metrics.AvgLogLikelihood = 0;
            }

            Vector p = new DenseVector(this.num_categories);
            this.polr.classifyFull(p, v);
            int estimated = p.maxValueIndex();
            int correct = (estimated == actual ? 1 : 0);
            metrics.AvgCorrect = metrics.AvgCorrect + (correct - metrics.AvgCorrect) / mu;
            this.polr.train(actual, v);

            k++;
            metrics.TotalRecordsProcessed = k;
            //          if (x == this.BatchSize - 1) {

            /*            System.err
                            .printf(
            "Worker %s:\t Iteration: %s, Trained Recs: %10d, AvgLL: %10.3f, Percent Correct: %10.2f, VF: %d\n",
            this.internalID, this.CurrentIteration, k, metrics.AvgLogLikelihood,
            metrics.AvgCorrect * 100, batch_vec_factory_time);
              */
            //          }

            this.polr.close();

        } else {

            //          this.LocalBatchCountForIteration++;
            // this.input_split.ResetToStartOfSplit();
            // nothing else to process in split!
            //          break;

        } // if

    } // for the batch size

    System.err.printf(
            "Worker %s:\t Iteration: %s, Trained Recs: %10d, AvgLL: %10.3f, Percent Correct: %10.2f, VF: %d\n",
            this.internalID, this.CurrentIteration, k, metrics.AvgLogLikelihood, metrics.AvgCorrect * 100,
            batch_vec_factory_time);

    /*    } else {
          System.err
          .printf(
              "Worker %s:\t Trained Recs: %10d,  AvgLL: %10.3f, Percent Correct: %10.2f, [Done With Iteration]\n",
              this.internalID, k, metrics.AvgLogLikelihood,
              metrics.AvgCorrect * 100);
                  
        } // if 
      */
    return new ParameterVectorGradientUpdatable(this.GenerateUpdate());
}

From source file:fr.lig.sigma.astral.gui.graph.sugiyama.SugiyamaLayerStack.java

void xPosDown(int staticIndex, int flexIndex) {
    List<Node<E>> flex = layers.get(flexIndex);
    for (int i = 0; i < flex.size(); i++) {
        Node<E> n = flex.get(i);
        double min = i > 0 ? flex.get(i - 1).getPos().x + flex.get(i - 1).getSize().x + X_SEP
                : -Double.MAX_VALUE;
        List<Node<E>> neighbors = getConnectedTo(n, staticIndex);
        double avg = avgX(neighbors);
        if (!Double.isNaN(avg)) {
            n.setPos(max(min, avg - n.getSize().x / 2d), n.getPos().y);
        }/*from   w  w  w  .j  a v a  2s  .  com*/
    }
}

From source file:eagle.log.entity.filter.BooleanExpressionComparator.java

/**
 *
 * @param row List[KeyValue] All key values in a row
 *
 * @return 0 to filter out row [false], otherwise to include row into scanner [true]
 *//*from ww  w.  j  a v a  2 s .  c  om*/
@Override
public int compareTo(List<KeyValue> row) {
    Map<String, Double> context = new HashMap<String, Double>();
    for (KeyValue kv : row) {
        String qualifierName = new String(kv.getQualifier());

        // Because assume just handle about double value
        // so ignore tag whose value is String
        if (!this.ed.isTag(qualifierName)) {
            Qualifier qualifier = this.ed.getQualifierNameMap().get(qualifierName);
            String displayName = qualifier.getDisplayName();
            if (displayName == null)
                displayName = qualifierName;
            try {
                if (this.requiredFields.contains(displayName)) {
                    EntitySerDeser serDeser = qualifier.getSerDeser();
                    double value = EntityQualifierUtils.convertObjToDouble(serDeser.deserialize(kv.getValue()));
                    if (Double.isNaN(value)) {
                        context.put(displayName, value);
                    }
                }
            } catch (Exception ex) {
                LOG.warn("Failed to parse value of field " + displayName + " as double, ignore: "
                        + ex.getMessage(), ex);
            }
        }
    }
    return compareTo(context);
}

From source file:net.sf.mzmine.modules.peaklistmethods.dataanalysis.heatmaps.HeatMapTask.java

public void run() {

    setStatus(TaskStatus.PROCESSING);//from   w ww.  j  a v a 2s . com

    logger.info("Heat map plot");

    if (plegend) {
        newPeakList = groupingDataset(selectedParameter, referenceGroup.toString());
    } else {
        newPeakList = modifySimpleDataset(selectedParameter, referenceGroup.toString());
    }

    if (newPeakList.length == 0 || newPeakList[0].length == 0) {
        setStatus(TaskStatus.ERROR);
        errorMessage = "The data for heat map is empty.";
        return;
    }

    Rengine rEngine = null;
    try {
        rEngine = RUtilities.getREngine();
    } catch (Throwable t) {
        setStatus(TaskStatus.ERROR);
        errorMessage = "Heat map requires R but it could not be loaded (" + t.getMessage() + ')';
        return;
    }

    finishedPercentage = 0.3f;

    synchronized (RUtilities.R_SEMAPHORE) {

        // Load gplots library
        if (rEngine.eval("require(gplots)").asBool().isFALSE()) {
            setStatus(TaskStatus.ERROR);
            errorMessage = "Heap maps plot requires the \"gplots\" R package, which could not be loaded. Please add it to your R installation.";
        }

        try {

            if (outputType.contains("png")) {
                if (height < 500 || width < 500) {

                    setStatus(TaskStatus.ERROR);
                    errorMessage = "Figure height or width is too small. Minimun height and width is 500.";
                    return;
                }
            }

            rEngine.eval("dataset<- matrix(\"\",nrow =" + newPeakList[0].length + ",ncol=" + newPeakList.length
                    + ")");

            if (plegend) {
                rEngine.eval("stars<- matrix(\"\",nrow =" + newPeakList[0].length + ",ncol="
                        + newPeakList.length + ")");
            }

            // assing the values to the matrix
            for (int row = 0; row < newPeakList[0].length; row++) {

                for (int column = 0; column < newPeakList.length; column++) {

                    int r = row + 1;
                    int c = column + 1;

                    double value = newPeakList[column][row];

                    if (plegend) {
                        String pValue = pValueMatrix[column][row];
                        rEngine.eval("stars[" + r + "," + c + "] = \"" + pValue + "\"");
                    }

                    if (!Double.isInfinite(value) && !Double.isNaN(value)) {

                        rEngine.eval("dataset[" + r + "," + c + "] = " + value);
                    } else {

                        rEngine.eval("dataset[" + r + "," + c + "] = NA");
                    }
                }
            }
            finishedPercentage = 0.4f;

            rEngine.eval("dataset <- apply(dataset, 2, as.numeric)");

            // Assign row names to the data set
            long rows = rEngine.rniPutStringArray(rowNames);
            rEngine.rniAssign("rowNames", rows, 0);
            rEngine.eval("rownames(dataset)<-rowNames");

            // Assign column names to the data set
            long columns = rEngine.rniPutStringArray(colNames);
            rEngine.rniAssign("colNames", columns, 0);
            rEngine.eval("colnames(dataset)<-colNames");

            finishedPercentage = 0.5f;

            // Remove the rows with too many NA's. The distances between
            // rows can't be calculated if the rows don't have
            // at least one sample in common.
            rEngine.eval(" d <- as.matrix(dist(dataset))");
            rEngine.eval("d[upper.tri(d)] <- 0");
            rEngine.eval("dataset <- dataset[-na.action(na.omit(d)),]");

            finishedPercentage = 0.8f;

            String marginParameter = "margins = c(" + columnMargin + "," + rowMargin + ")";
            rEngine.eval(
                    "br<-c(seq(from=min(dataset,na.rm=T),to=0,length.out=256),seq(from=0,to=max(dataset,na.rm=T),length.out=256))",
                    false);

            // Possible output file types
            if (outputType.contains("pdf")) {

                rEngine.eval("pdf(\"" + outputFile + "\", height=" + height + ", width=" + width + ")");
            } else if (outputType.contains("fig")) {

                rEngine.eval("xfig(\"" + outputFile + "\", height=" + height + ", width=" + width
                        + ", horizontal = FALSE, pointsize = 12)");
            } else if (outputType.contains("svg")) {

                // Load RSvgDevice library
                if (rEngine.eval("require(RSvgDevice)").asBool().isFALSE()) {

                    throw new IllegalStateException(
                            "The \"RSvgDevice\" R package couldn't be loaded - is it installed in R?");
                }

                rEngine.eval("devSVG(\"" + outputFile + "\", height=" + height + ", width=" + width + ")");
            } else if (outputType.contains("png")) {

                rEngine.eval("png(\"" + outputFile + "\", height=" + height + ", width=" + width + ")");
            }

            if (plegend) {

                rEngine.eval("heatmap.2(dataset," + marginParameter
                        + ", trace=\"none\", col=bluered(length(br)-1), breaks=br, cellnote=stars, notecol=\"black\", notecex="
                        + starSize + ", na.color=\"grey\")", false);
            } else {

                rEngine.eval(
                        "heatmap.2(dataset," + marginParameter
                                + ", trace=\"none\", col=bluered(length(br)-1), breaks=br, na.color=\"grey\")",
                        false);
            }

            rEngine.eval("dev.off()", false);
            finishedPercentage = 1.0f;

        } catch (Throwable t) {

            throw new IllegalStateException("R error during the heat map creation", t);
        }
    }

    setStatus(TaskStatus.FINISHED);

}

From source file:org.tsho.dmc2.core.chart.Bifurcation2DRenderer.java

public void render(final Graphics2D g2, final Rectangle2D dataArea, final PlotRenderingInfo info) {

    int numVar = model.getNVar();

    if (model instanceof ODE) {

        boolean pointBeyondPoincareSection;
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        int dim = initialValue.length;

        final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length;
        final Paint[] colorArray = new Color[colorArrayLen];
        for (int i = 0; i < colorArrayLen; i++) {
            colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i];
        }//ww w .j  av a2 s  .  c  o  m

        double[] fPars = new double[fixedParameters.length];
        System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length);
        double[] initVars = new double[initialValue.length];
        System.arraycopy(initialValue, 0, initVars, 0, initialValue.length);

        double[] result = new double[dim];
        double[][] periodArray = new double[period][dim];

        for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) {

            fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM);

            for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) {

                fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT);

                stepper.setParameters(fPars);
                stepper.setInitialValue(initVars);
                stepper.initialize();
                stepper.step();
                stepper.getCurrentValue(result);

                int h = 0;
                int transX, transY;

                double[] currentPoint = new double[numVar];
                double[] previousPoint = new double[numVar];
                stepper.getCurrentValue(currentPoint);
                stepper.getCurrentValue(previousPoint);
                pointBeyondPoincareSection = positionWrtPoincareSection(currentPoint);

                Paint color = Color.white;
                double[] cycleStartPoint = new double[numVar];
                int actualPeriod = period + 1;

                for (int jj = 0; jj < time / step; jj++) {
                    stepper.step();
                    stepper.getCurrentValue(currentPoint);

                    if (positionWrtPoincareSection(currentPoint) == pointBeyondPoincareSection) {
                        stepper.getCurrentValue(previousPoint);
                        continue;
                    }

                    pointBeyondPoincareSection = !pointBeyondPoincareSection;
                    double[] pointOnSection = pointOnPoincareSection(previousPoint, currentPoint);
                    stepper.setInitialValue(pointOnSection);
                    stepper.initialize();
                    stepper.getCurrentValue(currentPoint);
                    stepper.getCurrentValue(previousPoint);

                    h++;

                    if (h == transients) {
                        for (int kk = 0; kk < numVar; kk++)
                            cycleStartPoint[kk] = currentPoint[kk];
                    }
                    if (h > transients) {
                        if (distance(currentPoint, cycleStartPoint) < epsilon) {
                            actualPeriod = h - transients;
                            break;
                        }
                        if (h >= transients + period)
                            break;
                    }
                }

                stepper.getCurrentValue(result);

                for (h = 0; h < dim; h++) {
                    if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) {
                        color = Color.black; // black == infinity
                    }
                }

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }

                if (actualPeriod <= period) { // found period
                    color = colorArray[actualPeriod - 1];
                }

                g2.setPaint(color);
                g2.drawRect((int) i, (int) j, 1, 1);

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }
            }

        }
        state = STATE_FINISHED;

    } else {
        ValueAxis domainAxis = plot.getDomainAxis();
        ValueAxis rangeAxis = plot.getRangeAxis();

        int dim = initialValue.length;

        final int colorArrayLen = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length;
        final Paint[] colorArray = new Color[colorArrayLen];
        for (int i = 0; i < colorArrayLen; i++) {
            colorArray[i] = DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i];
        }

        double[] fPars = new double[fixedParameters.length];
        System.arraycopy(fixedParameters, 0, fPars, 0, fixedParameters.length);
        double[] initVars = new double[initialValue.length];
        System.arraycopy(initialValue, 0, initVars, 0, initialValue.length);

        double[] result = new double[dim];
        double[][] periodArray = new double[period + 1][dim];

        for (double i = dataArea.getMinX(); i <= dataArea.getMaxX(); i += 1) {

            fPars[firstParameterIdx] = domainAxis.java2DToValue(i, dataArea, RectangleEdge.BOTTOM);

            for (double j = dataArea.getMinY(); j < dataArea.getMaxY(); j += 1) {

                fPars[secondParameterIdx] = rangeAxis.java2DToValue(j, dataArea, RectangleEdge.LEFT);

                stepper.setParameters(fPars);
                stepper.setInitialValue(initVars);
                stepper.initialize();
                stepper.step();
                stepper.getCurrentValue(result);

                for (int h = 1; h < transients; h++) {
                    if (stopped) {
                        state = STATE_STOPPED;
                        return;
                    }
                    stepper.step();
                }

                stepper.getCurrentValue(result);

                Paint color = Color.white; // white == longer period
                for (int h = 0; h < dim; h++) {
                    if (Math.abs(result[h]) > infinity || Double.isNaN(result[h])) {
                        color = Color.black; // black == infinity
                        break;
                    }
                }

                if (color != Color.black) {
                    // get maxPeriod next values
                    for (int h = 0; h <= period; h++) {
                        if (stopped) {
                            state = STATE_STOPPED;
                            return;
                        }

                        stepper.step();
                        stepper.getCurrentValue(result);

                        for (int k = 0; k < dim; k++) {
                            periodArray[h][k] = result[k];
                        }
                    }

                    int h, k = -1;
                    for (h = 1; h <= period; h++) {
                        for (k = 0; k < dim; k++) {
                            if (Math.abs(periodArray[0][k] - periodArray[h][k]) >= epsilon) {
                                break;
                            }
                        }
                        if (k == dim) {
                            break;
                        }
                    }

                    if (h <= period) { // found period
                        color = colorArray[h - 1];
                    }
                }
                g2.setPaint(color);
                g2.drawRect((int) i, (int) j, 1, 1);

                if (stopped) {
                    state = STATE_STOPPED;
                    return;
                }
            }
        }
        state = STATE_FINISHED;
    }

}

From source file:no.met.jtimeseries.chart.XYCardinalSplineRenderer.java

/**
 * Draws the item (first pass). This method draws the lines connecting the
 * items. Instead of drawing separate lines, a GeneralPath is constructed
 * and drawn at the end of the series painting.
 *
 * @param g2//w w w.  j a v a 2  s.  co  m
 *            the graphics device.
 * @param state
 *            the renderer state.
 * @param plot
 *            the plot (can be used to obtain standard color information
 *            etc).
 * @param dataset
 *            the dataset.
 * @param pass
 *            the pass.
 * @param series
 *            the series index (zero-based).
 * @param item
 *            the item index (zero-based).
 * @param domainAxis
 *            the domain axis.
 * @param rangeAxis
 *            the range axis.
 * @param dataArea
 *            the area within which the data is being drawn.
 */
@Override
protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset,
        int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) {

    RectangleEdge xAxisLocation = plot.getDomainAxisEdge();
    RectangleEdge yAxisLocation = plot.getRangeAxisEdge();

    // get the data points
    double x1 = dataset.getXValue(series, item);
    double y1 = dataset.getYValue(series, item);
    double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation);
    double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation);

    // collect points
    if (!Double.isNaN(transX1) && !Double.isNaN(transY1)) {
        ControlPoint p = new ControlPoint(
                plot.getOrientation() == PlotOrientation.HORIZONTAL ? (float) transY1 : (float) transX1,
                plot.getOrientation() == PlotOrientation.HORIZONTAL ? (float) transX1 : (float) transY1);
        if (!this.points.contains(p)) {
            this.points.add(p);
        }
    }
    if (item == dataset.getItemCount(series) - 1) {
        State s = (State) state;
        // construct path
        // we need at least two points to draw something
        if (this.points.size() > 1) {
            ControlPoint cp0 = this.points.get(0);
            s.seriesPath.moveTo(cp0.x, cp0.y);
            // we need at least 2 points to spline. Draw simple line
            // for less then 2 points
            if (this.points.size() == 2) {
                ControlPoint cp1 = this.points.get(1);
                s.seriesPath.lineTo(cp1.x, cp1.y);

            } else {
                // construct spline
                // number of intervals (i.e. parametric curve would be
                // evaluted n+1 times)
                // set the minimum resolution
                int minimumN = 1;
                int maximumN = 4;

                // add two more points at the top and the end for drawing the curve between the first two and last two points
                this.points.add(0, this.points.get(0));
                this.points.add(this.points.get(this.points.size() - 1));

                // set the minimum distance when using minimumN
                double smallDistance = Math.pow(Math.pow(points.get(3).x - points.get(0).x, 2)
                        + Math.pow(points.get(3).y - points.get(0).y, 2), 0.5);

                double currentDistance;
                double currentN;

                List<ControlPoint> newPoints;
                for (int i = 0; i < this.points.size() - 3; i++) {
                    currentDistance = Math.pow(Math.pow(points.get(i + 3).x - points.get(i).x, 2)
                            + Math.pow(points.get(i + 3).y - points.get(i).y, 2), 0.5);
                    currentN = minimumN * currentDistance / smallDistance;
                    currentN = currentN > maximumN ? maximumN : currentN;
                    newPoints = evaluateCardinal2DAtNplusOneValues(this.points.get(i), this.points.get(i + 1),
                            this.points.get(i + 2), this.points.get(i + 3), tension, (int) currentN);
                    for (int j = 0; j < newPoints.size(); j++) {
                        s.seriesPath.lineTo(newPoints.get(j).x, newPoints.get(j).y);
                    }
                }
            }
            s.seriesPath.lineTo(points.get(points.size() - 1).x, points.get(points.size() - 1).y);
            // draw path
            drawFirstPassShape(g2, pass, series, item, s.seriesPath);

        }

        // reset points vector
        this.points = new Vector<ControlPoint>();
    }
}

From source file:com.clust4j.algo.AbstractClusterer.java

final private Array2DRowRealMatrix initData(final RealMatrix data) {
    final int m = data.getRowDimension(), n = data.getColumnDimension();
    final double[][] ref = new double[m][n];
    final HashSet<Double> unique = new HashSet<>();

    // Used to compute variance on the fly for summaries later...
    double[] sum = new double[n];
    double[] sumSq = new double[n];
    double[] maxes = VecUtils.rep(Double.NEGATIVE_INFINITY, n);
    double[] mins = VecUtils.rep(Double.POSITIVE_INFINITY, n);

    // This will store summaries for each column + a header
    ModelSummary summaries = new ModelSummary(
            new Object[] { "Feature #", "Variance", "Std. Dev", "Mean", "Max", "Min" });

    /*// w w w .  ja  va 2  s  . c o  m
     * Internally performs the copy
     */
    double entry;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            entry = data.getEntry(i, j);

            if (Double.isNaN(entry)) {
                error(new NaNException("NaN in input data. " + "Select a matrix imputation method for "
                        + "incomplete records"));
            } else {
                // copy the entry
                ref[i][j] = entry;
                unique.add(entry);

                // capture stats...
                sumSq[j] += entry * entry;
                sum[j] += entry;
                maxes[j] = FastMath.max(entry, maxes[j]);
                mins[j] = FastMath.min(entry, mins[j]);

                // if it's the last row, we can compute these:
                if (i == m - 1) {
                    double var = (sumSq[j] - (sum[j] * sum[j]) / (double) m) / ((double) m - 1.0);
                    if (var == 0) {
                        warn("zero variance in feature " + j);
                    }

                    summaries.add(new Object[] { j, // feature num
                            var, // var
                            m < 2 ? Double.NaN : FastMath.sqrt(var), // std dev
                            sum[j] / (double) m, // mean
                            maxes[j], // max
                            mins[j] // min
                    });
                }
            }
        }
    }

    // Log the summaries
    summaryLogger(formatter.format(summaries));

    if (unique.size() == 1)
        this.singular_value = true;

    /*
     * Don't need to copy again, because already internally copied...
     */
    return new Array2DRowRealMatrix(ref, false);
}