Example usage for java.lang Math E

List of usage examples for java.lang Math E

Introduction

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

Prototype

double E

To view the source code for java.lang Math E.

Click Source Link

Document

The double value that is closer than any other to e, the base of the natural logarithms.

Usage

From source file:edu.rice.cs.bioinfo.programs.phylonet.algos.network.InferMLNetworkFromSequences.java

protected double findNonUltrametricOptimalBranchLength(final String[] gtTaxa,
        final Network<Object> speciesNetwork, final Map<String, String> allele2species,
        final List<Tuple<char[], Integer>> sequences, final RateModel rModel, final double theta) {
    boolean continueRounds = true; // keep trying to improve network

    for (NetNode<Object> node : speciesNetwork.dfs()) {
        for (NetNode<Object> parent : node.getParents()) {
            node.setParentDistance(parent, theta);
            if (node.isNetworkNode()) {
                //node.setParentDistance(parent,0.0);
                node.setParentProbability(parent, 0.5);
            }/*  w  ww  . j ava 2s  .c om*/
        }
    }

    //long start = System.currentTimeMillis();
    double initalProb = computeProbability(gtTaxa, speciesNetwork, allele2species, sequences, rModel, theta);
    //System.out.println(initalProb);
    //System.out.print("\n"+(System.currentTimeMillis()-start));
    //computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList);

    final Container<Double> lnGtProbOfSpeciesNetwork = new Container<Double>(initalProb); // records the GTProb of the network at all times
    //final Container<Integer> callCount = new Container<Integer>(0);

    int roundIndex = 0;
    for (; roundIndex < _maxRounds && continueRounds; roundIndex++) {
        /*
        * Prepare a random ordering of network edge examinations each of which attempts to change a branch length or hybrid prob to improve the GTProb score.
        */
        double lnGtProbLastRound = lnGtProbOfSpeciesNetwork.getContents();
        List<Proc> assigmentActions = new ArrayList<Proc>(); // store adjustment commands here.  Will execute them one by one later.

        for (final NetNode<Object> parent : edu.rice.cs.bioinfo.programs.phylonet.structs.network.util.Networks
                .postTraversal(speciesNetwork)) {

            for (final NetNode<Object> child : parent.getChildren()) {

                assigmentActions.add(new Proc() {
                    public void execute() {

                        UnivariateFunction functionToOptimize = new UnivariateFunction() {
                            public double value(double suggestedBranchLength) {
                                //System.out.print(" l/"+child.getName()+" ");
                                //callCount.setContents(callCount.getContents()+1);
                                double incumbentBranchLength = child.getParentDistance(parent);

                                child.setParentDistance(parent, suggestedBranchLength);

                                double lnProb = computeProbability(gtTaxa, speciesNetwork, allele2species,
                                        sequences, rModel, theta);
                                //System.out.println("Changing branch ("+parent.getName()+","+child.getName()+") to " + suggestedBranchLength);
                                //System.out.println(network2String(speciesNetwork)+": " + lnProb);

                                if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // did improve, keep change
                                {
                                    lnGtProbOfSpeciesNetwork.setContents(lnProb);

                                } else // didn't improve, roll back change
                                {
                                    child.setParentDistance(parent, incumbentBranchLength);
                                }
                                return lnProb;
                            }
                        };
                        BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent.

                        try {
                            optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE,
                                    Double.MIN_VALUE, _maxBranchLength);
                        } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded
                        {
                        }

                    }
                });
            }
        }

        for (final NetNode<Object> child : speciesNetwork.getNetworkNodes()) // find every hybrid node
        {

            Iterator<NetNode<Object>> hybridParents = child.getParents().iterator();
            final NetNode hybridParent1 = hybridParents.next();
            final NetNode hybridParent2 = hybridParents.next();

            assigmentActions.add(new Proc() {
                public void execute() {
                    UnivariateFunction functionToOptimize = new UnivariateFunction() {
                        public double value(double suggestedProb) {
                            //callCount.setContents(callCount.getContents()+1);
                            //System.out.print(" p/"+child.getName()+" ");
                            double incumbentHybridProbParent1 = child.getParentProbability(hybridParent1);

                            child.setParentProbability(hybridParent1, suggestedProb);
                            child.setParentProbability(hybridParent2, 1.0 - suggestedProb);

                            double lnProb = computeProbability(gtTaxa, speciesNetwork, allele2species,
                                    sequences, rModel, theta);
                            //System.out.println("Changing node probability to "+ suggestedProb);
                            //System.out.println(network2String(speciesNetwork)+": " + lnProb);
                            //System.out.println(Math.abs(computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList) - lnProb));
                            if (lnProb > lnGtProbOfSpeciesNetwork.getContents()) // change improved GTProb, keep it
                            {

                                lnGtProbOfSpeciesNetwork.setContents(lnProb);
                            } else // change did not improve, roll back
                            {

                                child.setParentProbability(hybridParent1, incumbentHybridProbParent1);
                                child.setParentProbability(hybridParent2, 1.0 - incumbentHybridProbParent1);
                            }
                            return lnProb;
                        }
                    };
                    BrentOptimizer optimizer = new BrentOptimizer(_Brent1, _Brent2); // very small numbers so we control when brent stops, not brent.

                    try {
                        optimizer.optimize(_maxTryPerBranch, functionToOptimize, GoalType.MAXIMIZE, 0, 1.0);
                    } catch (TooManyEvaluationsException e) // _maxAssigmentAttemptsPerBranchParam exceeded
                    {
                    }
                    //System.out.println(network2String(speciesNetwork) + " : " + lnGtProbOfSpeciesNetwork.getContents());
                }
            });

        }

        // add hybrid probs to hybrid edges
        if (_seed == null) {
            //Collections.shuffle(assigmentActions);
        }
        for (Proc assigment : assigmentActions) // for each change attempt, perform attempt
        {
            assigment.execute();
        }

        if (((double) lnGtProbOfSpeciesNetwork.getContents()) == lnGtProbLastRound) // if no improvement was made wrt to last around, stop trying to find a better assignment
        {
            continueRounds = false;
        } else if (lnGtProbOfSpeciesNetwork.getContents() > lnGtProbLastRound) // improvement was made, ensure it is large enough wrt to improvement threshold to continue searching
        {

            double improvementPercentage = Math.pow(Math.E,
                    (lnGtProbOfSpeciesNetwork.getContents() - lnGtProbLastRound)) - 1.0; // how much did we improve over last round
            if (improvementPercentage < _improvementThreshold) // improved, but not enough to keep searching
            {
                continueRounds = false;
            }
        } else {
            throw new IllegalStateException("Should never have decreased prob.");
        }
    }
    //System.out.println(callCount.getContents());
    //System.out.println(computeProbability(speciesNetwork, distinctTrees, species2alleles, nbTreeAndCountAndBinaryIDList) + " vs. " + lnGtProbOfSpeciesNetwork.getContents());
    return lnGtProbOfSpeciesNetwork.getContents();
}

From source file:io.smartspaces.activity.annotation.StandardConfigurationPropertyAnnotationProcessorTest.java

@Test
public void shadowedFields_differentTypes_ok() {
    final String propertySuperX = "super.x";
    final String propertySubX = "sub.x";

    class Super {
        @ConfigurationProperty(propertySuperX)
        int x;// ww  w  . j ava  2s  .  com
    }

    class Sub extends Super {
        @ConfigurationProperty(propertySubX)
        Double x;
    }

    int superX = 123;
    Double subX = Math.E;
    configuration.setProperty(propertySuperX, "" + superX);
    configuration.setProperty(propertySubX, "" + subX);
    Sub sub = new Sub();
    injectConfigValues(sub);

    assertEquals(sub.x, subX);
    Super sup = sub;
    assertEquals(sup.x, superX);
}

From source file:it.unibo.alchemist.language.protelis.util.ProtelisLoader.java

private static <T> AnnotatedTree<?> parseExpression(final Expression e,
        final Map<FasterString, FunctionDefinition> nameToFun,
        final Map<FunctionDef, FunctionDefinition> funToFun, final AtomicInteger id) {
    if (e instanceof DoubleVal) {
        return new NumericConstant(((DoubleVal) e).getVal());
    }// w  ww .j  a  v a2 s  . c o m
    if (e instanceof StringVal) {
        return new Constant<>(((StringVal) e).getVal());
    }
    if (e instanceof BooleanVal) {
        return new Constant<>(((BooleanVal) e).isVal());
    }
    if (e instanceof TupleVal) {
        final List<Expression> expr = extractArgs((TupleVal) e);
        List<AnnotatedTree<?>> list = new ArrayList<>();
        for (Expression exp : expr) {
            list.add(parseExpression(exp, nameToFun, funToFun, id));
        }
        final AnnotatedTree<?>[] args = new AnnotatedTree<?>[list.size()];
        int i = 0;
        for (AnnotatedTree<?> t : list) {
            args[i++] = t;
        }
        return new CreateTuple(args);
    }
    if (e instanceof VAR) {
        return new Variable(((VAR) e).getName());
    }
    if (e == null) {
        throw new IllegalArgumentException("null expression, this is a bug.");
    }
    final EObject eRef = e.getReference();
    if (eRef != null) {
        /*
         * Function or method call
         */
        if (eRef instanceof JvmOperation) {
            final JvmOperation m = (JvmOperation) eRef;
            return parseMethod(m, extractArgs(e), nameToFun, funToFun, id);
        } else if (eRef instanceof FunctionDef) {
            final FunctionDef fun = (FunctionDef) eRef;
            return parseFunction(fun, extractArgs(e), nameToFun, funToFun, id);
        } else {
            throw new IllegalStateException("I do not know how I should interpret a call to a "
                    + eRef.getClass().getSimpleName() + " object.");
        }
    }
    final String name = e.getName();
    if (name == null) {
        /*
         * Envelope: recurse in
         */
        final EObject val = e.getV();
        return parseExpression((Expression) val, nameToFun, funToFun, id);
    }
    if (BINARY_OPERATORS.contains(name) && e.getLeft() != null && e.getRight() != null) {
        return new BinaryOp(name, parseExpression(e.getLeft(), nameToFun, funToFun, id),
                parseExpression(e.getRight(), nameToFun, funToFun, id));
    }
    if (UNARY_OPERATORS.contains(name) && e.getLeft() == null && e.getRight() != null) {
        return new UnaryOp(name, parseExpression(e.getRight(), nameToFun, funToFun, id));
    }
    if (name.equals(REP_NAME)) {
        final RepInitialize ri = e.getInit().getArgs().get(0);
        final String x = ri.getX().getName();
        return new RepCall<>(new FasterString(x), parseExpression(ri.getW(), nameToFun, funToFun, id),
                parseBlock(e.getBody(), nameToFun, funToFun, id));
    }
    if (name.equals(IF_NAME)) {
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Boolean> cond = (AnnotatedTree<Boolean>) parseExpression(e.getCond(), nameToFun,
                funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<T> then = (AnnotatedTree<T>) parseBlock(e.getThen(), nameToFun, funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<T> elze = (AnnotatedTree<T>) parseBlock(e.getElse(), nameToFun, funToFun, id);
        return new If<>(cond, then, elze);
    }
    if (name.equals(PI_NAME)) {
        return new Constant<>(Math.PI);
    }
    if (name.equals(E_NAME)) {
        return new Constant<>(Math.E);
    }
    if (name.equals(RAND_NAME)) {
        return new Random();
    }
    if (name.equals(DT_NAME)) {
        return new Dt();
    }
    if (name.equals(SELF_NAME)) {
        return new Self();
    }
    if (name.equals(NBR_NAME)) {
        return new NBRCall(parseExpression(e.getArg(), nameToFun, funToFun, id));
    }
    if (name.equals(ALIGNED_MAP)) {
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Field> arg = (AnnotatedTree<Field>) parseExpression(e.getArg(), nameToFun, funToFun,
                id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<FunctionDefinition> cond = (AnnotatedTree<FunctionDefinition>) parseExpression(
                e.getCond(), nameToFun, funToFun, id);
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<FunctionDefinition> op = (AnnotatedTree<FunctionDefinition>) parseExpression(
                e.getOp(), nameToFun, funToFun, id);
        final AnnotatedTree<?> def = parseExpression(e.getDefault(), nameToFun, funToFun, id);
        return new AlignedMap(arg, cond, op, def);
    }
    if (name.equals(LAMBDA_NAME)) {
        final FunctionDefinition lambda = new FunctionDefinition("l$" + id.getAndIncrement(),
                extractArgsFromLambda(e));
        final AnnotatedTree<?> body = parseBlock(e.getBody(), nameToFun, funToFun, id);
        lambda.setBody(body);
        return new Constant<>(lambda);
    }
    if (name.equals(NBR_RANGE)) {
        return new NBRRange();
    }
    if (name.equals(EVAL_NAME)) {
        final AnnotatedTree<?> arg = parseExpression(e.getArg(), nameToFun, funToFun, id);
        return new Eval(arg);
    }
    if (name.equals(DOT_NAME)) {
        final AnnotatedTree<?> target = parseExpression(e.getLeft(), nameToFun, funToFun, id);
        final List<AnnotatedTree<?>> args = parseArgs(extractArgs(e), nameToFun, funToFun, id);
        return new DotOperator(e.getMethodName(), target, args);
    }
    if (name.equals(MUX_NAME)) {
        final AnnotatedTree<?> cond = parseExpression(e.getCond(), nameToFun, funToFun, id);
        final AnnotatedTree<?> then = parseBlock(e.getThen(), nameToFun, funToFun, id);
        final AnnotatedTree<?> elze = parseBlock(e.getElse(), nameToFun, funToFun, id);
        return new TernaryOp(MUX_NAME, cond, then, elze);
    }
    if (name.endsWith(HOOD_END)) {
        final String op = name.replace(HOOD_END, "");
        final HoodOp hop = HoodOp.get(op);
        if (hop == null) {
            throw new UnsupportedOperationException("Unsupported hood operation: " + op);
        }
        @SuppressWarnings(UNCHECKED)
        final AnnotatedTree<Field> arg = (AnnotatedTree<Field>) parseExpression(e.getArg(), nameToFun, funToFun,
                id);
        return new HoodCall(arg, hop, e.isInclusive());
    }
    throw new UnsupportedOperationException(
            "Unsupported operation: " + (e.getName() != null ? e.getName() : "Unknown"));
}

From source file:edu.ucla.stat.SOCR.applications.demo.BinomialTradingApplication.java

public void updateAllNodes() {
    //System.out.println("so="+So+" E="+EP+" Days="+t_days+" interest="+rate+" Sigma="+sigma+" n="+n);

    if (0 <= t_days && t_days <= 365)
        t = ((double) (t_days)) / 365;
    else {/*from  w w w  .ja  v a  2 s. com*/
        System.out.println("Error -- The time (in days) must be in the range [0; 365]!");
        t_days = 0;
        t = 0;
    }

    up = Math.exp(sigma * Math.sqrt(t / n)); // proportion UP price
    down = 1 / up; // proportion DOWN price

    Price = new double[n + 1][n + 1];
    // Price of the Stock Price[k][l] is the price of the stock at
    // level k (0<=k<=n) and outcome l (0<=l<n+1)
    Diff = new double[n + 1][n + 1];
    // Difference = Price of the Call Diff[k][l] is the Call-Price of the stock at 
    // level k (1<=k<=n) and outcome l (0<=l<n+1)

    rp = Math.pow(1 + rate, t / n) - 1; // rp = interest rate-per-period
    //probUp= (1+rp-down)/(up-down);      // Probability of Going UP. Prob of going DOWN is respectively (1-p)
    double dt = t / n;
    double a = Math.pow(Math.E, rate * dt);
    probUp = (a - down) / (up - down);
    // Compute the Stock Prices
    for (int k = 0; k <= n; k++) {
        //System.out.println("============Computing-StockPrices-at-level("+k+")==================");
        for (int l = 0; l <= k; l++) {
            Price[k][l] = So * Math.pow(up, k - l) * Math.pow(down, l);

            // Print to GraphPanel's JTextArea

            // Also Print to STD_OUT
            //System.out.println("Price["+k+"]["+l+"]="+Price[k][l]);
        }
        //System.out.println("============End-of-level("+k+")==================\n");
    }

    // Compute the DIFF values, Prices of calls
    for (int k = n; k >= 0; k--) {
        //System.out.println("============Computing DIFF (Price of call/put) at level("+k+")==================");
        if (choice.indexOf("put") != -1) { //put
            if (k == n) { // These are the last leaf-nodes of the Binomial tree
                for (int l = 0; l <= k; l++) {
                    if (Price[k][l] < EP)
                        Diff[k][l] = EP - Price[k][l];
                    else
                        Diff[k][l] = 0; // Price is NOT Excercised
                }
            } else {
                for (int l = 0; l <= k; l++) {
                    // Print to GraphPanel's JTextArea
                    //Diff[k][l] = (Diff[k+1][l]*probUp + Diff[k+1][l+1]*(1-probUp)) / (1+rp);  --save
                    Diff[k][l] = (Diff[k + 1][l] * probUp + Diff[k + 1][l + 1] * (1 - probUp))
                            * Math.pow(Math.E, -rate * dt);
                    if (choice.indexOf("american") != -1 && (Diff[k][l] < EP - Price[k][l])) {
                        Diff[k][l] = Price[k][l] - EP;
                    }

                    // Also Print to STD_OUT
                    //System.out.println("Diff["+k+"]["+l+"] = "+Diff[k][l]);
                }
                //System.out.println("============End-of-level("+k+")==================\n");
            }
        } else { //call
            if (k == n) { // These are the last leaf-nodes of the Binomial tree
                for (int l = 0; l <= k; l++) {
                    if (Price[k][l] > EP)
                        Diff[k][l] = Price[k][l] - EP;
                    else
                        Diff[k][l] = 0; // Price is NOT Excercised
                }
            } else {
                for (int l = 0; l <= k; l++) {
                    // Print to GraphPanel's JTextArea
                    //Diff[k][l] = (Diff[k+1][l]*probUp + Diff[k+1][l+1]*(1-probUp)) / (1+rp);  --save
                    Diff[k][l] = (Diff[k + 1][l] * probUp + Diff[k + 1][l + 1] * (1 - probUp))
                            * Math.pow(Math.E, -rate * dt);
                    if (choice.indexOf("american") != -1 && (Diff[k][l] < Price[k][l] - EP)) {
                        //int americanCall = (Price[k][l]*probUp + Price[k][l]*(1-probUp))*Math.pow(Math.E, -rate*dt);
                        //if (americanCall > Diff[k][l])
                        //   Diff[k][l] = americanCall;
                        Diff[k][l] = Price[k][l] - EP;
                    }

                    // Also Print to STD_OUT
                    //System.out.println("Diff["+k+"]["+l+"] = "+Diff[k][l]);
                }
                //System.out.println("============End-of-level("+k+")==================\n");
            }
        }
    }

    updateGraph();
}

From source file:ubic.gemma.analysis.expression.diff.LinearModelAnalyzer.java

/**
 * Log transform if necessary, do any required filtering prior to analysis.
 * /* www  .  jav  a2s . c  o m*/
 * @param quantitationType
 * @param dmatrix
 */
private ExpressionDataDoubleMatrix filterAndLogTransform(QuantitationType quantitationType,
        ExpressionDataDoubleMatrix dmatrix) {

    ScaleType scaleType = findScale(quantitationType, dmatrix.getMatrix());

    if (scaleType.equals(ScaleType.LOG2)) {
        log.info("Data is already on a log2 scale");
    } else if (scaleType.equals(ScaleType.LN)) {
        log.info(" **** Converting from ln to log2 **** ");
        MatrixStats.convertToLog2(dmatrix.getMatrix(), Math.E);
    } else if (scaleType.equals(ScaleType.LOG10)) {
        log.info(" **** Converting from log10 to log2 **** ");
        MatrixStats.convertToLog2(dmatrix.getMatrix(), 10);
    } else if (scaleType.equals(ScaleType.LINEAR)) {
        log.info(" **** LOG TRANSFORMING **** ");
        MatrixStats.logTransform(dmatrix.getMatrix());
    } else if (scaleType.equals(ScaleType.COUNT)) {
        // note: counts per million log2 transform is already taken care of in MeanVarianceEstimator
    } else {
        throw new UnsupportedOperationException("Can't figure out what scale the data are on");
    }

    /*
     * We do this second because doing it first causes some kind of subtle problem ... (round off? I could not
     * really track this down).
     * 
     * Remove zero-variance rows, but also rows that have lots of equal values even if variance is non-zero. This
     * happens when data is "clipped" (e.g., all values under 10 set to 10).
     */
    int r = dmatrix.rows();
    dmatrix = ExpressionExperimentFilter.zeroVarianceFilter(dmatrix);
    if (dmatrix.rows() < r) {
        log.info((r - dmatrix.rows()) + " rows removed due to low variance");
    }
    r = dmatrix.rows();
    /* FIXME refactor as constant. Idea is to skip this if the data set is really small, but this is totally ad hoc. */
    if (dmatrix.columns() > 4) {
        dmatrix = ExpressionExperimentFilter.tooFewDistinctValues(dmatrix, 0.5);
        if (dmatrix.rows() < r) {
            log.info((r - dmatrix.rows()) + " rows removed due to too many identical values");
        }
    }

    return dmatrix;

}

From source file:org.lockss.util.ObjectSerializerTester.java

/**
 * <p>Builds a sample {@link org.lockss.util.TypedEntryMap}
 * ready to marshal in tests.</p>/*from ww w  .j av  a 2 s  .c  o  m*/
 * <p>If subclasses override this method, they must make sure to
 * create a TypedEntryMap full of many data types to maximize the
 * difficulty of the test.</p>
 * @return A newly allocated
 *         {@link org.lockss.util.TypedEntryMap} filled with
 *         many interesting keys and values.
 */
protected TypedEntryMap makeSample_TypedEntryMap() throws Exception {
    TypedEntryMap tmap = new TypedEntryMap();

    /* Basic data types */
    tmap.putBoolean("boolean.true", true);
    tmap.putBoolean("boolean.false", false);
    tmap.putDouble("double.Math.PI", Math.PI);
    tmap.putDouble("double.Math.E", Math.E);
    tmap.putFloat("float.Float.MAX_VALUE", Float.MAX_VALUE);
    tmap.putFloat("float.0.12345f", 0.12345f);
    tmap.putInt("int.Integer.MIN_VALUE", Integer.MIN_VALUE);
    tmap.putInt("int.Integer.12345", 12345);
    tmap.putLong("long.Long.MAX_VALUE", Long.MAX_VALUE);
    tmap.putLong("long.6507245723L", 6507245723L);
    tmap.putString("string.\"LOCKSS rocks\"", "LOCKSS rocks");
    tmap.putString("string.\"\"", "");

    tmap.putUrl("url.\"http://www.lockss.org/\"", new URL("http://www.lockss.org/"));
    tmap.putUrl("url.\"http://www.stanford.edu/\"", new URL("http://www.stanford.edu/"));

    /* Collections */
    tmap.putCollection("collection.list.homogeneous", ListUtil.list("E", "F", "G", "H"));
    tmap.putCollection("collection.list.heterogeneous", ListUtil.list(new Float(1.0), "two", new Long(3)));
    return tmap;
}

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

/**
 * Converts LN to LOG10/* www  .  ja  va 2 s. c o  m*/
 *
 * @param ln log(x)
 * @return log10(x)
 */
public static double lnToLog10(final double ln) {
    return ln * Math.log10(Math.E);
}