Example usage for com.google.common.collect LinkedHashMultiset create

List of usage examples for com.google.common.collect LinkedHashMultiset create

Introduction

In this page you can find the example usage for com.google.common.collect LinkedHashMultiset create.

Prototype

public static <E> LinkedHashMultiset<E> create(Iterable<? extends E> elements) 

Source Link

Document

Creates a new LinkedHashMultiset containing the specified elements.

Usage

From source file:com.github.fhirschmann.clozegen.lib.util.MultisetUtils.java

/**
 * Sorts a multiset by its counts and returns a new {@link LinkedHashMultiset}.
 *
 * @param <E> the type of the multiset elements
 * @param multiset to multiset to sort/*  w w  w. ja va  2  s  .  c  om*/
 * @return a new mutable sorted multiset
 */
public static <E> LinkedHashMultiset<E> sortMultiSet(final Multiset<E> multiset) {
    final ImmutableMultiset<E> immutableSet = Multisets.copyHighestCountFirst(multiset);
    return LinkedHashMultiset.create(immutableSet);
}

From source file:com.github.fhirschmann.clozegen.lib.util.MultisetUtils.java

/**
 * Merges two multisets./*w  w  w . j a va2  s  . c  o m*/
 *
 * @param <E> the type of the elements of both multisets
 * @param multiset1 multiset to merge
 * @param multiset2 multiset to merge
 * @return a new merged multiset
 */
public static <E> Multiset<E> mergeMultiSets(final Multiset<E> multiset1, final Multiset<E> multiset2) {
    final Multiset<E> multiset = LinkedHashMultiset.create(multiset1);
    Iterators.addAll(multiset, multiset2.iterator());
    return multiset;
}

From source file:com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle.java

/**
 * Change the route this vehicle is following. The route must adhere to the
 * following requirements:/* w  ww.j  av a2 s .  c o m*/
 * <ul>
 * <li>Parcels that have not yet been picked up can at maximum occur twice in
 * the route.</li>
 * <li>Parcels that have been picked up can occur at maximum once in the
 * route.</li>
 * <li>Parcels that are delivered may not occur in the route.</li>
 * </ul>
 * These requirements are <b>not</b> checked defensively! It is the callers
 * responsibility to make sure this is the case. Note that the underlying
 * models normally <i>should</i> throw exceptions whenever a vehicle attempts
 * to revisit an already delivered parcel.
 * <p>
 * In some cases the models do not allow this vehicle to change its route
 * immediately. If this is the case the route is changed the next time this
 * vehicle enters its {@link #waitState}. If
 * {@link #isDelayedRouteChangingAllowed()} is set to <code>false</code> any
 * attempts to do this will result in a runtime exception, in this case the
 * caller must ensure that a route can be changed immediately or call this
 * method at a later time. The situations when the route is changed
 * immediately are:
 * <ul>
 * <li>If the vehicle is waiting.</li>
 * <li>If diversion is allowed and the vehicle is not currently servicing.
 * </li>
 * <li>If the current route is empty.</li>
 * <li>If the first destination in the new route equals the first destination
 * of the current route.</li>
 * </ul>
 * @param r The route to set. The elements are copied from the
 *          {@link Iterable} using its iteration order.
 */
public void setRoute(Iterable<? extends Parcel> r) {
    final Iterable<Parcel> adjustedRoute = routeAdjuster.adjust(r, this);
    LOGGER.trace("{} setRoute {}", this, adjustedRoute);

    // note: the following checks can not detect if a parcel has been set to
    // multiple vehicles at the same time
    final Multiset<Parcel> routeSet = LinkedHashMultiset.create(adjustedRoute);
    for (final Parcel dp : routeSet.elementSet()) {
        final ParcelState state = getPDPModel().getParcelState(dp);
        checkArgument(!state.isDelivered(),
                "A parcel that is already delivered can not be part of a route. " + "Parcel %s in route %s.",
                dp, adjustedRoute);
        if (state.isTransitionState()) {
            if (state == ParcelState.PICKING_UP) {
                checkArgument(getPDPModel().getVehicleState(this) == VehicleState.PICKING_UP,
                        "When a parcel in the route is in PICKING UP state the vehicle "
                                + "must also be in that state, route: %s.",
                        adjustedRoute, getPDPModel().getVehicleState(this));
            } else {
                checkArgument(getPDPModel().getVehicleState(this) == VehicleState.DELIVERING,
                        "When a parcel in the route is in DELIVERING state the vehicle"
                                + " must also be in that state.");
            }
            checkArgument(getPDPModel().getVehicleActionInfo(this).getParcel() == dp,
                    "A parcel in the route that is being serviced should be serviced by"
                            + " this truck. This truck is servicing %s.",
                    getPDPModel().getVehicleActionInfo(this).getParcel());
        }

        final int frequency = routeSet.count(dp);
        if (state.isPickedUp()) {
            checkArgument(getPDPModel().getContents(this).contains(dp),
                    "A parcel that is in cargo state must be in cargo of this " + "vehicle.");
            checkArgument(frequency <= 1, "A parcel that is in cargo may not occur more than once in a route,"
                    + " found %s instance(s) of %s.", frequency, dp, state);
        } else {
            checkArgument(frequency <= 2,
                    "A parcel that is available may not occur more than twice in a "
                            + "route, found %s instance(s) of %s (with state %s). Route: %s.",
                    frequency, dp, state, adjustedRoute);
        }
    }

    final boolean firstEqualsFirst = firstEqualsFirstInRoute(adjustedRoute);
    final boolean divertable = isDiversionAllowed && !stateMachine.stateIs(serviceState);

    if (stateMachine.stateIs(waitState) || route.isEmpty() || divertable || firstEqualsFirst) {
        route = newLinkedList(adjustedRoute);
        newRoute = Optional.absent();
    } else {
        checkArgument(allowDelayedRouteChanges,
                "Diversion is not allowed in current state and delayed route changes "
                        + "are also not allowed, rejected route: %s.",
                adjustedRoute);
        newRoute = Optional.of(newLinkedList(adjustedRoute));
    }
}

From source file:de.bund.bfr.knime.pmmlite.core.PmmUtils.java

public static <T> T getMaxCounted(Collection<T> values) {
    return Collections.max(LinkedHashMultiset.create(values).entrySet(),
            (o1, o2) -> Integer.compare(o1.getCount(), o2.getCount())).getElement();
}

From source file:com.github.rinde.logistics.pdptw.mas.comm.RtSolverBidder.java

@SuppressWarnings({ "null", "unused" })
void reauction() {
    if (!reauctionsEnabled || assignedParcels.isEmpty()) {
        return;/*  w ww.ja v a  2 s.  co  m*/
    }
    LOGGER.trace("{} Considering a reauction, assignedParcels: {}.", decorator, assignedParcels.size());
    final ImmutableList<Parcel> currentRoute = ImmutableList.copyOf(((Truck) vehicle.get()).getRoute());
    final GlobalStateObject state = solverHandle.get()
            .getCurrentState(SolveArgs.create().noCurrentRoutes().useParcels(assignedParcels));
    final StatisticsDTO stats = Solvers.computeStats(state, ImmutableList.of(currentRoute));

    final Parcel lastReceivedParcel = Iterables.getLast(assignedParcels);

    if (!reauctioning.get()) {
        // find all swappable parcels, a parcel can be swapped if it is not yet in
        // cargo (it must occur twice in route for that)
        // TODO filter out parcels that will be visited within several seconds
        // (length of auction)
        final Multiset<Parcel> routeMultiset = LinkedHashMultiset.create(currentRoute);
        final Set<Parcel> swappableParcels = new LinkedHashSet<>();
        for (final Parcel ap : assignedParcels) {
            if (!pdpModel.get().getParcelState(ap).isPickedUp()
                    && !pdpModel.get().getParcelState(ap).isTransitionState()
                    && !state.getVehicles().get(0).getDestination().asSet().contains(ap)
                    && !ap.equals(lastReceivedParcel)) {
                swappableParcels.add(ap);
            }
        }

        final double baseline = objectiveFunction.computeCost(stats);
        double lowestCost = baseline;
        @Nullable
        Parcel toSwap = null;

        LOGGER.trace("Compute cost of swapping");
        for (final Parcel sp : swappableParcels) {
            final List<Parcel> newRoute = new ArrayList<>();
            newRoute.addAll(currentRoute);
            newRoute.removeAll(Collections.singleton(sp));
            final double cost = objectiveFunction
                    .computeCost(Solvers.computeStats(state, ImmutableList.of(ImmutableList.copyOf(newRoute))));
            if (cost < lowestCost) {
                lowestCost = cost;
                toSwap = sp;
            }
        }

        // we have found the most expensive parcel in the route, that is, removing
        // this parcel from the route will yield the greatest cost reduction.
        if (toSwap != null && !reauctioning.get() && !toSwap.equals(lastReceivedParcel)) {

            final Auctioneer<DoubleBid> auct = parcelAuctioneers.get(toSwap);
            if (auct.getLastUnsuccessTime() > 0
                    && state.getTime() - auct.getLastUnsuccessTime() <= reauctionCooldownPeriod) {
                LOGGER.trace("Not reauctioning, was unsuccessful too recently");
                return;
            }

            // try to reauction
            reauctioning.set(true);
            LOGGER.trace("Found most expensive parcel for reauction: {}.", toSwap);

            final double bidValue = bidFunction.computeBidValue(currentRoute.size(), lowestCost - baseline);
            final DoubleBid initialBid = DoubleBid.create(state.getTime(), decorator, toSwap, bidValue);

            auct.auctionParcel(decorator, state.getTime(), initialBid, new Listener() {
                @Override
                public void handleEvent(Event e) {
                    reauctioning.set(false);
                }
            });
        }
    }
}

From source file:com.github.rinde.rinsim.central.Solvers.java

static GlobalStateObject fixRoutes(GlobalStateObject state) {
    boolean firstVehicle = true;
    final ImmutableList.Builder<VehicleStateObject> vehicleList = ImmutableList.builder();
    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject vso = state.getVehicles().get(i);
        checkArgument(vso.getRoute().isPresent());

        final List<Parcel> route = new ArrayList<>(vso.getRoute().get());
        final Multiset<Parcel> routeContents = LinkedHashMultiset.create(route);
        for (final Parcel p : routeContents.elementSet()) {
            if (vso.getContents().contains(p)) {
                // should occur only once
                if (routeContents.count(p) > 1) {
                    // remove
                    route.remove(p);//from   w  w  w .j a va2  s  . co m
                    checkArgument(routeContents.count(p) == 2);
                }
            } else {
                // should occur twice
                if (routeContents.count(p) < 2) {
                    route.add(p);
                } else {
                    checkArgument(routeContents.count(p) == 2);
                }
            }
        }

        if (firstVehicle) {
            final Set<Parcel> unassigned = GlobalStateObjects.unassignedParcels(state);
            route.addAll(unassigned);
            route.addAll(unassigned);
            firstVehicle = false;
        }

        vehicleList.add(VehicleStateObject.create(vso.getDto(), vso.getLocation(), vso.getContents(),
                vso.getRemainingServiceTime(), vso.getDestination().orNull(), ImmutableList.copyOf(route)));

    }
    return GlobalStateObject.create(state.getAvailableParcels(), vehicleList.build(), state.getTime(),
            state.getTimeUnit(), state.getSpeedUnit(), state.getDistUnit());
}