Skip to content

Commit

Permalink
fixed issues, removed todos
Browse files Browse the repository at this point in the history
  • Loading branch information
rakow committed Mar 31, 2024
1 parent 2e73198 commit 18d1f50
Show file tree
Hide file tree
Showing 9 changed files with 237 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,37 @@ public PlanCandidate(String[] modes, double utility) {
this.utility = utility;
}

/**
* Return features vector with number of occurrences per mode.
*/
public static double[] occurrences(List<String> modes, String type) {

double[] ft = new double[modes.size()];

for (int i = 0; i < modes.size(); i++) {
int count = StringUtils.countMatches(type, modes.get(i));
ft[i] = count;
}

return ft;
}

/**
* Creates array of selected modes from plan type.
*/
public static String[] createModeArray(String planType) {
String[] modes = planType.split("-");
for (int i = 0; i < modes.length; i++) {

if (modes[i].equals("null"))
modes[i] = null;
else
modes[i] = modes[i].intern();
}

return modes;
}

/**
* Total estimated utility.
*/
Expand All @@ -39,6 +70,7 @@ public double getUtility() {

/**
* Get mode for trip i. Indexing starts at 0.
*
* @see #size()
*/
public String getMode(int i) {
Expand Down Expand Up @@ -71,25 +103,10 @@ public int size() {
return modes.length;
}

/**
* Return features vector with number of occurrences per mode.
*/
public static double[] occurrences(List<String> modes, String type) {

double[] ft = new double[modes.size()];

for (int i = 0; i < modes.size(); i++) {
int count = StringUtils.countMatches(type, modes.get(i));
ft[i] = count;
}

return ft;
}

/**
* Applies the routing modes of this candidate to a plan.
*
* @param plan plan to apply the modes to
* @param plan plan to apply the modes to
* @param partial if true, only trips that have changed mode will be replaced
*/
public void applyTo(Plan plan, boolean partial) {
Expand Down Expand Up @@ -119,15 +136,16 @@ public void applyTo(Plan plan, boolean partial) {
continue;

// don't update the trip if it has the same mode
if (currentType != null && currentType.length > k && currentType[k].equals(mode)) {
// k-1, because k was already incremented
if (currentType != null && currentType.length > k - 1 && currentType[k - 1].equals(mode)) {
continue;
}

// Replaces all trip elements and inserts single leg
final List<PlanElement> fullTrip =
planElements.subList(
planElements.indexOf(trip.getOriginActivity()) + 1,
planElements.indexOf(trip.getDestinationActivity()));
planElements.subList(
planElements.indexOf(trip.getOriginActivity()) + 1,
planElements.indexOf(trip.getDestinationActivity()));

fullTrip.clear();
Leg leg = PopulationUtils.createLeg(mode);
Expand Down Expand Up @@ -171,22 +189,6 @@ public String getPlanType() {
return b.toString().intern();
}

/**
* Creates array of selected modes from plan type.
*/
public static String[] createModeArray(String planType) {
String[] modes = planType.split("-");
for (int i = 0; i < modes.length; i++) {

if (modes[i].equals("null"))
modes[i] = null;
else
modes[i] = modes[i].intern();
}

return modes;
}

@Override
public int compareTo(PlanCandidate o) {
return Double.compare(o.utility, utility);
Expand All @@ -209,7 +211,7 @@ public int hashCode() {
@Override
public String toString() {
return "PlanCandidate{" +
"modes=" + Arrays.toString(modes) +
", utility=" + utility + '}';
"modes=" + Arrays.toString(modes) +
", utility=" + utility + '}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.matsim.core.controler.AbstractModule;
import org.matsim.core.replanning.choosers.StrategyChooser;
import org.matsim.core.replanning.strategies.DefaultPlanStrategiesModule;
import org.matsim.modechoice.replanning.WorstNotSelctedPlanSelector;
import org.matsim.modechoice.replanning.scheduled.AllBestPlansStrategyProvider;
import org.matsim.modechoice.replanning.scheduled.ReRouteSelectedStrategyProvider;
import org.matsim.modechoice.replanning.scheduled.ScheduledStrategyChooser;
Expand Down Expand Up @@ -101,11 +102,10 @@ public void install() {
int target = (int) Math.ceil(iters / getConfig().replanning().getFractionOfIterationsToDisableInnovation());

log.info("Adjusting number of iterations from {} to {}.", getConfig().controller().getLastIteration(), target);
getConfig().controller().setLastIteration(iters);
getConfig().controller().setLastIteration(target);
}

// bindPlanSelectorForRemoval().to()
// getConfig().replanning().setPlanSelectorForRemoval();
bindPlanSelectorForRemoval().to(WorstNotSelctedPlanSelector.class);

}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/* *********************************************************************** *
* project: org.matsim.*
* WorstPlanSelector.java
* *
* *********************************************************************** *
* *
* copyright : (C) 2009 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */

package org.matsim.modechoice.replanning;

import it.unimi.dsi.fastutil.objects.Object2IntMap;
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
import org.matsim.api.core.v01.population.HasPlansAndId;
import org.matsim.api.core.v01.population.Person;
import org.matsim.api.core.v01.population.Plan;
import org.matsim.core.replanning.selectors.PlanSelector;

/**
* See {@link org.matsim.core.replanning.selectors.WorstPlanForRemovalSelector}.
* This class is the same except the selected plan is not removed.
*/
public class WorstNotSelctedPlanSelector implements PlanSelector<Plan, Person> {

private static final String UNDEFINED_TYPE = "undefined";

@Override
public Plan selectPlan(HasPlansAndId<Plan, Person> person) {

// hashmap that returns "Integer" count for given plans type:
Object2IntMap<String> typeCounts = new Object2IntOpenHashMap<>();

// count how many plans per type an agent has:
for (Plan plan : person.getPlans()) {
String type = plan.getType();
if ( type==null ) {
type = UNDEFINED_TYPE ;
}
typeCounts.merge( type, 1, Integer::sum);
}

Plan worst = null;
double worstScore = Double.POSITIVE_INFINITY;
for (Plan plan : person.getPlans()) {

String type = plan.getType();
if ( type==null ) {
type = UNDEFINED_TYPE;
}
if ( person.getSelectedPlan() != plan && typeCounts.getInt( type ) > 1) {
// (if we have more than one plan of the same type:)

// if this plan has no score yet:
if (plan.getScore() == null || plan.getScore().isNaN() ) {
// say that the plan without score now is the "worst":
worst = plan;

// make sure that this one remains the selected plan:
worstScore = Double.NEGATIVE_INFINITY;

// otherwise do the usual logic to find the plan with the minimum score:
} else if ( plan.getScore() < worstScore) {
worst = plan;
worstScore = plan.getScore();
}
}
// (otherwise we just keep "worst=null")

}

if (worst == null) {
// there is exactly one plan, or we have of each plan-type exactly one.
// select the one with worst score globally, or the first one with score=null
for (Plan plan : person.getPlans()) {
if (plan.getScore() == null || plan.getScore().isNaN() ) {
return plan;
}
if (plan != person.getSelectedPlan() && plan.getScore() < worstScore) {
worst = plan;
worstScore = plan.getScore();
}
}
}
return worst;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,6 @@ public GenericPlanStrategy<Plan, Person> chooseStrategy(HasPlansAndId<Plan, Pers
double[] w = new double[weights.size()];
double total = 0;

if (replanningContext.getIteration() > 4)
total = 0;

int iterType = isScheduledIteration(replanningContext, scheduleConfig);

for (int i = 0; i < weights.size(); i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ public final class AgentSchedule {
*/
final String[] planCategories;

/**
* Aggregated weights for each plan category.
*/
final byte[] weights;
/**
* Number of trips in each plan.
*/
Expand All @@ -37,15 +41,17 @@ public final class AgentSchedule {
*/
int currentPlan = -1;

AgentSchedule(Id<Person> id, String[] planCategories, int length) {
AgentSchedule(Id<Person> id, String[] planCategories, byte[] weights, int length) {
this.id = id;
this.planCategories = planCategories;
this.weights = weights;
this.length = length;
}

private AgentSchedule(AgentSchedule other) {
this.id = other.id;
this.planCategories = other.planCategories;
this.weights = other.weights;
this.availablePlans.addAll(other.availablePlans);
this.indices.addAll(other.indices);
this.currentPlan = other.currentPlan;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,13 @@ void printScore(int offset) {

log.info("Targets: {} | Switches: {}", targets, switchTarget);
for (int i = 0; i < windowSize; i++) {
log.info("Iteration: {} | Target: {} | Switches: {}", (offset + i), scorer.getObserved()[i], scorer.getSwitches()[i]);

StringBuilder b = new StringBuilder();
for (int k = 0; k < targets.size(); k++) {
b.append(scorer.getObserved()[i * targets.size() + k]).append(" ");
}

log.info("Iteration: {} | Target: {}| Switches: {}", (offset + i), b.toString(), scorer.getSwitches()[i]);
}
}

Expand Down
Loading

0 comments on commit 18d1f50

Please sign in to comment.