Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development #1

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion contribs/railsim/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,65 @@
<scope>test</scope>
</dependency>

</dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.63.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.63.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.63.0</version>
</dependency>
<dependency> <!-- necessary for Java 9+ -->
<groupId>org.apache.tomcat</groupId>
<artifactId>annotations-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.63.0</version>
<scope>compile</scope>
</dependency>


</dependencies>

<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.7.1</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.25.1:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.63.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
package ch.sbb.matsim.contrib.railsim;
import ch.sbb.matsim.contrib.railsim.rl.RLClient;
import io.grpc.Grpc;
import io.grpc.InsecureServerCredentials;
import io.grpc.Server;
import io.grpc.stub.StreamObserver;
import ch.sbb.matsim.contrib.railsim.grpc.ProtoConfirmationResponse;
import ch.sbb.matsim.contrib.railsim.grpc.ProtoGrpcPort;
import ch.sbb.matsim.contrib.railsim.grpc.RailsimFactoryGrpc;
import ch.sbb.matsim.contrib.railsim.grpc.ProtoAgentIDs;
import org.matsim.api.core.v01.Scenario;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.scenario.ScenarioUtils;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
public class EnvironmentFactoryServer {

private static final Logger logger = Logger.getLogger(EnvironmentFactoryServer.class.getName());

private Server server;

private void start() throws IOException {
/* The port on which the server should run */
int factoryServerPort = 50051;
server = Grpc.newServerBuilderForPort(factoryServerPort, InsecureServerCredentials.create())
.addService(new RailsimFactory())
.build()
.start();
logger.info("Server started, listening on " + factoryServerPort);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
System.err.println("*** shutting down gRPC server since JVM is shutting down");
try {
EnvironmentFactoryServer.this.stop();
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
System.err.println("*** server shut down");
}
});
}

private void stop() throws InterruptedException {
if (server != null) {
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
}
}

/**
* Await termination on the main thread since the grpc library uses daemon threads.
*/
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}

/**
* Main launches the server from the command line.
*/
public static void main(String[] args) throws IOException, InterruptedException {
final EnvironmentFactoryServer server = new EnvironmentFactoryServer();
server.start();
server.blockUntilShutdown();
}


// Implementation of the gRPC service on the server-side.
private class RailsimFactory extends RailsimFactoryGrpc.RailsimFactoryImplBase {

Map<Integer, RailsimEnv> envMap = new HashMap<>();
@Override
public void getEnvironment(ProtoGrpcPort grpcPort, StreamObserver<ProtoConfirmationResponse> responseObserver) {
// Create an instance of Railsim environment and store it in a map
System.out.println("getEnvironment() -> Create env with id: "+grpcPort);

RLClient rlClient = new RLClient(grpcPort.getGrpcPort());
RailsimEnv env = new RailsimEnv(rlClient);

// Store the environment created with its key being the port
this.envMap.put(grpcPort.getGrpcPort(), env);

// Send the Ack message back to the client.
ProtoConfirmationResponse response = ProtoConfirmationResponse.newBuilder()
.setAck("OK")
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}

// TODO: Send the config name in the request body.
public void resetEnv(ProtoGrpcPort grpcPort, StreamObserver<ProtoAgentIDs> responseObserver) {
System.out.println("Reset env id: "+grpcPort);

String configFilename = "/Users/akashsinha/Documents/SBB/matsim-libs/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml";
// String configFilename = "/Users/akashsinha/Documents/SBB/matsim-libs/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microJunctionY/config.xml";
// String configFilename = "/Users/akashsinha/Documents/SBB/matsim-libs/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microStationRerouting/config.xml";


// fetch the object from map and reset it
RailsimEnv env = this.envMap.get(grpcPort.getGrpcPort());
List<String> agentIds = env.reset(configFilename);

//Create response using agentIds
ProtoAgentIDs response = ProtoAgentIDs.newBuilder()
.addAllAgentId(agentIds)
.build();

// Send the reply back to the client.
responseObserver.onNext(response);

// Indicate that no further messages will be sent to the client.
responseObserver.onCompleted();

// Start the simulation
//TODO: Should this be started on a different thread so that the endpoint is not blocked or is it automatically taken care of?
try{
env.startSimulation();
}finally{
env.shutdown();
}
}

public void getAgentIds(ProtoGrpcPort grpcPort, StreamObserver<ProtoAgentIDs> responseObserver){
String configFilename = "/Users/akashsinha/Documents/SBB/matsim-libs/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml";
Config config = ConfigUtils.loadConfig(configFilename);
Scenario scenario = ScenarioUtils.loadScenario(config);
RailsimEnv env = this.envMap.get(grpcPort.getGrpcPort());

List<String> agentIds = env.getAllTrainIds(scenario);
//Create response using agentIds
ProtoAgentIDs response = ProtoAgentIDs.newBuilder()
.addAllAgentId(agentIds)
.build();

// Send the reply back to the client.
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package ch.sbb.matsim.contrib.railsim;

//import ch.sbb.matsim.contrib.railsim.rl.RLClient;

import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimQSimModule;
import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimRLDispositionModule;
import ch.sbb.matsim.contrib.railsim.rl.RLClient;
import org.matsim.api.core.v01.Id;
import org.matsim.api.core.v01.Scenario;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.controler.Controler;
import org.matsim.core.controler.OutputDirectoryHierarchy;
import org.matsim.core.scenario.ScenarioUtils;
import org.matsim.pt.transitSchedule.api.Departure;
import org.matsim.pt.transitSchedule.api.TransitLine;
import org.matsim.pt.transitSchedule.api.TransitRoute;
import org.matsim.vehicles.Vehicle;


import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class RailsimEnv {
RLClient rlClient; // RLClient would be needed by RailsimEngine.
Controler controler;

public RailsimEnv(RLClient rlClient){
this.rlClient = rlClient;
}

public List<String> getAllTrainIds(Scenario scenario){

List<String> trainIds = new ArrayList<>();

List<TransitLine> transitLines = scenario.getTransitSchedule().getTransitLines().values().stream().collect(Collectors.toList());
for (TransitLine trainLine : transitLines){
List<TransitRoute> transitRoutes = trainLine.getRoutes().values().stream().collect(Collectors.toList());
for (TransitRoute transitRoute: transitRoutes){
List<Departure> departures= transitRoute.getDepartures().values().stream().collect(Collectors.toList());
for(Departure departure: departures){
Id<Vehicle> ID = departure.getVehicleId();
trainIds.add(ID.toString());
}
}
}
return trainIds;
}

public List<String> reset(String configFilename){

Config config = ConfigUtils.loadConfig(configFilename);
config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);
config.controller().setLastIteration(0);
config.controller().setDumpDataAtEnd(true);
config.controller().setCreateGraphs(false);

Scenario scenario = ScenarioUtils.loadScenario(config);
controler = new Controler(scenario);

controler.addOverridingModule(new RailsimModule());
controler.addOverridingQSimModule(new RailsimRLDispositionModule(rlClient));

// if you have other extensions that provide QSim components, call their configure-method here
controler.configureQSimComponents(components -> new RailsimQSimModule().configure(components));

// get all train Ids in this scenario.
return getAllTrainIds(scenario);
}

void startSimulation(){
controler.run();
}

void shutdown(){
this.rlClient.shutdown();
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

package ch.sbb.matsim.contrib.railsim;

import ch.sbb.matsim.contrib.railsim.qsimengine.RailsimRLDispositionModule;
import ch.sbb.matsim.contrib.railsim.rl.RLClient;
import org.matsim.api.core.v01.Scenario;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
Expand All @@ -42,20 +44,24 @@ public static void main(String[] args) {
if (args.length != 0) {
configFilename = args[0];
} else {
configFilename = "test/input/ch/sbb/matsim/contrib/railsim/integration/microOlten/config.xml";
configFilename = "/Users/akashsinha/Documents/SBB/matsim-libs/contribs/railsim/test/input/ch/sbb/matsim/contrib/railsim/integration/microTrackOppositeTrafficMany/config.xml";
}

Config config = ConfigUtils.loadConfig(configFilename);
config.controller().setOverwriteFileSetting(OutputDirectoryHierarchy.OverwriteFileSetting.deleteDirectoryIfExists);
config.controller().setLastIteration(0);
config.controller().setDumpDataAtEnd(true);
config.controller().setCreateGraphs(false);

Scenario scenario = ScenarioUtils.loadScenario(config);
Controler controler = new Controler(scenario);

controler.addOverridingModule(new RailsimModule());
controler.addOverridingQSimModule(new RailsimRLDispositionModule(new RLClient(9000)));


// if you have other extensions that provide QSim components, call their configure-method here
controler.configureQSimComponents(components -> new RailsimQSimModule().configure(components));

controler.run();
}

Expand Down
Loading