Skip to content

Commit

Permalink
Use java 8 features
Browse files Browse the repository at this point in the history
  • Loading branch information
Mathieu Bague committed Nov 9, 2016
1 parent c286e8c commit c444f93
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ private static class ImporterWrapper implements Importer {

private final List<String> names;

public ImporterWrapper(Importer importer, ComputationManager computationManager, List<String> names) {
ImporterWrapper(Importer importer, ComputationManager computationManager, List<String> names) {
this.importer = importer;
this.computationManager = computationManager;
this.names = names;
Expand Down Expand Up @@ -250,13 +250,10 @@ public static void importAll(Path dir, Importer importer, boolean parallel, Cons
importAll(dir, importer, dataSources);
if (parallel) {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<Future<?>> futures = new ArrayList<>();
try {
for (ReadOnlyDataSource dataSource : dataSources) {
futures.add(executor.submit(() -> {
doImport(dataSource, importer, consumer, listener);
}));
}
List<Future<?>> futures = dataSources.stream()
.map(ds -> executor.submit(() -> doImport(ds, importer, consumer, listener)))
.collect(Collectors.toList());
for (Future<?> future : futures) {
future.get();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ public String getDescription() {
}

@Override
@SuppressWarnings("static-access")
public Options getOptions() {
Options options = new Options();
options.addOption(Option.builder().longOpt("case-file")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ public String getDescription() {
}

@Override
@SuppressWarnings("static-access")
public Options getOptions() {
Options options = new Options();
options.addOption(Option.builder().longOpt("case-file")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ private SynchronizedHistoDbClient(HistoDbClient delegate) {
public HistoDbStats queryStats(Set<HistoDbAttributeId> attrIds, Interval interval, HistoDbHorizon horizon, boolean async) throws IOException, InterruptedException {
lock.lock();
try {
HistoDbStats stats = super.queryStats(attrIds, interval, horizon, async);
return stats;
return super.queryStats(attrIds, interval, horizon, async);
} finally {
lock.unlock();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,6 @@ public class LocalOnlineApplication extends NotificationBroadcasterSupport imple

private final ComputationManager computationManager;

private final ScheduledExecutorService ses;

private final ExecutorService es;

private final boolean enableJmx;

private OnlineWorkflow workflow ;
Expand Down Expand Up @@ -110,8 +106,6 @@ public class LocalOnlineApplication extends NotificationBroadcasterSupport imple

private final ScheduledFuture<?> future;

private final Map<String, OnlineWorkflowImpl> workflows = new ConcurrentHashMap<>();

private final TIntArrayList busyCores;

private final Lock listenersLock = new ReentrantLock();
Expand All @@ -129,8 +123,6 @@ public LocalOnlineApplication(OnlineConfig config,
MBeanRegistrationException, MalformedObjectNameException, NotCompliantMBeanException, IOException {
this.config = config;
this.computationManager = computationManager;
this.ses = ses;
this.es = es;

LOGGER.info("Version: {}", Version.VERSION);

Expand All @@ -152,15 +144,11 @@ public LocalOnlineApplication(OnlineConfig config,

}

future = ses.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
try {
notifyBusyCoresUpdate(false);
} catch (Throwable t) {
LOGGER.error(t.toString(), t);
}
future = ses.scheduleAtFixedRate(() -> {
try {
notifyBusyCoresUpdate(false);
} catch (Throwable t) {
LOGGER.error(t.toString(), t);
}
}, 0, 20, TimeUnit.SECONDS);
}
Expand Down Expand Up @@ -278,14 +266,10 @@ public void startWorkflow( OnlineWorkflowStartParameters start, OnlineWorkflowPa
OnlineApplicationListener listener = startParams.getOnlineApplicationListenerFactoryClass().newInstance().create();
workflow.addOnlineApplicationListener(listener);
}
} catch (InstantiationException e ) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}

try {
workflow.start(oCtx);
} catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,30 @@
*/
public interface LocalOnlineApplicationMBean {

public static final String BEAN_NAME = "eu.itesla_project.online:type=LocalOnlineApplicationMBean";
String BEAN_NAME = "eu.itesla_project.online:type=LocalOnlineApplicationMBean";

public static final String BUSY_CORES_ATTRIBUTE = "BusyCores";
String BUSY_CORES_ATTRIBUTE = "BusyCores";

public static final String WORK_STATES_ATTRIBUTE = "WorkflowStates";
String WORK_STATES_ATTRIBUTE = "WorkflowStates";

public static final String RUNNING_ATTRIBUTE = "Running";
String RUNNING_ATTRIBUTE = "Running";

public static final String WCA_RUNNING_ATTRIBUTE = "WcaRunning";
String WCA_RUNNING_ATTRIBUTE = "WcaRunning";

public static final String STATES_ACTIONS_ATTRIBUTE = "StateActions";
String STATES_ACTIONS_ATTRIBUTE = "StateActions";

// public static final String STABLE_CONTINGENCIES_ATTRIBUTE = "StableContingencies";
// String STABLE_CONTINGENCIES_ATTRIBUTE = "StableContingencies";

public static final String STATES_INDEXES_ATTRIBUTE = "StatesIndexes";
String STATES_INDEXES_ATTRIBUTE = "StatesIndexes";

public static final String INDEXES_SECURITY_RULES_ATTRIBUTE ="IndexSecurityRulesResults";
String INDEXES_SECURITY_RULES_ATTRIBUTE ="IndexSecurityRulesResults";

//public static final String UNSTABLE_CONTINGENCIES_ATTRIBUTE = "UnstableContingencies";
// String UNSTABLE_CONTINGENCIES_ATTRIBUTE = "UnstableContingencies";

public static final String WCA_CONTINGENCIES_ATTRIBUTE = "WcaContingencies";
String WCA_CONTINGENCIES_ATTRIBUTE = "WcaContingencies";

//Apogée
public static final String GENERATE_CARD_ATTRIBUTE = "Card";
//Apogee
// String GENERATE_CARD_ATTRIBUTE = "Card";

void ping();

Expand Down
31 changes: 15 additions & 16 deletions online-workflow/src/main/java/eu/itesla_project/online/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,20 @@ public class Utils {
private static final String EMPTY_CONTINGENCY_ID = "Empty-Contingency";

public static String actionsToJson(OnlineWorkflowResults wfResults, String contingencyId, Integer stateId) {
Map<String, Object> actionInfo = new HashMap<String, Object>();
Map<String, Object> actionInfo = new HashMap<>();
actionInfo.put("actions_found", wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId));
actionInfo.put("status", wfResults.getStateStatus(contingencyId, stateId));
List<Object> actions = new ArrayList<Object>();
List<Object> actions = new ArrayList<>();
for (String actionId : wfResults.getActionsIds(contingencyId, stateId)) {
if ( wfResults.getEquipmentsIds(contingencyId, stateId, actionId) != null
&& !wfResults.getEquipmentsIds(contingencyId, stateId, actionId).isEmpty() ) {
Map<String, Object> action = new HashMap<String, Object>();
List<Object> equipments = new ArrayList<Object>();
Map<String, Object> action = new HashMap<>();
List<Object> equipments = new ArrayList<>();
for (String equipmentId : wfResults.getEquipmentsIds(contingencyId, stateId, actionId)) {
ActionParameters actionParameters = wfResults.getParameters(contingencyId, stateId, actionId, equipmentId);
if ( actionParameters != null && !actionParameters.getNames().isEmpty() ) {
Map<String, Map<String, Object>> equipment = new HashMap<String, Map<String,Object>>();
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Map<String, Object>> equipment = new HashMap<>();
Map<String, Object> params = new HashMap<>();
for(String param : actionParameters.getNames()) {
params.put(param, actionParameters.getValue(param));
}
Expand All @@ -64,26 +64,26 @@ public static String actionsToJson(OnlineWorkflowResults wfResults, String conti
}

public static String actionsToJsonExtended(OnlineWorkflowResults wfResults, String contingencyId, Integer stateId) {
Map<String, Object> actionInfo = new HashMap<String, Object>();
Map<String, Object> actionInfo = new HashMap<>();
actionInfo.put("actions_found", wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId));
actionInfo.put("status", wfResults.getStateStatus(contingencyId, stateId));
String cause = wfResults.getCause(contingencyId, stateId);
if ( cause != null )
actionInfo.put("cause", cause);
if ( wfResults.getActionsIds(contingencyId, stateId) != null && !wfResults.getActionsIds(contingencyId, stateId).isEmpty() ) {
List<Object> actions = new ArrayList<Object>();
List<Object> actions = new ArrayList<>();
for (String actionId : wfResults.getActionsIds(contingencyId, stateId)) {
Map<String, Object> action = new HashMap<String, Object>();
Map<String, Object> action = new HashMap<>();
action.put("action_id", actionId);
if ( wfResults.getEquipmentsIds(contingencyId, stateId, actionId) != null
&& !wfResults.getEquipmentsIds(contingencyId, stateId, actionId).isEmpty() ) {
List<Object> equipments = new ArrayList<Object>();
List<Object> equipments = new ArrayList<>();
for (String equipmentId : wfResults.getEquipmentsIds(contingencyId, stateId, actionId)) {
Map<String, Object> equipment = new HashMap<String, Object>();
Map<String, Object> equipment = new HashMap<>();
equipment.put("equipment_id", equipmentId);
ActionParameters actionParameters = wfResults.getParameters(contingencyId, stateId, actionId, equipmentId);
if ( actionParameters != null && !actionParameters.getNames().isEmpty() ) {
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Object> params = new HashMap<>();
for(String param : actionParameters.getNames()) {
params.put(param, actionParameters.getValue(param));
}
Expand All @@ -109,13 +109,12 @@ public static Map<String, Boolean> runTDSimulation(Network network, Set<String>
ComputationManager computationManager, SimulatorFactory simulatorFactory,
ContingenciesAndActionsDatabaseClient contingencyDb,
Writer metricsContent) throws Exception {
Map<String, Boolean> tdSimulationResults = new HashMap<String, Boolean>();
Map<String, Boolean> tdSimulationResults = new HashMap<>();
Map<String, Object> initContext = new HashMap<>();
SimulationParameters simulationParameters = SimulationParameters.load();
// run stabilization
Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0);
stabilization.init(simulationParameters, initContext);
ImpactAnalysis impactAnalysis = null;
System.out.println("running stabilization on network " + network.getId());
StabilizationResult stabilizationResults = stabilization.run();
metricsContent.write("****** BASECASE " + network.getId()+"\n");
Expand All @@ -131,10 +130,10 @@ public static Map<String, Boolean> runTDSimulation(Network network, Set<String>
tdSimulationResults.put(EMPTY_CONTINGENCY_ID, true);
// check if there are contingencies to run impact analysis
if ( contingencyIds==null && contingencyDb.getContingencies(network).size()==0 )
contingencyIds = new HashSet<String>();
contingencyIds = new HashSet<>();
if ( contingencyIds==null || !contingencyIds.isEmpty() ) {
// run impact analysis
impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingencyDb);
ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingencyDb);
impactAnalysis.init(simulationParameters, initContext);
System.out.println("running impact analysis on network " + network.getId());
ImpactAnalysisResult impactAnalisResults = impactAnalysis.run(stabilizationResults.getState(), contingencyIds);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import eu.itesla_project.commons.tools.Tool;
import eu.itesla_project.computation.ComputationManager;
import eu.itesla_project.computation.local.LocalComputationManager;
import eu.itesla_project.iidm.import_.Importer;
import eu.itesla_project.iidm.import_.Importers;
import eu.itesla_project.iidm.network.Network;
import eu.itesla_project.modules.contingencies.ContingenciesAndActionsDatabaseClient;
Expand All @@ -39,8 +38,6 @@
//@AutoService(Tool.class)
public class RunTDSimulation implements Tool {

private static final String EMPTY_CONTINGENCY_ID = "Empty-Contingency";

private static Command COMMAND = new Command() {

@Override
Expand Down Expand Up @@ -121,26 +118,18 @@ private void writeCsvViolations(Path folder, Map<String, List<LimitViolation>> n
}
}
cvsWriter.flush();
} catch (IOException e) {
throw e;
} finally {
if ( cvsWriter!=null )
cvsWriter.close();
}
} catch (IOException e1) {
throw e1;
}
}

private void writeCsvTDResults(Path folder, Map<String, Map<String, Boolean>> tdSimulationsResults) throws IOException {
Path csvFile = getFile(folder, "simulation-results.csv");
System.out.println("writing simulation results to file " + csvFile.toString());
Set<String> securityIndexIds = new LinkedHashSet<>();
for (Map<String, Boolean> securityIndexesPerBasecase : tdSimulationsResults.values()) {
if (securityIndexesPerBasecase != null) {
securityIndexIds.addAll(securityIndexesPerBasecase.keySet());
}
}
tdSimulationsResults.values().stream().filter(m -> m != null).forEach(m -> securityIndexIds.addAll(m.keySet()));
String[] indexIds = securityIndexIds.toArray(new String[securityIndexIds.size()]);
Arrays.sort(indexIds);
try (FileWriter content = new FileWriter(csvFile.toFile())) {
Expand All @@ -166,26 +155,22 @@ private void writeCsvTDResults(Path folder, Map<String, Map<String, Boolean>> td
cvsWriter.writeRecord(values);
}
cvsWriter.flush();
} catch (IOException e) {
throw e;
} finally {
if ( cvsWriter!=null )
cvsWriter.close();
}
} catch (IOException e1) {
throw e1;
}
}

@Override
public void run(CommandLine line) throws Exception {
Path caseFile = Paths.get(line.getOptionValue("case-file"));
Set<String> contingencyIds = line.hasOption("contingencies") ? Sets.newHashSet(line.getOptionValue("contingencies").split(",")) : null;
boolean emptyContingency = line.hasOption("empty-contingency") ? true : false;
boolean emptyContingency = line.hasOption("empty-contingency");
Path outputFolder = line.hasOption("output-folder") ? Paths.get(line.getOptionValue("output-folder")) : null;

Map<String, List<LimitViolation>> networksViolations = new HashMap<String, List<LimitViolation>>();
Map<String, Map<String, Boolean>> tdSimulationsResults = new HashMap<String, Map<String,Boolean>>();
Map<String, List<LimitViolation>> networksViolations = new HashMap<>();
Map<String, Map<String, Boolean>> tdSimulationsResults = new HashMap<>();
Path metricsFile = getFile(outputFolder, "metrics.log");
try (ComputationManager computationManager = new LocalComputationManager();
FileWriter metricsContent = new FileWriter(metricsFile.toFile())) {
Expand All @@ -194,8 +179,6 @@ public void run(CommandLine line) throws Exception {
ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass().newInstance().create();
SimulatorFactory simulatorFactory = config.getSimulatorFactoryClass().newInstance();

Importer importer = Importers.getImporter("CIM1", computationManager);

if (Files.isRegularFile(caseFile)) {
// load the network
Network network = Importers.loadNetwork(caseFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@
@AutoService(Tool.class)
public class RunTDSimulationsMpiTool implements Tool {

private static final String EMPTY_CONTINGENCY_ID = "Empty-Contingency";

private static Command COMMAND = new Command() {

@Override
Expand Down Expand Up @@ -117,7 +115,7 @@ public void run(CommandLine line) throws Exception {
LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalOnlineApplicationMBean.class, false);


boolean emptyContingency = line.hasOption("empty-contingency") ? true : false;
boolean emptyContingency = line.hasOption("empty-contingency");
Path caseFile = Paths.get(line.getOptionValue("case-file"));
application.runTDSimulations(startconfig, caseFile.toString(), line.getOptionValue("contingencies"), Boolean.toString(emptyContingency), line.getOptionValue("output-folder"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ public String getDescription() {
}

@Override
@SuppressWarnings("static-access")
public Options getOptions() {
Options options = new Options();
options.addOption(Option.builder().longOpt("case-file")
Expand Down

0 comments on commit c444f93

Please sign in to comment.