List of usage examples for java.lang Math log
@HotSpotIntrinsicCandidate public static double log(double a)
From source file:mzmatch.ipeak.normalisation.VanDeSompele.java
public static void main(String args[]) { try {/* w w w.ja va2s . c o m*/ Tool.init(); // parse the commandline options Options options = new Options(); CmdLineParser cmdline = new CmdLineParser(options); // check whether we need to show the help cmdline.parse(args); if (options.help) { Tool.printHeader(System.out, application, version); cmdline.printUsage(System.out, ""); return; } if (options.verbose) { Tool.printHeader(System.out, application, version); cmdline.printOptions(); } // check the command-line parameters { // if the output directories do not exist, create them if (options.output != null) Tool.createFilePath(options.output, true); } // load the data if (options.verbose) System.out.println("Loading data"); ParseResult result = PeakMLParser.parse(new FileInputStream(options.input), true); Header header = result.header; IPeakSet<IPeakSet<? extends IPeak>> peaksets = (IPeakSet<IPeakSet<? extends IPeak>>) result.measurement; int nrmeasurements = header.getNrMeasurementInfos(); // remove the stability factor annotation for (IPeak peak : peaksets) peak.removeAnnotation("stability factor"); // load the database if (options.verbose) System.out.println("Loading the molecule database"); HashMap<String, Molecule> database = MoleculeIO.parseXml(new FileInputStream(options.database)); // filter the set to include only identifiable metabolites if (options.verbose) System.out.println("Creating selection"); Vector<IPeakSet<? extends IPeak>> selection = new Vector<IPeakSet<? extends IPeak>>(); for (Molecule molecule : database.values()) { double mass = molecule.getMass(Mass.MONOISOTOPIC); double delta = PeriodicTable.PPM(mass, options.ppm); // get the most intense peak containing all the measurements Vector<IPeakSet<? extends IPeak>> neighbourhoud = peaksets.getPeaksInMassRange(mass - delta, mass + delta); Collections.sort(neighbourhoud, IPeak.sort_intensity_descending); for (IPeakSet<? extends IPeak> neighbour : neighbourhoud) if (count(neighbour) == nrmeasurements) { selection.add(neighbour); break; } } // calculate the stability factor for each peak in the selection if (options.verbose) System.out.println("Calculating stability factors"); for (int peakid1 = 0; peakid1 < selection.size(); ++peakid1) { double stddeviations[] = new double[selection.size()]; IPeakSet<? extends IPeak> peakset1 = selection.get(peakid1); for (int peakid2 = 0; peakid2 < selection.size(); ++peakid2) { IPeakSet<? extends IPeak> peakset2 = selection.get(peakid2); double values[] = new double[nrmeasurements]; for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) { int measurementid1 = peakset1.get(measurementid).getMeasurementID(); int setid1 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid1)); int measurementid2 = peakset2.get(measurementid).getMeasurementID(); int setid2 = header.indexOfSetInfo(header.getSetInfoForMeasurementID(measurementid2)); if (setid1 != setid2 || measurementid1 != measurementid2) System.err.println("[WARNING]: differing setid or spectrumid for comparison"); values[measurementid] = Math.log(peakset1.get(measurementid).getIntensity() / peakset2.get(measurementid).getIntensity()) / Math.log(2); } stddeviations[peakid2] = Statistical.stddev(values); } peakset1.addAnnotation("stability factor", Statistical.mean(stddeviations)); } // sort on the stability factor Collections.sort(selection, new IPeak.AnnotationAscending("stability factor")); // take the top 10% and calculate the geometric mean if (options.verbose) System.out.println("Calculating normalisation factors"); int nrselected = (int) (0.1 * selection.size()); if (nrselected < 10) nrselected = (10 < selection.size() ? 10 : selection.size()); double normalization_factors[] = new double[nrmeasurements]; for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) { double values[] = new double[nrselected]; for (int i = 0; i < nrselected; ++i) { IPeak peak = selection.get(i).get(measurementid); values[i] = peak.getIntensity(); } normalization_factors[measurementid] = Statistical.geomean(values); } // scale the found normalization factors double maxnf = Statistical.max(normalization_factors); for (int sampleid = 0; sampleid < nrmeasurements; ++sampleid) normalization_factors[sampleid] /= maxnf; // write the selection if needed if (options.selection != null) { if (options.verbose) System.out.println("Writing original selection data"); PeakMLWriter.write(result.header, selection, null, new GZIPOutputStream(new FileOutputStream(options.selection)), null); } // normalize all the peaks if (options.verbose) System.out.println("Normalizing all the entries"); for (IPeakSet<? extends IPeak> peakset : peaksets) { for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) { // TODO why did I do this again ? int id = 0; int setid = 0; int spectrumid = 0; for (int i = 0; i < header.getNrSetInfos(); ++i) { SetInfo set = header.getSetInfos().get(i); if (id + set.getNrMeasurementIDs() > measurementid) { setid = i; spectrumid = measurementid - id; break; } else id += set.getNrMeasurementIDs(); } MassChromatogram<Peak> masschromatogram = null; for (IPeak p : peakset) { int mymeasurementid = p.getMeasurementID(); int mysetid = header.indexOfSetInfo(header.getSetInfoForMeasurementID(mymeasurementid)); if (mysetid == setid && mymeasurementid == spectrumid) { masschromatogram = (MassChromatogram<Peak>) p; break; } } if (masschromatogram == null) continue; for (IPeak peak : masschromatogram.getPeaks()) peak.setIntensity(peak.getIntensity() / normalization_factors[measurementid]); } } // write the selection if needed if (options.selection_normalized != null) { if (options.verbose) System.out.println("Writing the normalized selection data"); PeakMLWriter.write(result.header, selection, null, new GZIPOutputStream(new FileOutputStream(options.selection_normalized)), null); } // write the factors if needed if (options.factors != null) { if (options.verbose) System.out.println("Writing the normalization factors"); PrintStream out = new PrintStream(options.factors); for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) out.println(header.getMeasurementInfo(measurementid).getLabel() + "\t" + normalization_factors[measurementid]); } // write the plot if needed if (options.img != null) { if (options.verbose) System.out.println("Writing the graph"); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); JFreeChart linechart = ChartFactory.createLineChart(null, "measurement", "normalization factor", dataset, PlotOrientation.VERTICAL, false, // legend false, // tooltips false // urls ); CategoryPlot plot = (CategoryPlot) linechart.getPlot(); CategoryAxis axis = (CategoryAxis) plot.getDomainAxis(); axis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer(); renderer.setSeriesShapesFilled(0, true); renderer.setSeriesShapesVisible(0, true); linechart.setBackgroundPaint(Color.WHITE); linechart.setBorderVisible(false); linechart.setAntiAlias(true); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); // create the datasets for (int measurementid = 0; measurementid < nrmeasurements; ++measurementid) dataset.addValue(normalization_factors[measurementid], "", header.getMeasurementInfo(measurementid).getLabel()); JFreeChartTools.writeAsPDF(new FileOutputStream(options.img), linechart, 800, 500); } // write the normalized values if (options.verbose) System.out.println("Writing the normalized data"); PeakMLWriter.write(result.header, peaksets.getPeaks(), null, new GZIPOutputStream(new FileOutputStream(options.output)), null); } catch (Exception e) { Tool.unexpectedError(e, application); } }
From source file:Main.java
public static double normal(double u, double s) // Random normal distribution with mean u and standard deviation s { double fac, rsq, v1, v2; if (iset == 0) { do {//w w w . j a v a 2s . co m v1 = 2.0 * Math.random() - 1.0; v2 = 2.0 * Math.random() - 1.0; rsq = v1 * v1 + v2 * v2; } while (rsq >= 1.0 || rsq == 0.0); fac = Math.sqrt(-2.0 * Math.log(rsq) / rsq); gset = v1 * fac; iset = 1; return (u + s * (v2 * fac)); } else { iset = 0; return (u + s * gset); } }
From source file:lsafunctions.LSA.java
public static RealMatrix calculateTfIdf(RealMatrix M) { int tf;/*from w w w. ja va 2 s . co m*/ double idf; int df; double ndf; for (int j = 0; j < M.getRowDimension(); j++) { df = calcDf(j, M); // System.out.println("J:"+j+" df:"+df); for (int k = 0; k < M.getColumnDimension(); k++) { tf = (int) M.getEntry(j, k); ndf = M.getColumnDimension() / df; idf = Math.log(ndf) / Math.log(2); M.setEntry(j, k, idf * tf); } } //M.print(NumberFormat.INTEGER_FIELD, M.getColumnDimension()); M = normalizeMatrix(M); return M; }
From source file:Main.java
/** * @return The tile index for the latitude at the given zoom *//*from w w w .jav a 2 s . c o m*/ public static int toTileY(double lat, int zoom) { lat = 0.5 - ((Math.log(Math.tan((Math.PI / 4) + ((0.5 * Math.PI * lat) / 180))) / Math.PI) / 2.0); int scale = 1 << zoom; return (int) (lat * scale); }
From source file:edu.byu.nlp.stats.GammaDistribution.java
/** * self-contained gamma generator. Multiply result with scale parameter (or * divide by rate parameter). After Teh (npbayes). * // w w w .j av a 2s .c o m * Taken From knowceans. */ public static double sample(double shape, RandomGenerator rnd) { Preconditions.checkArgument(shape > 0.0); Preconditions.checkNotNull(rnd); if (shape == 1.0) { /* Exponential */ return -Math.log(rnd.nextDouble()); } else if (shape < 1.0) { /* Use Johnk's generator */ double cc = 1.0 / shape; double dd = 1.0 / (1.0 - shape); while (true) { double xx = Math.pow(rnd.nextDouble(), cc); double yy = xx + Math.pow(rnd.nextDouble(), dd); if (yy <= 1.0) { // FIXME: assertion error for rr = 0.010817814317923407 // assert yy != 0 && xx / yy > 0 : "rr = " + rr; // INFO: this if is a hack if (yy != 0 && xx / yy > 0) { return -Math.log(rnd.nextDouble()) * xx / yy; } } } } else { /* rr > 1.0 */ /* Use bests algorithm */ double bb = shape - 1.0; double cc = 3.0 * shape - 0.75; while (true) { double uu = rnd.nextDouble(); double vv = rnd.nextDouble(); double ww = uu * (1.0 - uu); double yy = Math.sqrt(cc / ww) * (uu - 0.5); double xx = bb + yy; if (xx >= 0) { double zz = 64.0 * ww * ww * ww * vv * vv; assert zz > 0 && bb != 0 && xx / bb > 0; if ((zz <= (1.0 - 2.0 * yy * yy / xx)) || (Math.log(zz) <= 2.0 * (bb * Math.log(xx / bb) - yy))) { return xx; } } } } }
From source file:Util.java
/** * Returns the sum of two doubles expressed in log space, * that is,/*from w w w. j a v a 2 s .c o m*/ * <pre> * sumLogProb = log (e^a + e^b) * = log e^a(1 + e^(b-a)) * = a + log (1 + e^(b-a)) * </pre> * * By exponentiating <tt>b-a</tt>, we obtain better numerical precision than * we would if we calculated <tt>e^a</tt> or <tt>e^b</tt> directly. * <P> * Note: This function is just like * {@link cc.mallet.fst.Transducer#sumNegLogProb sumNegLogProb} * in <TT>Transducer</TT>, * except that the logs aren't negated. */ public static double sumLogProb(double a, double b) { if (a == Double.NEGATIVE_INFINITY) return b; else if (b == Double.NEGATIVE_INFINITY) return a; else if (b < a) return a + Math.log(1 + Math.exp(b - a)); else return b + Math.log(1 + Math.exp(a - b)); }
From source file:com.fpuna.preproceso.util.Util.java
public static Double calculateShannonEntropy(double valuesD[]) { Map<String, Integer> map = new HashMap<String, Integer>(); List<String> values = new ArrayList<String>(); for (Double d : valuesD) { values.add(d.toString());/*from w ww . jav a 2s . c o m*/ } // count the occurrences of each value for (String sequence : values) { if (!map.containsKey(sequence)) { map.put(sequence, 0); } map.put(sequence, map.get(sequence) + 1); } // calculate the entropy Double result = 0.0; for (String sequence : map.keySet()) { Double frequency = (double) map.get(sequence) / values.size(); result -= frequency * (Math.log(frequency) / Math.log(2)); } return result; }
From source file:emlab.util.TrendEstimator.java
public static double[] estimateGeometricTrend(double[][] input, double[] predictionYears) { //Get logarithm of second trend for (int i = 0; i < input.length; i++) { input[i][1] = Math.log(input[i][1]); }//from w w w . j a v a 2 s. c o m //input[1]=log; SimpleRegression sr = new SimpleRegression(); sr.addData(input); double result[] = new double[predictionYears.length]; for (int i = 0; i < result.length; i++) { result[i] = Math.exp(sr.predict(predictionYears[i])); } return result; }
From source file:Main.java
private static int getDoubleChars(double number, char[] buf, int charPos, int significantDigits) { if (number != number) { STR_NAN.getChars(0, STR_NAN_LEN, buf, charPos); return charPos + STR_NAN_LEN; }/*from www . j av a 2 s . c o m*/ //we need to detect -0.0 to be compatible with JDK boolean negative = (Double.doubleToRawLongBits(number) & 0x8000000000000000L) != 0; if (negative) { buf[charPos++] = '-'; number = -number; } if (number == Double.POSITIVE_INFINITY) { STR_INFINITY.getChars(0, STR_INFINITY_LEN, buf, charPos); return charPos + STR_INFINITY_LEN; } if (number == 0) { buf[charPos++] = '0'; buf[charPos++] = '.'; buf[charPos++] = '0'; } else { int exponent = 0; // calc. the power (base 10) for the given number: int pow = (int) Math.floor(Math.log(number) / LN10); // use exponential formatting if number too big or too small if (pow < -3 || pow > 6) { exponent = pow; number /= Math.exp(LN10 * exponent); } // if // Recalc. the pow if exponent removed and d has changed pow = (int) Math.floor(Math.log(number) / LN10); // Decide how many insignificant zeros there will be in the // lead of the number. int insignificantDigits = -Math.min(0, pow); // Force it to start with at least "0." if necessarry pow = Math.max(0, pow); double divisor = Math.pow(10, pow); // Loop over the significant digits (17 for double, 8 for float) for (int i = 0, end = significantDigits + insignificantDigits, div; i < end; i++) { // Add the '.' when passing from 10^0 to 10^-1 if (pow == -1) { buf[charPos++] = '.'; } // if // Find the divisor div = (int) (number / divisor); // This might happen with 1e6: pow = 5 ( instead of 6 ) if (div == 10) { buf[charPos++] = '1'; buf[charPos++] = '0'; } // if else { buf[charPos] = (char) (div + '0'); charPos++; } // else number -= div * divisor; divisor /= 10.0; pow--; // Break the loop if we have passed the '.' if (number == 0 && divisor < 0.1) break; } // for // Remove trailing zeros while (buf[charPos - 1] == '0') charPos--; // Avoid "4." instead of "4.0" if (buf[charPos - 1] == '.') charPos++; if (exponent != 0) { buf[charPos++] = 'E'; if (exponent < 0) { buf[charPos++] = '-'; exponent = -exponent; } if (exponent >= 100) buf[charPos++] = (char) (exponent / 100 + '0'); if (exponent >= 10) buf[charPos++] = (char) (exponent / 10 % 10 + '0'); buf[charPos++] = (char) (exponent % 10 + '0'); } // if } return charPos; }
From source file:Main.java
public static String getHumanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); }