List of usage examples for java.lang Double isInfinite
public static boolean isInfinite(double v)
From source file:com.tiendd.uet.predicting.AbstractRecommender.java
/** * Post each iteration, we do things:/*from ww w .j a v a 2 s . c om*/ * <ol> * <li>print debug information</li> * <li>check if converged</li> * <li>if not, adjust learning rate</li> * </ol> * * @param iter * current iteration * @return boolean: true if it is converged; false otherwise * @throws LibrecException * if error occurs */ protected boolean isConverged(int iter) throws LibrecException { float delta_loss = (float) (lastLoss - loss); // print out debug info if (verbose) { String recName = getClass().getSimpleName().toString(); String info = recName + " iter " + iter + ": loss = " + loss + ", delta_loss = " + delta_loss; LOG.info(info); } if (Double.isNaN(loss) || Double.isInfinite(loss)) { // LOG.error("Loss = NaN or Infinity: current settings does not fit // the recommender! Change the settings and try again!"); throw new LibrecException( "Loss = NaN or Infinity: current settings does not fit the recommender! Change the settings and try again!"); } // check if converged boolean converged = Math.abs(loss) < 1e-5; lastLoss = loss; return converged; }
From source file:com.epam.catgenome.manager.wig.WigManager.java
private double queryWig(BigWigFile bigWigFile, String chrName, int start, int end) throws IOException { List<BigSummary> summarize; try {/*from www. j a v a2s . c o m*/ summarize = bigWigFile.summarize(chrName, start, end, 1, true); } catch (NoSuchElementException e) { LOGGER.info(e.getMessage(), e); return 0; } double res = 0.0; for (BigSummary summary : summarize) { if (!Double.isNaN(summary.getMaxValue()) && !Double.isInfinite(summary.getMaxValue())) { res += summary.getMaxValue(); } } return res; }
From source file:com.hdfs.concat.crush.Crush.java
boolean createJobConfAndParseArgs(String... args) throws ParseException, IOException { job = new JobConf(getConf(), Crush.class); /*//from w w w . ja v a 2 s . c o m * Turn off speculative execution because that's just wasting network io. */ job.setMapSpeculativeExecution(false); job.setReduceSpeculativeExecution(false); /* * Turn off pre-emption because we don't want to kill a task after two hours of network io. */ job.set("mapred.fairscheduler.preemption", "false"); tmpDir = new Path("tmp/crush-" + UUID.randomUUID()); outDir = new Path(tmpDir, "out"); double threshold = 0.75; List<String> regexes = asList(".+"); List<String> replacements = asList("crushed_file-${crush.timestamp}-${crush.task.num}-${crush.file.num}"); List<String> inFormats = asList(SequenceFileInputFormat.class.getName()); List<String> outFormats = asList(SequenceFileOutputFormat.class.getName()); String crushTimestamp; Options options = buildOptions(); CommandLine cli = new GnuParser().parse(options, args); if (cli.hasOption("?")) { BufferedReader reader = new BufferedReader( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("help.txt"))); try { String line; while (null != (line = reader.readLine())) { System.out.println(line); } } finally { reader.close(); } return false; } if (cli.hasOption("verbose")) { console = Verbosity.VERBOSE; } else if (cli.hasOption("info")) { console = Verbosity.INFO; } else { console = Verbosity.NONE; } if (cli.hasOption("ignore-regex")) { ignoredFiles = Pattern.compile(cli.getOptionValue("ignore-regex")).matcher(""); } excludeSingleFileDirs = !cli.hasOption("include-single-file-dirs"); String[] nonOptions = cli.getArgs(); if (2 == nonOptions.length) { /* * Stand alone mode accepts two arguments. */ mode = Mode.STAND_ALONE; srcDir = new Path(nonOptions[0]); dest = new Path(nonOptions[1]); if (cli.hasOption("input-format")) { inFormats = asList(cli.getOptionValue("input-format")); } if (cli.hasOption("output-format")) { outFormats = asList(cli.getOptionValue("output-format")); } replacements = asList(dest.getName()); crushTimestamp = Long.toString(currentTimeMillis()); } else { /* * The previous version expected three or four arguments. The third one specified the number of tasks to use, which is an * integral number, just like the third argument in the new version, which is a timestamp. We tell the two apart by looking * at the value of the argument. A timestamp is going to be a huge, 14-digit number while the number of tasks should be much * smaller. */ if ((args.length == 4 || args.length == 3) && args.length == nonOptions.length && args[2].length() != 14) { int maxTasks = Integer.parseInt(args[2]); if (maxTasks <= 0 || maxTasks > 4000) { throw new IllegalArgumentException("Tasks must be in the range [1, 4000]: " + maxTasks); } job.setInt("mapred.reduce.tasks", maxTasks); maxFileBlocks = Integer.MAX_VALUE; crushTimestamp = Long.toString(currentTimeMillis()); srcDir = new Path(args[0]); dest = new Path(args[1]); mode = Mode.CLONE; if (args.length == 4) { if (args[3].equals("TEXT")) { /* * These are the defaults except with text input and output formats. */ inFormats = asList(TextInputFormat.class.getName()); outFormats = asList(TextOutputFormat.class.getName()); } else if (!args[3].equals("SEQUENCE")) { throw new IllegalArgumentException("Type must be either TEXT or SEQUENCE: " + args[3]); } } } else { /* * V2 style arguments. */ if (cli.hasOption("threshold")) { threshold = Double.parseDouble(cli.getOptionValue("threshold")); if (0 >= threshold || 1 < threshold || Double.isInfinite(threshold) || Double.isNaN(threshold)) { throw new IllegalArgumentException("Block size threshold must be in (0, 1]: " + threshold); } } if (cli.hasOption("max-file-blocks")) { int maxFileBlocksOption = Integer.parseInt(cli.getOptionValue("max-file-blocks")); if (0 > maxFileBlocksOption) { throw new IllegalArgumentException( "Maximum file size in blocks must be positive: " + maxFileBlocksOption); } maxFileBlocks = maxFileBlocksOption; } else { maxFileBlocks = 8; } if (cli.hasOption("regex")) { regexes = asList(cli.getOptionValues("regex")); } if (cli.hasOption("replacement")) { replacements = asList(cli.getOptionValues("replacement")); } if (cli.hasOption("input-format")) { inFormats = asList(cli.getOptionValues("input-format")); } if (cli.hasOption("output-format")) { outFormats = asList(cli.getOptionValues("output-format")); } if (3 != nonOptions.length) { throw new IllegalArgumentException( "Could not find source directory, out directory, and job timestamp"); } srcDir = new Path(nonOptions[0]); dest = new Path(nonOptions[1]); crushTimestamp = nonOptions[2]; if (cli.hasOption("clone")) { mode = Mode.CLONE; } else { mode = Mode.MAP_REDUCE; } if (!crushTimestamp.matches("\\d{14}")) { throw new IllegalArgumentException( "Crush timestamp must be 14 digits yyyymmddhhMMss: " + crushTimestamp); } } dfsBlockSize = parseDfsBlockSize(job); maxEligibleSize = (long) (dfsBlockSize * threshold); } /* * Add the crush specs and compression options to the configuration. */ job.set("crush.timestamp", crushTimestamp); if (ignoredFiles != null) { job.set("crush.ignore-regex", ignoredFiles.pattern().pattern()); } if (regexes.size() != replacements.size() || replacements.size() != inFormats.size() || inFormats.size() != outFormats.size()) { throw new IllegalArgumentException( "Must be an equal number of regex, replacement, in-format, and out-format options"); } job.setInt("crush.num.specs", regexes.size()); matchers = new ArrayList<Matcher>(regexes.size()); for (int i = 0; i < regexes.size(); i++) { job.set(format("crush.%d.regex", i), regexes.get(i)); matchers.add(Pattern.compile(regexes.get(i)).matcher("dummy")); job.set(format("crush.%d.regex.replacement", i), replacements.get(i)); String inFmt = inFormats.get(i); if ("sequence".equals(inFmt)) { inFmt = SequenceFileInputFormat.class.getName(); } else if ("text".equals(inFmt)) { inFmt = TextInputFormat.class.getName(); } else { try { if (!FileInputFormat.class.isAssignableFrom(Class.forName(inFmt))) { throw new IllegalArgumentException("Not a FileInputFormat:" + inFmt); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Not a FileInputFormat:" + inFmt); } } job.set(format("crush.%d.input.format", i), inFmt); String outFmt = outFormats.get(i); if ("sequence".equals(outFmt)) { outFmt = SequenceFileOutputFormat.class.getName(); } else if ("text".equals(outFmt)) { outFmt = TextOutputFormat.class.getName(); } else { try { if (!FileOutputFormat.class.isAssignableFrom(Class.forName(outFmt))) { throw new IllegalArgumentException("Not a FileOutputFormat:" + outFmt); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Not a FileOutputFormat:" + outFmt); } } job.set(format("crush.%d.output.format", i), outFmt); } String codec = cli.getOptionValue("compress"); if (null == codec) { codec = DefaultCodec.class.getName(); } else if ("none".equals(codec)) { codec = null; } else if ("gzip".equals(codec)) { codec = GzipCodec.class.getName(); } else { try { if (!CompressionCodec.class.isAssignableFrom(Class.forName(codec))) { throw new IllegalArgumentException("Not a CompressionCodec: " + codec); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Not a CompressionCodec: " + codec); } } if (null == codec) { job.setBoolean("mapred.output.compress", false); } else { job.setBoolean("mapred.output.compress", true); job.set("mapred.output.compression.type", "BLOCK"); job.set("mapred.output.compression.codec", codec); try { CompressionCodec instance = (CompressionCodec) Class.forName(codec).newInstance(); codecExtension = instance.getDefaultExtension(); } catch (Exception e) { throw new AssertionError(); } } return true; }
From source file:net.sf.mzmine.modules.peaklistmethods.dataanalysis.heatmaps.HeatMapTask.java
private void scale(double[][] peakList) { DescriptiveStatistics stdDevStats = new DescriptiveStatistics(); for (int columns = 0; columns < peakList.length; columns++) { stdDevStats.clear();//from w w w .java 2s. com for (int row = 0; row < peakList[columns].length; row++) { if (!Double.isInfinite(peakList[columns][row]) && !Double.isNaN(peakList[columns][row])) { stdDevStats.addValue(peakList[columns][row]); } } double stdDev = stdDevStats.getStandardDeviation(); for (int row = 0; row < peakList[columns].length; row++) { if (stdDev != 0) { peakList[columns][row] = peakList[columns][row] / stdDev; } } } }
From source file:edu.toronto.cs.phenotips.measurements.internal.DefaultMeasurementsChartConfigurationsFactory.java
/** * Read and return a setting from the configuration, parsing it as a {@code double} number, falling back on the * provided default value.//from w w w.j av a2 s . c o m * * @param settingName the name of the setting to read * @param defaultValue the default value to use when there's no value specified in the configuration, or the * specified value is not a valid double number * @param configuration the configuration bundle with all the settings * @return the configured value, if one is configured as a valid {@code double} number, or the default value * otherwise */ private double getDoubleSetting(String settingName, double defaultValue, ResourceBundle configuration) { double result = defaultValue; if (configuration.containsKey(settingName)) { try { result = Double.parseDouble(configuration.getString(settingName)); if (Double.isNaN(result) || Double.isInfinite(result)) { this.logger.warn("Invalid chart settings for [{}]: value should be finite, was [{}]", settingName, configuration.getString(settingName)); result = defaultValue; } } catch (NumberFormatException ex) { // Fall back to the default value this.logger.warn("Invalid chart settings for [{}]: invalid double [{}]", settingName, configuration.getString(settingName)); } } return result; }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.algorithm.DBEA.java
/** * Updates the ideal point and intercepts given the new solution. * // w w w . j av a 2s. co m * @param solution the new solution */ void updateIdealPointAndIntercepts(Solution solution) { if (!solution.violatesConstraints()) { // update the ideal point for (int j = 0; j < problem.getNumberOfObjectives(); j++) { idealPoint[j] = Math.min(idealPoint[j], solution.getObjective(j)); intercepts[j] = Math.max(intercepts[j], solution.getObjective(j)); } // compute the axis intercepts Population feasibleSolutions = getFeasibleSolutions(population); feasibleSolutions.add(solution); Population nondominatedSolutions = getNondominatedFront(feasibleSolutions); if (!nondominatedSolutions.isEmpty()) { // find the points with the largest value in each objective Population extremePoints = new Population(); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { extremePoints.add(largestObjectiveValue(i, nondominatedSolutions)); } if (numberOfUniqueSolutions(extremePoints) != problem.getNumberOfObjectives()) { for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = extremePoints.get(i).getObjective(i); } } else { try { RealMatrix b = new Array2DRowRealMatrix(problem.getNumberOfObjectives(), 1); RealMatrix A = new Array2DRowRealMatrix(problem.getNumberOfObjectives(), problem.getNumberOfObjectives()); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { b.setEntry(i, 0, 1.0); for (int j = 0; j < problem.getNumberOfObjectives(); j++) { A.setEntry(i, j, extremePoints.get(i).getObjective(j)); } } double numerator = new LUDecomposition(A).getDeterminant(); b.scalarMultiply(numerator); RealMatrix normal = MatrixUtils.inverse(A).multiply(b); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = numerator / normal.getEntry(i, 0); if (intercepts[i] <= 0 || Double.isNaN(intercepts[i]) || Double.isInfinite(intercepts[i])) { intercepts[i] = extremePoints.get(i).getObjective(i); } } } catch (RuntimeException e) { for (int i = 0; i < problem.getNumberOfObjectives(); i++) { intercepts[i] = extremePoints.get(i).getObjective(i); } } } } } }
From source file:be.ugent.maf.cellmissy.analysis.doseresponse.impl.DoseResponseLMOptimizer.java
/** * Copy of super source code. Decompose a matrix A as A.P = Q.R using * Householder transforms.// www . ja va 2 s.c om * <p> * As suggested in the P. Lascaux and R. Theodor book * <i>Analyse numérique matricielle appliquée à l'art * de l'ingénieur</i> (Masson, 1986), instead of representing the * Householder transforms with u<sub>k</sub> unit vectors such that: * <pre> * H<sub>k</sub> = I - 2u<sub>k</sub>.u<sub>k</sub><sup>t</sup> * </pre> we use <sub>k</sub> non-unit vectors such that: * <pre> * H<sub>k</sub> = I - beta<sub>k</sub>v<sub>k</sub>.v<sub>k</sub><sup>t</sup> * </pre> where v<sub>k</sub> = a<sub>k</sub> - alpha<sub>k</sub> * e<sub>k</sub>. The beta<sub>k</sub> coefficients are provided upon exit * as recomputing them from the v<sub>k</sub> vectors would be costly.</p> * <p> * This decomposition handles rank deficient cases since the tranformations * are performed in non-increasing columns norms order thanks to columns * pivoting. The diagonal elements of the R matrix are therefore also in * non-increasing absolute values order.</p> * * @param jacobian Weighted Jacobian matrix at the current point. * @param solvedCols Number of solved point. * @return data used in other methods of this class. * @throws ConvergenceException if the decomposition cannot be performed. */ private InternalData qrDecomposition(RealMatrix jacobian, int solvedCols) throws ConvergenceException { // Code in this class assumes that the weighted Jacobian is -(W^(1/2) J), // hence the multiplication by -1. final double[][] weightedJacobian = jacobian.scalarMultiply(-1).getData(); final int nR = weightedJacobian.length; final int nC = weightedJacobian[0].length; final int[] permutation = new int[nC]; final double[] diagR = new double[nC]; final double[] jacNorm = new double[nC]; final double[] beta = new double[nC]; // initializations for (int k = 0; k < nC; ++k) { permutation[k] = k; double norm2 = 0; for (int i = 0; i < nR; ++i) { double akk = weightedJacobian[i][k]; norm2 += akk * akk; } jacNorm[k] = FastMath.sqrt(norm2); } // transform the matrix column after column for (int k = 0; k < nC; ++k) { // select the column with the greatest norm on active components int nextColumn = -1; double ak2 = Double.NEGATIVE_INFINITY; for (int i = k; i < nC; ++i) { double norm2 = 0; for (int j = k; j < nR; ++j) { double aki = weightedJacobian[j][permutation[i]]; norm2 += aki * aki; } if (Double.isInfinite(norm2) || Double.isNaN(norm2)) { throw new ConvergenceException(LocalizedFormats.UNABLE_TO_PERFORM_QR_DECOMPOSITION_ON_JACOBIAN, nR, nC); } if (norm2 > ak2) { nextColumn = i; ak2 = norm2; } } if (ak2 <= getRankingThreshold()) { return new InternalData(weightedJacobian, permutation, k, diagR, jacNorm, beta); } int pk = permutation[nextColumn]; permutation[nextColumn] = permutation[k]; permutation[k] = pk; // choose alpha such that Hk.u = alpha ek double akk = weightedJacobian[k][pk]; double alpha = (akk > 0) ? -FastMath.sqrt(ak2) : FastMath.sqrt(ak2); double betak = 1.0 / (ak2 - akk * alpha); beta[pk] = betak; // transform the current column diagR[pk] = alpha; weightedJacobian[k][pk] -= alpha; // transform the remaining columns for (int dk = nC - 1 - k; dk > 0; --dk) { double gamma = 0; for (int j = k; j < nR; ++j) { gamma += weightedJacobian[j][pk] * weightedJacobian[j][permutation[k + dk]]; } gamma *= betak; for (int j = k; j < nR; ++j) { weightedJacobian[j][permutation[k + dk]] -= gamma * weightedJacobian[j][pk]; } } } return new InternalData(weightedJacobian, permutation, solvedCols, diagR, jacNorm, beta); }
From source file:etomica.math.SpecialFunctions.java
/** * Calculates the modified bessel function of the first kind (I) for a given order and the variable x. * Right now works only for integer orders. * Reference: http://mathworld.wolfram.com/ModifiedBesselFunctionoftheFirstKind.html * @author rsubrama//from w w w . j a v a 2s.co m * @param order * @param x * @return double y */ public static double besselI(int order, double x) { if (x == 0) return 0; if (Double.isInfinite(x) || Double.isNaN(x)) throw new IllegalArgumentException("Illegal argument " + x); double term1 = Math.pow(0.5 * x, order); boolean done = false; int k = 1; double tol = 1E-10; int maxK = 10000; double newSum = 1.0; double oldSum = 0.0; double y1 = 1.0 / factorial(order); do { oldSum = newSum; y1 *= x * x / (4.0 * k * (k + order)); newSum += y1; double y2 = newSum - oldSum; if (y2 * y2 < tol) done = true; k++; } while (!done && k <= maxK); if (!done) throw new RuntimeException("Failed to converge!!"); double y = term1 * newSum; // if (Double.isInfinite(y) || Double.isNaN(y)) throw new RuntimeException("Oops"+y); return y; }
From source file:com.offbynull.peernetic.debug.visualizer.JGraphXVisualizer.java
private void zoomFit() { SwingUtilities.invokeLater(() -> { double compWidth = component.getWidth(); double compHeight = component.getHeight(); double compLen = Math.min(compWidth, compHeight); mxGraphView view = graph.getView(); double oldScale = view.getScale(); mxPoint oldTranslate = view.getTranslate(); mxRectangle graphBounds = view.getGraphBounds(); double graphX = (graphBounds.getX()) / oldScale - oldTranslate.getX(); double graphY = (graphBounds.getY()) / oldScale - oldTranslate.getY(); double graphWidth = (graphBounds.getWidth()) / oldScale; double graphHeight = (graphBounds.getHeight()) / oldScale; double graphEndX = graphX + graphWidth; double graphEndY = graphY + graphHeight; double viewLen = Math.max(graphEndX, graphEndY); if (Double.isInfinite(viewLen) || Double.isNaN(viewLen) || viewLen <= 0.0) { view.setScale(1.0);// w w w . j av a2 s . co m } else { double newScale = compLen / viewLen; view.setScale(newScale); } }); }
From source file:com.rapidminer.tools.Tools.java
/** * Returns a number string with no fraction digits if possible. Otherwise the given number of * digits will be returned.//w w w .j av a 2s. com */ public static String formatIntegerIfPossible(double value, int numberOfDigits, boolean groupingCharacter) { if (Double.isNaN(value)) { return "?"; } if (Double.isInfinite(value)) { if (value < 0) { return "-" + FORMAT_SYMBOLS.getInfinity(); } else { return FORMAT_SYMBOLS.getInfinity(); } } long longValue = Math.round(value); if (Math.abs(longValue - value) < IS_DISPLAY_ZERO) { INTEGER_FORMAT.setGroupingUsed(groupingCharacter); return INTEGER_FORMAT.format(longValue); } else { return formatNumber(value, numberOfDigits, groupingCharacter); } }