Example usage for java.lang Math log10

List of usage examples for java.lang Math log10

Introduction

In this page you can find the example usage for java.lang Math log10.

Prototype

@HotSpotIntrinsicCandidate
public static double log10(double a) 

Source Link

Document

Returns the base 10 logarithm of a double value.

Usage

From source file:org.esa.s1tbx.calibration.gpf.calibrators.Radarsat2Calibrator.java

/**
 * Called by the framework in order to compute a tile for the given target band.
 * <p>The default implementation throws a runtime exception with the message "not implemented".</p>
 *
 * @param targetBand The target band./*  ww  w  .jav a 2s . c  o m*/
 * @param targetTile The current tile associated with the target band to be computed.
 * @param pm         A progress monitor which should be used to determine computation cancelation requests.
 * @throws OperatorException If an error occurs during computation of the target raster.
 */
public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {

    final Rectangle targetTileRectangle = targetTile.getRectangle();
    final int x0 = targetTileRectangle.x;
    final int y0 = targetTileRectangle.y;
    final int w = targetTileRectangle.width;
    final int h = targetTileRectangle.height;

    Tile sourceRaster1 = null;
    ProductData srcData1 = null;
    ProductData srcData2 = null;
    Band sourceBand1 = null;

    final String[] srcBandNames = targetBandNameToSourceBandName.get(targetBand.getName());
    if (srcBandNames.length == 1) {
        sourceBand1 = sourceProduct.getBand(srcBandNames[0]);
        sourceRaster1 = calibrationOp.getSourceTile(sourceBand1, targetTileRectangle);
        srcData1 = sourceRaster1.getDataBuffer();
    } else {
        sourceBand1 = sourceProduct.getBand(srcBandNames[0]);
        final Band sourceBand2 = sourceProduct.getBand(srcBandNames[1]);
        sourceRaster1 = calibrationOp.getSourceTile(sourceBand1, targetTileRectangle);
        final Tile sourceRaster2 = calibrationOp.getSourceTile(sourceBand2, targetTileRectangle);
        srcData1 = sourceRaster1.getDataBuffer();
        srcData2 = sourceRaster2.getDataBuffer();
    }

    final Unit.UnitType tgtBandUnit = Unit.getUnitType(targetBand);
    final Unit.UnitType srcBandUnit = Unit.getUnitType(sourceBand1);

    final ProductData trgData = targetTile.getDataBuffer();
    final TileIndex srcIndex = new TileIndex(sourceRaster1);
    final TileIndex tgtIndex = new TileIndex(targetTile);

    final int maxY = y0 + h;
    final int maxX = x0 + w;

    double sigma = 0.0, dn, dn2, i, q, phaseTerm = 0.0;
    int srcIdx, tgtIdx;

    for (int y = y0; y < maxY; ++y) {
        srcIndex.calculateStride(y);
        tgtIndex.calculateStride(y);

        for (int x = x0; x < maxX; ++x) {
            srcIdx = srcIndex.getIndex(x);
            tgtIdx = tgtIndex.getIndex(x);

            if (srcBandUnit == Unit.UnitType.AMPLITUDE) {
                dn = srcData1.getElemDoubleAt(srcIdx);
                dn2 = dn * dn;
            } else if (srcBandUnit == Unit.UnitType.INTENSITY) {
                dn2 = srcData1.getElemDoubleAt(srcIdx);
            } else if (srcBandUnit == Unit.UnitType.REAL) {
                i = srcData1.getElemDoubleAt(srcIdx);
                q = srcData2.getElemDoubleAt(srcIdx);
                dn2 = i * i + q * q;
                if (tgtBandUnit == Unit.UnitType.REAL) {
                    phaseTerm = i / Math.sqrt(dn2);
                } else if (tgtBandUnit == Unit.UnitType.IMAGINARY) {
                    phaseTerm = q / Math.sqrt(dn2);
                }
            } else if (srcBandUnit == Unit.UnitType.INTENSITY_DB) {
                dn2 = FastMath.pow(10, srcData1.getElemDoubleAt(srcIdx) / 10.0); // convert dB to linear scale
            } else {
                throw new OperatorException("RadarSat2 Calibration: unhandled unit");
            }

            if (isComplex) {
                if (gains != null) {
                    sigma = dn2 / (gains[x + subsetOffsetX] * gains[x + subsetOffsetX]);
                    if (outputImageInComplex) {
                        sigma = Math.sqrt(sigma) * phaseTerm;
                    }
                }
            } else {
                sigma = dn2 + offset;
                if (gains != null) {
                    sigma /= gains[x + subsetOffsetX];
                }
            }

            if (outputImageScaleInDb) { // convert calibration result to dB
                if (sigma < underFlowFloat) {
                    sigma = -underFlowFloat;
                } else {
                    sigma = 10.0 * Math.log10(sigma);
                }
            }

            trgData.setElemDoubleAt(tgtIdx, sigma);
        }
    }
}

From source file:org.knime.knip.io.nodes.imgwriter2.ImgWriter2NodeModel.java

/**
 * {@inheritDoc}//from w w w.j  a v  a 2s. c  o  m
 */
@SuppressWarnings("unchecked")
@Override
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec)
        throws Exception {

    checkDimensionMapping();

    String directory = null;
    // only initialize output directory when needed
    if (!m_useAbsolutePaths.getBooleanValue()) {
        Path folderPath = createOutputPath();
        directory = folderPath.toString();
        if (!directory.endsWith("/")) { // fix directory path
            directory += "/";
        }
    }

    // loop constants
    final boolean overwrite = m_overwrite.getBooleanValue();
    final boolean useCustomName = m_customNameOption.getBooleanValue();
    final boolean useAbsolutPaths = m_useAbsolutePaths.getBooleanValue();
    final boolean forceMkdir = m_forceMkdir.getBooleanValue();
    final String customName = m_customFileName.getStringValue();
    final int nameColIndex = inData[0].getDataTableSpec().findColumnIndex(m_filenameColumn.getStringValue());
    final int imgColIndex = inData[0].getDataTableSpec().findColumnIndex(m_imgColumn.getStringValue());
    final String format = m_format.getStringValue();
    final String compression = m_compression.getStringValue();

    /* File name number magic */
    // get number of digits needed for padding
    final int digits = (int) Math.log10(inData[0].getRowCount()) + 1;
    final String digitStringFormat = "%0" + digits + "d";
    int imgCount = 0;

    // loop variables
    ImgPlus<T> img;
    String outfile;
    boolean error = false;

    final ImgWriter2 writer = new ImgWriter2().setWriteSequantially(m_writeSequentially.getBooleanValue())
            .setFramesPerSecond(m_frameRate.getIntValue());

    for (DataRow row : inData[0]) {

        // set the filename
        if (useAbsolutPaths) {
            outfile = ((StringValue) row.getCell(nameColIndex)).getStringValue();
        } else if (useCustomName) {
            outfile = directory + customName + String.format(digitStringFormat, imgCount);
        } else if (nameColIndex == -1) {
            outfile = directory + row.getKey().getString();
        } else { // file name column configured
            try {
                outfile = directory + ((StringValue) row.getCell(nameColIndex)).getStringValue();
            } catch (ClassCastException e1) {
                throw new IllegalArgumentException(
                        "Missing value in the filename column in row: " + row.getKey());
            }
        }
        outfile += "." + writer.getSuffix(format);

        // handle file location
        final File f = FileUtil.resolveToPath(FileUtil.toURL(outfile)).toFile();

        if (f.exists()) {
            if (overwrite) {
                LOGGER.warn("The file " + outfile + " already exits and will be OVERWRITTEN.");
                f.delete();

            } else {
                throw new InvalidSettingsException(
                        "The file " + outfile + " exits and must not be overwritten due to user settings.");
            }
            // filename contained path to non existent directory
        } else if (!f.getParentFile().exists()) {
            if (forceMkdir) {
                LOGGER.info("Creating directory: " + f.getParentFile().getPath());
                FileUtils.forceMkdir(f.getParentFile());
            } else {
                throw new InvalidSettingsException("Output directory " + f.getParentFile().getPath()
                        + " doesn't exist, you can force the creation" + " in the node settings.");
            }
        }

        try {
            img = ((ImgPlusValue<T>) row.getCell(imgColIndex)).getImgPlus();
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Missing value in the img column in row: " + row.getKey());
        }

        // create dimensions mapping
        final int[] map = createDimMapping(img);

        try {
            writer.writeImage(img, FileUtil.resolveToPath(FileUtil.toURL(outfile)).toString(), format,
                    compression, map);

        } catch (final FormatException | IOException e) {
            LOGGER.error("Error while writing image " + outfile + " : " + e.getMessage(), e);
            error = true;
        } catch (final UnsupportedOperationException e) {
            LOGGER.error("Error while writing image " + outfile + " : "
                    + "Check the filename for illegal characters! " + e.getMessage(), e);
            error = true;
        }

        exec.setProgress((double) imgCount / inData[0].getRowCount());
        exec.checkCanceled();
        imgCount++;
    }

    if (error) {
        setWarningMessage("Some errors occured during the writing process!");
    }

    return null;

}

From source file:org.esa.s1tbx.calibration.gpf.calibrators.CosmoSkymedCalibrator.java

/**
 * Apply calibrations to the given point. The following calibrations are included: calibration constant,
 * antenna pattern compensation, range spreading loss correction and incidence angle correction.
 *
 * @param v                   The pixel value.
 * @param slantRange          The slant range (in m).
 * @param satelliteHeight     The distance from satellite to earth centre (in m).
 * @param sceneToEarthCentre  The distance from the backscattering element position to earth centre (in m).
 * @param localIncidenceAngle The local incidence angle (in degrees).
 * @param bandPolar           The source band polarization index.
 * @param bandUnit            The source band unit.
 * @param subSwathIndex       The sub swath index for current pixel for wide swath product case.
 * @return The calibrated pixel value./* w w  w  . j a v  a2  s . co  m*/
 */
public double applyCalibration(final double v, final double rangeIndex, final double azimuthIndex,
        final double slantRange, final double satelliteHeight, final double sceneToEarthCentre,
        final double localIncidenceAngle, final String bandName, final String bandPolar,
        final Unit.UnitType bandUnit, int[] subSwathIndex) {

    double Ks = 1.0;
    if (applyConstantCorrection) {
        Ks = calibrationFactor.get(bandPolar.toUpperCase());
    }

    double sigma = 0.0;
    if (bandUnit == Unit.UnitType.AMPLITUDE) {
        sigma = v * v;
    } else if (bandUnit == Unit.UnitType.INTENSITY || bandUnit == Unit.UnitType.REAL
            || bandUnit == Unit.UnitType.IMAGINARY) {
        sigma = v;
    } else if (bandUnit == Unit.UnitType.INTENSITY_DB) {
        sigma = FastMath.pow(10, v / 10.0); // convert dB to linear scale
    } else {
        throw new OperatorException("Unknown band unit");
    }

    if (applyRangeSpreadingLossCorrection)
        sigma *= FastMath.pow(referenceSlantRange, 2 * referenceSlantRangeExp);

    if (applyIncidenceAngleCorrection)
        sigma *= FastMath.sin(referenceIncidenceAngle);

    sigma /= (rescalingFactor * rescalingFactor * Ks);

    if (outputImageScaleInDb) { // convert calibration result to dB
        if (sigma < underFlowFloat) {
            sigma = -underFlowFloat;
        } else {
            sigma = 10.0 * Math.log10(sigma);
        }
    }
    return sigma;
}

From source file:no.sintef.ict.splcatool.CoveringArrayChvatal.java

private void generate2(int coverLimit, Integer sizelimit) {
    // Get a list of vars
    List<BooleanVariableInterface> vars = new ArrayList<BooleanVariableInterface>(cnf.getVariables());
    List<List<Integer>> solutions = new ArrayList<List<Integer>>(initial);

    // Calculate uncovered tuples
    List<Pair2> uncovered = new ArrayList<Pair2>();
    List<BooleanVariableInterface> vars2 = new ArrayList<BooleanVariableInterface>(vars);
    long ignored = 0;
    long alreadyCovered = 0;
    for (BooleanVariableInterface var1 : vars) {
        vars2.remove(var1);
        for (BooleanVariableInterface var2 : vars2) {

            // Set pairs
            Pair2 unc;/*from  w w  w.  j  a v  a 2 s.  c  om*/
            if (!coverOnlyOnes) {
                if (coverZerosOnly) {
                    unc = new Pair2(idnr);
                    unc.v1 = var1;
                    unc.b1 = false;
                    unc.v2 = var2;
                    unc.b2 = false;
                    if (!CALib.isCovered(idnr, unc, solutions)) {
                        uncovered.add(unc);
                    } else {
                        alreadyCovered++;
                    }
                }
                unc = new Pair2(idnr);
                unc.v1 = var1;
                unc.b1 = false;
                unc.v2 = var2;
                unc.b2 = true;
                if (!CALib.isCovered(idnr, unc, solutions)) {
                    uncovered.add(unc);
                } else {
                    alreadyCovered++;
                }
                unc = new Pair2(idnr);
                unc.v1 = var1;
                unc.b1 = true;
                unc.v2 = var2;
                unc.b2 = false;
                if (!CALib.isCovered(idnr, unc, solutions)) {
                    uncovered.add(unc);
                } else {
                    alreadyCovered++;
                }
            }
            unc = new Pair2(idnr);
            unc.v1 = var1;
            unc.b1 = true;
            unc.v2 = var2;
            unc.b2 = true;
            if (!CALib.isCovered(idnr, unc, solutions)) {
                uncovered.add(unc);
            } else {
                alreadyCovered++;
            }
        }
    }

    System.out.println("Uncovered pairs left: " + uncovered.size());

    // If starting from a covering array or doing a cover limit, start by finding invalids
    boolean invalidRemoved = false;
    long invalids = 0;
    if (coverLimit != 100 || initial.size() > 0) {
        System.out.println(
                "Removing invalid first when given a cover limit or a size limit or an initial covering array");
        int diff = uncovered.size();
        uncovered = getInvalid(0, uncovered);
        diff -= uncovered.size();
        System.out.println("Invalid: " + diff);
        invalids = diff;
        invalidRemoved = true;
    }

    // Check
    if (coverOnlyOnes) {
        if (uncovered.size() + alreadyCovered + invalids != MathUtils.binomialCoefficient(vars.size(), 2)) {
            System.out.println("Internal error: Wrong number of tuples");
            System.exit(-1);
        }
    } else if (!coverZerosOnly) {
        if (uncovered.size() + alreadyCovered + invalids != 3 * MathUtils.binomialCoefficient(vars.size(), 2)) {
            System.out.println("Internal error: Wrong number of tuples");
            System.exit(-1);
        }
    } else {
        if (uncovered.size() + alreadyCovered + invalids != 4 * MathUtils.binomialCoefficient(vars.size(), 2)) {
            System.out.println("Internal error: Wrong number of tuples");
            System.exit(-1);
        }
    }

    // Get solver
    SAT4JSolver satSolver = null;
    try {
        satSolver = cnf.getSAT4JSolver();
    } catch (ContradictionException e) {
    }

    // Cover
    long grandTotal = uncovered.size() + alreadyCovered;
    while (true) {
        // Calculate coverage
        coverage = (grandTotal - uncovered.size()) * 100 / grandTotal;

        // Stop at limit
        if (invalidRemoved && coverLimit <= coverage)
            break;

        // Check for limit
        if (solutions.size() >= sizelimit)
            break;

        // Mix
        Set<Pair2> mix = new HashSet<Pair2>(uncovered);

        List<Pair2> canBeSet = new ArrayList<Pair2>();
        List<Pair2> x = new ArrayList<Pair2>(uncovered);

        // assumptions
        Set<Integer> sol = new HashSet<Integer>();

        //System.out.println("Uncovered: " +uncovered.size());
        for (int i = 0; i < x.size(); i++) {
            if (i % 1000 == 0)
                System.out.println(i + "/" + x.size());

            // Get the two pairs
            boolean b1 = x.get(i).b1;
            boolean b2 = x.get(i).b2;
            BooleanVariableInterface v1 = x.get(i).v1;
            BooleanVariableInterface v2 = x.get(i).v2;
            Pair p1 = new Pair();
            p1.v = v1;
            p1.b = b1;
            Pair p2 = new Pair();
            p2.v = v2;
            p2.b = b2;

            // Set it
            int var1nr, var2nr;
            var1nr = (b1 ? 1 : -1) * idnr.get(v1.getID());
            var2nr = (b2 ? 1 : -1) * idnr.get(v2.getID());

            // Check
            try {
                // List
                List<Integer> assumpsList = new ArrayList<Integer>();
                for (int a : sol) {
                    assumpsList.add(a);
                }
                if (assumpsList.contains(-var1nr))
                    continue;
                if (assumpsList.contains(-var2nr))
                    continue;

                assumpsList.add(var1nr);
                assumpsList.add(var2nr);

                // Convert
                int assumpsArray[] = new int[assumpsList.size()];
                int c = 0;
                for (int a : assumpsList) {
                    assumpsArray[c] = a;
                    c++;
                }
                IVecInt assumps = new VecInt(assumpsArray);

                // Check
                if (satSolver.solver.isSatisfiable(assumps)) {
                    sol.add(var1nr);
                    sol.add(var2nr);
                    canBeSet.add(x.get(i));
                    mix.remove(x.get(i));
                }
            } catch (org.sat4j.specs.TimeoutException e1) {
            }
        }

        uncovered = new ArrayList<Pair2>(mix);

        // Convert
        int asssumpsArray[] = new int[sol.size()];
        int c = 0;
        for (int a : sol) {
            asssumpsArray[c] = a;
            c++;
        }
        IVecInt assumps = new VecInt(asssumpsArray);

        try {
            satSolver.solver.isSatisfiable(assumps);
        } catch (org.sat4j.specs.TimeoutException e1) {
        }
        int[] s = satSolver.solver.model();
        List<Integer> solution = new ArrayList<Integer>();
        for (int z : s)
            solution.add(z);

        // Remove invalid at some round
        if (!invalidRemoved) {
            if ((int) Math.log10(canBeSet.size()) <= (int) Math.log10(cnf.getVariables().size())) {
                System.out.println("Removing invalid");
                int diff = uncovered.size();
                uncovered = getInvalid(0, uncovered);
                diff -= uncovered.size();
                System.out.println("Invalid: " + diff);
                invalidRemoved = true;
            }
        }

        // Calculate coverage
        coverage = (grandTotal - uncovered.size()) * 100 / grandTotal;

        // Check if done
        if (canBeSet.size() == 0) {
            System.out.println("Breaking at " + uncovered.size() + " invalids");
            break;
        } else {
            System.out.println("Covered at " + (uncovered.size() + canBeSet.size()) + ", " + canBeSet.size()
                    + ", progress: " + coverage + "%");
            //System.out.println(canBeSet);
        }

        // Return
        solutions.add(solution);
    }

    // Done
    result = solutions;
}

From source file:com.wildplot.android.ankistats.Forecast.java

public double ticsCalcX(int pixelDistance, Rectangle field, int start, int end) {
    double deltaRange = end - start;
    int ticlimit = field.width / pixelDistance;
    double tics = Math.pow(10, (int) Math.log10(deltaRange / ticlimit));
    while (2.0 * (deltaRange / (tics)) <= ticlimit) {
        tics /= 2.0;/* w  w  w  . j  ava2s. co  m*/
    }
    while ((deltaRange / (tics)) / 2 >= ticlimit) {
        tics *= 2.0;
    }
    return tics;
}

From source file:org.broadinstitute.gatk.utils.MathUtils.java

/**
 * Converts a real space array of numbers (typically probabilities) into a log10 array
 *
 * @param prRealSpace/*from  w w w.j a v  a  2s. com*/
 * @return
 */
public static double[] toLog10(final double[] prRealSpace) {
    double[] log10s = new double[prRealSpace.length];
    for (int i = 0; i < prRealSpace.length; i++) {
        log10s[i] = Math.log10(prRealSpace[i]);
    }
    return log10s;
}

From source file:dsp.unige.figures.ChannelHelper.java

/**
 * Returns the noise level in dBW//from  ww  w.  j  ava 2s.  c o m
 * 
 * @param sta
 *            the station object
 * @param sat
 *            the satellite object
 * @return the noise level in [dBW]
 */
public static double getNdBW(Station sta, Satellite sat) {
    return getN0dBW(sta, sat) + 10 * Math.log10(sat.transponderBandwidth) + 30; // KHz to Hz
}

From source file:org.processmining.analysis.performance.advanceddottedchartanalysis.ui.DottedChartPanel.java

/**
 * adjusts the viewable are of the log (zoom)
 *///from w w w  .ja  va 2s  . c  o  m
public void setViewportZoomIn() {
    Dimension d = dca.getViewportSize();
    int width = Math.abs(p1.x - p2.x);
    int height = Math.abs(p1.y - p2.y);

    int value = (int) (Math.log10(this.getWidth() * (d.getWidth() / width) / dca.getViewportSize().getWidth())
            * 1000.0);
    if (value > 3000)
        return;
    value = (int) (Math.log10(this.getHeight() * (d.getHeight() / height) / dca.getViewportSize().getHeight())
            * 1000.0);
    if (value > 3000)
        return;

    updWidth = (int) (this.getWidth() * (d.getWidth() / width));
    updHight = (int) (this.getHeight() * (d.getHeight() / height));
    Dimension dim = new Dimension(updWidth, updHight);
    int pos_x = Math.min(p1.x, p2.x);
    int pos_y = Math.min(p1.y, p2.y);

    Point p = new Point((int) (pos_x * d.getWidth() / width), (int) (pos_y * d.getHeight() / height));
    this.setPreferredSize(dim);
    coUtil.updateMilli2pixelsRatio(this.getWidth(), BORDER);
    this.revalidate();
    dca.setScrollBarPosition(p);
    p1 = null;
    p2 = null;
    adjustSlideBar();
}

From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.util.tree.NumberArithmetic.java

/**
 * Returns the base-10 logarithm of the number.  If the numbers is
 * negative and function protection is enabled, then this function returns
 * the base-10 logarithm of the absolute value of the number.  If the
 * number is near zero and function protection is enabled, this function
 * returns {@code 0.0}./*from   w  w w .jav a2 s. co m*/
 * 
 * @param a the number
 * @return the base-10 logarithm of the number
 * @see Math#log10(double)
 */
public static Number log10(Number a) {
    if ((a.doubleValue() < Settings.EPS) && Settings.isProtectedFunctions()) {
        double value = Math.abs(a.doubleValue());

        if (value < Settings.EPS) {
            return 0.0;
        } else {
            return Math.log10(value);
        }
    } else {
        return Math.log10(a.doubleValue());
    }
}

From source file:frequencyanalysis.FrequencyAnalysis.java

public static float findFitnessOfString(Map quadGramData, String plainText) {
    float ans = 0.0f;

    for (int i = 0; i < plainText.length(); i++) {
        if (i + 3 < plainText.length()) {
            String quadGram = String.valueOf(plainText.charAt(i)) + String.valueOf(plainText.charAt(i + 1))
                    + String.valueOf(plainText.charAt(i + 2)) + String.valueOf(plainText.charAt(i + 3));

            if (quadGramData.containsKey(quadGram)) {
                Integer occurances = (Integer) quadGramData.get(quadGram);
                float logAns = (float) Math.log10(occurances / 2500000.0f);
                ans += logAns;/*w  w w .  j av a 2 s .c  o m*/
            }
            // We approxmiate no occurances with -9,4, since 1 occurance is about -6.3, just a random guess
            else {
                ans += -9.4f;
            }
        }
    }

    return ans;
}