Example usage for java.lang Math rint

List of usage examples for java.lang Math rint

Introduction

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

Prototype

public static double rint(double a) 

Source Link

Document

Returns the double value that is closest in value to the argument and is equal to a mathematical integer.

Usage

From source file:tv.dyndns.kishibe.qmaclone.server.Game.java

@VisibleForTesting
void calculateRating(List<PlayerStatus> players) {
    NormalDistribution normalDistribution = new NormalDistribution();

    // /*from  w  ww . j ava2 s. co  m*/
    // http://topcoder.g.hatena.ne.jp/n4_t/20081222/
    // http://apps.topcoder.com/wiki/display/tc/Algorithm+Competition+Rating+System
    Preconditions.checkState(2 <= players.size());

    int numCoders = players.size();
    double sumRating = 0.0;
    for (PlayerStatus player : players) {
        sumRating += player.getRating();
    }
    double aveRating = sumRating / numCoders;

    // The competition factor is calculated:
    double sumVolatility2 = 0.0;
    double sumDiffRatingAveRating = 0.0;
    for (PlayerStatus player : players) {
        sumVolatility2 += player.getVolatility() * player.getVolatility();
        double diffRatingAveRating = player.getRating() - aveRating;
        sumDiffRatingAveRating += diffRatingAveRating * diffRatingAveRating;
    }
    double cf = Math.sqrt(sumVolatility2 / numCoders + sumDiffRatingAveRating / (numCoders - 1));

    // ??
    Collections.sort(players, new Comparator<PlayerStatus>() {
        @Override
        public int compare(PlayerStatus o1, PlayerStatus o2) {
            int black1;
            int black2;
            try {
                int userCode1 = o1.getUserCode();
                int rating1 = o1.getRating();
                int userCode2 = o2.getUserCode();
                int rating2 = o2.getRating();
                black1 = (restrictedUserUtils.checkAndUpdateRestrictedUser(userCode1, "127.0.0.1",
                        RestrictionType.MATCH) && rating1 > 1700) ? 1 : 0;
                black2 = (restrictedUserUtils.checkAndUpdateRestrictedUser(userCode2, "127.0.0.1",
                        RestrictionType.MATCH) && rating2 > 1700) ? 1 : 0;
            } catch (DatabaseException e) {
                throw Throwables.propagate(e);
            }
            return black1 != black2 ? black1 - black2 : o2.getScore() - o1.getScore();
        }
    });
    for (int i = 0; i < players.size(); ++i) {
        if (0 < i && players.get(i - 1).getScore() == players.get(i).getScore()) {
            // ?????
            players.get(i).setHumanRank(players.get(i - 1).getHumanRank());
        } else {
            players.get(i).setHumanRank(i + 1);
        }
    }
    // ??????
    // http://kishibe.dyndns.tv/qmaclone/wiki/wiki.cgi?page=BugTrack-QMAClone%2F490
    // for (PlayerStatus playerStatus : players) {
    // if (badUserManager.isLimitedUser(playerStatus.getUserCode(), null)) {
    // playerStatus.setHumanRank(players.size());
    // }
    // }

    for (PlayerStatus my : players) {
        if (!my.isHuman()) {
            continue;
        }

        double myRating = my.getRating();
        double myVolatility = my.getVolatility();

        // Win Probability Estimation Algorithm:
        double eRank = 0.5;
        for (PlayerStatus player : players) {
            double hisVolatility = player.getVolatility();
            double wp = 0.5;
            wp = 0.5 * (Erf
                    .erf((player.getRating() - myRating)
                            / Math.sqrt(2 * (hisVolatility * hisVolatility + myVolatility * myVolatility)))
                    + 1.0);

            // BugTrack-QMAClone/603 - QMAClone wiki
            // http://kishibe.dyndns.tv/qmaclone/wiki/wiki.cgi?page=BugTrack%2DQMAClone%2F603
            if (my != player && my.getUserCode() == player.getUserCode()) {
                wp = 0.0;
            }
            eRank += wp;
        }

        // The expected performance of the coder is calculated:
        double ePerf = -normalDistribution.inverseCumulativeProbability((eRank - 0.5) / numCoders);

        // The actual performance of each coder is calculated:
        double aPerf = -normalDistribution.inverseCumulativeProbability((my.getHumanRank() - 0.5) / numCoders);

        // The performed as rating of the coder is calculated:
        double perfAs = myRating + cf * (aPerf - ePerf);

        // The weight of the competition for the coder is calculated:
        double weight = 1.0 / (1 - (0.42 / (my.getPlayCount() + 1) + 0.18)) - 1.0;

        // A cap is calculated:
        double cap = 150 + 1500 / (my.getPlayCount() + 2);

        // The new rating of the coder is calculated:
        double newRating = (myRating + weight * perfAs) / (1.0 + weight);
        newRating = Math.min(newRating, myRating + cap);
        newRating = Math.max(newRating, myRating - cap);

        // The new volatility of the coder is calculated:
        double diffRating = newRating - myRating;
        double newVolatility = Math
                .sqrt(diffRating * diffRating / weight + myVolatility * myVolatility / (weight + 1));

        my.setNewRating((int) Math.rint(newRating));
        my.setNewVolatility((int) Math.rint(newVolatility));
    }

    // ?????
    Collections.sort(players, new Comparator<PlayerStatus>() {
        @Override
        public int compare(PlayerStatus o1, PlayerStatus o2) {
            return o2.getScore() - o1.getScore();
        }
    });
    for (int i = 0; i < players.size(); ++i) {
        if (0 < i && players.get(i - 1).getScore() == players.get(i).getScore()) {
            // ?????
            players.get(i).setHumanRank(players.get(i - 1).getHumanRank());
        } else {
            players.get(i).setHumanRank(i + 1);
        }
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchSOSRequestAnalyzer.java

private static void createSampleRequests() {
    int wallLevel = 20;
    int supportCount = 20;
    int maxAttackCount = 10;
    int maxFakeCount = 0;

    Village[] villages = GlobalOptions.getSelectedProfile().getTribe().getVillageList();
    Village[] attackerVillages = DataHolder.getSingleton().getTribeByName("Alexander25").getVillageList();

    for (int i = 0; i < supportCount; i++) {
        int id = (int) Math.rint(Math.random() * (villages.length - 1));
        Village target = villages[id];//ww  w. ja  v a2s .  co  m
        SOSRequest r = new SOSRequest(target.getTribe());
        TargetInformation info = r.addTarget(target);
        info.setWallLevel(wallLevel);

        TroopAmountFixed troops = new TroopAmountFixed();
        troops.setAmountForUnit("spear", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("sword", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("heavy", (int) Math.rint(Math.random() * 5000));
        info.setTroops(troops);

        int cnt = (int) Math.rint(maxAttackCount * Math.random());
        for (int j = 0; j < cnt; j++) {
            int idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
            Village v = attackerVillages[idx];
            info.addAttack(v, new Date(
                    System.currentTimeMillis() + Math.round(DateUtils.MILLIS_PER_DAY * 7 * Math.random())));
            for (int k = 0; k < (int) Math.rint(maxFakeCount * Math.random()); k++) {
                idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
                v = attackerVillages[idx];
                info.addAttack(v, new Date(System.currentTimeMillis() + Math.round(3600 * Math.random())));
            }
        }
        SOSManager.getSingleton().addRequest(r);
    }
}

From source file:org.prom5.analysis.petrinet.cpnexport.HLToCPNTranslator.java

/**
 * Check whether there are possibility dependencies defined for some places.
 * In the case that there are more than one possibility dependencies defined for
 * one place, then generate the correct distribution function for each of these
 * possibility dependencies//w  w w. j a  v  a  2  s  .  com
 * @param places List the list of places in the net.
 */
private void checkForPossibilityDependencies(List<Place> places) {
    Iterator<Place> placesIt = places.iterator();
    while (placesIt.hasNext()) {
        ColoredPlace place = (ColoredPlace) placesIt.next();
        HLChoice choice = highLevelPN.findChoice(place);
        // if choice exists for this place and is configured to be based on
        // probability
        if (choice != null && choice.getChoiceConfiguration() == ChoiceEnum.PROB) {
            // first normalize if needed
            double sum = 0.0;
            Iterator<HLCondition> probDepsNorm = choice.getConditions().iterator();
            while (probDepsNorm.hasNext()) {
                HLCondition probDepNorm = probDepsNorm.next();
                sum += probDepNorm.getProbability();
            }
            // check whether sum is 0, in that case use default values.
            if (sum == 0) {
                // use default values
                Iterator<HLCondition> dependencies = choice.getConditions().iterator();
                while (dependencies.hasNext()) {
                    HLCondition dependency = dependencies.next();
                    double prob = ((double) 1 / (double) choice.getConditions().size());
                    dependency.setProbability(prob);
                }
            } else {
                // use normalized values
                Iterator<HLCondition> dependencies = choice.getConditions().iterator();
                while (dependencies.hasNext()) {
                    HLCondition dependency = dependencies.next();
                    double prob = ((double) dependency.getProbability() / (double) sum);
                    dependency.setProbability(prob);
                }
            }
            // first find the multiplier for a round value
            // maxInt value in cpn is 1073741823
            // so the multiplier may be at most 100000000
            double multiplier = 1.0;
            Iterator<HLCondition> probDeps = choice.getConditions().iterator();
            while (probDeps.hasNext()) {
                HLCondition probDep = probDeps.next();
                double doubleVal = probDep.getProbability();
                while (Math.rint(doubleVal * multiplier) != (doubleVal * multiplier)
                        && multiplier <= 100000000) {
                    multiplier = multiplier * 10;
                }
            }
            // calculate the max value of all the probabilities
            int maxVal = 0;
            probDeps = choice.getConditions().iterator();
            while (probDeps.hasNext()) {
                HLCondition probDep = probDeps.next();
                maxVal += Math.round(probDep.getProbability() * multiplier);
            }
            // String distFunc = "round(uniform(0.0," + maxVal + ".0))";
            String distFunc = "discrete(0," + (maxVal - 1) + ")";
            // actually generate
            double cumulative = 0;
            Iterator<HLCondition> conditions = choice.getConditions().iterator();
            int i = 0;
            while (conditions.hasNext()) {
                HLCondition cond = conditions.next();
                if (i == 0) {
                    // the first one
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " < " + Math.round(cond.getProbability() * multiplier);
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                    cumulative = cumulative + Math.round(cond.getProbability() * multiplier);
                } else if (i == choice.getConditions().size() - 1) {
                    // the last one
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " >= " + ((int) cumulative);
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                } else {
                    // somewhere in the middle
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " >= " + ((int) cumulative) + " andalso " + cpnVarNameProb
                            + " < " + (Math.round(cumulative + (cond.getProbability() * multiplier)));
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                    cumulative = cumulative + Math.round(cond.getProbability() * multiplier);
                }
                // remember configuration option in colored pn structure
                // (needed for writing)
                HLActivity act = cond.getTarget();
                ModelGraphVertex targetNode = highLevelPN.findModelGraphVertexForActivity(act.getID());
                if (targetNode instanceof ColoredTransition) {
                    //((ColoredTransition) targetNode)
                    //      .existsProbabilityDependency(true);
                    ColoredTransition firstTransition = getFirstTransitionOnSubpage(
                            ((ColoredTransition) targetNode).getSubpage());
                    if (firstTransition != null) {
                        firstTransition.existsProbabilityDependency(true);
                    }
                }
                i++;
            }
        }
    }
}

From source file:edu.cudenver.bios.power.GLMMPowerCalculator.java

/**
 *  Find the sample size which achieves the desired power(s)
 *  specified in the input parameters.  Uses a bisection search.
 *
 * @param params GLMM input parameters/*w w  w  .  j a va 2  s  .c  om*/
 * @return sample size
 */
private GLMMPower getSampleSizeValue(GLMMPowerParameters params, Test test, PowerMethod method, double alpha,
        double sigmaScale, double betaScale, double targetPower, double quantile) {
    if (method == PowerMethod.UNCONDITIONAL_POWER) {
        GLMMPower power = new GLMMPower(test, alpha, targetPower, -1, -1, betaScale, sigmaScale, method,
                quantile, null);
        power.setErrorMessage(
                "We have temporarily disabled sample size calculations using the unconditional power method "
                        + "while we work on computational efficiency. " + "There are two alternatives." + "<ol>"
                        + "<li>" + "You may perform a power calculation for a given sample size, "
                        + "and iterate until you find a sample size and unconditional power that work for your design."
                        + "</li>" + "<li>" + "You may calculate sample size using quantile power "
                        + "calculated at the median power (0.50th quantile) instead of unconditional power. "
                        + "As noted in Glueck and Muller (2003) "
                        + "(see <a href=\"http://samplesizeshop.org/education/related-publications/\">Related Publications</a>), "
                        + "quantile power is a very good approximation for unconditional power." + "</li>"
                        + "</ol>" + "Thank you for your patience while we repair this functionality.");
        power.setErrorCode(PowerErrorEnum.POWER_METHOD_UNKNOWN);
        return power;
    }

    try {
        // rescale the beta and sigma matrices and create a test
        RealMatrix scaledBeta = params.getBeta().scalarMultiply(betaScale, true);
        RealMatrix scaledSigmaError = params.getSigmaError().scalarMultiply(sigmaScale);
        GLMMTest glmmTest = GLMMTestFactory.createGLMMTestForPower(test, params.getFApproximationMethod(test),
                params.getUnivariateCdfMethod(test), params.getUnivariateEpsilonMethod(test),
                params.getDesignEssence(), params.getXtXInverse(), STARTING_SAMPLE_SIZE, params.getDesignRank(),
                params.getBetweenSubjectContrast(), params.getWithinSubjectContrast(), params.getTheta(),
                scaledBeta, scaledSigmaError,
                (params.getConfidenceIntervalType() != ConfidenceIntervalType.NONE
                        ? params.getSampleSizeForEstimates() - params.getDesignMatrixRankForEstimates()
                        : 0));

        // calculate the noncentrality distribution
        NonCentralityDistribution nonCentralityDist = null;
        if (method != PowerMethod.CONDITIONAL_POWER) {
            nonCentralityDist = new NonCentralityDistribution(test, params.getDesignEssence(),
                    params.getXtXInverse(), STARTING_SAMPLE_SIZE, params.getBetweenSubjectContrast(),
                    params.getWithinSubjectContrast(), params.getTheta(), scaledBeta, scaledSigmaError,
                    params.getSigmaGaussianRandom(), params.isNonCentralityCDFExact());
        }

        // Calculate the maximum valid per group N. This avoids multiplication which exceeeds
        // Integer.MAX_VALUE. Moreover, by limiting to MAX_SAMPLE_SIZE, we avoid calculations
        // that take many seconds to complete.
        int designEssenceRows = params.getDesignEssence().getRowDimension();
        int maxPerGroupN = Math.min(Integer.MAX_VALUE / designEssenceRows, MAX_SAMPLE_SIZE);

        /*
         * find the upper bound on sample size.  That is,
         * find a sample size which produces power greater than or
         * equal to the desired power.
         * If an error occurs, we set an error code in the power result
         */
        SampleSizeBound upperBound = getSampleSizeUpperBound(glmmTest, nonCentralityDist, method, targetPower,
                alpha, quantile, maxPerGroupN);
        if (upperBound.getError() != null) {
            GLMMPower power = new GLMMPower(test, alpha, targetPower, upperBound.getActualPower(),
                    upperBound.getSampleSize(), betaScale, sigmaScale, method, quantile, null);
            switch (upperBound.getError()) {
            case MAX_SAMPLE_SIZE_EXCEEDED:
                power.setErrorMessage(
                        // TODO: is the following expression correct?
                        // "The total sample size for this case would exceed " + (maxPerGroupN * designEssenceRows) + ". "
                        "The total sample size for this case would be unreasonably large. "
                                + "For performance reasons, we are not computing its exact value.");
                power.setErrorCode(PowerErrorEnum.MAX_SAMPLE_SIZE_EXCEEDED);
                break;
            case SAMPLE_SIZE_UNDEFINED:
                power.setErrorMessage(NO_MEAN_DIFFERENCE_MESSAGE);
                power.setErrorCode(PowerErrorEnum.SAMPLE_SIZE_UNDEFINED);
                break;
            case SAMPLE_SIZE_UNDEFINED_DUE_TO_EXCEPTION:
                power.setErrorMessage("Sample size not well defined.");
                power.setErrorCode(PowerErrorEnum.SAMPLE_SIZE_UNDEFINED);
                break;
            }
            return power;
        }

        /*
         *  find the lower bound on sample size
         *  We search for a lower bound since the F approximations
         *  may be unstable for very small samples
         */
        // TODO: isn't the lower bound just half of the upper bound?????
        SampleSizeBound lowerBound = getSampleSizeLowerBound(glmmTest, nonCentralityDist, method, upperBound,
                alpha, quantile);
        assert lowerBound.getError() == null;

        /*
         * At this point we have valid boundaries for searching.
         * There are two possible scenarios
         * 1. The upper bound == lower bound.
         * 2. The upper bound != lower bound and lower bound exceeds required power.
         * In this case we just take the value at the lower bound.
         * 3. The upper bound != lower bound and lower bound is less than the required power.
         * In this case we bisection search
         */
        double calculatedPower;
        int perGroupSampleSize;

        if (upperBound.getSampleSize() == lowerBound.getSampleSize()) {
            // case 1
            calculatedPower = upperBound.getActualPower();
            perGroupSampleSize = upperBound.getSampleSize();
        } else if (lowerBound.getActualPower() >= targetPower) {
            // case 2
            calculatedPower = lowerBound.getActualPower();
            perGroupSampleSize = lowerBound.getSampleSize();
        } else {
            // case 3, bisection search time!
            // create a bisection search function to find the best per group sample size
            BisectionSolver solver = new BisectionSolver();
            SampleSizeFunction sampleSizeFunc = new SampleSizeFunction(glmmTest, nonCentralityDist, method,
                    targetPower, alpha, quantile);
            double solution = solver.solve(MAX_ITERATIONS, sampleSizeFunc, lowerBound.getSampleSize(),
                    upperBound.getSampleSize());
            perGroupSampleSize = (int) Math.rint(solution); // see https://samplesizeshop.atlassian.net/browse/SSS-120
            glmmTest.setPerGroupSampleSize(perGroupSampleSize);
            if (nonCentralityDist != null)
                nonCentralityDist.setPerGroupSampleSize(perGroupSampleSize);
            calculatedPower = getPowerByType(glmmTest, nonCentralityDist, method, alpha, quantile);
        }

        // build a confidence interval if requested
        GLMMPowerConfidenceInterval ci;
        if (params.getConfidenceIntervalType() != ConfidenceIntervalType.NONE) {
            ci = new GLMMPowerConfidenceInterval(params.getConfidenceIntervalType(),
                    params.getAlphaLowerConfidenceLimit(), params.getAlphaUpperConfidenceLimit(),
                    params.getSampleSizeForEstimates(), params.getDesignMatrixRankForEstimates(), alpha,
                    glmmTest);
        } else {
            ci = null;
        }

        return new GLMMPower(test, alpha, targetPower, calculatedPower,
                MatrixUtils.getTotalSampleSize(params.getDesignEssence(), perGroupSampleSize), betaScale,
                sigmaScale, method, quantile, ci);
    } catch (PowerException pe) {
        GLMMPower powerValue = new GLMMPower(test, alpha, targetPower, -1, -1, betaScale, sigmaScale, method,
                quantile, null);
        powerValue.setErrorCode(pe.getErrorCode());
        powerValue.setErrorMessage(pe.getMessage());
        return powerValue;
    }
}

From source file:org.processmining.analysis.petrinet.cpnexport.HLToCPNTranslator.java

/**
 * Check whether there are possibility dependencies defined for some places.
 * In the case that there are more than one possibility dependencies defined
 * for one place, then generate the correct distribution function for each
 * of these possibility dependencies/*w w w  . j  av  a2  s  .c  o m*/
 * 
 * @param places
 *            List the list of places in the net.
 */
private void checkForPossibilityDependencies(List<Place> places) {
    Iterator<Place> placesIt = places.iterator();
    while (placesIt.hasNext()) {
        ColoredPlace place = (ColoredPlace) placesIt.next();
        HLChoice choice = highLevelPN.findChoice(place);
        // if choice exists for this place and is configured to be based on
        // probability
        if (choice != null && choice.getChoiceConfiguration() == ChoiceEnum.PROB) {
            // first normalize if needed
            double sum = 0.0;
            Iterator<HLCondition> probDepsNorm = choice.getConditions().iterator();
            while (probDepsNorm.hasNext()) {
                HLCondition probDepNorm = probDepsNorm.next();
                sum += probDepNorm.getProbability();
            }
            // check whether sum is 0, in that case use default values.
            if (sum == 0) {
                // use default values
                Iterator<HLCondition> dependencies = choice.getConditions().iterator();
                while (dependencies.hasNext()) {
                    HLCondition dependency = dependencies.next();
                    double prob = ((double) 1 / (double) choice.getConditions().size());
                    dependency.setProbability(prob);
                }
            } else {
                // use normalized values
                Iterator<HLCondition> dependencies = choice.getConditions().iterator();
                while (dependencies.hasNext()) {
                    HLCondition dependency = dependencies.next();
                    double prob = ((double) dependency.getProbability() / (double) sum);
                    dependency.setProbability(prob);
                }
            }
            // first find the multiplier for a round value
            // maxInt value in cpn is 1073741823
            // so the multiplier may be at most 100000000
            double multiplier = 1.0;
            Iterator<HLCondition> probDeps = choice.getConditions().iterator();
            while (probDeps.hasNext()) {
                HLCondition probDep = probDeps.next();
                double doubleVal = probDep.getProbability();
                while (Math.rint(doubleVal * multiplier) != (doubleVal * multiplier)
                        && multiplier <= 100000000) {
                    multiplier = multiplier * 10;
                }
            }
            // calculate the max value of all the probabilities
            int maxVal = 0;
            probDeps = choice.getConditions().iterator();
            while (probDeps.hasNext()) {
                HLCondition probDep = probDeps.next();
                maxVal += Math.round(probDep.getProbability() * multiplier);
            }
            // String distFunc = "round(uniform(0.0," + maxVal + ".0))";
            String distFunc = "discrete(0," + (maxVal - 1) + ")";
            // actually generate
            double cumulative = 0;
            Iterator<HLCondition> conditions = choice.getConditions().iterator();
            int i = 0;
            while (conditions.hasNext()) {
                HLCondition cond = conditions.next();
                if (i == 0) {
                    // the first one
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " < " + Math.round(cond.getProbability() * multiplier);
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                    cumulative = cumulative + Math.round(cond.getProbability() * multiplier);
                } else if (i == choice.getConditions().size() - 1) {
                    // the last one
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " >= " + ((int) cumulative);
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                } else {
                    // somewhere in the middle
                    String cpnVarNameProb = variableTranslator.getCpnVarForProbDep(cond).getVarName();
                    String guard = cpnVarNameProb + " >= " + ((int) cumulative) + " andalso " + cpnVarNameProb
                            + " < " + (Math.round(cumulative + (cond.getProbability() * multiplier)));
                    generateProbabilityDependencySubpage(cond, distFunc, guard, cpnVarNameProb);
                    cumulative = cumulative + Math.round(cond.getProbability() * multiplier);
                }
                // remember configuration option in colored pn structure
                // (needed for writing)
                HLActivity act = cond.getTarget();
                ModelGraphVertex targetNode = highLevelPN.findModelGraphVertexForActivity(act.getID());
                if (targetNode instanceof ColoredTransition) {
                    // ((ColoredTransition) targetNode)
                    // .existsProbabilityDependency(true);
                    ColoredTransition firstTransition = getFirstTransitionOnSubpage(
                            ((ColoredTransition) targetNode).getSubpage());
                    if (firstTransition != null) {
                        firstTransition.existsProbabilityDependency(true);
                    }
                }
                i++;
            }
        }
    }
}

From source file:de.tor.tribes.io.DataHolder.java

public UnitHolder getRandomUnit() {
    int id = (int) (Math.rint(mUnits.size() * Math.random()));
    if (id >= mUnits.size()) {
        if (mUnits.isEmpty()) {
            return new UnitHolder();
        } else {//  w  w  w.  j  av a 2  s  .  c om
            id = 0;
        }
    }
    return mUnits.get(id);
}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private boolean redraw() {
    Village[][] mVisibleVillages = DataHolder.getSingleton().getVillages();

    if (mVisibleVillages == null || mBuffer == null) {
        return false;
    }/*from  w  w w  .  ja  v a2 s.  c o  m*/

    Graphics2D g2d = (Graphics2D) mBuffer.getGraphics();
    Composite tempC = g2d.getComposite();
    //clear
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
    g2d.fillRect(0, 0, mBuffer.getWidth(), mBuffer.getHeight());

    //reset composite
    g2d.setComposite(tempC);

    boolean markPlayer = GlobalOptions.getProperties().getBoolean("mark.villages.on.minimap");
    if (ServerSettings.getSingleton().getMapDimension() == null) {
        //could not draw minimap if dimensions are not loaded yet
        return false;
    }
    boolean showBarbarian = GlobalOptions.getProperties().getBoolean("show.barbarian");

    Color DEFAULT = Constants.DS_DEFAULT_MARKER;
    try {
        int mark = Integer.parseInt(GlobalOptions.getProperty("default.mark"));
        if (mark == 0) {
            DEFAULT = Constants.DS_DEFAULT_MARKER;
        } else if (mark == 1) {
            DEFAULT = Color.RED;
        } else if (mark == 2) {
            DEFAULT = Color.WHITE;
        }
    } catch (Exception e) {
        DEFAULT = Constants.DS_DEFAULT_MARKER;
    }

    Rectangle mapDim = ServerSettings.getSingleton().getMapDimension();
    double wField = mapDim.getWidth() / (double) visiblePart.width;
    double hField = mapDim.getHeight() / (double) visiblePart.height;

    UserProfile profile = GlobalOptions.getSelectedProfile();
    Tribe currentTribe = InvalidTribe.getSingleton();
    if (profile != null) {
        currentTribe = profile.getTribe();
    }

    for (int i = visiblePart.x; i < (visiblePart.width + visiblePart.x); i++) {
        for (int j = visiblePart.y; j < (visiblePart.height + visiblePart.y); j++) {
            Village v = mVisibleVillages[i][j];
            if (v != null) {
                Color markerColor = null;
                boolean isLeft = false;
                if (v.getTribe() == Barbarians.getSingleton()) {
                    isLeft = true;
                } else {
                    if ((currentTribe != null) && (v.getTribe().getId() == currentTribe.getId())) {
                        //village is owned by current player. mark it dependent on settings
                        if (markPlayer) {
                            markerColor = Color.YELLOW;
                        }
                    } else {
                        try {
                            Marker marker = MarkerManager.getSingleton().getMarker(v.getTribe());
                            if (marker != null && !marker.isShownOnMap()) {
                                marker = null;
                                markerColor = DEFAULT;
                            }

                            if (marker == null) {
                                marker = MarkerManager.getSingleton().getMarker(v.getTribe().getAlly());
                                if (marker != null && marker.isShownOnMap()) {
                                    markerColor = marker.getMarkerColor();
                                }
                            } else {
                                if (marker.isShownOnMap()) {
                                    markerColor = marker.getMarkerColor();
                                }
                            }
                        } catch (Exception e) {
                            markerColor = null;
                        }
                    }
                }

                if (!isLeft) {
                    if (markerColor != null) {
                        g2d.setColor(markerColor);
                    } else {
                        g2d.setColor(DEFAULT);
                    }
                    g2d.fillRect((int) Math.round((i - visiblePart.x) * wField),
                            (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField),
                            (int) Math.floor(hField));
                } else {
                    if (showBarbarian) {
                        g2d.setColor(Color.LIGHT_GRAY);
                        g2d.fillRect((int) Math.round((i - visiblePart.x) * wField),
                                (int) Math.round((j - visiblePart.y) * hField), (int) Math.floor(wField),
                                (int) Math.floor(hField));
                    }
                }
            }
        }
    }

    try {
        if (GlobalOptions.getProperties().getBoolean("map.showcontinents")) {
            g2d.setColor(Color.BLACK);
            Composite c = g2d.getComposite();
            Composite a = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f);
            Font f = g2d.getFont();
            Font t = new Font("Serif", Font.BOLD, (int) Math.round(30 * hField));
            g2d.setFont(t);
            int fact = 10;
            int mid = (int) Math.round(50 * wField);

            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    g2d.setComposite(a);

                    String conti = "K" + (j * 10 + i);
                    Rectangle2D bounds = g2d.getFontMetrics(t).getStringBounds(conti, g2d);
                    int cx = i * fact * 10 - visiblePart.x;
                    int cy = j * fact * 10 - visiblePart.y;
                    cx = (int) Math.round(cx * wField);
                    cy = (int) Math.round(cy * hField);
                    g2d.drawString(conti, (int) Math.rint(cx + mid - bounds.getWidth() / 2),
                            (int) Math.rint(cy + mid + bounds.getHeight() / 2));
                    g2d.setComposite(c);
                    int wk = 100;
                    int hk = 100;

                    if (i == 9) {
                        wk -= 1;
                    }
                    if (j == 9) {
                        hk -= 1;
                    }

                    g2d.drawRect(cx, cy, (int) Math.round(wk * wField), (int) Math.round(hk * hField));
                }
            }
            g2d.setFont(f);
        }
    } catch (Exception e) {
        logger.error("Creation of Minimap failed", e);
    }
    g2d.dispose();
    return true;
}

From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java

private List getAllTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = new java.util.ArrayList();

    //get lower bound value:
    double lowerBoundVal = getRange().getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }/* w  ww  .  j  av a  2  s  .  c o m*/
    //get upper bound value
    double upperBoundVal = getRange().getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    if (iBegCount == iEndCount && iBegCount > 0 && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    int numberOfGrids = 0;
    int numberOfTicks = 0;
    NumberTick lastTick = null;
    double tickVal;
    String tickLabel;
    //        tickVal = lowerBoundVal;
    //        
    //        tickLabel = Long.toString((long) Math.rint(tickVal));
    //        ticks.add(new NumberTick(new Double(tickVal), tickLabel,
    //              TextAnchor.CENTER_RIGHT, TextAnchor.CENTER_RIGHT, 0.0));
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each tick with a label to be displayed
        int jEndCount = 10;
        if (i == iEndCount) {
            //                jEndCount = 1;
        }

        for (int j = 0; j < jEndCount; j++) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use
                tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
                //first tick of group; create label text
                if (this.log10TickLabelsFlag) {
                    //if flag then
                    tickLabel = "10^" + i; //create "log10"-type label
                } else { //not "log10"-type label
                    if (this.expTickLabelsFlag) {
                        //if flag then
                        tickLabel = "1e" + i; //create "1e#"-type label
                    } else { //not "1e#"-type label
                        if (i >= 0) { // if positive exponent then
                                      // make integer
                            NumberFormat format = getNumberFormatOverride();
                            if (format != null) {
                                tickLabel = format.format(tickVal);
                            } else {
                                tickLabel = Long.toString((long) Math.rint(tickVal));
                            }
                        } else {
                            //negative exponent; create fractional value
                            //set exact number of fractional digits to
                            // be shown:
                            this.numberFormatterObj.setMaximumFractionDigits(-i);
                            //create tick label:
                            tickLabel = this.numberFormatterObj.format(tickVal);
                        }
                    }
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j;
                } //decrement to do 1.0 tick now
                tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (!zeroTickFlag) { // did not do zero tick last
                                     // iteration
                    if (i > iBegCount && i < iEndCount && Math.abs(tickVal - 1.0) < 0.0001) {
                        // not first or last tick on graph and value
                        // is 1.0
                        tickVal = 0.0; //change value to 0.0
                        zeroTickFlag = true; //indicate zero tick
                        tickLabel = "0"; //create label for tick
                    } else {
                        //first or last tick on graph or value is 1.0
                        //create label for tick:
                        tickLabel = createTickLabel(tickVal, i);
                    }
                } else { // not first tick of group
                    tickLabel = createTickLabel(tickVal, i);
                }
            }

            if (tickVal > upperBoundVal) {
                if (lastTick != null) {
                    String lastTickText = lastTick.getText();
                    if (lastTickText == null || lastTickText.trim().length() == 0) {
                        ticks.remove(lastTick);
                        ticks.add(new NumberTick(lastTick.getValue(),
                                createTickLabel(lastTick.getValue(), i - 1), lastTick.getTextAnchor(),
                                lastTick.getRotationAnchor(), lastTick.getAngle()));
                    }
                }
                if (ticks.size() < 2) {
                    double definition = Math.abs(lowerBoundVal - upperBoundVal);
                    int numberOfDigits = 0;
                    if (definition >= 1)
                        numberOfDigits = 0;
                    else {
                        numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
                    }
                    tickVal = lowerBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                    tickVal = upperBoundVal;
                    if (definition > 1)
                        tickLabel = Long.toString((long) Math.rint(tickVal));
                    else
                        tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
                    ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                            TextAnchor.CENTER_RIGHT, 0.0));
                }
                return ticks; //if past highest data value then exit method
            }

            if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = -Math.PI / 2.0;
                    } else {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                    } else {
                        anchor = TextAnchor.CENTER_LEFT;
                        rotationAnchor = TextAnchor.CENTER_LEFT;
                    }
                }
                //create tick object and add to list:
                lastTick = new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle);
                ticks.add(lastTick);
                if (tickLabel != null && tickLabel.trim().length() > 0)
                    numberOfTicks++;
                numberOfGrids++;
            }
        }
    }
    if (ticks.size() < 2) {
        double definition = Math.abs(lowerBoundVal - upperBoundVal);
        int numberOfDigits = 0;
        if (definition >= 1)
            numberOfDigits = 0;
        else {
            numberOfDigits = (int) Math.ceil((-Math.log10(definition)));
        }
        tickVal = lowerBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
        tickVal = upperBoundVal;
        if (definition > 1)
            tickLabel = Long.toString((long) Math.rint(tickVal));
        else
            tickLabel = (new Formatter()).format("%." + numberOfDigits + "f", tickVal).toString();
        ticks.add(new NumberTick(new Double(tickVal), tickLabel, TextAnchor.CENTER_RIGHT,
                TextAnchor.CENTER_RIGHT, 0.0));
    }
    return ticks;
}

From source file:org.earthtime.UPb_Redux.dateInterpretation.WeightedMeanGraphPanel.java

/**
 *
 *//*from w  ww  .  j  av a2s  .  co m*/
public void preparePanel() {

    zoomMaxX = 0;
    zoomMaxY = 0;
    zoomMinX = 0;
    zoomMinY = 0;

    setDisplayOffsetY(0.0);
    setDisplayOffsetX(0.0);

    this.removeAll();

    // walk selectedDateModels and get min and max of both sample date weighted mean graphs
    // X-axis is merely for layout, so map it to the size of panel
    setMinX(0.0);
    setMaxX(getGraphWidth());

    // Y-axis is going to be the age associated with the weighted means
    setMinY(ReduxConstants.MAX_DATE_ANNUM);//4.5E9 );
    setMaxY(0.0);

    for (int i = 0; i < selectedSampleDateModels.length; i++) {
        for (int j = 1; j < 9; j++) {
            if (selectedSampleDateModels[i][j] instanceof SampleDateModel) {

                double wmMax = ((SampleDateModel) selectedSampleDateModels[i][j]).//
                        DetermineMaxDatePlusTwoSigma();
                if (wmMax > maxY) {
                    setMaxY(wmMax);
                }

                double wmMin = ((SampleDateModel) selectedSampleDateModels[i][j]).//
                        DetermineMinDateLessTwoSigma();
                if (wmMin < minY) {
                    setMinY(wmMin);
                }

            }
        }
    }

    // convert to Ma
    setMinY(minY / 1.0E6);
    setMaxY(maxY / 1.0E6);

    // force margin Y
    double rangeY = (getMaxY_Display() - getMinY_Display());
    setMaxY(maxY + 0.15 * rangeY);

    // determine the y axis tic
    double minYtic = Math.ceil(getMinY_Display() * 100) / 100;
    double maxYtic = Math.floor(getMaxY_Display() * 100) / 100;
    double deltay = Math.rint((maxYtic - minYtic) * 10 + 0.5);
    double yTic = deltay / 100;
    setMinY((minY - 0.25 * rangeY) - 9 * yTic);

    //        setInRandomMode( false );
    //        System.out.println("Init " + minX + "  " + minY + "  " + maxX + "   " + maxY);
}

From source file:org.gumtree.vis.plot1d.LogarithmizableAxis.java

/**
 * Calculates the positions of the tick labels for the axis, storing the
 * results in the tick label list (ready for drawing).
 *
 * @param g2  the graphics device./*from w  w  w  . j av a2s.c  o  m*/
 * @param dataArea  the area in which the plot should be drawn.
 * @param edge  the location of the axis.
 *
 * @return A list of ticks.
 */
protected List logRefreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = new java.util.ArrayList();

    //get lower bound value:
    double lowerBoundVal = getRange().getLowerBound();
    //if small log values and lower bound value too small
    // then set to a small value (don't allow <= 0):
    if (this.smallLogFlag && lowerBoundVal < SMALL_LOG_VALUE) {
        lowerBoundVal = SMALL_LOG_VALUE;
    }
    //get upper bound value
    double upperBoundVal = getRange().getUpperBound();

    //get log10 version of lower bound and round to integer:
    int iBegCount = (int) Math.rint(switchedLog10(lowerBoundVal));
    //get log10 version of upper bound and round to integer:
    int iEndCount = (int) Math.rint(switchedLog10(upperBoundVal));

    if (iBegCount == iEndCount && iBegCount > 0 && Math.pow(10, iBegCount) > lowerBoundVal) {
        //only 1 power of 10 value, it's > 0 and its resulting
        // tick value will be larger than lower bound of data
        --iBegCount; //decrement to generate more ticks
    }

    double tickVal;
    String tickLabel;
    boolean zeroTickFlag = false;
    for (int i = iBegCount; i <= iEndCount; i++) {
        //for each tick with a label to be displayed
        int jEndCount = 10;
        if (i == iEndCount) {
            jEndCount = 1;
        }

        for (int j = 0; j < jEndCount; j++) {
            //for each tick to be displayed
            if (this.smallLogFlag) {
                //small log values in use
                tickVal = Math.pow(10, i) + (Math.pow(10, i) * j);
                if (j == 0) {
                    //first tick of group; create label text
                    if (this.log10TickLabelsFlag) {
                        //if flag then
                        tickLabel = "10^" + i; //create "log10"-type label
                    } else { //not "log10"-type label
                        if (this.expTickLabelsFlag) {
                            //if flag then
                            tickLabel = "1e" + i; //create "1e#"-type label
                        } else { //not "1e#"-type label
                            if (i >= 0) { // if positive exponent then
                                          // make integer
                                NumberFormat format = getNumberFormatOverride();
                                if (format != null) {
                                    tickLabel = format.format(tickVal);
                                } else {
                                    tickLabel = Long.toString((long) Math.rint(tickVal));
                                }
                            } else {
                                //negative exponent; create fractional value
                                //set exact number of fractional digits to
                                // be shown:
                                this.numberFormatterObj.setMaximumFractionDigits(-i);
                                //create tick label:
                                tickLabel = this.numberFormatterObj.format(tickVal);
                            }
                        }
                    }
                } else { //not first tick to be displayed
                    tickLabel = ""; //no tick label
                }
            } else { //not small log values in use; allow for values <= 0
                if (zeroTickFlag) { //if did zero tick last iter then
                    --j;
                } //decrement to do 1.0 tick now
                tickVal = (i >= 0) ? Math.pow(10, i) + (Math.pow(10, i) * j)
                        : -(Math.pow(10, -i) - (Math.pow(10, -i - 1) * j));
                if (j == 0) { //first tick of group
                    if (!zeroTickFlag) { // did not do zero tick last
                                         // iteration
                        if (i > iBegCount && i < iEndCount && Math.abs(tickVal - 1.0) < 0.0001) {
                            // not first or last tick on graph and value
                            // is 1.0
                            tickVal = 0.0; //change value to 0.0
                            zeroTickFlag = true; //indicate zero tick
                            tickLabel = "0"; //create label for tick
                        } else {
                            //first or last tick on graph or value is 1.0
                            //create label for tick:
                            if (this.log10TickLabelsFlag) {
                                //create "log10"-type label
                                tickLabel = (((i < 0) ? "-" : "") + "10^" + Math.abs(i));
                            } else {
                                if (this.expTickLabelsFlag) {
                                    //create "1e#"-type label
                                    tickLabel = (((i < 0) ? "-" : "") + "1e" + Math.abs(i));
                                } else {
                                    NumberFormat format = getNumberFormatOverride();
                                    if (format != null) {
                                        tickLabel = format.format(tickVal);
                                    } else {
                                        tickLabel = Long.toString((long) Math.rint(tickVal));
                                    }
                                }
                            }
                        }
                    } else { // did zero tick last iteration
                        tickLabel = ""; //no label
                        zeroTickFlag = false; //clear flag
                    }
                } else { // not first tick of group
                    tickLabel = ""; //no label
                    zeroTickFlag = false; //make sure flag cleared
                }
            }

            if (tickVal > upperBoundVal) {
                return ticks; //if past highest data value then exit method
            }

            if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) {
                //tick value not below lowest data value
                TextAnchor anchor = null;
                TextAnchor rotationAnchor = null;
                double angle = 0.0;
                if (isVerticalTickLabels()) {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = -Math.PI / 2.0;
                    } else {
                        anchor = TextAnchor.BOTTOM_CENTER;
                        rotationAnchor = TextAnchor.BOTTOM_CENTER;
                        angle = Math.PI / 2.0;
                    }
                } else {
                    if (edge == RectangleEdge.LEFT) {
                        anchor = TextAnchor.CENTER_RIGHT;
                        rotationAnchor = TextAnchor.CENTER_RIGHT;
                    } else {
                        anchor = TextAnchor.CENTER_LEFT;
                        rotationAnchor = TextAnchor.CENTER_LEFT;
                    }
                }
                //create tick object and add to list:
                ticks.add(new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle));
            }
        }
    }
    return ticks;
}