Commit 00fb0844 authored by Vladislav Kiselev's avatar Vladislav Kiselev

Refactoring.

parent d233ebf1
...@@ -3,7 +3,11 @@ ...@@ -3,7 +3,11 @@
rm -f raw_result.txt rm -f raw_result.txt
rm -f result.txt rm -f result.txt
java -classpath "../out/production/Conversion" inport.Main to_MiniZinc in.ipp conversion_0.dzn java -classpath "../out/production/Conversion" inport.Main to_MiniZinc_0 in.ipp conversion_0.dzn
mzn2fzn -o model.fzn "../constraints/conversion_0.mzn" conversion_0.dzn
N_LINES=$(wc -l model.fzn)
echo "Model size : $N_LINES"
START=$(date +%s.%N) START=$(date +%s.%N)
...@@ -12,6 +16,6 @@ minizinc --solver Gecode "../constraints/conversion_0.mzn" conversion_0.dzn >> r ...@@ -12,6 +16,6 @@ minizinc --solver Gecode "../constraints/conversion_0.mzn" conversion_0.dzn >> r
END=$(date +%s.%N) END=$(date +%s.%N)
DIFF=$(echo "$END - $START" | bc) DIFF=$(echo "$END - $START" | bc)
echo $(DIFF) echo $DIFF
java -classpath "../out/production/Conversion" inport.Main resolve_result in.ipp raw_result.txt result.txt java -classpath "../out/production/Conversion" inport.Main resolve_result in.ipp raw_result.txt result.txt
...@@ -257,24 +257,46 @@ public class ConversionUtil { ...@@ -257,24 +257,46 @@ public class ConversionUtil {
return true; return true;
} }
static public void portToMiniZinc(TaskCase task, String fileName) throws IOException { private static class Task {
try(FileWriter writer = new FileWriter(fileName, false)) { private FileWriter writer = null;
int n_intervals = (int)task.getPlanningInterval(); private final String fileName;
writer.write("n_intervals = " + n_intervals + ";\n"); private final TaskCase task;
writer.write("n_operations = " + task.getTemplates().size() + ";\n");
private final int n_intervals;
private final ArrayList<Berth> berths;
private final Map<Pair<Integer, Boolean>, Integer> locationNumberById;
private final BiFunction<Integer, Boolean, Integer> getLocNById;
private final ArrayList<MovingObject> movingObjects;
private final Function<MovingObject, Integer> mObjToN;
private final ArrayList<OperationTemplate> operationTemplates;
private final ArrayList<Storage> storages;
private final ArrayList<Cargo> cargoes;
private final int nObjWithStorage;
private final Map<Integer, Integer> storNById;
private final Map<Integer, Integer> cargoNById;
ArrayList<Berth> berths = new ArrayList<>(task.getBerths()); Task(TaskCase task, String fileName) {
Map<Pair<Integer, Boolean>, Integer> locationNumberById = new TreeMap<>(new PairComparator()); this.fileName = fileName;
this.task = task;
n_intervals = (int)task.getPlanningInterval();
berths = new ArrayList<>(task.getBerths());
locationNumberById = new TreeMap<>(new PairComparator());
for (Berth berth : berths) { for (Berth berth : berths) {
locationNumberById.put(new Pair<>(berth.getId(), false), locationNumberById.size()); locationNumberById.put(new Pair<>(berth.getId(), false), locationNumberById.size());
locationNumberById.put(new Pair<>(berth.getId(), true), locationNumberById.size()); locationNumberById.put(new Pair<>(berth.getId(), true), locationNumberById.size());
} }
writer.write("n_locations = " + locationNumberById.size() + ";\n");
BiFunction<Integer, Boolean, Integer> getLocNById = getLocNById = (Integer id, Boolean isMoored) -> locationNumberById.get(new Pair<>(id, isMoored));
(Integer id, Boolean isMoored) -> locationNumberById.get(new Pair<>(id, isMoored));
ArrayList<MovingObject> movingObjects = new ArrayList<>(); movingObjects = new ArrayList<>();
Map<Integer, Integer> mObjNumberById = new TreeMap<>(); Map<Integer, Integer> mObjNumberById = new TreeMap<>();
for (MovingObject obj : task.getShips()) { for (MovingObject obj : task.getShips()) {
mObjNumberById.put(obj.getId(), movingObjects.size()); mObjNumberById.put(obj.getId(), movingObjects.size());
...@@ -288,13 +310,28 @@ public class ConversionUtil { ...@@ -288,13 +310,28 @@ public class ConversionUtil {
mObjNumberById.put(obj.getId(), movingObjects.size()); mObjNumberById.put(obj.getId(), movingObjects.size());
movingObjects.add(obj); movingObjects.add(obj);
} }
writer.write("n_moving_obj = " + movingObjects.size() + ";\n");
writer.write("\n");
Function<MovingObject, Integer> mObjToN = (MovingObject obj) -> mObjNumberById.get(obj.getId()); mObjToN = (MovingObject obj) -> mObjNumberById.get(obj.getId());
operationTemplates = new ArrayList<>(task.getTemplates());
storages = new ArrayList<>(task.getStorages());
cargoes = new ArrayList<>(task.getCargoes());
ArrayList<OperationTemplate> operationTemplates = new ArrayList<>(task.getTemplates()); storNById = new TreeMap<>();
{ // Операции прибытия/отбытия в локацию. (В том числе и швартовка.) for (int i = 0; i < storages.size(); i++) {
storNById.put(storages.get(i).getId(), i);
}
cargoNById = new TreeMap<>();
for (int i = 0; i < task.getCargoes().size(); i++) {
cargoNById.put(cargoes.get(i).getId(), i);
}
nObjWithStorage = movingObjects.size() + storages.size();
}
/* Операции прибытия/отбытия в локацию. (В том числе и швартовка.) */
private void arrivalAndDepartureOperations() throws IOException {
ArrayList<ArrayList<ArrayList<Integer>>> arrivalOp = new ArrayList<>(); ArrayList<ArrayList<ArrayList<Integer>>> arrivalOp = new ArrayList<>();
ArrayList<ArrayList<ArrayList<Integer>>> departureOp = new ArrayList<>(); ArrayList<ArrayList<ArrayList<Integer>>> departureOp = new ArrayList<>();
for (int i = 0; i < movingObjects.size(); i++) { for (int i = 0; i < movingObjects.size(); i++) {
...@@ -339,7 +376,9 @@ public class ConversionUtil { ...@@ -339,7 +376,9 @@ public class ConversionUtil {
write2DArrayOfSetAs3DArray(writer, "departure_op", departureOp); write2DArrayOfSetAs3DArray(writer, "departure_op", departureOp);
writer.write("\n"); writer.write("\n");
} }
{ // Начальные положения объектов.
/* Начальные положения объектов. */
private void initialLocations() throws IOException {
ArrayList<Integer> initialStates = integerArray(movingObjects.size(), 0); ArrayList<Integer> initialStates = integerArray(movingObjects.size(), 0);
for (MovingObjectState state : task.getVesselInitialState()) { for (MovingObjectState state : task.getVesselInitialState()) {
initialStates.set(mObjToN.apply(state.getVessel()), getLocNById.apply(state.getLocation().getId(), false)); initialStates.set(mObjToN.apply(state.getVessel()), getLocNById.apply(state.getLocation().getId(), false));
...@@ -347,7 +386,9 @@ public class ConversionUtil { ...@@ -347,7 +386,9 @@ public class ConversionUtil {
writeArray(writer, "initial_m_obj_loc", initialStates, (Integer p) -> p + 1); writeArray(writer, "initial_m_obj_loc", initialStates, (Integer p) -> p + 1);
writer.write("\n"); writer.write("\n");
} }
{ // Окна погоды.
/* Окна погоды. */
private void weatherWindows() throws IOException {
ArrayList<Integer> bw_op = new ArrayList<>(); ArrayList<Integer> bw_op = new ArrayList<>();
ArrayList<Integer> bw_start = new ArrayList<>(); ArrayList<Integer> bw_start = new ArrayList<>();
ArrayList<Integer> bw_fin = new ArrayList<>(); ArrayList<Integer> bw_fin = new ArrayList<>();
...@@ -368,7 +409,9 @@ public class ConversionUtil { ...@@ -368,7 +409,9 @@ public class ConversionUtil {
writeArray(writer, "bw_fin", bw_fin); writeArray(writer, "bw_fin", bw_fin);
writer.write("\n"); writer.write("\n");
} }
{ // Непрерывность перемещения и швартовки.
/* Непрерывность перемещения и швартовки. */
private void operationsContinuity() throws IOException {
ArrayList<Integer> operationsDuration = integerArray(operationTemplates.size(), 0); ArrayList<Integer> operationsDuration = integerArray(operationTemplates.size(), 0);
ArrayList<Boolean> isMovingObj = new ArrayList<>(); ArrayList<Boolean> isMovingObj = new ArrayList<>();
for (int i = 0; i < operationTemplates.size(); i++) { for (int i = 0; i < operationTemplates.size(); i++) {
...@@ -389,14 +432,18 @@ public class ConversionUtil { ...@@ -389,14 +432,18 @@ public class ConversionUtil {
writeArray(writer, "operations_duration", operationsDuration); writeArray(writer, "operations_duration", operationsDuration);
writeArray(writer, "is_continuous_operation", isMovingObj); writeArray(writer, "is_continuous_operation", isMovingObj);
} }
{ // Конечные положения объектов.
/* Конечные положения объектов. */
private void finalLocations() throws IOException {
ArrayList<Integer> finalStates = integerArray(movingObjects.size(), -1); ArrayList<Integer> finalStates = integerArray(movingObjects.size(), -1);
for (MovingObjectState state : task.getVesselEndState()) { for (MovingObjectState state : task.getVesselEndState()) {
finalStates.set(mObjToN.apply(state.getVessel()), getLocNById.apply(state.getLocation().getId(), false)); finalStates.set(mObjToN.apply(state.getVessel()), getLocNById.apply(state.getLocation().getId(), false));
} }
writeArray(writer, "final_m_obj_loc", finalStates, (Integer p) -> p + 1); writeArray(writer, "final_m_obj_loc", finalStates, (Integer p) -> p + 1);
} }
{ // Наличие всех ресурсов на месте, в том числе и самого корабля.
/* Наличие всех ресурсов на месте, в том числе и самого корабля. */
private void presenceOfResourcesInLocation() throws IOException {
// TODO ресурсы покрываются "Конфликтующими операциями" (кроме наличия корабля на месте). // TODO ресурсы покрываются "Конфликтующими операциями" (кроме наличия корабля на месте).
ArrayList<Set<Integer>> operationsResources = new ArrayList<>(); ArrayList<Set<Integer>> operationsResources = new ArrayList<>();
ArrayList<Integer> operationsStartLoc = integerArray(operationTemplates.size(), 0); ArrayList<Integer> operationsStartLoc = integerArray(operationTemplates.size(), 0);
...@@ -440,7 +487,9 @@ public class ConversionUtil { ...@@ -440,7 +487,9 @@ public class ConversionUtil {
writeArrayOfSetAs2DArray(writer, "operations_resources", operationsResources); writeArrayOfSetAs2DArray(writer, "operations_resources", operationsResources);
writer.write("\n"); writer.write("\n");
} }
{ // Конфликтующие операции.
/* Конфликтующие операции. */
private void conflictingOperations() throws IOException {
ArrayList<Pair<Integer, Integer>> conflictingPairs = new ArrayList<>(); ArrayList<Pair<Integer, Integer>> conflictingPairs = new ArrayList<>();
for (int i = 0; i < operationTemplates.size(); i++) { for (int i = 0; i < operationTemplates.size(); i++) {
for (int j = i + 1; j < operationTemplates.size(); j++) { for (int j = i + 1; j < operationTemplates.size(); j++) {
...@@ -454,27 +503,9 @@ public class ConversionUtil { ...@@ -454,27 +503,9 @@ public class ConversionUtil {
writeArray(writer, "confl_op_2", conflictingPairs, Pair::getValue); writeArray(writer, "confl_op_2", conflictingPairs, Pair::getValue);
writer.write("\n"); writer.write("\n");
} }
// Грузоообработка.
ArrayList<Storage> storages = new ArrayList<>(task.getStorages());
ArrayList<Cargo> cargoes = new ArrayList<>(task.getCargoes());
Map<Integer, Integer> storNById = new TreeMap<>();
for (int i = 0; i < storages.size(); i++) {
storNById.put(storages.get(i).getId(), i);
}
Map<Integer, Integer> cargoNById = new TreeMap<>(); /* Ограничения на вместимость. */
for (int i = 0; i < task.getCargoes().size(); i++) { private void maxStorageVolume() throws IOException {
cargoNById.put(cargoes.get(i).getId(), i);
}
int nObjWithStorage = movingObjects.size() + storages.size();
writer.write("n_obj_with_storage = " + nObjWithStorage + ";\n");
writer.write("n_cargo_types = " + cargoes.size() + ";\n");
{ // Ограничения на вместимость.
ArrayList<Integer> maxStorageVol = new ArrayList<>(); ArrayList<Integer> maxStorageVol = new ArrayList<>();
for (MovingObject obj : movingObjects) { for (MovingObject obj : movingObjects) {
...@@ -490,7 +521,9 @@ public class ConversionUtil { ...@@ -490,7 +521,9 @@ public class ConversionUtil {
writeArray(writer, "max_storage_vol", maxStorageVol); writeArray(writer, "max_storage_vol", maxStorageVol);
writer.write("\n"); writer.write("\n");
} }
{ // Граничные условия хранилищ.
/* Граничные состояния хранилищ. */
private void boundaryStorageStates() throws IOException {
// TODO выделить отдельно общий код. // TODO выделить отдельно общий код.
ArrayList<ArrayList<Integer>> initialStorageVol = new ArrayList<>(); ArrayList<ArrayList<Integer>> initialStorageVol = new ArrayList<>();
ArrayList<ArrayList<Integer>> finalStorageVol = new ArrayList<>(); ArrayList<ArrayList<Integer>> finalStorageVol = new ArrayList<>();
...@@ -528,7 +561,9 @@ public class ConversionUtil { ...@@ -528,7 +561,9 @@ public class ConversionUtil {
write2DArrayOfInt(writer, "initial_storage_vol", initialStorageVol); write2DArrayOfInt(writer, "initial_storage_vol", initialStorageVol);
write2DArrayOfInt(writer, "final_storage_vol", finalStorageVol); write2DArrayOfInt(writer, "final_storage_vol", finalStorageVol);
} }
{ // Потоки грузов.
/* Потоки грузов. */
private void cargoFlows() throws IOException {
ArrayList<ArrayList<ArrayList<Integer>>> cargoFlows = new ArrayList<>(); ArrayList<ArrayList<ArrayList<Integer>>> cargoFlows = new ArrayList<>();
for (int i = 0; i < nObjWithStorage; i++) { for (int i = 0; i < nObjWithStorage; i++) {
cargoFlows.add(new ArrayList<>()); cargoFlows.add(new ArrayList<>());
...@@ -562,7 +597,9 @@ public class ConversionUtil { ...@@ -562,7 +597,9 @@ public class ConversionUtil {
} }
writer.write("]);\n\n"); writer.write("]);\n\n");
} }
{ // Грузовые операции со всеми хранилищами.
/* Грузовые операции со всеми хранилищами. */
private void cargoOperations() throws IOException {
ArrayList<ArrayList<ArrayList<Integer>>> involvedOperations = new ArrayList<>(); ArrayList<ArrayList<ArrayList<Integer>>> involvedOperations = new ArrayList<>();
ArrayList<Integer> loadingOpDelta = new ArrayList<>(); ArrayList<Integer> loadingOpDelta = new ArrayList<>();
ArrayList<Integer> loadingOpN = new ArrayList<>(); ArrayList<Integer> loadingOpN = new ArrayList<>();
...@@ -597,7 +634,9 @@ public class ConversionUtil { ...@@ -597,7 +634,9 @@ public class ConversionUtil {
writeArray(writer, "loading_op_n", loadingOpN, (Integer i) -> i + 1); writeArray(writer, "loading_op_n", loadingOpN, (Integer i) -> i + 1);
writer.write("\n"); writer.write("\n");
} }
{ // Ограничение на необходимость полезной операции между движениями к одному пункту назначения.
/* Ограничение на необходимость полезной операции между движениями к одному пункту назначения. */
private void constraintOnUsefulOperationBetweenMovements() throws IOException {
ArrayList<Set<Integer>> objUsefulOperations = new ArrayList<>(); ArrayList<Set<Integer>> objUsefulOperations = new ArrayList<>();
ArrayList<Set<Integer>> movingOpOfObj = new ArrayList<>(); ArrayList<Set<Integer>> movingOpOfObj = new ArrayList<>();
...@@ -644,8 +683,47 @@ public class ConversionUtil { ...@@ -644,8 +683,47 @@ public class ConversionUtil {
writeArrayOfSetAs2DArray(writer, "moving_op_of_obj", movingOpOfObj); writeArrayOfSetAs2DArray(writer, "moving_op_of_obj", movingOpOfObj);
writer.write("\n"); writer.write("\n");
} }
void portToMiniZinc_0() throws IOException {
try {
writer = new FileWriter(fileName, false);
writer.write("n_intervals = " + n_intervals + ";\n");
writer.write("n_operations = " + task.getTemplates().size() + ";\n");
writer.write("n_locations = " + locationNumberById.size() + ";\n");
writer.write("n_moving_obj = " + movingObjects.size() + ";\n");
writer.write("\n");
arrivalAndDepartureOperations();
initialLocations();
weatherWindows();
operationsContinuity();
finalLocations();
presenceOfResourcesInLocation();
conflictingOperations();
writer.write("n_obj_with_storage = " + nObjWithStorage + ";\n");
writer.write("n_cargo_types = " + cargoes.size() + ";\n");
maxStorageVolume();
boundaryStorageStates();
cargoFlows();
cargoOperations();
constraintOnUsefulOperationBetweenMovements();
} finally {
if (writer != null) {
writer.close();
} }
} }
}
}
static public void portToMiniZinc_0(TaskCase task, String fileName) throws IOException {
Task taskData = new Task(task, fileName);
taskData.portToMiniZinc_0();
}
static public void resolveMiniZincResults(TaskCase task, String fileName) throws IOException, ParserException { static public void resolveMiniZincResults(TaskCase task, String fileName) throws IOException, ParserException {
List<Operation> operations = null; List<Operation> operations = null;
......
...@@ -11,13 +11,13 @@ public class Main { ...@@ -11,13 +11,13 @@ public class Main {
String type = args[0]; String type = args[0];
switch (type) { switch (type) {
case "to_MiniZinc" : { case "to_MiniZinc_0" : {
String input = args[1]; String input = args[1];
String output = args[2]; String output = args[2];
TaskCase task = new TaskCase(); TaskCase task = new TaskCase();
try { try {
task.deserialize(input); task.deserialize(input);
ConversionUtil.portToMiniZinc(task, output); ConversionUtil.portToMiniZinc_0(task, output);
} catch (IOException ex) { } catch (IOException ex) {
System.out.println(ex.getMessage()); System.out.println(ex.getMessage());
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment