Example usage for org.joda.time Duration Duration

List of usage examples for org.joda.time Duration Duration

Introduction

In this page you can find the example usage for org.joda.time Duration Duration.

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:com.github.dbourdette.otto.data.DataTableUtils.java

License:Apache License

/**
 * Finds best Duration of rows for a {@link SimpleDataTable} based on given table interval
 *///from   w  ww  .ja va  2s.  c o  m
public static Duration findBest(Interval interval) {
    Duration duration = new Duration(interval.getStart(), interval.getEnd());

    if (duration.isShorterThan(ONE_DAY) || duration.equals(ONE_DAY)) {
        return Duration.standardMinutes(5);
    } else if (duration.isShorterThan(FIVE_DAYS) || duration.equals(FIVE_DAYS)) {
        return Duration.standardMinutes(30);
    } else {
        return Duration.standardDays(1);
    }
}

From source file:com.github.rinde.gpem17.eval.Evaluate.java

License:Apache License

public static ExperimentResults execute(Iterable<GPProgram<GpGlobal>> programs, boolean realtime,
        FileProvider.Builder scenarioFiles, File resDir, boolean createTimeStampedResDir,
        @Nullable Function<Scenario, Scenario> scenarioConverter, boolean createTmpFiles, ReauctOpt reauctOpt,
        Gendreau06ObjectiveFunction objFuncUsedAtRuntime, RpOpt routePlanner, boolean enableTimeMeasurements,
        boolean addOptaPlannerMAS, long heuristicComputationDelay, String... expArgs) {
    checkArgument(realtime ^ scenarioConverter != null);
    final long startTime = System.currentTimeMillis();

    if (createTimeStampedResDir) {
        resDir = createExperimentDir(resDir);
    } else {//from   ww  w .java  2 s .c om
        resDir.mkdirs();
    }

    boolean evolution = scenarioConverter != null;

    ResultWriter rw = new VanLonHolvoetResultWriter(resDir, GPEM17.OBJ_FUNC,
            scenarioFiles.build().get().iterator().next().getParent().toString(), realtime, true,
            createTmpFiles, evolution);
    Experiment.Builder exp = Experiment.builder().addScenarios(scenarioFiles).showGui(GPEM17.gui())
            .showGui(false)
            .usePostProcessor(new GpemPostProcessor(GPEM17.OBJ_FUNC,
                    evolution ? FailureStrategy.INCLUDE : FailureStrategy.RETRY, false))
            .computeLocal().withRandomSeed(123).repeat(3)
            // SEED_REPS,REPS,SCENARIO,CONFIG
            .withOrdering(SimulationProperty.SEED_REPS, SimulationProperty.REPS, SimulationProperty.SCENARIO,
                    SimulationProperty.CONFIG)

            .addResultListener(rw);

    if (!realtime) {
        exp.addResultListener(new SimRuntimeLogger(resDir));
    }
    if (realtime) {
        exp.setScenarioReader(ScenarioIO.readerAdapter(ScenarioConverter.TO_ONLINE_REALTIME_250))
                .withWarmup(30000).addResultListener(new CommandLineProgress(System.out))
                .withThreads((int) Math.floor((Runtime.getRuntime().availableProcessors() - 1) / 2d));
    } else if (scenarioConverter == null) {
        exp.setScenarioReader(ScenarioIO.readerAdapter(ScenarioConverter.TO_ONLINE_SIMULATED_250))
                .addResultListener(new CommandLineProgress(System.out));
    } else {
        exp.setScenarioReader(ScenarioIO.readerAdapter(scenarioConverter));
    }

    if (addOptaPlannerMAS) {
        exp.addConfiguration(createOptaPlanner(enableTimeMeasurements));
    }

    int counter = 0;
    StringBuilder sb = new StringBuilder();
    for (GPProgram<GpGlobal> prog : programs) {
        String progId = "c" + counter++;
        sb.append(progId).append(" = ").append(prog.getId()).append(System.lineSeparator());

        if (realtime) {
            exp.addConfiguration(GPEM17.createRtConfig(prog, progId, reauctOpt, objFuncUsedAtRuntime,
                    routePlanner, enableTimeMeasurements, heuristicComputationDelay));
        } else {
            exp.addConfiguration(GPEM17.createStConfig(prog, progId, reauctOpt, objFuncUsedAtRuntime,
                    enableTimeMeasurements));
        }
    }

    try {
        Files.write(sb, new File(rw.getExperimentDirectory(), "configs.txt"), Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    final Optional<ExperimentResults> results = exp.perform(System.out, expArgs);
    final long duration = System.currentTimeMillis() - startTime;
    if (!results.isPresent()) {
        return null;
    }

    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    System.out.println("Done, computed " + results.get().getResults().size() + " simulations in "
            + duration / 1000d + "s (" + PeriodFormat.getDefault().print(dur.toPeriod()) + ")");
    return results.get();
}

From source file:com.github.rinde.gpem17.evo.StatsLogger.java

License:Apache License

public void finalStatistics(final EvolutionState state, final int result) {
    super.finalStatistics(state, result);

    // convert to ms duration
    final Duration dur = new Duration(startTime, System.nanoTime()).dividedBy(1000000L);

    System.out.println("End of evolutionary run.");
    System.out.println("Total runtime: " + PeriodFormat.getDefault().print(dur.toPeriod()));

    File firstGenDir = new File(experimentDirectory, "/generation0");
    File lastGenDir = new File(experimentDirectory, "/generation" + state.generation);

    while (lastGenDir.listFiles().length != firstGenDir.listFiles().length) {
        System.out.println("Waiting for all results to be written to disk.");
        try {// w w w.jav  a 2  s. c o  m
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
    System.out.println("Done.");

}

From source file:com.github.rinde.rinsim.experiment.CommandLineProgress.java

License:Apache License

@Override
public void receive(SimulationResult result) {
    if (result.getResultObject() instanceof FailureStrategy) {
        failures++;/*  w  w  w.  j a  v a  2 s  .co  m*/
    } else {
        received++;
    }
    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    printStream.println(Joiner.on("").join(received, SLASH, total, " (failures: ", failures, ", duration: ",
            PeriodFormat.getDefault().print(dur.toPeriod()), ", memory free/total/max (M): ", memorySummary(),
            ")"));
}

From source file:com.github.rinde.rinsim.experiment.CommandLineProgress.java

License:Apache License

@Override
public void doneComputing(ExperimentResults results) {
    final Duration dur = new Duration(startTime, System.currentTimeMillis());
    printStream.println("Computing done, duration: " + PeriodFormat.getDefault().print(dur.toPeriod()) + ".");
    printMemorySummary(printStream);//from   w  w w. j  av a2s. c  o m
}

From source file:com.google.android.apps.forscience.whistlepunk.review.TimestampPickerController.java

License:Open Source License

public String getTimeString() {
    Duration duration;//from  ww w  .j a v  a 2  s.  c  o  m
    String prefix = "";
    if (mSelectedTime.isAfter(mZeroTime) || mSelectedTime.isEqual(mZeroTime)) {
        duration = new Duration(mZeroTime, mSelectedTime);
    } else {
        duration = new Duration(mSelectedTime, mZeroTime);
        prefix = mNegativePrefix;
    }
    return prefix + mPeriodFormatter.print(duration.toPeriod());
}

From source file:com.google.cloud.dataflow.sdk.transforms.windowing.TimeTrigger.java

License:Apache License

@VisibleForTesting
static Instant alignedTo(Instant point, Duration size, Instant offset) {
    long millisSinceStart = new Duration(offset, point).getMillis() % size.getMillis();
    return millisSinceStart == 0 ? point : point.plus(size).minus(millisSinceStart);
}

From source file:com.google.sampling.experiential.server.MigrationBackendServlet.java

License:Open Source License

private void convertScheduleTimeLongsToSignalTimeObjects() {
    long t1 = System.currentTimeMillis();
    log.info("Starting convertScheduleTimes from Long to SignalTime objects");
    PersistenceManager pm = null;//from   w ww .  j  a  va  2 s .c  o  m
    try {
        pm = PMF.get().getPersistenceManager();
        javax.jdo.Query newQuery = pm.newQuery(Experiment.class);
        List<Experiment> updatedExperiments = Lists.newArrayList();
        List<Experiment> experiments = (List<Experiment>) newQuery.execute();
        for (Experiment experiment : experiments) {
            SignalSchedule schedule = experiment.getSchedule();
            if (schedule != null && schedule.getSignalTimes().isEmpty()) {
                if (schedule.getScheduleType() != SignalScheduleDAO.SELF_REPORT
                        && schedule.getScheduleType() != SignalScheduleDAO.ESM) {
                    log.info("Converting for experiment: " + experiment.getTitle());
                    List<SignalTime> signalTimes = Lists.newArrayList();
                    List<Long> times = schedule.getTimes();
                    for (Long long1 : times) {
                        signalTimes.add(new SignalTime(null, SignalTimeDAO.FIXED_TIME,
                                SignalTimeDAO.OFFSET_BASIS_SCHEDULED_TIME, (int) long1.longValue(),
                                SignalTimeDAO.MISSED_BEHAVIOR_USE_SCHEDULED_TIME, 0, ""));
                    }
                    schedule.setSignalTimes(signalTimes);
                    experiment.setSchedule(schedule);
                    updatedExperiments.add(experiment);
                }
            }
        }
        pm.makePersistentAll(updatedExperiments);
    } finally {
        pm.close();
    }
    long t2 = System.currentTimeMillis();
    long seconds = new Duration(t1, t2).getStandardSeconds();
    log.info("Done converting signal times. " + seconds + "seconds to complete");
}

From source file:com.hamdikavak.humanmobility.modeling.FirstPassageTime.java

License:Open Source License

/**
 * Returns first passage time, the probability to find a person in the same
 * place after a period of time.//from w  w  w  .  j  a va2s . c  o  m
 * 
 * @param traces
 *            Location traces of an individual sorted from old to new. If
 *            GPS locations are used, these locations have to be clustered
 *            using a classification algorithm such as DBSCAN and assigned a
 *            location id. If cellphone towers are used, tower id should be
 *            enough.
 * 
 * @return All hour differences between a person's first appearance in a
 *         place vs. all consequent appearances.
 */
public List<Long> calculateFirstPassageTime(List<ExtendedLocationTrace> traces) {

    ExtendedLocationTrace firstElementOfThisUniqueId;
    List<Long> uniqueLocationIds = new ArrayList<Long>();
    HashMap<Long, Boolean> oneLocationHourList = null;
    List<Long> entireHourList = new ArrayList<Long>();

    // identify all unique locations
    uniqueLocationIds = extractUniqueLocationIds(traces);

    // for each unique location
    //   - find the first record that location appears in user's location
    //     trace history
    //   - find other records regarding visits to the same place and find time
    //     difference between that record and the first record.
    //   - keep all hour differences in a list

    for (Long aUniqueLocationId : uniqueLocationIds) {
        firstElementOfThisUniqueId = null;
        oneLocationHourList = new HashMap<Long, Boolean>();
        logger.info("FPT location  id:" + aUniqueLocationId);

        for (int i = 0; i < traces.size(); i++) {
            if (traces.get(i).getLocationId() == aUniqueLocationId) {

                // if this is the first appearance, mark as first
                if (firstElementOfThisUniqueId == null) {
                    firstElementOfThisUniqueId = traces.get(i);
                    continue;
                }

                // calculate the time interval between visits to this
                // location
                Long hourDifference = (long) new Duration(firstElementOfThisUniqueId.getUTCTime(),
                        traces.get(i).getUTCTime()).toStandardHours().getHours();

                // let's make sure hour difference is not larger than our
                // intended hour investigation length
                if (hourDifference <= lengthInHours) {
                    // we keep hour appearances in a hashmap key to ensure we
                    // do not overestimate multiple very close location
                    // reports.
                    oneLocationHourList.put(hourDifference, true);
                }

            }
        }
        entireHourList.addAll(oneLocationHourList.keySet());
    }
    List<Long> result = new ArrayList<Long>();
    for (int i = 0; i < entireHourList.size(); i++) {
        result.add(entireHourList.get(i));
    }
    return result;
}

From source file:com.hamdikavak.humanmobility.modeling.LocationReport.java

License:Open Source License

/**
 * //from   ww  w.ja v a  2s .  c om
 * @param date1 first event date
 * @param date2 second event date
 * @param unit time unit
 * @return duration duration (default millisecond)
 */
private long calculateDuration(DateTime date1, DateTime date2, TimeUnit unit) {

    if (unit == TimeUnit.SECONDS) {
        return Math.abs(new Duration(date1, date2).getStandardSeconds());
    } else if (unit == TimeUnit.MINUTES) {
        return Math.abs(new Duration(date1, date2).getStandardMinutes());
    } else if (unit == TimeUnit.HOURS) {
        return Math.abs(new Duration(date1, date2).getStandardHours());
    } else if (unit == TimeUnit.DAYS) {
        return Math.abs(new Duration(date1, date2).getStandardDays());
    }

    return 0;
}