Commit 84e05452 authored by Marta Różańska's avatar Marta Różańska
Browse files

Merge branch 'ZPP2019Master' into ZPP-for-Melodic

# Conflicts:
#	zpp-solver/cp_sampler/pom.xml
#	zpp-solver/cp_sampler/src/main/java/eu/melodic/upperware/cp_sampler/Sampler.java
#	zpp-solver/cp_sampler/src/main/java/eu/melodic/upperware/cp_sampler/xmi_writer/XMIWriter.java
#	zpp-solver/cp_sampler/src/test/java/SamplerTest.java
#	zpp-solver/genetic-solver/pom.xml
#	zpp-solver/mcts-solver/pom.xml
#	zpp-solver/node-candidates-solver/pom.xml
#	zpp-solver/pom.xml
#	zpp-solver/pt-solver/pom.xml
parents a88bc0db 93666b21
......@@ -20,4 +20,9 @@ build/
nbbuild/
dist/
nbdist/
.nb-gradle/
\ No newline at end of file
.nb-gradle/
### MCTS tree printing ###
zpp-solver/testing_module/src/main/resources/nodes*
zpp-solver/testing_module/src/main/resources/tree*
\ No newline at end of file
......@@ -101,6 +101,17 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>exec</classifier>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
......
......@@ -336,4 +336,4 @@ public class CommonConstraintProblemParser implements ConstraintProblemParser {
return expression instanceof ComposedExpression;
}
}
}
\ No newline at end of file
......@@ -11,6 +11,7 @@ import org.chocosolver.solver.variables.Variable;
import org.chocosolver.solver.variables.impl.FixedIntVarImpl;
import org.chocosolver.solver.variables.impl.FixedRealVarImpl;
import java.time.Clock;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -35,6 +36,21 @@ public class SolverParsedData {
return result;
}
public List<CpSolution> solve(int timeLimit) {
Solver solver = model.getSolver();
solver.limitTime(timeLimit + "s");
List<CpSolution> result = new ArrayList<>();
Clock clock = Clock.systemDefaultZone();
long startTime = clock.millis();
long currentTime = startTime;
while (currentTime - startTime <= 1000*timeLimit && solver.solve()) {
result.add(createCpSolution());
solver.limitTime(timeLimit + "s");
currentTime = clock.millis();
}
return result;
}
private CpSolution createCpSolution() {
Map<String, IntVar> intResult = intVars.values()
......
......@@ -84,6 +84,9 @@ public final class NodeCandidatePredicates {
Double latitude = null;
Location tempLocation = nodeCandidate.getLocation();
do {
if (tempLocation == null) {
System.out.println("O NIE");
}
final GeoLocation geoLocation = tempLocation.getGeoLocation();
if (geoLocation != null) {
latitude = geoLocation.getLatitude();
......
......@@ -19,6 +19,7 @@ import eu.paasage.upperware.security.authapi.token.JWTService;
import lombok.extern.slf4j.Slf4j;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
......@@ -33,18 +34,16 @@ public class UtilityGeneratorApplication {
utilityFunctionEvaluator = new UtilityFunctionEvaluator(camelModelFilePath, cpModelFilePath, readFromFile, nodeCandidates, properties, melodicSecurityProperties, penaltyFunctionProperties, jwtService);
}
@SafeVarargs
public UtilityGeneratorApplication(String camelModelFilePath, String cpModelFilePath, boolean readFromFile, NodeCandidates nodeCandidates, UtilityGeneratorProperties properties,
MelodicSecurityProperties melodicSecurityProperties, JWTService jwtService, PenaltyFunctionProperties penaltyFunctionProperties,
Map.Entry<TemplateProvider.AvailableTemplates, Double>... utilityComponents) {
List<Map.Entry<TemplateProvider.AvailableTemplates, Double>> utilityComponents) {
log.info("Creating template Utility Generator");
checkWeightsOfUtilityComponents(utilityComponents);
utilityFunctionEvaluator = new UtilityFunctionEvaluator(camelModelFilePath, cpModelFilePath, readFromFile, nodeCandidates, properties,
melodicSecurityProperties, penaltyFunctionProperties, jwtService, utilityComponents);
}
@SafeVarargs
public UtilityGeneratorApplication(String cpModelFilePath, NodeCandidates nodeCandidates, Map.Entry<TemplateProvider.AvailableTemplates, Double>... utilityComponents) {
public UtilityGeneratorApplication(String cpModelFilePath, NodeCandidates nodeCandidates, List<Map.Entry<TemplateProvider.AvailableTemplates, Double>> utilityComponents) {
log.info("Creating template Utility Generator");
checkWeightsOfUtilityComponents(utilityComponents);
utilityFunctionEvaluator = new UtilityFunctionEvaluator( cpModelFilePath, nodeCandidates, utilityComponents);
......@@ -54,10 +53,9 @@ public class UtilityGeneratorApplication {
return this.utilityFunctionEvaluator.evaluate(solution);
}
@SafeVarargs
private final void checkWeightsOfUtilityComponents(Map.Entry<TemplateProvider.AvailableTemplates, Double>... utilityComponents) {
if (Stream.of(utilityComponents).map(Map.Entry::getValue).reduce(0.0, Double::sum) > 1.0
|| Stream.of(utilityComponents).map(Map.Entry::getValue).anyMatch(weight -> weight < 0)) {
private final void checkWeightsOfUtilityComponents(List<Map.Entry<TemplateProvider.AvailableTemplates, Double>> utilityComponents) {
if (utilityComponents.stream().map(Map.Entry::getValue).reduce(0.0, Double::sum) > 1.0
|| utilityComponents.stream().map(Map.Entry::getValue).anyMatch(weight -> weight < 0)) {
throw new RuntimeException("Sum of weights must be smaller or equal to 1 and non-negative!");
}
}
......
......@@ -25,9 +25,7 @@ import static java.util.Objects.isNull;
@Slf4j
public class EvaluatingUtils {
static Collection<ConfigurationElement> convertSolutionToNodeCandidates(Collection<VariableDTO> variables, NodeCandidates nodeCandidates, Collection<VariableValueDTO> solution) {
public static Collection<ConfigurationElement> convertSolutionToNodeCandidates(Collection<VariableDTO> variables, NodeCandidates nodeCandidates, Collection<VariableValueDTO> solution) {
log.debug("Converting solution to Node Candidates");
Collection<ConfigurationElement> newConfiguration = new ArrayList<>();
......
......@@ -72,10 +72,9 @@ public class UtilityFunctionEvaluator {
constraintProblemExtractor.endWorkWithCPModel();
}
@SafeVarargs
public UtilityFunctionEvaluator(String camelModelFilePath, String cpModelFilePath, boolean readFromFile, NodeCandidates nodeCandidates, UtilityGeneratorProperties properties,
MelodicSecurityProperties melodicSecurityProperties, PenaltyFunctionProperties penaltyFunctionProperties, JWTService jwtService,
Map.Entry<TemplateProvider.AvailableTemplates, Double>... utilityComponents) {
List<Map.Entry<TemplateProvider.AvailableTemplates, Double>> utilityComponents) {
Objects.requireNonNull(properties.getUtilityGenerator().getDlmsControllerUrl(), "Utility Generator properties with DLMS Controller URL does not exist");
this.nodeCandidates = Objects.requireNonNull(nodeCandidates, "List of Node Candidates is null");
......@@ -99,8 +98,7 @@ public class UtilityFunctionEvaluator {
constraintProblemExtractor.endWorkWithCPModel();
}
@SafeVarargs
public UtilityFunctionEvaluator(String cpModelFilePath, NodeCandidates nodeCandidates, Map.Entry<TemplateProvider.AvailableTemplates, Double>... utilityComponents) {
public UtilityFunctionEvaluator(String cpModelFilePath, NodeCandidates nodeCandidates, List<Map.Entry<TemplateProvider.AvailableTemplates, Double>> utilityComponents) {
this.nodeCandidates = Objects.requireNonNull(nodeCandidates, "List of Node Candidates is null");
ConstraintProblemExtractor constraintProblemExtractor = new ConstraintProblemExtractor(cpModelFilePath, true);
......@@ -140,7 +138,7 @@ public class UtilityFunctionEvaluator {
Collection<ConfigurationElement> newConfiguration = convertSolutionToNodeCandidates(this.variablesFromConstraintProblem, this.nodeCandidates, solution);
if (newConfiguration.isEmpty()) {
log.info("No Node Candidate for the evaluated solution, returning 0");
log.debug("No Node Candidate for the evaluated solution, returning 0");
return 0;
} else if (!this.deployedConfiguration.isEmpty() && EvaluatingUtils.areUnmoveableComponentsMoved(this.unmoveableComponents, this.deployedConfiguration, newConfiguration)) {
log.info("Proposed solution moves the unmoveable component, returning 0");
......
......@@ -5,6 +5,7 @@ import eu.paasage.upperware.metamodel.cp.VariableType;
import lombok.extern.slf4j.Slf4j;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
......@@ -25,10 +26,9 @@ public class TemplateProvider {
RAM_MIN_MAX
};
@SafeVarargs
public static String getTemplate(Collection<VariableDTO> variablesFromConstraintProblem,
Map.Entry<AvailableTemplates, Double>... utilityComponents) {
return getSum( Stream.of(utilityComponents).map( (template) ->
List<Map.Entry<AvailableTemplates, Double>> utilityComponents) {
return getSum( utilityComponents.stream().map( (template) ->
multiply( template.getValue().toString(), getTemplate(variablesFromConstraintProblem, template.getKey()))
).collect(Collectors.toList()));
}
......
......@@ -130,14 +130,14 @@ class TemplateUtilityFCRTest extends Specification{
newConfiguration.add(new IntVariableValueDTO(lbStorageName, 10))
UtilityGeneratorApplication utilityGenerator =
new UtilityGeneratorApplication("src/main/test/resources/FCRForTemplates-CP.xmi",
mockNodeCandidates, new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 1.0d))
mockNodeCandidates, Arrays.asList(new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 1.0d)))
UtilityGeneratorApplication utilityGenerator2 =
new UtilityGeneratorApplication("src/main/test/resources/FCRForTemplates-CP.xmi",
mockNodeCandidates,
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 0.5d),
Arrays.asList(new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 0.5d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.CORES, 0.5d*0.333d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.DISK, 0.5d*0.333d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.RAM, 0.5d*0.333d))
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.RAM, 0.5d*0.333d)))
when:
double result = utilityGenerator.evaluate(newConfiguration)
double result2 = utilityGenerator2.evaluate(newConfiguration)
......@@ -173,14 +173,14 @@ class TemplateUtilityFCRTest extends Specification{
UtilityGeneratorApplication utilityGenerator =
new UtilityGeneratorApplication(path, "src/main/test/resources/FCRForTemplates-CP.xmi", true,
mockNodeCandidates, utilityGeneratorProperties, securityProperties, jwtService, properties,
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 1.0d))
Arrays.asList(new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 1.0d)))
UtilityGeneratorApplication utilityGenerator2 =
new UtilityGeneratorApplication(path, "src/main/test/resources/FCRForTemplates-CP.xmi", true,
mockNodeCandidates, utilityGeneratorProperties, securityProperties, jwtService, properties,
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 0.5d),
Arrays.asList(new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.COST, 0.5d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.CORES, 0.5d*0.333d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.DISK, 0.5d*0.333d),
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.RAM, 0.5d*0.333d))
new AbstractMap.SimpleEntry<TemplateProvider.AvailableTemplates, Double>(TemplateProvider.AvailableTemplates.RAM, 0.5d*0.333d)))
when:
double result = utilityGenerator.evaluate(newConfiguration)
double result2 = utilityGenerator2.evaluate(newConfiguration)
......
......@@ -3,36 +3,52 @@ package cp_wrapper;
import cp_wrapper.parser.CPParsedData;
import cp_wrapper.parser.CPParser;
import cp_wrapper.utility_provider.UtilityProvider;
import cp_wrapper.utils.DomainHandler;
import cp_wrapper.utils.domain_handler.DomainHandler;
import cp_wrapper.utils.numeric_value.*;
import cp_wrapper.utils.numeric_value.implementations.DoubleValue;
import cp_wrapper.utils.variable_orderer.HeuristicVariableOrderer;
import cp_wrapper.utils.VariableNumericType;
import cp_wrapper.utils.cp_variable.VariableNumericType;
import cp_wrapper.utils.variable_orderer.RandomVariableOrderer;
import cp_wrapper.utils.variable_orderer.VariableOrderer;
import eu.melodic.upperware.utilitygenerator.cdo.cp_model.DTO.VariableDTO;
import eu.melodic.upperware.utilitygenerator.cdo.cp_model.DTO.VariableValueDTO;
import eu.melodic.upperware.utilitygenerator.cdo.cp_model.DTO.VariableValueDTOFactory;
import eu.paasage.upperware.metamodel.cp.*;
import lombok.Getter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;
public class CPWrapper {
private VariableOrderer variableOrderer;
private CPParsedData cpParsedData;
private UtilityProvider utilityProvider;
@Getter
private Collection<VariableDTO> variableDTOCollection;
@Getter
private long numberOfComponents;
public void parse(ConstraintProblem constraintProblem, UtilityProvider utility) {
CPParser cpParser = new CPParser();
cpParsedData = cpParser.parse(constraintProblem);
this.utilityProvider = utility;
this.variableOrderer = new HeuristicVariableOrderer(cpParsedData.getConstraintGraph());
this.variableOrderer = new HeuristicVariableOrderer(cpParsedData.getConstraintGraph(), cpParsedData.getVariables());
this.numberOfComponents = cpParsedData.getVariables().stream().map(CpVariable::getComponentId).distinct().count();
this.variableDTOCollection = cpParsedData.getVariables().stream()
.map(variable -> new VariableDTO(variable.getId(), variable.getComponentId(), variable.getVariableType()))
.collect(Collectors.toList());
}
public void setVariableOrdering(VariableOrderer vO) {
this.variableOrderer = vO;
public void parseWithRandomOrder(ConstraintProblem constraintProblem, UtilityProvider utility) {
CPParser cpParser = new CPParser();
cpParsedData = cpParser.parse(constraintProblem);
this.utilityProvider = utility;
this.numberOfComponents = cpParsedData.getVariables().stream().map(CpVariable::getComponentId).distinct().count();
this.variableOrderer = new RandomVariableOrderer(cpParsedData.getVariables());
this.variableDTOCollection = cpParsedData.getVariables().stream()
.map(variable -> new VariableDTO(variable.getId(), variable.getComponentId(), variable.getVariableType()))
.collect(Collectors.toList());
}
public boolean checkIfFeasible(List<Integer> assignment) {
......@@ -43,26 +59,12 @@ public class CPWrapper {
return cpParsedData.getVariableDomain(variableOrderer.getNameFromIndex(variableIndex));
}
private NumericValueInterface getVariableValueFromDomainIndex(int varIndex, int value) {
String variableName = variableOrderer.getNameFromIndex(varIndex);
Domain domain = cpParsedData.getVariableDomain(variableName);
if (DomainHandler.isRangeDomain(domain)) {
return DomainHandler.getRangeValue(value, (RangeDomain) domain);
} else if (DomainHandler.isNumericListDomain(domain)) {
return DomainHandler.getNumericListValue(value, (NumericListDomain) domain);
}
throw new RuntimeException("Only domains of types RangeDomain, NumericListDomain are supported!");
public int getIndexFromValue(NumericValueInterface value, int variable) {
return DomainHandler.getValueIndex(value, getVariableDomain(variable));
}
private Map<String, NumericValueInterface> getAssignmentFromValueList(List<Integer> assignments) {
Map<String, NumericValueInterface> vars = new HashMap<>();
for (int i = 0; i < assignments.size(); i++) {
if (variableOrderer.exists(i)) {
vars.put(variableOrderer.getNameFromIndex(i), getVariableValueFromDomainIndex(i, assignments.get(i)));
}
}
return vars;
public int getVariableIndexFromComponentAndType(String componentId, VariableType type) {
return this.variableOrderer.getIndexFromComponentType(componentId, type);
}
public int countViolatedConstraints(List<Integer> assignments) {
......@@ -85,19 +87,17 @@ public class CPWrapper {
public List<VariableValueDTO> assignmentToVariableValueDTOList(List<Integer> assignments) {
List<VariableValueDTO> result = new ArrayList<>();
for (int i = 0; i < assignments.size(); i++) {
NumericValueInterface val = getVariableValueFromDomainIndex(i, assignments.get(i));
NumericValueInterface value = getVariableValueFromDomainIndex(i, assignments.get(i));
if (cpParsedData.getVariableType(variableOrderer.getNameFromIndex(i)) == VariableNumericType.INT) {
if (!(val.isInteger())) {
if (!(value.isInteger())) {
throw new RuntimeException("");
}
result.add( VariableValueDTOFactory.createElement(variableOrderer.getNameFromIndex(i), val.getIntValue())
);
result.add(VariableValueDTOFactory.createElement(variableOrderer.getNameFromIndex(i), value.getIntValue()));
} else {
if (!(val instanceof DoubleValue)) {
if (!(value instanceof DoubleValue)) {
throw new RuntimeException("Variable " + variableOrderer.getNameFromIndex(i) +" is not of double type!");
}
result.add( VariableValueDTOFactory.createElement( variableOrderer.getNameFromIndex(i), val.getDoubleValue())
);
result.add( VariableValueDTOFactory.createElement(variableOrderer.getNameFromIndex(i), value.getDoubleValue()));
}
}
return result;
......@@ -123,4 +123,34 @@ public class CPWrapper {
public int getVariablesCount() {
return cpParsedData.getVariableNames().size();
}
public String getNameFromIndex(int index) {
return this.variableOrderer.getNameFromIndex(index);
}
public int getValueFromIndex(int value, int variableIndex) {
return getVariableValueFromDomainIndex(variableIndex, value).getIntValue();
}
private NumericValueInterface getVariableValueFromDomainIndex(int varIndex, int value) {
Domain domain = cpParsedData.getVariableDomain(variableOrderer.getNameFromIndex(varIndex));
if (DomainHandler.isRangeDomain(domain)) {
return DomainHandler.getRangeValue(value, (RangeDomain) domain);
} else if (DomainHandler.isNumericListDomain(domain)) {
return DomainHandler.getNumericListValue(value, (NumericListDomain) domain);
}
throw new RuntimeException("Only domains of types RangeDomain, NumericListDomain are supported!");
}
private Map<String, NumericValueInterface> getAssignmentFromValueList(List<Integer> assignments) {
Map<String, NumericValueInterface> vars = new HashMap<>();
for (int i = 0; i < assignments.size(); i++) {
if (variableOrderer.exists(i)) {
vars.put(variableOrderer.getNameFromIndex(i), getVariableValueFromDomainIndex(i, assignments.get(i)));
}
}
return vars;
}
}
......@@ -4,8 +4,8 @@ package cp_wrapper.parser;
*/
import cp_wrapper.utils.constraint.Constraint;
import cp_wrapper.utils.ConstraintGraph;
import cp_wrapper.utils.VariableNumericType;
import cp_wrapper.utils.constraint_graph.ConstraintGraph;
import cp_wrapper.utils.cp_variable.VariableNumericType;
import cp_wrapper.utils.numeric_value.NumericValueInterface;
//import eu.melodic.upperware.cpsolver.solver.parser.creator.*;
......@@ -22,8 +22,8 @@ public class CPParsedData {
private Collection<Constant> constants;
private Collection<CpMetric> metrics;
private Collection<Constraint> constraints;
@Getter
private Collection<CpVariable> variables;
//private IntVarCreator intVarCreator;
static final List<BasicTypeEnum> ACCEPTED_INT_TYPES = Arrays.asList(BasicTypeEnum.INTEGER, BasicTypeEnum.LONG);
@Getter
private ConstraintGraph constraintGraph;
......@@ -33,12 +33,6 @@ public class CPParsedData {
return nameToVariable.keySet();
}
protected void init() {
//intVarCreator = new IntVarCreator();
initializeConstraintGraph();
initializeNameToVariable();
}
public boolean checkIfFeasible(Map<String, NumericValueInterface> variables) {
for (Constraint c : constraints) {
if (!c.evaluate(variables)) {
......@@ -48,15 +42,6 @@ public class CPParsedData {
return true;
}
BasicTypeEnum getDomainType(Domain domain) {
if (domain instanceof RangeDomain) {
return ((RangeDomain) domain).getType();
} else if (domain instanceof NumericListDomain) {
return ((NumericListDomain) domain).getType();
}
throw new RuntimeException(format("Unsupported Domain type %s, only RangeDomain and NumericListDomain are supported",
domain.getClass().getSimpleName()));
}
public int countViolatedConstraints(Map<String, NumericValueInterface> variables) {
return constraints.stream()
.map(c -> c.evaluate(variables) ? 0 : 1)
......@@ -67,34 +52,21 @@ public class CPParsedData {
return constraintGraph.getVariableHeuristicEvaluation(variable, variables);
}
public void updateMetrics(Collection<CpMetric> metrics) {
//TODO
}
public Domain getVariableDomain(String variable) {
return nameToVariable.get(variable).getDomain();
}
public VariableNumericType getVariableType(String name) {
if (nameToVariable.get(name) instanceof CpVariable && ACCEPTED_INT_TYPES.contains(getDomainType((nameToVariable.get(name)).getDomain()))) {
if (ACCEPTED_INT_TYPES.contains(getDomainType((nameToVariable.get(name)).getDomain()))) {
return VariableNumericType.INT;
} else {
return VariableNumericType.DOUBLE;
}
}
private void initializeNameToVariable() {
nameToVariable = new HashMap<String, CpVariable>();
for (CpVariable var : variables) {
nameToVariable.put(var.getId(), var);
}
}
private void initializeConstraintGraph() {
List<String> variableNames =
variables.stream()
.map(CPElement::getId)
.collect(Collectors.toList());
constraintGraph = new ConstraintGraph(constraints, variableNames);
void init() {
initializeConstraintGraph();
initializeNameToVariable();
}
void postConstants(Collection<Constant> constants) {
......@@ -109,4 +81,29 @@ public class CPParsedData {
void postVariables(Collection<CpVariable> variables) {
this.variables = variables;
}
private BasicTypeEnum getDomainType(Domain domain) {
if (domain instanceof RangeDomain) {
return ((RangeDomain) domain).getType();
} else if (domain instanceof NumericListDomain) {
return ((NumericListDomain) domain).getType();
}
throw new RuntimeException(format("Unsupported Domain type %s, only RangeDomain and NumericListDomain are supported",
domain.getClass().getSimpleName()));
}
private void initializeNameToVariable() {
nameToVariable = new HashMap<>();
for (CpVariable var : variables) {
nameToVariable.put(var.getId(), var);
}
}
private void initializeConstraintGraph() {
List<String> variableNames =
variables.stream()
.map(CPElement::getId)
.collect(Collectors.toList());
constraintGraph = new ConstraintGraph(constraints, variableNames);
}
}
package cp_wrapper.solution;
import eu.melodic.upperware.utilitygenerator.cdo.cp_model.DTO.VariableValueDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class CpSolution {
private List<VariableValueDTO> solution;
private double utility;
}
package cp_wrapper.utility_provider;
public interface UtilityProviderFactory {
UtilityProvider create();
}
package cp_wrapper.utility_provider.implementations;
import cp_wrapper.utility_provider.UtilityProvider;
import eu.melodic.upperware.utilitygenerator.UtilityGeneratorApplication;
import eu.melodic.upperware.utilitygenerator.cdo.cp_model.DTO.VariableValueDTO;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
public class ParallelUtilityProviderImpl implements UtilityProvider {
final private List<UtilityGeneratorApplication> utility;
final private List<Boolean> occupied;
final private ReentrantLock mutex = new ReentrantLock();
public ParallelUtilityProviderImpl(List<UtilityGeneratorApplication> utility) {
this.utility = utility;
occupied = utility.stream().map(util -> false).collect(Collectors.toList());
}
@Override
public double evaluate(List<VariableValueDTO> result) {
int utilityIndex = chooseUtility();
double evaluation = utility.get(utilityIndex).evaluate(result);
freeUtility(utilityIndex);
return evaluation;
}
private int chooseUtility() {
mutex.lock();
int index = occupied.indexOf(false);
occupied.set(index, true);
mutex.unlock();
return index;
}
synchronized private void freeUtility(int index) {
mutex