Skip to content

Commit

Permalink
improve how guice bindings are used
Browse files Browse the repository at this point in the history
  • Loading branch information
rakow committed Oct 13, 2023
1 parent 0477a37 commit ac11b92
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 122 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import org.matsim.contrib.drt.speedup.DrtSpeedUpParams;
import org.matsim.core.controler.events.IterationEndsEvent;
import org.matsim.core.controler.listener.IterationEndsListener;
import org.matsim.core.modal.ModalInjector;
import org.matsim.core.utils.misc.OptionalTime;

import java.util.SplittableRandom;
Expand All @@ -41,23 +40,13 @@ public class BasicDrtEstimator implements DrtEstimator, IterationEndsListener {
private GlobalEstimate currentEst;
private RegressionResults fare;

@Inject
public BasicDrtEstimator(ModalInjector injector) {
public BasicDrtEstimator(DrtEventSequenceCollector collector, DrtEstimatorConfigGroup config,
DrtConfigGroup drtConfig, DrtSpeedUpParams speedUpParams) {
//zones = injector.getModal(DrtZonalSystem.class);
collector = injector.getModal(DrtEventSequenceCollector.class);
config = injector.getModal(DrtEstimatorConfigGroup.class);
drtConfig = injector.getModal(DrtConfigGroup.class);

DrtSpeedUpParams modal;
try {
DrtSpeedUp speedUp = injector.getModal(DrtSpeedUp.class);
modal = speedUp.getParams();
} catch (Exception e) {
modal = null;
// speed-up not installed
}

speedUpParams = modal;
this.collector = collector;
this.config = config;
this.drtConfig = drtConfig;
this.speedUpParams = speedUpParams;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import org.matsim.core.controler.listener.AfterMobsimListener;
import org.matsim.core.controler.listener.ShutdownListener;
import org.matsim.core.controler.listener.StartupListener;
import org.matsim.core.modal.ModalInjector;
import org.matsim.core.utils.misc.OptionalTime;

import java.io.IOException;
Expand All @@ -40,10 +39,10 @@ public final class DrtEstimateAnalyzer implements StartupListener, ShutdownListe

private CSVPrinter csv;

public DrtEstimateAnalyzer(ModalInjector injector) {
estimator = injector.getModal(DrtEstimator.class);
collector = injector.getModal(DrtEventSequenceCollector.class);
config = injector.getModal(DrtEstimatorConfigGroup.class);
public DrtEstimateAnalyzer(DrtEstimator estimator, DrtEventSequenceCollector collector, DrtEstimatorConfigGroup config) {
this.estimator = estimator;
this.collector = collector;
this.config = config;
}

@Override
Expand Down Expand Up @@ -99,7 +98,7 @@ private Iterable<Number> calcMetrics(int iteration) {
for (DrtEventSequenceCollector.EventSequence seq : collector.getPerformedRequestSequences().values()) {
if (seq.getPickedUp().isPresent() && seq.getDroppedOff().isPresent()) {

// TODO: many attributes are not filled
// many attributes are not filled, when using the constructor
DrtRoute route = new DrtRoute(seq.getSubmitted().getFromLinkId(), seq.getSubmitted().getToLinkId());
route.setDirectRideTime(seq.getSubmitted().getUnsharedRideTime());
route.setDistance(seq.getSubmitted().getUnsharedRideDistance());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,23 @@
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.matsim.api.core.v01.TransportMode;
import org.matsim.contrib.drt.extension.estimator.BasicDrtEstimator;
import org.matsim.contrib.drt.extension.estimator.DrtEstimator;
import org.matsim.contrib.drt.run.DrtConfigGroup;
import org.matsim.contrib.dvrp.run.Modal;
import org.matsim.contrib.util.ReflectiveConfigGroupWithConfigurableParameterSets;

public class DrtEstimatorConfigGroup extends ReflectiveConfigGroupWithConfigurableParameterSets implements Modal {

private static final Logger log = LogManager.getLogger(DrtConfigGroup.class);
/**
* Type of estimator, which will be installed in {@link DrtEstimatorModule}.
*/
public enum EstimatorType {
BASIC,

/**
* Custom estimator, that needs to provided via binding.
*/
CUSTOM
}

public static final String GROUP_NAME = "drtEstimator";

Expand All @@ -34,21 +39,20 @@ public DrtEstimatorConfigGroup(String mode) {
public String mode = TransportMode.drt;

@Parameter
@Comment("Fully qualified class name of the estimator that should be used.")
@Comment("Estimator typed to be used. In case of 'CUSTOM', guice bindings needs to be provided.")
@NotNull
public Class<? extends DrtEstimator> estimator = BasicDrtEstimator.class;
public EstimatorType estimator = EstimatorType.BASIC;

@Parameter
@Comment("Decay of the exponential moving average.")
@Positive
public double decayFactor = 0.5;

@Parameter
@Comment("Randomize estimates with standard deviation")
@Comment("Factor multiplied with standard deviation to randomize estimates.")
@PositiveOrZero
public double randomization = 0.1;


@Override
public String getMode() {
return mode;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
package org.matsim.contrib.drt.extension.estimator.run;

import com.google.inject.Singleton;
import org.matsim.contrib.drt.analysis.DrtEventSequenceCollector;
import org.matsim.contrib.drt.extension.estimator.BasicDrtEstimator;
import org.matsim.contrib.drt.extension.estimator.DrtEstimateAnalyzer;
import org.matsim.contrib.drt.extension.estimator.DrtEstimator;
import org.matsim.contrib.drt.run.DrtConfigGroup;
import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup;
import org.matsim.contrib.drt.speedup.DrtSpeedUp;
import org.matsim.contrib.drt.speedup.DrtSpeedUpParams;
import org.matsim.contrib.dvrp.run.AbstractDvrpModeModule;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.controler.AbstractModule;
import org.matsim.core.modal.ModalInjector;
import org.matsim.core.modal.ModalProviders;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;

/**
* Main module that needs to be installed if any estimator is to be used.
Expand All @@ -20,44 +23,63 @@ public class DrtEstimatorModule extends AbstractModule {
@Override
public void install() {

MultiModeDrtEstimatorConfigGroup config = ConfigUtils.addOrGetModule(getConfig(), MultiModeDrtEstimatorConfigGroup.class);
MultiModeDrtConfigGroup drtConfigs = MultiModeDrtConfigGroup.get(getConfig());
MultiModeDrtEstimatorConfigGroup configs = ConfigUtils.addOrGetModule(getConfig(), MultiModeDrtEstimatorConfigGroup.class);

for (DrtEstimatorConfigGroup group : config.getModalElements()) {
install(new ModeModule(group));
for (DrtConfigGroup cfg : drtConfigs.getModalElements()) {

Optional<DrtEstimatorConfigGroup> estCfg = configs.getModalElement(cfg.mode);

estCfg.ifPresent(drtEstimatorConfigGroup -> install(new ModeModule(cfg, drtEstimatorConfigGroup)));
}
}

static final class ModeModule extends AbstractDvrpModeModule {

private final DrtConfigGroup cfg;
private final DrtEstimatorConfigGroup group;

public ModeModule(DrtEstimatorConfigGroup group) {
public ModeModule(DrtConfigGroup cfg, DrtEstimatorConfigGroup group) {
super(group.mode);
this.cfg = cfg;
this.group = group;
}

@Override
public void install() {

bindModal(DrtEstimator.class).toProvider(modalProvider(
// try with default injections and overwrite
if (group.estimator == DrtEstimatorConfigGroup.EstimatorType.BASIC) {
bindModal(DrtEstimator.class).toProvider(modalProvider(
getter -> {
DrtSpeedUpParams modal = null;
try {
Constructor<? extends DrtEstimator> constructor = group.estimator.getDeclaredConstructor(ModalInjector.class);
return constructor.newInstance(ModalProviders.createInjector(getter));
} catch (NoSuchMethodException e) {
throw new RuntimeException("Could not find constructor for DRT estimator. You need to have a public constructor with one parameter accepting ModalInjector", e);
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Could not instantiate DRT estimator", e);
DrtSpeedUp speedUp = getter.getModal(DrtSpeedUp.class);
modal = speedUp.getParams();
} catch (Exception e) {
// This happens if the speed-up is not installed
// there is no other way to check it
}

return new BasicDrtEstimator(getter.getModal(DrtEventSequenceCollector.class),
group,
cfg,
modal);
}
)).in(Singleton.class);
)).in(Singleton.class);
}

addControlerListenerBinding().to(modalKey(DrtEstimator.class));

bindModal(DrtEstimatorConfigGroup.class).toInstance(group);

// Needs to run before estimators
bindModal(DrtEstimateAnalyzer.class).toProvider(modalProvider(getter -> new DrtEstimateAnalyzer(ModalProviders.createInjector(getter)))).in(Singleton.class);
bindModal(DrtEstimateAnalyzer.class)
.toProvider(
modalProvider(getter -> new DrtEstimateAnalyzer(getter.getModal(DrtEstimator.class), getter.getModal(DrtEventSequenceCollector.class), group))
)
.in(Singleton.class);

addControlerListenerBinding().to(modalKey(DrtEstimateAnalyzer.class));

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package org.matsim.contrib.drt.extension.estimator.run;

import java.util.Collection;
import java.util.Optional;
import java.util.function.Supplier;

import org.matsim.contrib.dvrp.run.MultiModal;
Expand Down Expand Up @@ -91,4 +92,12 @@ public void addParameterSet(DrtEstimatorConfigGroup set) {
public Collection<DrtEstimatorConfigGroup> getModalElements() {
return (Collection<DrtEstimatorConfigGroup>)getParameterSets(DrtEstimatorConfigGroup.GROUP_NAME);
}

/**
* Find estimator config for specific mode.
*/
public Optional<DrtEstimatorConfigGroup> getModalElement(String mode) {
return getModalElements().stream().filter(m -> m.getMode().equals(mode)).findFirst();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ public void install() {
getter.getModal(DrtEventSequenceCollector.class)))).asEagerSingleton();
addControlerListenerBinding().to(modalKey(DrtSpeedUp.class));
});

bindModal(DefaultStopTimeCalculator.class).toProvider(modalProvider(getter -> {
return new DefaultStopTimeCalculator(drtCfg.stopDuration);
})).in(Singleton.class);

bindModal(StopTimeCalculator.class).to(modalKey(DefaultStopTimeCalculator.class));

install(new AdaptiveTravelTimeMatrixModule(drtCfg.mode));
Expand Down
21 changes: 0 additions & 21 deletions matsim/src/main/java/org/matsim/core/modal/ModalInjector.java

This file was deleted.

42 changes: 0 additions & 42 deletions matsim/src/main/java/org/matsim/core/modal/ModalInjectorImpl.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,6 @@ public T get() {
};
}

/**
* Creates modal injector from getter.
*/
public static ModalInjectorImpl createInjector(InstanceGetter<? extends Annotation> getter) {
return new ModalInjectorImpl(getter);
}

public static final class InstanceGetter<M extends Annotation> {
private final String mode;
private final Injector injector;
Expand Down

0 comments on commit ac11b92

Please sign in to comment.