Search in sources :

Example 1 with TObjectIntMap

use of gnu.trove.map.TObjectIntMap in project OpenTripPlanner by opentripplanner.

the class PointSet method buildIdIndexMapIfNeeded.

/**
 * Build the ID - Index map if needed.
 */
private synchronized void buildIdIndexMapIfNeeded() {
    // by this method in another thread while this instantiation was blocked.
    if (idIndexMap == null) {
        // make a local object, don't expose to public view until it's built
        TObjectIntMap idIndexMap = new TObjectIntHashMap<String>(this.capacity, 1f, -1);
        for (int i = 0; i < this.capacity; i++) {
            if (ids[i] != null) {
                if (idIndexMap.containsKey(ids[i])) {
                    LOG.error("Duplicate ID {} in pointset.", ids[i]);
                } else {
                    idIndexMap.put(ids[i], i);
                }
            }
        }
        // now expose to public view; reference assignment is an atomic operation
        this.idIndexMap = idIndexMap;
    }
}
Also used : TObjectIntMap(gnu.trove.map.TObjectIntMap) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap)

Example 2 with TObjectIntMap

use of gnu.trove.map.TObjectIntMap in project scheduler by btrplace.

the class CMinMigrations method injectPlacementHeuristic.

private void injectPlacementHeuristic(ReconfigurationProblem p, Parameters ps, IntVar cost) {
    List<CShareableResource> rcs = rp.getSourceModel().getViews().stream().filter(v -> v instanceof ShareableResource).map(v -> (CShareableResource) rp.getView(v.getIdentifier())).collect(Collectors.toList());
    useResources = !rcs.isEmpty();
    Model mo = p.getSourceModel();
    Mapping map = mo.getMapping();
    OnStableNodeFirst schedHeuristic = new OnStableNodeFirst(p);
    // Get the VMs to place
    Set<VM> onBadNodes = new HashSet<>(p.getManageableVMs());
    // Get the VMs that runs and have a pretty low chances to move
    Set<VM> onGoodNodes = map.getRunningVMs(map.getOnlineNodes());
    onGoodNodes.removeAll(onBadNodes);
    List<VMTransition> goodActions = p.getVMActions(onGoodNodes);
    List<VMTransition> badActions = p.getVMActions(onBadNodes);
    Solver s = p.getSolver();
    // Get the VMs to move for exclusion issue
    Set<VM> vmsToExclude = new HashSet<>(p.getManageableVMs());
    for (Iterator<VM> ite = vmsToExclude.iterator(); ite.hasNext(); ) {
        VM vm = ite.next();
        if (!(map.isRunning(vm) && p.getFutureRunningVMs().contains(vm))) {
            ite.remove();
        }
    }
    List<AbstractStrategy<?>> strategies = new ArrayList<>();
    Map<IntVar, VM> pla = VMPlacementUtils.makePlacementMap(p);
    if (!vmsToExclude.isEmpty()) {
        List<VMTransition> actions = new LinkedList<>();
        // Get all the involved slices
        for (VM vm : vmsToExclude) {
            if (p.getFutureRunningVMs().contains(vm)) {
                actions.add(p.getVMAction(vm));
            }
        }
        placeVMs(ps, strategies, actions, schedHeuristic, pla);
    }
    TObjectIntMap<VM> costs = CShareableResource.getWeights(rp, rcs);
    badActions.sort((v2, v1) -> costs.get(v1.getVM()) - costs.get(v2.getVM()));
    goodActions.sort((v2, v1) -> costs.get(v1.getVM()) - costs.get(v2.getVM()));
    placeVMs(ps, strategies, badActions, schedHeuristic, pla);
    placeVMs(ps, strategies, goodActions, schedHeuristic, pla);
    // Reinstantations. Try to reinstantiate first
    List<IntVar> migs = new ArrayList<>();
    for (VMTransition t : rp.getVMActions()) {
        if (t instanceof RelocatableVM) {
            migs.add(((RelocatableVM) t).getRelocationMethod());
        }
    }
    strategies.add(Search.intVarSearch(new FirstFail(rp.getModel()), new IntDomainMax(), migs.toArray(new IntVar[migs.size()])));
    if (!p.getNodeActions().isEmpty()) {
        // Boot some nodes if needed
        IntVar[] starts = p.getNodeActions().stream().map(Transition::getStart).toArray(IntVar[]::new);
        strategies.add(new IntStrategy(starts, new FirstFail(rp.getModel()), new IntDomainMin()));
        // Fix the duration. The side effect will be that states will be fixed as well
        // with the objective to not do un-necessary actions
        IntVar[] durations = p.getNodeActions().stream().map(Transition::getDuration).toArray(IntVar[]::new);
        strategies.add(new IntStrategy(durations, new FirstFail(rp.getModel()), new IntDomainMin()));
    }
    postCostConstraints();
    // /SCHEDULING PROBLEM
    MovementGraph gr = new MovementGraph(rp);
    IntVar[] starts = dSlices(rp.getVMActions()).map(Slice::getStart).filter(v -> !v.isInstantiated()).toArray(IntVar[]::new);
    strategies.add(new IntStrategy(starts, new StartOnLeafNodes(rp, gr), new IntDomainMin()));
    strategies.add(new IntStrategy(schedHeuristic.getScope(), schedHeuristic, new IntDomainMin()));
    IntVar[] ends = rp.getVMActions().stream().map(Transition::getEnd).filter(v -> !v.isInstantiated()).toArray(IntVar[]::new);
    strategies.add(Search.intVarSearch(new MyInputOrder<>(s), new IntDomainMin(), ends));
    // At this stage only it matters to plug the cost constraints
    strategies.add(new IntStrategy(new IntVar[] { p.getEnd(), cost }, new MyInputOrder<>(s, this), new IntDomainMin()));
    s.setSearch(new StrategiesSequencer(s.getEnvironment(), strategies.toArray(new AbstractStrategy[strategies.size()])));
}
Also used : Slice(org.btrplace.scheduler.choco.Slice) OnStableNodeFirst(org.btrplace.scheduler.choco.constraint.mttr.OnStableNodeFirst) SchedulerException(org.btrplace.scheduler.SchedulerException) Transition(org.btrplace.scheduler.choco.transition.Transition) StrategiesSequencer(org.chocosolver.solver.search.strategy.strategy.StrategiesSequencer) Solver(org.chocosolver.solver.Solver) Search(org.chocosolver.solver.search.strategy.Search) CObjective(org.btrplace.scheduler.choco.constraint.CObjective) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) IntDomainMin(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMin) TObjectIntMap(gnu.trove.map.TObjectIntMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) VM(org.btrplace.model.VM) FirstFail(org.chocosolver.solver.search.strategy.selectors.variables.FirstFail) Mapping(org.btrplace.model.Mapping) WorstFit(org.btrplace.scheduler.choco.constraint.mttr.WorstFit) Map(java.util.Map) ReconfigurationProblem(org.btrplace.scheduler.choco.ReconfigurationProblem) StartOnLeafNodes(org.btrplace.scheduler.choco.constraint.mttr.StartOnLeafNodes) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) MinMigrations(org.btrplace.model.constraint.MinMigrations) LinkedList(java.util.LinkedList) RandomVMPlacement(org.btrplace.scheduler.choco.constraint.mttr.RandomVMPlacement) Model(org.btrplace.model.Model) BiggestDimension(org.btrplace.scheduler.choco.constraint.mttr.load.BiggestDimension) Iterator(java.util.Iterator) MovementGraph(org.btrplace.scheduler.choco.constraint.mttr.MovementGraph) HostingVariableSelector(org.btrplace.scheduler.choco.constraint.mttr.HostingVariableSelector) Set(java.util.Set) MyInputOrder(org.btrplace.scheduler.choco.constraint.mttr.MyInputOrder) Parameters(org.btrplace.scheduler.choco.Parameters) Collectors(java.util.stream.Collectors) VMPlacementUtils(org.btrplace.scheduler.choco.constraint.mttr.VMPlacementUtils) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) Objects(java.util.Objects) IntVar(org.chocosolver.solver.variables.IntVar) List(java.util.List) Stream(java.util.stream.Stream) IntStrategy(org.chocosolver.solver.search.strategy.strategy.IntStrategy) ShareableResource(org.btrplace.model.view.ShareableResource) IntValueSelector(org.chocosolver.solver.search.strategy.selectors.values.IntValueSelector) Instance(org.btrplace.model.Instance) AbstractStrategy(org.chocosolver.solver.search.strategy.strategy.AbstractStrategy) IntDomainMax(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMax) Collections(java.util.Collections) Solver(org.chocosolver.solver.Solver) ArrayList(java.util.ArrayList) Mapping(org.btrplace.model.Mapping) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) AbstractStrategy(org.chocosolver.solver.search.strategy.strategy.AbstractStrategy) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) ShareableResource(org.btrplace.model.view.ShareableResource) IntVar(org.chocosolver.solver.variables.IntVar) MyInputOrder(org.btrplace.scheduler.choco.constraint.mttr.MyInputOrder) IntStrategy(org.chocosolver.solver.search.strategy.strategy.IntStrategy) IntDomainMin(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMin) FirstFail(org.chocosolver.solver.search.strategy.selectors.variables.FirstFail) StartOnLeafNodes(org.btrplace.scheduler.choco.constraint.mttr.StartOnLeafNodes) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) HashSet(java.util.HashSet) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) StrategiesSequencer(org.chocosolver.solver.search.strategy.strategy.StrategiesSequencer) LinkedList(java.util.LinkedList) MovementGraph(org.btrplace.scheduler.choco.constraint.mttr.MovementGraph) Slice(org.btrplace.scheduler.choco.Slice) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) VM(org.btrplace.model.VM) Model(org.btrplace.model.Model) Transition(org.btrplace.scheduler.choco.transition.Transition) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) OnStableNodeFirst(org.btrplace.scheduler.choco.constraint.mttr.OnStableNodeFirst) IntDomainMax(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMax)

Example 3 with TObjectIntMap

use of gnu.trove.map.TObjectIntMap in project scheduler by btrplace.

the class CMinMTTR method injectPlacementHeuristic.

private void injectPlacementHeuristic(ReconfigurationProblem p, Parameters ps, IntVar cost) {
    List<CShareableResource> rcs = rp.getSourceModel().getViews().stream().filter(v -> v instanceof ShareableResource).map(v -> (CShareableResource) rp.getView(v.getIdentifier())).collect(Collectors.toList());
    useResources = !rcs.isEmpty();
    Model mo = p.getSourceModel();
    Mapping map = mo.getMapping();
    OnStableNodeFirst schedHeuristic = new OnStableNodeFirst(p);
    // Get the VMs to place
    Set<VM> onBadNodes = new HashSet<>(p.getManageableVMs());
    // Get the VMs that runs and have a pretty low chances to move
    Set<VM> onGoodNodes = map.getRunningVMs(map.getOnlineNodes());
    onGoodNodes.removeAll(onBadNodes);
    List<VMTransition> goodActions = p.getVMActions(onGoodNodes);
    List<VMTransition> badActions = p.getVMActions(onBadNodes);
    Solver s = p.getSolver();
    // Get the VMs to move for exclusion issue
    Set<VM> vmsToExclude = new HashSet<>(p.getManageableVMs());
    for (Iterator<VM> ite = vmsToExclude.iterator(); ite.hasNext(); ) {
        VM vm = ite.next();
        if (!(map.isRunning(vm) && p.getFutureRunningVMs().contains(vm))) {
            ite.remove();
        }
    }
    List<AbstractStrategy<?>> strategies = new ArrayList<>();
    Map<IntVar, VM> pla = VMPlacementUtils.makePlacementMap(p);
    if (!vmsToExclude.isEmpty()) {
        List<VMTransition> actions = new LinkedList<>();
        // Get all the involved slices
        for (VM vm : vmsToExclude) {
            if (p.getFutureRunningVMs().contains(vm)) {
                actions.add(p.getVMAction(vm));
            }
        }
        placeVMs(ps, strategies, actions, schedHeuristic, pla);
    }
    TObjectIntMap<VM> costs = CShareableResource.getWeights(rp, rcs);
    badActions.sort((v2, v1) -> costs.get(v1.getVM()) - costs.get(v2.getVM()));
    goodActions.sort((v2, v1) -> costs.get(v1.getVM()) - costs.get(v2.getVM()));
    placeVMs(ps, strategies, badActions, schedHeuristic, pla);
    placeVMs(ps, strategies, goodActions, schedHeuristic, pla);
    // Reinstantations. Try to reinstantiate first
    List<IntVar> migs = new ArrayList<>();
    for (VMTransition t : rp.getVMActions()) {
        if (t instanceof RelocatableVM) {
            migs.add(((RelocatableVM) t).getRelocationMethod());
        }
    }
    strategies.add(Search.intVarSearch(new FirstFail(rp.getModel()), new IntDomainMax(), migs.toArray(new IntVar[migs.size()])));
    if (!p.getNodeActions().isEmpty()) {
        // Boot some nodes if needed
        IntVar[] starts = p.getNodeActions().stream().map(Transition::getStart).toArray(IntVar[]::new);
        strategies.add(new IntStrategy(starts, new FirstFail(rp.getModel()), new IntDomainMin()));
    }
    // /SCHEDULING PROBLEM
    MovementGraph gr = new MovementGraph(rp);
    IntVar[] starts = dSlices(rp.getVMActions()).map(Slice::getStart).filter(v -> !v.isInstantiated()).toArray(IntVar[]::new);
    strategies.add(new IntStrategy(starts, new StartOnLeafNodes(rp, gr), new IntDomainMin()));
    strategies.add(new IntStrategy(schedHeuristic.getScope(), schedHeuristic, new IntDomainMin()));
    IntVar[] ends = rp.getVMActions().stream().map(Transition::getEnd).filter(v -> !v.isInstantiated()).toArray(IntVar[]::new);
    strategies.add(Search.intVarSearch(new MyInputOrder<>(s), new IntDomainMin(), ends));
    // At this stage only it matters to plug the cost constraints
    strategies.add(new IntStrategy(new IntVar[] { p.getEnd(), cost }, new MyInputOrder<>(s, this), new IntDomainMin()));
    s.setSearch(new StrategiesSequencer(s.getEnvironment(), strategies.toArray(new AbstractStrategy[strategies.size()])));
}
Also used : Slice(org.btrplace.scheduler.choco.Slice) SchedulerException(org.btrplace.scheduler.SchedulerException) Transition(org.btrplace.scheduler.choco.transition.Transition) StrategiesSequencer(org.chocosolver.solver.search.strategy.strategy.StrategiesSequencer) Solver(org.chocosolver.solver.Solver) Search(org.chocosolver.solver.search.strategy.Search) CObjective(org.btrplace.scheduler.choco.constraint.CObjective) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) IntDomainMin(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMin) TObjectIntMap(gnu.trove.map.TObjectIntMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) VM(org.btrplace.model.VM) FirstFail(org.chocosolver.solver.search.strategy.selectors.variables.FirstFail) Mapping(org.btrplace.model.Mapping) Map(java.util.Map) ReconfigurationProblem(org.btrplace.scheduler.choco.ReconfigurationProblem) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) LinkedList(java.util.LinkedList) Model(org.btrplace.model.Model) BiggestDimension(org.btrplace.scheduler.choco.constraint.mttr.load.BiggestDimension) Iterator(java.util.Iterator) Set(java.util.Set) Parameters(org.btrplace.scheduler.choco.Parameters) Collectors(java.util.stream.Collectors) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) Objects(java.util.Objects) IntVar(org.chocosolver.solver.variables.IntVar) MinMTTR(org.btrplace.model.constraint.MinMTTR) List(java.util.List) Stream(java.util.stream.Stream) IntStrategy(org.chocosolver.solver.search.strategy.strategy.IntStrategy) ShareableResource(org.btrplace.model.view.ShareableResource) IntValueSelector(org.chocosolver.solver.search.strategy.selectors.values.IntValueSelector) Instance(org.btrplace.model.Instance) AbstractStrategy(org.chocosolver.solver.search.strategy.strategy.AbstractStrategy) IntDomainMax(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMax) Collections(java.util.Collections) Solver(org.chocosolver.solver.Solver) ArrayList(java.util.ArrayList) Mapping(org.btrplace.model.Mapping) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) AbstractStrategy(org.chocosolver.solver.search.strategy.strategy.AbstractStrategy) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) ShareableResource(org.btrplace.model.view.ShareableResource) IntVar(org.chocosolver.solver.variables.IntVar) IntStrategy(org.chocosolver.solver.search.strategy.strategy.IntStrategy) IntDomainMin(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMin) FirstFail(org.chocosolver.solver.search.strategy.selectors.variables.FirstFail) CShareableResource(org.btrplace.scheduler.choco.view.CShareableResource) HashSet(java.util.HashSet) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) StrategiesSequencer(org.chocosolver.solver.search.strategy.strategy.StrategiesSequencer) LinkedList(java.util.LinkedList) Slice(org.btrplace.scheduler.choco.Slice) RelocatableVM(org.btrplace.scheduler.choco.transition.RelocatableVM) VM(org.btrplace.model.VM) Model(org.btrplace.model.Model) Transition(org.btrplace.scheduler.choco.transition.Transition) VMTransition(org.btrplace.scheduler.choco.transition.VMTransition) IntDomainMax(org.chocosolver.solver.search.strategy.selectors.values.IntDomainMax)

Example 4 with TObjectIntMap

use of gnu.trove.map.TObjectIntMap in project BiomeTweaker by superckl.

the class ScriptCommandMaxSpawnPackSize method perform.

@Override
public void perform() throws Exception {
    if (this.entityClass == null) {
        EntityEventHandler.setGlobalPackSize(this.size);
        return;
    }
    Class<?> clazz;
    try {
        clazz = Class.forName(this.entityClass);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Failed to load entity class: " + this.entityClass, e);
    }
    final Iterator<Biome> it = this.pack.getIterator();
    while (it.hasNext()) {
        final Biome biome = it.next();
        final TIntObjectMap<TObjectIntMap<String>> map = EntityEventHandler.getPackSizes();
        if (!map.containsKey(Biome.getIdForBiome(biome)))
            map.put(Biome.getIdForBiome(biome), new TObjectIntHashMap<String>());
        map.get(Biome.getIdForBiome(biome)).put(clazz.getName(), this.size);
    }
}
Also used : TObjectIntMap(gnu.trove.map.TObjectIntMap) Biome(net.minecraft.world.biome.Biome) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap)

Example 5 with TObjectIntMap

use of gnu.trove.map.TObjectIntMap in project OpenTripPlanner by opentripplanner.

the class ConvertToFrequency method apply.

public void apply(List<FrequencyEntry> frequencyEntries, List<TripTimes> scheduledTrips, Graph graph, BitSet servicesRunning, RaptorWorkerTimetable.BoardingAssumption assumption) {
    // preserve existing frequency entries
    this.frequencyEntries.addAll(frequencyEntries);
    Set<String> routeIds = new HashSet<>();
    if (routeId != null)
        Stream.of(routeId).forEach(routeIds::add);
    // loop over scheduled trips and figure out what to do with them
    for (TripTimes tt : scheduledTrips) {
        if (routeId == null || routeIds.contains(tt.trip.getRoute().getId().getId())) {
            // put this in the appropriate group for frequency conversion
            String key;
            switch(groupBy) {
                case ROUTE_DIRECTION:
                    key = tt.trip.getRoute().getId().getId() + "_" + tt.trip.getDirectionId();
                    break;
                case ROUTE:
                    key = tt.trip.getRoute().getId().getId();
                    break;
                case PATTERN:
                    key = graph.index.patternForTrip.get(tt.trip).getExemplar().getId().getId();
                    break;
                default:
                    throw new RuntimeException("Unrecognized group by value");
            }
            tripsToConvert.put(key, tt);
        } else {
            // don't touch this trip
            this.scheduledTrips.add(tt);
        }
    }
    // loop over all the groups and create frequency entries
    GROUPS: for (Map.Entry<String, Collection<TripTimes>> e : tripsToConvert.asMap().entrySet()) {
        // get just the running services
        List<TripTimes> group = e.getValue().stream().filter(tt -> servicesRunning.get(tt.serviceCode)).filter(tt -> windowStart < tt.getDepartureTime(0) && tt.getDepartureTime(0) < windowEnd).collect(Collectors.toList());
        if (group.isEmpty())
            continue GROUPS;
        if (group.size() == 1) {
            group.stream().forEach(scheduledTrips::add);
            continue GROUPS;
        }
        // find the dominant pattern
        TObjectIntMap<TripPattern> patternCount = new TObjectIntHashMap<>(5, 0.75f, 0);
        group.forEach(tt -> patternCount.adjustOrPutValue(graph.index.patternForTrip.get(tt.trip), 1, 1));
        int maxCount = 0;
        TripPattern tripPattern = null;
        for (TObjectIntIterator<TripPattern> it = patternCount.iterator(); it.hasNext(); ) {
            it.advance();
            if (it.value() > maxCount) {
                maxCount = it.value();
                tripPattern = it.key();
            }
        }
        // find a stop that is common to all trip patterns. Sort the list so that the same common stop is always returned
        NavigableSet<Stop> stops = new TreeSet<>((s1, s2) -> s1.getId().compareTo(s2.getId()));
        stops.addAll(tripPattern.getStops());
        patternCount.keySet().stream().forEach(p -> stops.retainAll(p.getStops()));
        if (stops.isEmpty()) {
            LOG.warn("Unable to find common stop for key {}, not converting to frequencies", e.getKey());
            scheduledTrips.addAll(e.getValue());
            continue GROUPS;
        }
        Stop stop = stops.stream().findFirst().get();
        // determine the median frequency at this stop
        // use a set to handle duplicated trips
        TIntSet arrivalTimes = new TIntHashSet();
        for (boolean filter : new boolean[] { true, false }) {
            for (TripTimes tt : group) {
                TripPattern tp = graph.index.patternForTrip.get(tt.trip);
                int arrivalTime = tt.getArrivalTime(tp.getStops().indexOf(stop));
                // however, if we apply the filter and end up with no trips at this stop, re-run with the filter disabled
                if (windowStart < arrivalTime && arrivalTime < windowEnd || !filter)
                    arrivalTimes.add(arrivalTime);
            }
            // if we didn't find stops, continue, which will turn off the filter
            if (arrivalTimes.size() > 1)
                break;
        }
        // now convert to elapsed times
        int[] arrivalTimeArray = arrivalTimes.toArray();
        Arrays.sort(arrivalTimeArray);
        int[] headway = new int[arrivalTimeArray.length - 1];
        for (int i = 1; i < arrivalTimeArray.length; i++) {
            headway[i - 1] = arrivalTimeArray[i] - arrivalTimeArray[i - 1];
        }
        Arrays.sort(headway);
        // the headway that we will use
        int aggregateHeadway;
        if (assumption == RaptorWorkerTimetable.BoardingAssumption.WORST_CASE)
            // simple: worst case analysis should use the worst case headway
            aggregateHeadway = Ints.max(headway);
        else {
            // we want the average headway, but we we want the average of the headways weighted
            // by themselves as if there is a two minute headway then a twenty-minute headway,
            // customers are ten times as likely to experience the twenty minute headway
            // (we want the average from the user's perspective, not the vehicle's perspective)
            // This is a weighted average where the weight is the same as the headway so it simplifies
            // to sum (headway^2) / sum(headway)
            aggregateHeadway = IntStream.of(headway).map(h -> h * h).sum() / IntStream.of(headway).sum();
        }
        LOG.info("Headway for route {} ({}) in direction {}: {}min", tripPattern.route.getShortName(), tripPattern.route.getId().getId(), tripPattern.directionId, aggregateHeadway / 60);
        // figure out running/dwell times based on the trips on this pattern
        final TripPattern chosenTp = tripPattern;
        List<TripTimes> candidates = group.stream().filter(tt -> graph.index.patternForTrip.get(tt.trip) == chosenTp).collect(Collectors.toList());
        // transposed from what you'd expect: stops on the rows
        int[][] hopTimes = new int[tripPattern.getStops().size() - 1][candidates.size()];
        int[][] dwellTimes = new int[tripPattern.getStops().size()][candidates.size()];
        int tripIndex = 0;
        for (TripTimes tt : candidates) {
            for (int stopIndex = 0; stopIndex < tripPattern.getStops().size(); stopIndex++) {
                dwellTimes[stopIndex][tripIndex] = tt.getDwellTime(stopIndex);
                if (stopIndex > 0)
                    hopTimes[stopIndex - 1][tripIndex] = tt.getArrivalTime(stopIndex) - tt.getDepartureTime(stopIndex - 1);
            }
            tripIndex++;
        }
        // collapse it down
        int[] meanHopTimes = new int[tripPattern.getStops().size() - 1];
        int hopIndex = 0;
        for (int[] hop : hopTimes) {
            meanHopTimes[hopIndex++] = IntStream.of(hop).sum() / hop.length;
        }
        int[] meanDwellTimes = new int[tripPattern.getStops().size()];
        int dwellIndex = 0;
        for (int[] dwell : dwellTimes) {
            meanDwellTimes[dwellIndex++] = IntStream.of(dwell).sum() / dwell.length;
        }
        // phew! now let's make a frequency entry
        TripTimes tt = new TripTimes(candidates.get(0));
        int cumulative = 0;
        for (int i = 0; i < tt.getNumStops(); i++) {
            tt.updateArrivalTime(i, cumulative);
            cumulative += meanDwellTimes[i];
            tt.updateDepartureTime(i, cumulative);
            if (i + 1 < tt.getNumStops())
                cumulative += meanHopTimes[i];
        }
        FrequencyEntry fe = new FrequencyEntry(windowStart - 60 * 60 * 3, windowEnd + 60 * 60 * 3, aggregateHeadway, false, tt);
        this.frequencyEntries.add(fe);
    }
}
Also used : IntStream(java.util.stream.IntStream) java.util(java.util) Logger(org.slf4j.Logger) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TObjectIntHashMap(gnu.trove.map.hash.TObjectIntHashMap) LoggerFactory(org.slf4j.LoggerFactory) Multimap(com.google.common.collect.Multimap) Ints(com.google.common.primitives.Ints) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) Collectors(java.util.stream.Collectors) TObjectIntMap(gnu.trove.map.TObjectIntMap) TIntSet(gnu.trove.set.TIntSet) TIntHashSet(gnu.trove.set.hash.TIntHashSet) RaptorWorkerTimetable(org.opentripplanner.profile.RaptorWorkerTimetable) HashMultimap(com.google.common.collect.HashMultimap) TObjectIntIterator(gnu.trove.iterator.TObjectIntIterator) Stop(org.onebusaway.gtfs.model.Stop) Stream(java.util.stream.Stream) Graph(org.opentripplanner.routing.graph.Graph) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TObjectIntMap(gnu.trove.map.TObjectIntMap) Stop(org.onebusaway.gtfs.model.Stop) TIntSet(gnu.trove.set.TIntSet) TObjectIntIterator(gnu.trove.iterator.TObjectIntIterator) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TripPattern(org.opentripplanner.routing.edgetype.TripPattern) TIntHashSet(gnu.trove.set.hash.TIntHashSet) FrequencyEntry(org.opentripplanner.routing.trippattern.FrequencyEntry) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Aggregations

TObjectIntMap (gnu.trove.map.TObjectIntMap)5 TObjectIntHashMap (gnu.trove.map.hash.TObjectIntHashMap)3 Collectors (java.util.stream.Collectors)3 Stream (java.util.stream.Stream)3 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Map (java.util.Map)2 Objects (java.util.Objects)2 Set (java.util.Set)2 Instance (org.btrplace.model.Instance)2 Mapping (org.btrplace.model.Mapping)2 Model (org.btrplace.model.Model)2 VM (org.btrplace.model.VM)2 ShareableResource (org.btrplace.model.view.ShareableResource)2 SchedulerException (org.btrplace.scheduler.SchedulerException)2 Parameters (org.btrplace.scheduler.choco.Parameters)2