index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/ComponentRepository.java
|
package ai.libs.jaicore.components.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.Optional;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstanceConstraint;
import ai.libs.jaicore.components.api.IComponentRepository;
public class ComponentRepository extends ArrayList<IComponent> implements IComponentRepository {
private static final long serialVersionUID = 3966345495009688845L;
private final Collection<IComponentInstanceConstraint> constraints = new ArrayList<>();
public ComponentRepository() {
this(new ArrayList<>());
}
public ComponentRepository(final Collection<? extends IComponent> components) {
this(components, new ArrayList<>());
}
public ComponentRepository(final Collection<? extends IComponent> components, final Collection<? extends IComponentInstanceConstraint> constraints) {
super();
this.addAll(components);
this.constraints.addAll(constraints);
}
@Override
public Component getComponent(final String name) {
Optional<IComponent> opt = this.stream().filter(c -> c.getName().equals(name)).findAny();
if (!opt.isPresent()) {
throw new NoSuchElementException();
}
return (Component)opt.get();
}
@Override
public Collection<IComponentInstanceConstraint> getConstraints() {
return this.constraints;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + this.constraints.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ComponentRepository other = (ComponentRepository) obj;
return this.constraints.equals(other.constraints);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/ComponentUtil.java
|
package ai.libs.jaicore.components.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import ai.libs.jaicore.basic.kvstore.KVStore;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IComponentRepository;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDomain;
import ai.libs.jaicore.components.api.IRequiredInterfaceDefinition;
import ai.libs.jaicore.components.exceptions.ComponentNotFoundException;
/**
* The ComponentUtil class can be used to deal with Components in a convenient way. For instance, for a given component (type) it can be used to return a parameterized ComponentInstance.
*
* @author wever
*/
public class ComponentUtil {
private ComponentUtil() {
/* Intentionally left blank to prevent instantiation of this class. */
}
/**
* This procedure returns a ComponentInstance of the given Component with default parameterization. Note that required interfaces are not resolved.
*
* @param component
* The component for which a random parameterization is to be returned.
* @return An instantiation of the component with default parameterization.
*/
public static ComponentInstance getDefaultParameterizationOfComponent(final IComponent component) {
Map<String, String> parameterValues = new HashMap<>();
for (IParameter p : component.getParameters()) {
parameterValues.put(p.getName(), p.getDefaultValue() + "");
}
return componentInstanceWithNoRequiredInterfaces(component, parameterValues);
}
/**
* This procedure returns a valid random parameterization of a given component. Random decisions are made with the help of the given Random object. Note that required interfaces are not resolved.
*
* @param component
* The component for which a random parameterization is to be returned.
* @param rand
* The Random instance for making the random decisions.
* @return An instantiation of the component with valid random parameterization.
*/
public static ComponentInstance getRandomParameterizationOfComponent(final IComponent component, final Random rand) {
ComponentInstance ci;
do {
Map<String, String> parameterValues = new HashMap<>();
for (IParameter p : component.getParameters()) {
if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {
String[] values = ((CategoricalParameterDomain) p.getDefaultDomain()).getValues();
parameterValues.put(p.getName(), values[rand.nextInt(values.length)]);
} else {
NumericParameterDomain numDomain = (NumericParameterDomain) p.getDefaultDomain();
if (numDomain.isInteger()) {
if ((int) (numDomain.getMax() - numDomain.getMin()) > 0) {
parameterValues.put(p.getName(), ((int) (rand.nextInt((int) (numDomain.getMax() - numDomain.getMin())) + numDomain.getMin())) + "");
} else {
if (p.getDefaultValue() instanceof Double) {
parameterValues.put(p.getName(), ((int) (double) p.getDefaultValue()) + "");
} else {
parameterValues.put(p.getName(), (int) p.getDefaultValue() + "");
}
}
} else {
parameterValues.put(p.getName(), (rand.nextDouble() * (numDomain.getMax() - numDomain.getMin()) + numDomain.getMin()) + "");
}
}
}
ci = componentInstanceWithNoRequiredInterfaces(component, parameterValues);
} while (!ComponentInstanceUtil.isValidComponentInstantiation(ci));
return ci;
}
public static ComponentInstance minParameterizationOfComponent(final IComponent component) {
Map<String, String> parameterValues = new HashMap<>();
for (IParameter p : component.getParameters()) {
if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {
parameterValues.put(p.getName(), p.getDefaultValue() + "");
} else {
NumericParameterDomain numDomain = (NumericParameterDomain) p.getDefaultDomain();
if (numDomain.isInteger()) {
if ((int) (numDomain.getMax() - numDomain.getMin()) > 0) {
parameterValues.put(p.getName(), (int) numDomain.getMin() + "");
} else {
parameterValues.put(p.getName(), (int) p.getDefaultValue() + "");
}
} else {
parameterValues.put(p.getName(), numDomain.getMin() + "");
}
}
}
ComponentInstance ci = componentInstanceWithNoRequiredInterfaces(component, parameterValues);
ComponentInstanceUtil.checkComponentInstantiation(ci);
return ci;
}
public static ComponentInstance maxParameterizationOfComponent(final IComponent component) {
Map<String, String> parameterValues = new HashMap<>();
for (IParameter p : component.getParameters()) {
if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {
parameterValues.put(p.getName(), p.getDefaultValue() + "");
} else {
NumericParameterDomain numDomain = (NumericParameterDomain) p.getDefaultDomain();
if (numDomain.isInteger()) {
if ((int) (numDomain.getMax() - numDomain.getMin()) > 0) {
parameterValues.put(p.getName(), (int) numDomain.getMax() + "");
} else {
parameterValues.put(p.getName(), (int) p.getDefaultValue() + "");
}
} else {
parameterValues.put(p.getName(), numDomain.getMax() + "");
}
}
}
ComponentInstance ci = componentInstanceWithNoRequiredInterfaces(component, parameterValues);
ComponentInstanceUtil.checkComponentInstantiation(ci);
return ci;
}
private static ComponentInstance componentInstanceWithNoRequiredInterfaces(final IComponent component, final Map<String, String> parameterValues) {
return new ComponentInstance(component, parameterValues, new HashMap<>());
}
public static List<ComponentInstance> categoricalParameterizationsOfComponent(final IComponent component) {
Map<String, String> parameterValues = new HashMap<>();
List<ComponentInstance> parameterizedInstances = new ArrayList<>();
List<IParameter> categoricalParameters = new ArrayList<>();
int maxParameterIndex = 0;
for (IParameter p : component.getParameters()) {
if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {
String[] values = ((CategoricalParameterDomain) p.getDefaultDomain()).getValues();
if (values.length > maxParameterIndex) {
maxParameterIndex = values.length;
}
categoricalParameters.add(p);
} else {
parameterValues.put(p.getName(), p.getDefaultValue() + "");
}
}
for (int parameterIndex = 0; parameterIndex < maxParameterIndex; parameterIndex++) {
Map<String, String> categoricalParameterValues = new HashMap<>();
for (int i = 0; i < categoricalParameters.size(); i++) {
String parameterValue = null;
String[] values = ((CategoricalParameterDomain) categoricalParameters.get(i).getDefaultDomain()).getValues();
if (parameterIndex < values.length) {
parameterValue = values[parameterIndex];
} else {
parameterValue = categoricalParameters.get(i).getDefaultValue() + "";
}
categoricalParameterValues.put(categoricalParameters.get(i).getName(), parameterValue);
}
categoricalParameterValues.putAll(parameterValues);
parameterizedInstances.add(new ComponentInstance(component, categoricalParameterValues, new HashMap<>()));
}
return parameterizedInstances;
}
/**
* Searches and returns all components within a collection of components that provide a specific interface.
*
* @param components
* The collection of components to search in.
* @param providedInterface
* The interface of interest.
* @return A sub-collection of components all of which provide the requested providedInterface.
*/
public static Collection<IComponent> getComponentsProvidingInterface(final Collection<? extends IComponent> components, final String providedInterface) {
return components.stream().filter(x -> x.getProvidedInterfaces().contains(providedInterface)).collect(Collectors.toList());
}
/**
* Enumerates all possible component instances for a specific root component and a collection of components for resolving required interfaces. Hyperparameters are set to the default value.
*
* @param rootComponent
* The component to be considered the root.
* @param components
* The collection fo components that is used for resolving required interfaces recursively.
* @return A collection of component instances of the given root component with all possible algorithm choices.
*/
public static Collection<IComponentInstance> getAllAlgorithmSelectionInstances(final IComponent rootComponent, final Collection<? extends IComponent> components) {
Collection<IComponentInstance> instanceList = new LinkedList<>();
instanceList.add(ComponentUtil.getDefaultParameterizationOfComponent(rootComponent));
for (IRequiredInterfaceDefinition requiredInterface : rootComponent.getRequiredInterfaces()) {
List<IComponentInstance> tempList = new LinkedList<>();
Collection<IComponent> possiblePlugins = ComponentUtil.getComponentsProvidingInterface(components, requiredInterface.getName());
for (IComponentInstance ci : instanceList) {
for (IComponent possiblePlugin : possiblePlugins) {
for (IComponentInstance reqICI : getAllAlgorithmSelectionInstances(possiblePlugin, components)) {
IComponentInstance copyOfCI = new ComponentInstance(ci.getComponent(), new HashMap<>(ci.getParameterValues()), new HashMap<>(ci.getSatisfactionOfRequiredInterfaces()));
copyOfCI.getSatisfactionOfRequiredInterfaces().put(requiredInterface.getId(), Arrays.asList(reqICI));
tempList.add(copyOfCI);
}
}
}
instanceList.clear();
instanceList.addAll(tempList);
}
return instanceList;
}
/**
* Enumerates all possible component instances for a specific root component and a collection of components for resolving required interfaces. Hyperparameters are set to the default value.
*
* @param requiredInterface
* The interface required to be provided by the root components.
* @param components
* The collection fo components that is used for resolving required interfaces recursively.
* @return A collection of component instances of the given root component with all possible algorithm choices.
*/
public static Collection<IComponentInstance> getAllAlgorithmSelectionInstances(final String requiredInterface, final Collection<? extends IComponent> components) {
Collection<IComponentInstance> instanceList = new ArrayList<>();
components.stream().filter(x -> x.getProvidedInterfaces().contains(requiredInterface)).map(x -> getAllAlgorithmSelectionInstances(x, components)).forEach(instanceList::addAll);
return instanceList;
}
public static int getNumberOfUnparametrizedCompositions(final Collection<? extends IComponent> components, final String requiredInterface) {
if (hasCycles(components, requiredInterface)) {
return -1;
}
Collection<IComponent> candidates = components.stream().filter(c -> c.getProvidedInterfaces().contains(requiredInterface)).collect(Collectors.toList());
int numCandidates = 0;
for (IComponent candidate : candidates) {
int waysToResolveComponent = 0;
if (candidate.getRequiredInterfaces().isEmpty()) {
waysToResolveComponent = 1;
} else {
for (IRequiredInterfaceDefinition reqIFaceDef : candidate.getRequiredInterfaces()) {
String reqIFace = reqIFaceDef.getName();
int numberOfSolutionPerSlotForThisInterface = getNumberOfUnparametrizedCompositions(components, reqIFace);
int subSolutionsForThisInterface = 0;
if (reqIFaceDef.isOptional() || reqIFaceDef.getMin() == 0) {
subSolutionsForThisInterface++;
}
/* now consider all numbers i of positive realizations of this required interface */
for (int i = Math.max(1, reqIFaceDef.getMin()); i <= reqIFaceDef.getMax(); i++) {
int numberOfPossibleRealizationsForThisFixedNumberOfSlots = 1;
int numCandidatesForNextSlot = numberOfSolutionPerSlotForThisInterface;
for (int j = 0; j < i; j++) {
numberOfPossibleRealizationsForThisFixedNumberOfSlots *= numCandidatesForNextSlot;
if (reqIFaceDef.isUniqueComponents()) {
numCandidatesForNextSlot--;
}
}
subSolutionsForThisInterface += numberOfPossibleRealizationsForThisFixedNumberOfSlots;
}
if (waysToResolveComponent > 0) {
waysToResolveComponent *= subSolutionsForThisInterface;
} else {
waysToResolveComponent = subSolutionsForThisInterface;
}
}
}
numCandidates += waysToResolveComponent;
}
return numCandidates;
}
public static int getNumberOfParametrizations(final IComponent component) {
int combos = 1;
for (IParameter p : component.getParameters()) {
IParameterDomain domain = p.getDefaultDomain();
if (domain instanceof NumericParameterDomain) {
NumericParameterDomain nDomain = (NumericParameterDomain) domain;
if (!nDomain.isInteger()) {
return Integer.MAX_VALUE;
}
combos *= nDomain.getMax() - nDomain.getMin() + 1;
} else if (domain instanceof CategoricalParameterDomain) {
combos *= ((CategoricalParameterDomain) domain).getValues().length;
}
}
return combos;
}
public static Collection<IComponentInstance> getAllInstantiations(final IComponent component) {
if (!component.getRequiredInterfaces().isEmpty()) {
throw new IllegalArgumentException("Full grounding only enabled for atomic components (without required interfaces).");
}
int numInstances = getNumberOfParametrizations(component);
if (numInstances > 100000) {
throw new IllegalArgumentException("Component " + component.getName() + " has " + numInstances + " possible instantiations. Only up to 100000 are supported.");
}
/* collect param domains as lists */
List<String> paramNames = new ArrayList<>();
List<Collection<Object>> params = new ArrayList<>();
for (IParameter p : component.getParameters()) {
paramNames.add(p.getName());
IParameterDomain domain = p.getDefaultDomain();
if (domain instanceof NumericParameterDomain) {
NumericParameterDomain nDomain = (NumericParameterDomain) domain;
List<Object> items = new ArrayList<>();
for (int i = (int) nDomain.getMin(); i <= nDomain.getMax(); i++) {
items.add(i);
}
params.add(items);
} else if (domain instanceof CategoricalParameterDomain) {
params.add(Arrays.asList((Object[]) ((CategoricalParameterDomain) domain).getValues()));
}
}
/* if this one is not parametrizable */
if (params.isEmpty()) {
return Arrays.asList(ComponentUtil.getDefaultParameterizationOfComponent(component));
}
/* build cartesian product */
Collection<List<Object>> combos = SetUtil.cartesianProduct(params);
List<IComponentInstance> instances = new ArrayList<>();
combos.forEach(c -> {
Map<String, String> paramMap = new HashMap<>();
for (int i = 0; i < paramNames.size(); i++) {
paramMap.put(paramNames.get(i), c.get(i).toString());
}
instances.add(new ComponentInstance(component, paramMap, new HashMap<>()));
});
return instances;
}
public static ComponentInstance getRandomParametrization(final IComponentInstance componentInstance, final Random rand) {
ComponentInstance randomParametrization = getRandomParameterizationOfComponent(componentInstance.getComponent(), rand);
componentInstance.getSatisfactionOfRequiredInterfaces().entrySet()
.forEach(x -> randomParametrization.getSatisfactionOfRequiredInterfaces().put(x.getKey(), Arrays.asList(getRandomParametrization(x.getValue().iterator().next(), rand))));
return randomParametrization;
}
public static boolean hasCycles(final Collection<? extends IComponent> components, final String requiredInterface) {
return hasCycles(components, requiredInterface, new LinkedList<>());
}
private static boolean hasCycles(final Collection<? extends IComponent> components, final String requiredInterface, final List<String> componentList) {
Collection<IComponent> candidates = components.stream().filter(c -> c.getProvidedInterfaces().contains(requiredInterface)).collect(Collectors.toList());
for (IComponent c : candidates) {
if (componentList.contains(c.getName())) {
return true;
}
List<String> componentListCopy = new LinkedList<>(componentList);
componentListCopy.add(c.getName());
for (IRequiredInterfaceDefinition subRequiredInterface : c.getRequiredInterfaces()) {
if (hasCycles(components, subRequiredInterface.getName(), componentListCopy)) {
return true;
}
}
}
return false;
}
public static KVStore getStatsForComponents(final Collection<Component> components) {
KVStore stats = new KVStore();
int numComponents = 0;
int numNumericParams = 0;
int numIntParams = 0;
int numDoubleParams = 0;
int numCatParams = 0;
int numBoolParams = 0;
int otherParams = 0;
for (Component c : components) {
numComponents++;
for (IParameter p : c.getParameters()) {
if (p.getDefaultDomain() instanceof CategoricalParameterDomain) {
numCatParams++;
if (p.getDefaultDomain() instanceof BooleanParameterDomain) {
numBoolParams++;
}
} else if (p.getDefaultDomain() instanceof NumericParameterDomain) {
numNumericParams++;
if (((NumericParameterDomain) p.getDefaultDomain()).isInteger()) {
numIntParams++;
} else {
numDoubleParams++;
}
} else {
otherParams++;
}
}
}
stats.put("nComponents", numComponents);
stats.put("nNumericParameters", numNumericParams);
stats.put("nIntegerParameters", numIntParams);
stats.put("nContinuousParameters", numDoubleParams);
stats.put("nCategoricalParameters", numCatParams);
stats.put("nBooleanParameters", numBoolParams);
stats.put("nOtherParameters", otherParams);
return stats;
}
/**
* Returns a collection of components that is relevant to resolve all recursive dependency when the request concerns a component with the provided required interface.
*
* @param components
* A collection of component to search for relevant components.
* @param requiredInterface
* The requested required interface.
* @return The collection of affected components when requesting the given required interface.
*/
public static Collection<IComponent> getAffectedComponents(final Collection<? extends IComponent> components, final String requiredInterface) {
Collection<IComponent> affectedComponents = new HashSet<>(ComponentUtil.getComponentsProvidingInterface(components, requiredInterface));
if (affectedComponents.isEmpty()) {
throw new IllegalArgumentException("Could not resolve the requiredInterface " + requiredInterface);
}
Set<IComponent> recursiveResolvedComps = new HashSet<>();
affectedComponents.forEach(x -> x.getRequiredInterfaces().stream().map(iface -> getAffectedComponents(components, iface.getName())).forEach(recursiveResolvedComps::addAll));
affectedComponents.addAll(recursiveResolvedComps);
return affectedComponents;
}
public static IComponent getComponentByName(final String componentName, final Collection<? extends IComponent> components) throws ComponentNotFoundException {
for (IComponent component : components) {
if (component.getName().equals(componentName)) {
return component;
}
}
throw new ComponentNotFoundException("No Component with this name loaded: " + componentName);
}
/**
* Creates a randomly samples instantiation of the component. Required interfaces are configured at random too.
*
* @param component
* The root component to be instantiated.
* @param componentRepository
* The repository of available components for satisfying required interfaces.
* @param random
* The pseudo-randomness object.
* @return A component instance of the provided component that is fully configured including the satisfaction of required interfaces.
*/
public static IComponentInstance getRandomInstantiationOfComponent(final String componentName, final IComponentRepository componentRepository, final Random random) {
return getRandomInstantiationOfComponent(componentRepository.getComponent(componentName), componentRepository, random);
}
/**
* Creates a randomly samples instantiation of the component. Required interfaces are configured at random too.
*
* @param component
* The root component to be instantiated.
* @param componentRepository
* The repository of available components for satisfying required interfaces.
* @param random
* The pseudo-randomness object.
* @return A component instance of the provided component that is fully configured including the satisfaction of required interfaces.
*/
public static IComponentInstance getRandomInstantiationOfComponent(final IComponent component, final IComponentRepository componentRepository, final Random random) {
IComponentInstance ci = getRandomParameterizationOfComponent(component, random);
for (IRequiredInterfaceDefinition reqI : component.getRequiredInterfaces()) {
List<IComponent> pluginComponents = new ArrayList<>(ComponentUtil.getComponentsProvidingInterface(componentRepository, reqI.getName()));
int numSatisfactions = 0;
if (reqI.getMin() == reqI.getMax()) {
numSatisfactions = reqI.getMin();
} else {
numSatisfactions = Math.min(pluginComponents.size(), (reqI.getMin() + random.nextInt(reqI.getMax() - reqI.getMin())));
}
List<IComponentInstance> satCIList = new ArrayList<>();
while (satCIList.size() < numSatisfactions) {
IComponent randomComponent = pluginComponents.get(random.nextInt(pluginComponents.size()));
IComponentInstance randomCI = getRandomInstantiationOfComponent(randomComponent, componentRepository, random);
if (reqI.isUniqueComponents()) {
pluginComponents.remove(randomComponent);
}
satCIList.add(randomCI);
}
ci.getSatisfactionOfRequiredInterfaces().put(reqI.getId(), satCIList);
}
return ci;
}
public static boolean areSame(final IComponentInstance c1, final IComponentInstance c2) {
return c1.getComponent().getName().equals(c2.getComponent().getName());
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/CompositionProblemUtil.java
|
package ai.libs.jaicore.components.model;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.math3.geometry.euclidean.oned.Interval;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfiguration;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDependency;
import ai.libs.jaicore.components.api.IParameterDomain;
public class CompositionProblemUtil {
private static final Logger logger = LoggerFactory.getLogger(CompositionProblemUtil.class);
private CompositionProblemUtil() {
/* avoid instantiation */
}
public static Collection<IComponent> getComponentsThatResolveProblem(final SoftwareConfigurationProblem<?> configurationProblem) {
return getComponentsThatProvideInterface(configurationProblem, configurationProblem.getRequiredInterface());
}
public static Collection<IComponent> getComponentsThatProvideInterface(final SoftwareConfigurationProblem<?> configurationProblem, final String requiredInterface){
return configurationProblem.getComponents().stream().filter(c -> c.getProvidedInterfaces().contains(requiredInterface)).collect(Collectors.toList());
}
/**
* Computes a list of all component instances of the given composition.
*
* @param composition
* @return List of components in right to left depth-first order
*/
public static List<IComponentInstance> getComponentInstancesOfComposition(final IComponentInstance composition) {
List<IComponentInstance> components = new LinkedList<>();
Deque<IComponentInstance> componentInstances = new ArrayDeque<>();
componentInstances.push(composition);
IComponentInstance curInstance;
while (!componentInstances.isEmpty()) {
curInstance = componentInstances.pop();
components.add(curInstance);
for (Collection<IComponentInstance> instances : curInstance.getSatisfactionOfRequiredInterfaces().values()) {
instances.forEach(componentInstances::push);
}
}
return components;
}
/**
* Computes a String of component names that appear in the composition which can be used as an identifier for the composition
*
* @param composition
* @return String of all component names in right to left depth-first order
*/
public static String getComponentNamesOfComposition(final IComponentInstance composition) {
StringBuilder builder = new StringBuilder();
Deque<IComponentInstance> componentInstances = new ArrayDeque<>();
componentInstances.push(composition);
IComponentInstance curInstance;
while (!componentInstances.isEmpty()) {
curInstance = componentInstances.pop();
builder.append(curInstance.getComponent().getName());
if (curInstance.getSatisfactionOfRequiredInterfaces() != null) {
for (Collection<IComponentInstance> instances : curInstance.getSatisfactionOfRequiredInterfaces().values()) {
instances.forEach(componentInstances::push);
}
}
}
return builder.toString();
}
/**
* Computes a list of all components of the given composition.
*
* @param composition
* @return List of components in right to left depth-first order
*/
public static List<IComponent> getComponentsOfComposition(final IComponentInstance composition) {
List<IComponent> components = new LinkedList<>();
Deque<IComponentInstance> componentInstances = new ArrayDeque<>();
componentInstances.push(composition);
IComponentInstance curInstance;
while (!componentInstances.isEmpty()) {
curInstance = componentInstances.pop();
components.add(curInstance.getComponent());
for (Collection<IComponentInstance> instances : curInstance.getSatisfactionOfRequiredInterfaces().values()) {
instances.forEach(componentInstances::push);
}
}
return components;
}
public static boolean isDependencyPremiseSatisfied(final IParameterDependency dependency, final Map<IParameter, IParameterDomain> values) {
logger.debug("Checking satisfcation of dependency {} with values {}", dependency, values);
for (Collection<Pair<IParameter, IParameterDomain>> condition : dependency.getPremise()) {
boolean check = isDependencyConditionSatisfied(condition, values);
logger.trace("Result of check for condition {}: {}", condition, check);
if (!check) {
return false;
}
}
return true;
}
public static boolean isDependencyConditionSatisfied(final Collection<Pair<IParameter, IParameterDomain>> condition, final Map<IParameter, IParameterDomain> values) {
for (Pair<IParameter, IParameterDomain> conditionItem : condition) {
IParameter param = conditionItem.getX();
if (!values.containsKey(param)) {
throw new IllegalArgumentException("Cannot check condition " + condition + " as the value for parameter " + param.getName() + " is not defined in " + values);
}
if (values.get(param) == null) {
throw new IllegalArgumentException("Cannot check condition " + condition + " as the value for parameter " + param.getName() + " is NULL in " + values);
}
IParameterDomain requiredDomain = conditionItem.getY();
IParameterDomain actualDomain = values.get(param);
if (!requiredDomain.subsumes(actualDomain)) {
return false;
}
}
return true;
}
public static List<Interval> getNumericParameterRefinement(final Interval interval, final double focus, final boolean integer, final INumericParameterRefinementConfiguration refinementConfig) {
double inf = interval.getInf();
double sup = interval.getSup();
/* if there is nothing to refine anymore */
if (inf == sup) {
return new ArrayList<>();
}
/*
* if this is an integer and the number of comprised integers are at most as
* many as the branching factor, enumerate them
*/
if (integer && (Math.floor(sup) - Math.ceil(inf) + 1 <= refinementConfig.getRefinementsPerStep())) {
List<Interval> proposedRefinements = new ArrayList<>();
for (int i = (int) Math.ceil(inf); i <= (int) Math.floor(sup); i++) {
proposedRefinements.add(new Interval(i, i));
}
return proposedRefinements;
}
/*
* if the interval is already below the threshold for this parameter, no more
* refinements will be allowed
*/
if (sup - inf < refinementConfig.getIntervalLength()) {
return new ArrayList<>();
}
if (!refinementConfig.isInitRefinementOnLogScale()) {
List<Interval> proposedRefinements = refineOnLinearScale(interval, refinementConfig.getRefinementsPerStep(), refinementConfig.getIntervalLength());
for (Interval proposedRefinement : proposedRefinements) {
assert proposedRefinement.getInf() >= inf && proposedRefinement.getSup() <= sup : "The proposed refinement [" + proposedRefinement.getInf() + ", " + proposedRefinement.getSup() + "] is not a sub-interval of [" + inf + ", "
+ sup + "].";
if (proposedRefinement.equals(interval)) {
throw new IllegalStateException("No real refinement! Intervals are identical.");
}
}
return proposedRefinements;
}
List<Interval> proposedRefinements = refineOnLogScale(interval, refinementConfig.getRefinementsPerStep(), 2, focus);
for (Interval proposedRefinement : proposedRefinements) {
double epsilon = 1E-7;
assert proposedRefinement.getInf() + epsilon >= inf && proposedRefinement.getSup() <= sup + epsilon : "The proposed refinement [" + proposedRefinement.getInf() + ", " + proposedRefinement.getSup()
+ "] is not a sub-interval of [" + inf + ", " + sup + "].";
if (proposedRefinement.equals(interval)) {
throw new IllegalStateException("No real refinement! Intervals are identical.");
}
}
return proposedRefinements;
}
public static List<Interval> refineOnLinearScale(final Interval interval, final int maxNumberOfSubIntervals, final double minimumLengthOfIntervals) {
double min = interval.getInf();
double max = interval.getSup();
double length = max - min;
List<Interval> intervals = new ArrayList<>();
/* if no refinement is possible, return just the interval itself */
if (length <= minimumLengthOfIntervals) {
intervals.add(interval);
return intervals;
}
/* otherwise compute the sub-intervals */
int numberOfIntervals = Math.min((int) Math.ceil(length / minimumLengthOfIntervals), maxNumberOfSubIntervals);
double stepSize = length / numberOfIntervals;
for (int i = 0; i < numberOfIntervals; i++) {
intervals.add(new Interval(min + i * stepSize, min + ((i + 1) * stepSize)));
}
return intervals;
}
public static List<Interval> refineOnLogScale(final Interval interval, final int n, final double basis, final double pointOfConcentration) {
List<Interval> list = new ArrayList<>();
double min = interval.getInf();
double max = interval.getSup();
double length = max - min;
/*
* if the point of concentration is exactly on the left or the right of the
* interval, conduct the standard technique
*/
if (pointOfConcentration <= min || pointOfConcentration >= max) {
double lengthOfShortestInterval = length * (1 - basis) / (1 - Math.pow(basis, n));
if (pointOfConcentration <= min) {
double endOfLast = min;
for (int i = 0; i < n; i++) {
double start = endOfLast;
endOfLast = start + Math.pow(basis, i) * lengthOfShortestInterval;
list.add(new Interval(start, endOfLast));
}
} else {
double endOfLast = max;
for (int i = 0; i < n; i++) {
double start = endOfLast;
endOfLast = start - Math.pow(basis, i) * lengthOfShortestInterval;
list.add(new Interval(endOfLast, start));
}
Collections.reverse(list);
}
return list;
}
/*
* if the point of concentration is in the inner of the interval, split the
* interval correspondingly and recursively solve the problem
*/
double distanceFromMinToFocus = Math.abs(interval.getInf() - pointOfConcentration);
int segmentsForLeft = (int) Math.max(1, Math.floor(n * distanceFromMinToFocus / length));
int segmentsForRight = n - segmentsForLeft;
list.addAll(refineOnLogScale(new Interval(min, pointOfConcentration), segmentsForLeft, basis, pointOfConcentration));
list.addAll(refineOnLogScale(new Interval(pointOfConcentration, max), segmentsForRight, basis, pointOfConcentration));
return list;
}
public static void refineRecursively(final Interval interval, final int maxNumberOfSubIntervalsPerRefinement, final double basis, final double pointOfConcentration, final double factorForMaximumLengthOfFinestIntervals) {
/* first, do a logarithmic refinement */
List<Interval> initRefinement = refineOnLogScale(interval, maxNumberOfSubIntervalsPerRefinement, basis, pointOfConcentration);
Collections.reverse(initRefinement);
Deque<Interval> openRefinements = new LinkedList<>();
openRefinements.addAll(initRefinement);
int depth = 0;
do {
Interval intervalToRefine = openRefinements.pop();
if (logger.isInfoEnabled()) {
StringBuilder offsetSB = new StringBuilder();
for (int i = 0; i < depth; i++) {
offsetSB.append("\t");
}
logger.info("{}[{}, {}]", offsetSB, intervalToRefine.getInf(), intervalToRefine.getSup());
}
/* compute desired granularity for this specific interval */
double distanceToPointOfContentration = Math.min(Math.abs(intervalToRefine.getInf() - pointOfConcentration), Math.abs(intervalToRefine.getSup() - pointOfConcentration));
double maximumLengthOfFinestIntervals = Math.pow(distanceToPointOfContentration + 1, 2) * factorForMaximumLengthOfFinestIntervals;
logger.info("{} * {} = {}", Math.pow(distanceToPointOfContentration + 1, 2), factorForMaximumLengthOfFinestIntervals, maximumLengthOfFinestIntervals);
List<Interval> refinements = refineOnLinearScale(intervalToRefine, maxNumberOfSubIntervalsPerRefinement, maximumLengthOfFinestIntervals);
depth++;
if (refinements.size() == 1 && refinements.get(0).equals(intervalToRefine)) {
depth--;
} else {
Collections.reverse(refinements);
openRefinements.addAll(refinements);
}
} while (!openRefinements.isEmpty());
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/Dependency.java
|
package ai.libs.jaicore.components.model;
import java.io.Serializable;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDependency;
import ai.libs.jaicore.components.api.IParameterDomain;
public class Dependency implements IParameterDependency, Serializable {
private static final long serialVersionUID = -954852106121507946L;
private final Collection<Collection<Pair<IParameter, IParameterDomain>>> premise; // semantics are DNF (every entry is an AND-connected constraint)
private final Collection<Pair<IParameter, IParameterDomain>> conclusion;
@JsonCreator
public Dependency(@JsonProperty("premise") final Collection<Collection<Pair<IParameter, IParameterDomain>>> premise, @JsonProperty("conclusion") final Collection<Pair<IParameter, IParameterDomain>> conclusion) {
super();
this.premise = premise;
this.conclusion = conclusion;
}
@Override
public Collection<Collection<Pair<IParameter, IParameterDomain>>> getPremise() {
return this.premise;
}
@Override
public Collection<Pair<IParameter, IParameterDomain>> getConclusion() {
return this.conclusion;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.conclusion == null) ? 0 : this.conclusion.hashCode());
result = prime * result + ((this.premise == null) ? 0 : this.premise.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Dependency other = (Dependency) obj;
if (this.conclusion == null) {
if (other.conclusion != null) {
return false;
}
} else if (!this.conclusion.equals(other.conclusion)) {
return false;
}
if (this.premise == null) {
if (other.premise != null) {
return false;
}
} else if (!this.premise.equals(other.premise)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.premise);
sb.append(" => ");
sb.append(this.conclusion);
return sb.toString();
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/Interface.java
|
package ai.libs.jaicore.components.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import ai.libs.jaicore.components.api.IRequiredInterfaceDefinition;
@JsonPropertyOrder({ "id", "name", "optional", "min", "max" })
public class Interface implements IRequiredInterfaceDefinition, Serializable {
private static final long serialVersionUID = -668580435561427897L;
private final String id;
private final String name;
private final boolean optional;
private final boolean uniqueComponents;
private final boolean ordered;
private final Integer min;
private final Integer max;
@JsonCreator
public Interface(@JsonProperty("id") final String id, @JsonProperty("name") final String name, @JsonProperty("optional") final Boolean optional, @JsonProperty("uniquecomponents") final Boolean uniqueComponents, @JsonProperty("ordered") final Boolean ordered, @JsonProperty("min") final Integer min, @JsonProperty("max") final Integer max) {
this.id = id;
this.name = name;
this.optional = optional;
this.ordered = ordered;
this.uniqueComponents = uniqueComponents;
this.min = min;
this.max = max;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getMin() {
return this.min;
}
@Override
public int getMax() {
return this.max;
}
@Override
public boolean isUniqueComponents() {
return this.uniqueComponents;
}
@Override
public boolean isOrdered() {
return this.ordered;
}
@Override
public boolean isOptional() {
return this.optional;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
result = prime * result + ((this.max == null) ? 0 : this.max.hashCode());
result = prime * result + ((this.min == null) ? 0 : this.min.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + (this.optional ? 1231 : 1237);
result = prime * result + (this.ordered ? 1231 : 1237);
result = prime * result + (this.uniqueComponents ? 1231 : 1237);
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Interface other = (Interface) obj;
if (this.id == null) {
if (other.id != null) {
return false;
}
} else if (!this.id.equals(other.id)) {
return false;
}
if (this.max == null) {
if (other.max != null) {
return false;
}
} else if (!this.max.equals(other.max)) {
return false;
}
if (this.min == null) {
if (other.min != null) {
return false;
}
} else if (!this.min.equals(other.min)) {
return false;
}
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
if (this.optional != other.optional) {
return false;
}
if (this.ordered != other.ordered) {
return false;
}
return this.uniqueComponents == other.uniqueComponents;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/NumericParameterDomain.java
|
package ai.libs.jaicore.components.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.libs.jaicore.basic.sets.Interval;
import ai.libs.jaicore.components.api.IParameterDomain;
public class NumericParameterDomain extends Interval implements IParameterDomain {
private static final long serialVersionUID = 7445944456747209248L;
@JsonCreator
public NumericParameterDomain(@JsonProperty("integer") final boolean isInteger, @JsonProperty("min") final double min, @JsonProperty("max") final double max) {
super(isInteger, min, max);
}
@Override
public boolean subsumes(final IParameterDomain otherDomain) {
if (!(otherDomain instanceof NumericParameterDomain)) {
return false;
}
return this.subsumes((Interval)otherDomain);
}
@Override
public boolean isEquals(final Object obj0, final Object obj1) {
return Math.abs(Double.parseDouble(obj0 + "") - Double.parseDouble(obj1 + "")) < 1E-8;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/NumericParameterRefinementConfiguration.java
|
package ai.libs.jaicore.components.model;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfiguration;
public class NumericParameterRefinementConfiguration implements INumericParameterRefinementConfiguration {
private final boolean initRefinementOnLogScale;
private final double focusPoint;
private final double logBasis;
private final boolean initWithExtremalPoints; // make the end-points of the interval explicit choices on the first level
private final int refinementsPerStep;
private final double intervalLength;
public NumericParameterRefinementConfiguration(final boolean initWithExtremalPoints, final int refinementsPerStep, final double intervalLength) {
this(Double.NaN, 0, initWithExtremalPoints, refinementsPerStep, intervalLength);
}
public NumericParameterRefinementConfiguration(final double focusPoint, final double logBasis, final boolean initWithExtremalPoints, final int refinementsPerStep, final double intervalLength) {
super();
if (intervalLength <= 0) {
throw new IllegalArgumentException("Interval length must be strictly positive but is " + intervalLength);
}
this.focusPoint = focusPoint;
this.logBasis = logBasis;
this.initRefinementOnLogScale = !Double.isNaN(focusPoint);
this.initWithExtremalPoints = initWithExtremalPoints;
this.refinementsPerStep = refinementsPerStep;
this.intervalLength = intervalLength;
}
@Override
public boolean isInitRefinementOnLogScale() {
return this.initRefinementOnLogScale;
}
@Override
public double getFocusPoint() {
return this.focusPoint;
}
@Override
public double getLogBasis() {
return this.logBasis;
}
@Override
public boolean isInitWithExtremalPoints() {
return this.initWithExtremalPoints;
}
@Override
public int getRefinementsPerStep() {
return this.refinementsPerStep;
}
@Override
public double getIntervalLength() {
return this.intervalLength;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[InitiallyLogScale:");
sb.append(this.initRefinementOnLogScale);
sb.append(",RefinementsPerStep:");
sb.append(this.refinementsPerStep);
sb.append(",intervalLength:");
sb.append(this.intervalLength);
sb.append("]");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(this.focusPoint);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + (this.initRefinementOnLogScale ? 1231 : 1237);
result = prime * result + (this.initWithExtremalPoints ? 1231 : 1237);
temp = Double.doubleToLongBits(this.intervalLength);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.logBasis);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + this.refinementsPerStep;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
NumericParameterRefinementConfiguration other = (NumericParameterRefinementConfiguration) obj;
if (Double.doubleToLongBits(this.focusPoint) != Double.doubleToLongBits(other.focusPoint)) {
return false;
}
if (this.initRefinementOnLogScale != other.initRefinementOnLogScale) {
return false;
}
if (this.initWithExtremalPoints != other.initWithExtremalPoints) {
return false;
}
if (Double.doubleToLongBits(this.intervalLength) != Double.doubleToLongBits(other.intervalLength)) {
return false;
}
if (Double.doubleToLongBits(this.logBasis) != Double.doubleToLongBits(other.logBasis)) {
return false;
}
return this.refinementsPerStep == other.refinementsPerStep;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/NumericParameterRefinementConfigurationMap.java
|
package ai.libs.jaicore.components.model;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfigurationMap;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfiguration;
import ai.libs.jaicore.components.api.IParameter;
public class NumericParameterRefinementConfigurationMap extends HashMap<String, Map<String, NumericParameterRefinementConfiguration>> implements INumericParameterRefinementConfigurationMap {
@Override
public Collection<String> getParameterNamesForWhichARefinementIsDefined(final IComponent component) {
return this.get(component.getName()).keySet();
}
@Override
public INumericParameterRefinementConfiguration getRefinement(final IComponent component, final IParameter parameter) {
return this.getRefinement(component.getName(), parameter.getName());
}
@Override
public INumericParameterRefinementConfiguration getRefinement(final String componentName, final String parameterName) {
return this.get(componentName).get(parameterName);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/Parameter.java
|
package ai.libs.jaicore.components.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDomain;
@JsonPropertyOrder({ "name", "defaultDomain", "defaultValue" })
public class Parameter implements IParameter, Serializable {
private static final long serialVersionUID = 8735407907221383716L;
private final String name;
private final IParameterDomain defaultDomain;
private final Serializable defaultValue;
@SuppressWarnings("unused")
private Parameter() {
// for serialization purposes
this.name = null;
this.defaultDomain = null;
this.defaultValue = null;
}
@JsonCreator
public Parameter(@JsonProperty("name") final String name, @JsonProperty("defaultDomain") final IParameterDomain defaultDomain, @JsonProperty("defaultValue") final Serializable defaultValue) {
super();
this.name = name;
this.defaultDomain = defaultDomain;
if (!defaultDomain.contains(defaultValue)) {
throw new IllegalArgumentException("The domain provided for parameter " + name + " is " + defaultDomain + " and does not contain the assigned default value " + defaultValue);
}
this.defaultValue = defaultValue;
}
@Override
public String getName() {
return this.name;
}
public IParameterDomain getDefaultDomain() {
return this.defaultDomain;
}
public Object getDefaultValue() {
return this.defaultValue;
}
public boolean isDefaultValue(final Object value) {
return this.defaultDomain.isEquals(this.defaultValue, value);
}
public boolean isNumeric() {
return this.defaultDomain instanceof NumericParameterDomain;
}
public boolean isCategorical() {
return this.defaultDomain instanceof CategoricalParameterDomain;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.defaultDomain == null) ? 0 : this.defaultDomain.hashCode());
result = prime * result + ((this.defaultValue == null) ? 0 : this.defaultValue.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Parameter other = (Parameter) obj;
if (this.defaultDomain == null) {
if (other.defaultDomain != null) {
return false;
}
} else if (!this.defaultDomain.equals(other.defaultDomain)) {
return false;
}
if (this.defaultValue == null) {
if (other.defaultValue != null) {
return false;
}
} else if (!this.defaultValue.equals(other.defaultValue)) {
return false;
}
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
return this.name;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/RefinementConfiguredSoftwareConfigurationProblem.java
|
package ai.libs.jaicore.components.model;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfiguration;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfigurationMap;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.serialization.ComponentSerialization;
/**
* In this problem, the core software configuration problem is extended by predefining how the the parameters may be refined
*
* @author fmohr
*
* @param <V>
*/
public class RefinementConfiguredSoftwareConfigurationProblem<V extends Comparable<V>> extends SoftwareConfigurationProblem<V> {
private final INumericParameterRefinementConfigurationMap paramRefinementConfig;
public RefinementConfiguredSoftwareConfigurationProblem(final Collection<? extends IComponent> components, final String requiredInterface, final IObjectEvaluator<IComponentInstance, V> compositionEvaluator,
final INumericParameterRefinementConfigurationMap paramRefinementConfig) {
this(new SoftwareConfigurationProblem<>(components, requiredInterface, compositionEvaluator), paramRefinementConfig);
}
public RefinementConfiguredSoftwareConfigurationProblem(final RefinementConfiguredSoftwareConfigurationProblem<V> problemTemplate, final Collection<? extends IComponent> components,
final INumericParameterRefinementConfigurationMap paramRefinementConfig) {
this(components, problemTemplate.getRequiredInterface(), problemTemplate.getCompositionEvaluator(), paramRefinementConfig);
}
public RefinementConfiguredSoftwareConfigurationProblem(final RefinementConfiguredSoftwareConfigurationProblem<V> problemTemplate, final IObjectEvaluator<IComponentInstance, V> evaluator) {
this(problemTemplate.getComponents(), problemTemplate.getRequiredInterface(), evaluator, problemTemplate.getParamRefinementConfig());
}
public RefinementConfiguredSoftwareConfigurationProblem(final RefinementConfiguredSoftwareConfigurationProblem<V> problemTemplate, final String requiredInterface) {
this(problemTemplate.getComponents(), requiredInterface, problemTemplate.getCompositionEvaluator(), problemTemplate.getParamRefinementConfig());
}
public RefinementConfiguredSoftwareConfigurationProblem(final File configurationFile, final String requiredInterface, final IObjectEvaluator<IComponentInstance, V> compositionEvaluator) throws IOException {
super(configurationFile, requiredInterface, compositionEvaluator);
this.paramRefinementConfig = new ComponentSerialization().deserializeParamMap(configurationFile);
/* check that parameter refinements are defined for all components */
for (IComponent c : this.getComponents()) {
for (IParameter p : c.getParameters()) {
if (p.isNumeric()) {
if (this.paramRefinementConfig.getRefinement(c, p) == null) {
throw new IllegalArgumentException("Error in parsing config file " + configurationFile.getAbsolutePath() + ". No refinement config was delivered for numeric parameter " + p.getName() + " of component " + c.getName());
}
NumericParameterDomain domain = (NumericParameterDomain)p.getDefaultDomain();
INumericParameterRefinementConfiguration refinementConfig = this.paramRefinementConfig.getRefinement(c, p);
double range = domain.getMax() - domain.getMin();
if (range > 0 && refinementConfig.getIntervalLength() >= range) {
throw new IllegalArgumentException("Error in parsing config file " + configurationFile.getAbsolutePath() + ". The defined interval length " + refinementConfig.getIntervalLength() + " for parameter " + p.getName() + " of component " + c.getName() + " is not strictly smaller than the parameter range " + (domain.getMax() - domain.getMin() + " of interval [" + domain.getMin() + ", " + domain.getMax() + "]. No refinement is possible hence."));
}
}
}
}
}
public RefinementConfiguredSoftwareConfigurationProblem(final SoftwareConfigurationProblem<V> coreProblem, final INumericParameterRefinementConfigurationMap paramRefinementConfig) {
super(coreProblem);
this.paramRefinementConfig = paramRefinementConfig;
}
public INumericParameterRefinementConfigurationMap getParamRefinementConfig() {
return this.paramRefinementConfig;
}
@Override
public int hashCode() {
final int prime = 31;
return prime + ((this.paramRefinementConfig == null) ? 0 : this.paramRefinementConfig.hashCode());
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
RefinementConfiguredSoftwareConfigurationProblem<?> other = (RefinementConfiguredSoftwareConfigurationProblem<?>) obj;
if (this.paramRefinementConfig == null) {
if (other.paramRefinementConfig != null) {
return false;
}
} else if (!this.paramRefinementConfig.equals(other.paramRefinementConfig)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/SoftwareConfigurationProblem.java
|
package ai.libs.jaicore.components.model;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.api4.java.common.attributedobjects.IObjectEvaluator;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IComponentRepository;
import ai.libs.jaicore.components.serialization.ComponentSerialization;
import ai.libs.jaicore.logging.ToJSONStringUtil;
public class SoftwareConfigurationProblem<V extends Comparable<V>> {
private final IComponentRepository components;
private final String requiredInterface;
private final IObjectEvaluator<IComponentInstance, V> compositionEvaluator;
public SoftwareConfigurationProblem(final File configurationFile, final String requiredInerface, final IObjectEvaluator<IComponentInstance, V> compositionEvaluator) throws IOException {
this.components = new ComponentSerialization().deserializeRepository(configurationFile);
this.requiredInterface = requiredInerface;
if (requiredInerface == null || requiredInerface.isEmpty()) {
throw new IllegalArgumentException("Invalid required interface \"" + requiredInerface + "\"");
}
this.compositionEvaluator = compositionEvaluator;
}
public SoftwareConfigurationProblem(final Collection<? extends IComponent> components, final String requiredInterface, final IObjectEvaluator<IComponentInstance, V> compositionEvaluator) {
super();
this.components = new ComponentRepository(components);
this.requiredInterface = requiredInterface;
this.compositionEvaluator = compositionEvaluator;
if (requiredInterface == null || requiredInterface.isEmpty()) {
throw new IllegalArgumentException("Invalid required interface \"" + requiredInterface + "\"");
}
}
public SoftwareConfigurationProblem(final SoftwareConfigurationProblem<V> problem) {
this(problem.getComponents(), problem.requiredInterface, problem.compositionEvaluator);
}
public IComponentRepository getComponents() {
return this.components;
}
public String getRequiredInterface() {
return this.requiredInterface;
}
public IObjectEvaluator<IComponentInstance, V> getCompositionEvaluator() {
return this.compositionEvaluator;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.components == null) ? 0 : this.components.hashCode());
result = prime * result + ((this.compositionEvaluator == null) ? 0 : this.compositionEvaluator.hashCode());
result = prime * result + ((this.requiredInterface == null) ? 0 : this.requiredInterface.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
SoftwareConfigurationProblem<?> other = (SoftwareConfigurationProblem<?>) obj;
if (this.components == null) {
if (other.components != null) {
return false;
}
} else if (!this.components.equals(other.components)) {
return false;
}
if (this.compositionEvaluator == null) {
if (other.compositionEvaluator != null) {
return false;
}
} else if (!this.compositionEvaluator.equals(other.compositionEvaluator)) {
return false;
}
if (this.requiredInterface == null) {
if (other.requiredInterface != null) {
return false;
}
} else if (!this.requiredInterface.equals(other.requiredInterface)) {
return false;
}
return true;
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("components", this.components);
fields.put("requiredInterface", this.requiredInterface);
fields.put("compositionEvaluator", this.compositionEvaluator);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/model/UnparametrizedComponentInstance.java
|
package ai.libs.jaicore.components.model;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.logging.ToJSONStringUtil;
public class UnparametrizedComponentInstance {
private final String componentName;
private final Map<String, List<UnparametrizedComponentInstance>> satisfactionOfRequiredInterfaces;
public UnparametrizedComponentInstance(final String componentName, final Map<String, List<UnparametrizedComponentInstance>> satisfactionOfRequiredInterfaces) {
super();
this.componentName = componentName;
this.satisfactionOfRequiredInterfaces = satisfactionOfRequiredInterfaces;
}
public UnparametrizedComponentInstance(final IComponentInstance composition) {
Map<String, List<IComponentInstance>> resolvedRequiredInterfaces = composition.getSatisfactionOfRequiredInterfaces();
this.satisfactionOfRequiredInterfaces = new HashMap<>();
resolvedRequiredInterfaces.keySet().forEach(r -> this.satisfactionOfRequiredInterfaces.put(r, resolvedRequiredInterfaces.get(r).stream().map(UnparametrizedComponentInstance::new).collect(Collectors.toList())));
this.componentName = composition.getComponent().getName();
}
public String getComponentName() {
return this.componentName;
}
public Map<String, List<UnparametrizedComponentInstance>> getSatisfactionOfRequiredInterfaces() {
return this.satisfactionOfRequiredInterfaces;
}
/**
* Determines the sub-composition under a path of required interfaces
**/
public UnparametrizedComponentInstance getSubComposition(final List<String> path) {
UnparametrizedComponentInstance current = this;
for (String requiredInterface : path) {
if (!current.getSatisfactionOfRequiredInterfaces().containsKey(requiredInterface)) {
throw new IllegalArgumentException("Invalid path " + path + " (size " + path.size() + "). The component " + current.getComponentName() + " does not have a required interface with id \"" + requiredInterface + "\"");
}
List<UnparametrizedComponentInstance> provisionOfRequiredInterface = current.getSatisfactionOfRequiredInterfaces().get(requiredInterface);
if (provisionOfRequiredInterface.size() > 1) {
throw new UnsupportedOperationException("Currently it is not possible to filter along paths with several instances!!");
}
current = provisionOfRequiredInterface.get(0);
}
return current;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.componentName).append(this.satisfactionOfRequiredInterfaces).hashCode();
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || obj.getClass() != UnparametrizedComponentInstance.class) {
return false;
}
UnparametrizedComponentInstance other = (UnparametrizedComponentInstance) obj;
return new EqualsBuilder().append(this.componentName, other.componentName).append(this.satisfactionOfRequiredInterfaces, other.satisfactionOfRequiredInterfaces).isEquals();
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("componentName", this.componentName);
fields.put("satisfactionOfRequiredInterfaces", this.satisfactionOfRequiredInterfaces);
return ToJSONStringUtil.toJSONString(this.getClass().getSimpleName(), fields);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/optimizingfactory/BaseFactory.java
|
package ai.libs.jaicore.components.optimizingfactory;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.exceptions.ComponentInstantiationFailedException;
public interface BaseFactory<T> {
public T getComponentInstantiation(IComponentInstance groundComponent) throws ComponentInstantiationFailedException, InterruptedException;
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/optimizingfactory/OptimizingFactory.java
|
package ai.libs.jaicore.components.optimizingfactory;
import java.util.HashMap;
import java.util.Map;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.AAlgorithm;
import ai.libs.jaicore.basic.algorithm.AlgorithmFinishedEvent;
import ai.libs.jaicore.basic.algorithm.AlgorithmInitializedEvent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IEvaluatedSoftwareConfigurationSolution;
import ai.libs.jaicore.components.exceptions.ComponentInstantiationFailedException;
import ai.libs.jaicore.components.model.SoftwareConfigurationProblem;
import ai.libs.jaicore.logging.ToJSONStringUtil;
public class OptimizingFactory<P extends SoftwareConfigurationProblem<V>, T, C extends IEvaluatedSoftwareConfigurationSolution<V>, V extends Comparable<V>> extends AAlgorithm<OptimizingFactoryProblem<P, T, V>, T> {
/* logging */
private Logger localLogger = LoggerFactory.getLogger(OptimizingFactory.class);
private String loggerName;
private final SoftwareConfigurationAlgorithmFactory<P, C, V, ?> factoryForOptimizationAlgorithm;
private T constructedObject;
private V performanceOfObject;
private IComponentInstance componentInstanceOfObject;
private final SoftwareConfigurationAlgorithm<P, C, V> optimizer;
public OptimizingFactory(final OptimizingFactoryProblem<P, T, V> problem, final SoftwareConfigurationAlgorithmFactory<P, C, V, ?> factoryForOptimizationAlgorithm) {
super(problem);
this.factoryForOptimizationAlgorithm = factoryForOptimizationAlgorithm;
this.optimizer = this.factoryForOptimizationAlgorithm.getAlgorithm(this.getInput().getConfigurationProblem());
this.optimizer.registerListener(new Object() {
@Subscribe
public void receiveAlgorithmEvent(final IAlgorithmEvent event) {
if (!(event instanceof AlgorithmInitializedEvent || event instanceof AlgorithmFinishedEvent)) {
OptimizingFactory.this.post(event);
}
}
});
}
@Override
public IAlgorithmEvent nextWithException() throws AlgorithmException, InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
switch (this.getState()) {
case CREATED:
/* initialize optimizer */
IAlgorithmEvent initEvent = this.optimizer.next();
assert initEvent instanceof AlgorithmInitializedEvent : "The first event emitted by the optimizer has not been its AlgorithmInitializationEvent";
return this.activate();
case ACTIVE:
C solutionModel = this.optimizer.call();
try {
this.constructedObject = this.getInput().getBaseFactory().getComponentInstantiation(solutionModel.getComponentInstance());
this.performanceOfObject = solutionModel.getScore();
this.componentInstanceOfObject = solutionModel.getComponentInstance();
return this.terminate();
} catch (ComponentInstantiationFailedException e) {
throw new AlgorithmException("Could not conduct next step in OptimizingFactory due to an exception in the component instantiation.", e);
}
default:
throw new IllegalStateException("Cannot do anything in state " + this.getState());
}
}
@Override
public T call() throws AlgorithmException, InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException {
while (this.hasNext()) {
this.nextWithException();
}
return this.constructedObject;
}
/**
* @return the optimizer that is used for building the object
*/
public SoftwareConfigurationAlgorithm<P, C, V> getOptimizer() {
return this.optimizer;
}
public AlgorithmInitializedEvent init() {
IAlgorithmEvent e = null;
while (this.hasNext()) {
e = this.next();
if (e instanceof AlgorithmInitializedEvent) {
return (AlgorithmInitializedEvent) e;
}
}
throw new IllegalStateException("Could not complete initialization");
}
public V getPerformanceOfObject() {
return this.performanceOfObject;
}
public IComponentInstance getComponentInstanceOfObject() {
return this.componentInstanceOfObject;
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.localLogger.info("Switching logger from {} to {}", this.localLogger.getName(), name);
this.loggerName = name;
this.localLogger = LoggerFactory.getLogger(name);
this.localLogger.info("Activated logger {} with name {}", name, this.localLogger.getName());
if (this.optimizer instanceof ILoggingCustomizable) {
this.optimizer.setLoggerName(name + ".optimizer");
}
super.setLoggerName(this.loggerName + "._algorithm");
}
@Override
public String toString() {
Map<String, Object> fields = new HashMap<>();
fields.put("factoryForOptimizationAlgorithm", this.factoryForOptimizationAlgorithm);
fields.put("constructedObject", this.constructedObject);
fields.put("performanceOfObject", this.performanceOfObject);
fields.put("optimizer", this.optimizer);
return ToJSONStringUtil.toJSONString(fields);
}
@Override
public void cancel() {
this.localLogger.info("Received cancel. First canceling the optimizer {}, then my own routine!", this.optimizer.getId());
this.optimizer.cancel();
this.localLogger.debug("Now canceling the OptimizingFactory itself.");
super.cancel();
assert this.isCanceled() : "Cancel-flag must be true at end of cancel routine!";
}
@Override
public void setTimeout(final Timeout to) {
super.setTimeout(to);
this.localLogger.info("Forwarding timeout {} to optimizer.", to);
this.optimizer.setTimeout(to);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/optimizingfactory/OptimizingFactoryProblem.java
|
package ai.libs.jaicore.components.optimizingfactory;
import ai.libs.jaicore.components.model.SoftwareConfigurationProblem;
public class OptimizingFactoryProblem<P extends SoftwareConfigurationProblem<V>, T, V extends Comparable<V>> {
private final BaseFactory<T> baseFactory;
private final P configurationProblem;
public OptimizingFactoryProblem(final BaseFactory<T> baseFactory, final P configurationProblem) {
super();
this.baseFactory = baseFactory;
this.configurationProblem = configurationProblem;
}
public BaseFactory<T> getBaseFactory() {
return this.baseFactory;
}
public P getConfigurationProblem() {
return this.configurationProblem;
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/optimizingfactory/SoftwareConfigurationAlgorithm.java
|
package ai.libs.jaicore.components.optimizingfactory;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
import ai.libs.jaicore.basic.algorithm.AOptimizer;
import ai.libs.jaicore.components.api.IEvaluatedSoftwareConfigurationSolution;
import ai.libs.jaicore.components.model.SoftwareConfigurationProblem;
public abstract class SoftwareConfigurationAlgorithm<P extends SoftwareConfigurationProblem<V>, O extends IEvaluatedSoftwareConfigurationSolution<V>, V extends Comparable<V>> extends AOptimizer<P, O, V> {
protected SoftwareConfigurationAlgorithm(final P input) {
super(input);
}
protected SoftwareConfigurationAlgorithm(final IOwnerBasedAlgorithmConfig config, final P input) {
super(config, input);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/optimizingfactory/SoftwareConfigurationAlgorithmFactory.java
|
package ai.libs.jaicore.components.optimizingfactory;
import org.api4.java.algorithm.IAlgorithmFactory;
import ai.libs.jaicore.components.api.IEvaluatedSoftwareConfigurationSolution;
import ai.libs.jaicore.components.model.SoftwareConfigurationProblem;
public interface SoftwareConfigurationAlgorithmFactory<P extends SoftwareConfigurationProblem<V>, O extends IEvaluatedSoftwareConfigurationSolution<V>, V extends Comparable<V>, A extends SoftwareConfigurationAlgorithm<P, O, V>> extends IAlgorithmFactory<P, O, A> {
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/serialization/ComponentInstanceDeserializer.java
|
package ai.libs.jaicore.components.serialization;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.ArrayNode;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.model.ComponentInstance;
public class ComponentInstanceDeserializer extends StdDeserializer<ComponentInstance> {
/**
*
*/
private static final long serialVersionUID = 4216559441244072999L;
private transient Collection<IComponent> possibleComponents; // the idea is not to serialize the deserializer, so this can be transient
public ComponentInstanceDeserializer(final Collection<? extends IComponent> possibleComponents) {
super(ComponentInstance.class);
this.possibleComponents = new ArrayList<>(possibleComponents);
}
public ComponentInstance readFromJson(final String json) throws IOException {
return this.readAsTree(new ObjectMapper().readTree(json));
}
@SuppressWarnings("unchecked")
public ComponentInstance readAsTree(final JsonNode p) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// read the parameter values
Map<String, String> parameterValues = new HashMap<>();
if (p.has("params")) {
parameterValues = mapper.treeToValue(p.get("params"), HashMap.class);
}
// read the component
String componentName = p.get("component").toString().replace("\"", "");
IComponent component = this.possibleComponents.stream().filter(c -> c.getName().equals(componentName)).findFirst().orElseThrow(NoSuchElementException::new);
Map<String, List<IComponentInstance>> satisfactionOfRequiredInterfaces = new HashMap<>();
// recursively resolve the requiredInterfaces
JsonNode n = p.get("requiredInterfaces");
if (n != null) {
Iterator<String> fields = n.fieldNames();
while (fields.hasNext()) {
String key = fields.next();
ArrayNode provisions = (ArrayNode)n.get(key);
List<IComponentInstance> componentInstances = new ArrayList<>();
for (JsonNode ci : provisions) {
componentInstances.add(this.readAsTree(ci));
}
satisfactionOfRequiredInterfaces.put(key, componentInstances);
}
}
return new ComponentInstance(component, parameterValues, satisfactionOfRequiredInterfaces);
}
@Override
public ComponentInstance deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
return this.readAsTree(p.readValueAsTree());
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/serialization/ComponentSerialization.java
|
package ai.libs.jaicore.components.serialization;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.math3.geometry.euclidean.oned.Interval;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import ai.libs.jaicore.basic.FileUtil;
import ai.libs.jaicore.basic.ResourceFile;
import ai.libs.jaicore.basic.ResourceUtil;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.components.api.IComponent;
import ai.libs.jaicore.components.api.IComponentInstance;
import ai.libs.jaicore.components.api.IComponentInstanceConstraint;
import ai.libs.jaicore.components.api.IComponentRepository;
import ai.libs.jaicore.components.api.INumericParameterRefinementConfigurationMap;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDependency;
import ai.libs.jaicore.components.api.IParameterDomain;
import ai.libs.jaicore.components.api.IRequiredInterfaceDefinition;
import ai.libs.jaicore.components.model.BooleanParameterDomain;
import ai.libs.jaicore.components.model.CategoricalParameterDomain;
import ai.libs.jaicore.components.model.Component;
import ai.libs.jaicore.components.model.ComponentInstanceConstraint;
import ai.libs.jaicore.components.model.ComponentRepository;
import ai.libs.jaicore.components.model.Dependency;
import ai.libs.jaicore.components.model.Interface;
import ai.libs.jaicore.components.model.NumericParameterDomain;
import ai.libs.jaicore.components.model.NumericParameterRefinementConfiguration;
import ai.libs.jaicore.components.model.NumericParameterRefinementConfigurationMap;
import ai.libs.jaicore.components.model.Parameter;
public class ComponentSerialization implements ILoggingCustomizable {
public static final String FIELD_COMPONENTS = "components";
public static final String FIELD_CONSTRAINTS = "constraints";
public static final String FIELD_PARAMETERS = "parameters";
public static final String FIELD_VALUES = "values";
public static final String DTYPE_DOUBLE = "double";
public static final String DTYPE_INT = "int";
private static final String FIELD_DEFAULT = "default";
private static final String MSG_CANNOT_PARSE_LITERAL = "Cannot parse literal ";
private static final Pattern PATTERN_DEPENDENCY = Pattern.compile("(\\S+)\\s*(?:(=)(.*)|(in) (\\[.*\\]|\\{.*\\}))");
private Logger logger = LoggerFactory.getLogger(ComponentSerialization.class);
public ComponentSerialization() {
}
public ComponentSerialization(final String loggerName) {
this();
this.setLoggerName(loggerName);
}
public JsonNode serialize(final Collection<? extends IComponent> components) {
ObjectMapper om = new ObjectMapper();
ObjectNode on = om.createObjectNode();
on.put("repository", "derived");
ArrayNode componentArray = om.createArrayNode();
for (IComponent c : components) {
componentArray.add(this.serialize(c));
}
on.set(FIELD_COMPONENTS, componentArray);
return on;
}
public JsonNode serialize(final IComponent component) {
ObjectMapper om = new ObjectMapper();
ObjectNode on = om.createObjectNode();
on.put("name", component.getName());
ArrayNode params = om.createArrayNode();
for (IParameter p : component.getParameters()) {
params.add(this.serialize(p));
}
on.set(FIELD_PARAMETERS, params);
ArrayNode requiredInterfaces = om.createArrayNode();
for (IRequiredInterfaceDefinition ri : component.getRequiredInterfaces()) {
ObjectNode rin = om.createObjectNode();
rin.put("id", ri.getId());
rin.put("name", ri.getName());
requiredInterfaces.add(rin);
}
on.set("requiredInterface", requiredInterfaces);
ArrayNode providedInterfaces = om.createArrayNode();
for (String pi : component.getProvidedInterfaces()) {
requiredInterfaces.add(pi);
}
on.set("providedInterface", providedInterfaces);
return on;
}
public JsonNode serialize(final IParameter param) {
ObjectMapper om = new ObjectMapper();
ObjectNode on = om.createObjectNode();
on.put("name", param.getName());
IParameterDomain domain = param.getDefaultDomain();
on.put(FIELD_DEFAULT, param.getDefaultValue().toString());
if (domain instanceof CategoricalParameterDomain) {
on.put("type", "cat");
ArrayNode vals = om.createArrayNode();
for (String val : ((CategoricalParameterDomain) domain).getValues()) {
vals.add(val);
}
on.set(FIELD_VALUES, vals);
} else {
NumericParameterDomain nDomain = (NumericParameterDomain) domain;
on.put("type", nDomain.isInteger() ? DTYPE_INT : DTYPE_DOUBLE);
on.put("min", nDomain.getMin());
on.put("max", nDomain.getMax());
}
return on;
}
public JsonNode serialize(final IComponentInstance instance) {
Objects.requireNonNull(instance);
ObjectMapper om = new ObjectMapper();
ObjectNode on = om.createObjectNode();
/* define component and params */
on.put(FIELD_COMPONENTS, instance.getComponent().getName());
ObjectNode params = om.createObjectNode();
for (String paramName : instance.getParameterValues().keySet()) {
params.put(paramName, instance.getParameterValues().get(paramName));
}
on.set("params", params);
/* define how required interfaces have been resolved */
ObjectNode requiredInterfaces = om.createObjectNode();
for (String requiredInterface : instance.getSatisfactionOfRequiredInterfaces().keySet()) {
ArrayNode componentInstancesHere = om.createArrayNode();
instance.getSatisfactionOfRequiredInterfaces().get(requiredInterface).forEach(ci -> componentInstancesHere.add(this.serialize(ci)));
requiredInterfaces.set(requiredInterface, componentInstancesHere);
}
on.set("requiredInterfaces", requiredInterfaces);
return on;
}
public JsonNode readRepositoryFile(final File jsonFile) throws IOException {
return this.readRepositoryFile(jsonFile, new HashMap<>());
}
public JsonNode readRepositoryFile(final File jsonFile, final Map<String, String> templateVars) throws IOException {
return this.readRepositoryFile(jsonFile, templateVars, new ArrayList<>());
}
private JsonNode readRepositoryFile(final File jsonFile, final Map<String, String> templateVars, final List<String> parsedFiles) throws IOException {
/* read in file as string */
this.logger.info("Parse file {} with environment variables: {}", jsonFile.getAbsolutePath(), templateVars);
String jsonDescription;
if (jsonFile instanceof ResourceFile) {
jsonDescription = ResourceUtil.readResourceFileToString(((ResourceFile) jsonFile).getPathName());
} else {
jsonDescription = FileUtil.readFileAsString(jsonFile);
}
jsonDescription = jsonDescription.replaceAll("/\\*(.*)\\*/", "");
for (Entry<String, String> replacementRule : templateVars.entrySet()) {
jsonDescription = jsonDescription.replace("{$" + replacementRule.getKey() + "}", replacementRule.getValue());
}
/* convert the string into a JsonNode */
ObjectMapper om = new ObjectMapper();
JsonNode rootNode = om.readTree(jsonDescription);
JsonNode compNode = rootNode.get(FIELD_COMPONENTS);
if (compNode != null && !compNode.isArray()) {
throw new IllegalArgumentException("Components field in repository file " + jsonFile.getAbsolutePath() + " is not defined or not an array!");
}
ArrayNode compNodeAsArray = compNode != null ? (ArrayNode) compNode : om.createArrayNode();
if (compNode == null) {
((ObjectNode) rootNode).set(FIELD_COMPONENTS, compNodeAsArray);
}
if (this.logger.isInfoEnabled()) {
compNodeAsArray.forEach(n -> this.logger.info("Adding component {}", n));
}
/* if there are includes, resolve them now and attach the components of all of them to the component array */
JsonNode includes = rootNode.path("include");
File baseFolder = jsonFile.getParentFile();
for (JsonNode includePathNode : includes) {
String path = includePathNode.asText();
File subFile;
if (baseFolder instanceof ResourceFile) {
subFile = new ResourceFile((ResourceFile) baseFolder, path);
} else {
subFile = new File(baseFolder, path);
}
if (!parsedFiles.contains(subFile.getCanonicalPath())) {
parsedFiles.add(subFile.getCanonicalPath());
this.logger.debug("Recursively including component repository from {}.", subFile);
JsonNode subRepository = this.readRepositoryFile(subFile, templateVars);
JsonNode compsInSubRepository = subRepository.get(FIELD_COMPONENTS);
ArrayNode compsInSubRepositoryAsArray = (ArrayNode) compsInSubRepository;
compNodeAsArray.addAll(compsInSubRepositoryAsArray);
}
}
return rootNode;
}
public IComponentRepository deserializeRepository(final File jsonFile) throws IOException {
return this.deserializeRepository(jsonFile, new HashMap<>());
}
public IComponentRepository deserializeRepository(final File jsonFile, final Map<String, String> templateVars) throws IOException {
try {
return this.deserializeRepository(this.readRepositoryFile(jsonFile, templateVars));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Found a problem when parsing repository file " + jsonFile, e);
}
}
public IComponentRepository deserializeRepository(final String repository) throws IOException {
return this.deserializeRepository(new ObjectMapper().readTree(repository));
}
public INumericParameterRefinementConfigurationMap deserializeParamMap(final File jsonFile) throws IOException {
return this.deserializeParamMap(this.readRepositoryFile(jsonFile));
}
public INumericParameterRefinementConfigurationMap deserializeParamMap(final String json) throws IOException {
return this.deserializeParamMap(new ObjectMapper().readTree(json));
}
public INumericParameterRefinementConfigurationMap deserializeParamMap(final JsonNode rootNode) {
return this.deserializeRepositoryAndParamConfig(rootNode).getY();
}
public IComponentRepository deserializeRepository(final JsonNode rootNode) {
return this.deserializeRepositoryAndParamConfig(rootNode).getX();
}
private void checkThatParameterDefinitionHasNameAndType(final JsonNode parameter) {
if (!parameter.has("name")) {
throw new IllegalArgumentException("No name defined for parameter node \"" + parameter + "\"");
}
if (!parameter.has("type")) {
throw new IllegalArgumentException("No type defined for parameter \"" + parameter.get("name").asText() + "\"");
}
}
public IParameter deserializeParameter(final JsonNode parameter) {
this.checkThatParameterDefinitionHasNameAndType(parameter);
String name = parameter.get("name").asText();
if (!parameter.has(FIELD_DEFAULT)) {
throw new IllegalArgumentException("No default value defined for parameter \"" + name + "\"");
}
JsonNode defValNode = parameter.get(FIELD_DEFAULT);
String type = parameter.get("type").asText();
switch (type) {
case DTYPE_INT:
case DTYPE_INT + "-log":
case DTYPE_DOUBLE:
case DTYPE_DOUBLE + "-log":
if (!parameter.has("min")) {
throw new IllegalArgumentException("No min value defined for parameter " + name);
}
if (!parameter.has("max")) {
throw new IllegalArgumentException("No max value defined for parameter " + name);
}
double min = parameter.get("min").asDouble();
double max = parameter.get("max").asDouble();
return new Parameter(name, new NumericParameterDomain(type.equals("int") || type.equals("int-log"), min, max), defValNode.asDouble());
case "bool":
case "boolean":
return new Parameter(name, new BooleanParameterDomain(), defValNode.asBoolean());
case "cat":
case "categoric":
case "categorical":
if (!parameter.has(FIELD_VALUES)) {
throw new IllegalArgumentException("Categorical parameter \"" + name + "\" has no field \"values\" for the possible values defined!");
}
JsonNode valuesNode = parameter.get(FIELD_VALUES);
List<String> values = new LinkedList<>();
if (valuesNode.isTextual()) {
values.addAll(Arrays.stream(valuesNode.asText().split(",")).collect(Collectors.toList()));
} else {
for (JsonNode value : valuesNode) {
values.add(value.asText());
}
}
return new Parameter(name, new CategoricalParameterDomain(values), defValNode.asText());
default:
throw new IllegalArgumentException("Unsupported parameter type " + type);
}
}
public NumericParameterRefinementConfiguration deserializeParamRefinement(final JsonNode parameter) {
this.checkThatParameterDefinitionHasNameAndType(parameter);
String name = parameter.get("name").asText();
String type = parameter.get("type").asText();
if (!type.startsWith(DTYPE_INT) && !type.startsWith(DTYPE_DOUBLE)) {
throw new IllegalArgumentException("Parameter type is " + type + " and hence not numeric!");
}
if (!parameter.has("refineSplits")) {
throw new IllegalArgumentException("Please specify the parameter \"refineSplits\" for the parameter \"" + name + "\" in component \"" + name + "\"");
}
if (!parameter.has("minInterval")) {
throw new IllegalArgumentException("Please specify a strictly positive parameter value for \"minInterval\" for the parameter \"" + name + "\" in component \"" + name + "\"");
}
boolean initWithExtremal = false;
int refineSplits = parameter.get("refineSplits").asInt();
double minInterval = parameter.get("minInterval").asDouble();
if (type.endsWith("-log")) {
return new NumericParameterRefinementConfiguration(parameter.get("focus").asDouble(), parameter.get("basis").asDouble(), initWithExtremal, refineSplits, minInterval);
} else {
return new NumericParameterRefinementConfiguration(initWithExtremal, refineSplits, minInterval);
}
}
public Pair<IParameter, IParameterDomain> deserializeDependencyConditionTerm(final IComponent component, final String condition) {
Matcher m = PATTERN_DEPENDENCY.matcher(condition.trim());
if (!m.find()) {
throw new IllegalArgumentException(MSG_CANNOT_PARSE_LITERAL + condition.trim() + ". Literals must be of the form \"<a> P <b>\" where P is either '=' or 'in'.");
}
String lhs = m.group(1).trim();
String cond = (m.group(2) != null ? m.group(2) : m.group(4)).trim();
String rhs = (cond.equals("=") ? m.group(3) : m.group(5)).trim();
IParameter param = component.getParameter(lhs);
if (param.isNumeric()) {
return this.deserializeDependencyConditionTermForNumericalParam(param, lhs, cond, rhs);
} else if (param.isCategorical()) {
return this.deserializeDependencyConditionTermForCategoricalParam(param, lhs, cond, rhs);
} else {
throw new IllegalArgumentException("Parameter \"" + param.getName() + "\" must be numeric or categorical!");
}
}
public Pair<IParameter, IParameterDomain> deserializeDependencyConditionTermForCategoricalParam(final IParameter param, final String lhs, final String comp, final String rhs) {
switch (comp) {
case "=":
return new Pair<>(param, new CategoricalParameterDomain(new String[] { rhs }));
case "in":
if (!rhs.startsWith("[") && !rhs.startsWith("{")) {
throw new IllegalArgumentException("Illegal literal \"" + lhs + "\" in \"" + rhs + "\". This should be a set, but the target is not described by [...] or {...}");
}
Collection<String> values = rhs.startsWith("[") ? SetUtil.unserializeList(rhs) : SetUtil.unserializeSet(rhs);
return new Pair<>(param, new CategoricalParameterDomain(values));
default:
throw new IllegalArgumentException(MSG_CANNOT_PARSE_LITERAL + lhs + " " + comp + " " + rhs + ". Currently no support for predicate \"" + comp + "\".");
}
}
public Pair<IParameter, IParameterDomain> deserializeDependencyConditionTermForNumericalParam(final IParameter param, final String lhs, final String comp, final String rhs) {
switch (comp) {
case "=":
double val = Double.parseDouble(rhs);
return new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), val, val));
case "in":
Interval interval = SetUtil.unserializeInterval("[" + rhs.substring(1, rhs.length() - 1) + "]");
return new Pair<>(param, new NumericParameterDomain(((NumericParameterDomain) param.getDefaultDomain()).isInteger(), interval.getInf(), interval.getSup()));
default:
throw new IllegalArgumentException(MSG_CANNOT_PARSE_LITERAL + lhs + " " + comp + " " + rhs + ". Currently no support for predicate \"" + comp + "\".");
}
}
public IParameterDependency deserializeParameterDependency(final IComponent c, final JsonNode dependency) {
/* parse precondition */
String pre = dependency.get("pre").asText();
Collection<Collection<Pair<IParameter, IParameterDomain>>> premise = new ArrayList<>();
Collection<String> monoms = Arrays.asList(pre.split("\\|"));
for (String monom : monoms) {
Collection<String> literals = Arrays.asList(monom.split("&"));
Collection<Pair<IParameter, IParameterDomain>> monomInPremise = new ArrayList<>();
for (String literal : literals) {
monomInPremise.add(this.deserializeDependencyConditionTerm(c, literal));
}
premise.add(monomInPremise);
}
/* parse postcondition */
Collection<Pair<IParameter, IParameterDomain>> conclusion = new ArrayList<>();
String post = dependency.get("post").asText();
Collection<String> literals = Arrays.asList(post.split("&"));
for (String literal : literals) {
conclusion.add(this.deserializeDependencyConditionTerm(c, literal));
}
return new Dependency(premise, conclusion);
}
public IRequiredInterfaceDefinition deserializeRequiredInterface(final JsonNode requiredInterface) {
/* read in relevant variables for required interface definition */
if (!requiredInterface.has("id")) {
throw new IllegalArgumentException("No id has been specified for a required interface " + requiredInterface);
}
if (!requiredInterface.has("name")) {
throw new IllegalArgumentException("No name has been specified for a required interface " + requiredInterface);
}
String id = requiredInterface.get("id").asText();
boolean optional = requiredInterface.has("optional") && requiredInterface.get("optional").asBoolean(); // default is false
boolean unique = requiredInterface.has("unique") && requiredInterface.get("unique").asBoolean(); // default is false
boolean ordered = !requiredInterface.has("ordered") || requiredInterface.get("ordered").asBoolean(); // default is true
int min = requiredInterface.has("min") ? requiredInterface.get("min").asInt() : 1;
int max = requiredInterface.has("max") ? requiredInterface.get("max").asInt() : min;
if (min > max) {
throw new IllegalArgumentException(min + " = min > max = " + max + " for required interface " + requiredInterface);
}
return new Interface(id, requiredInterface.get("name").asText(), optional, unique, ordered, min, max);
}
public IComponent deserializeComponent(final JsonNode component) {
Component c = new Component(component.get("name").asText());
if (c.getName().contains("-")) {
throw new IllegalArgumentException("Illegal component name " + c.getName() + ". No hyphens allowed. Please only use [a-zA-z0-9].");
}
// add provided interfaces
for (JsonNode providedInterface : component.path("providedInterface")) {
c.addProvidedInterface(providedInterface.asText());
}
// add required interfaces
for (JsonNode requiredInterface : component.path("requiredInterface")) {
try {
c.addRequiredInterface(this.deserializeRequiredInterface(requiredInterface));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Error when parsing required interface of component \"" + c.getName() + "\"", e);
}
}
/* attach parameters */
for (JsonNode parameter : component.get(FIELD_PARAMETERS)) {
c.addParameter(this.deserializeParameter(parameter));
}
/* now parse dependencies */
if (component.has("dependencies")) {
for (JsonNode dependency : component.get("dependencies")) {
c.addDependency(this.deserializeParameterDependency(c, dependency));
}
}
return c;
}
public INumericParameterRefinementConfigurationMap deserializeParamRefinementConfiguration(final JsonNode component) {
NumericParameterRefinementConfigurationMap paramConfigs = new NumericParameterRefinementConfigurationMap();
Map<String, NumericParameterRefinementConfiguration> map = new HashMap<>();
String componentName = component.get("name").asText();
paramConfigs.put(componentName, map);
for (JsonNode parameter : component.get(FIELD_PARAMETERS)) {
String paramName = parameter.get("name").asText();
String type = parameter.get("type").asText();
if (type.startsWith(DTYPE_INT) || type.startsWith(DTYPE_DOUBLE)) {
try {
map.put(paramName, this.deserializeParamRefinement(parameter));
} catch (RuntimeException e) {
throw new IllegalArgumentException("Observed problems when processing parameter " + paramName + " of component " + componentName);
}
}
}
return paramConfigs;
}
public IComponentInstanceConstraint deserializeConstraint(final Collection<IComponent> components, final JsonNode constraint) {
boolean positive = !constraint.has("positive") || constraint.get("positive").asBoolean();
if (!constraint.has("premise")) {
throw new IllegalArgumentException("Constraint has no premise: " + constraint);
}
if (!constraint.has("conclusion")) {
throw new IllegalArgumentException("Constraint has no conclusion: " + constraint);
}
try {
IComponentInstance premise = new ComponentInstanceDeserializer(components).readAsTree(constraint.get("premise"));
IComponentInstance conclusion = new ComponentInstanceDeserializer(components).readAsTree(constraint.get("conclusion"));
return new ComponentInstanceConstraint(positive, premise, conclusion);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
public Pair<IComponentRepository, INumericParameterRefinementConfigurationMap> deserializeRepositoryAndParamConfig(final JsonNode rootNode) {
NumericParameterRefinementConfigurationMap paramConfigs = new NumericParameterRefinementConfigurationMap();
Set<String> uniqueComponentNames = new HashSet<>();
Map<String, JsonNode> componentMap = new HashMap<>();
/* create repository with components */
Collection<IComponent> components = new ArrayList<>();
JsonNode describedComponents = rootNode.path(FIELD_COMPONENTS);
if (describedComponents != null) {
for (JsonNode component : describedComponents) {
/* derive component */
IComponent c = this.deserializeComponent(component);
componentMap.put(c.getName(), component);
if (!uniqueComponentNames.add(c.getName())) {
throw new IllegalArgumentException("Noticed a component with duplicative component name: " + c.getName());
}
components.add(c);
/* derive parameter refinement description */
Map<String, NumericParameterRefinementConfiguration> paramConfig = ((NumericParameterRefinementConfigurationMap) this.deserializeParamRefinementConfiguration(component)).get(c.getName());
paramConfigs.put(c.getName(), paramConfig);
}
}
/* now parse constraints */
Collection<IComponentInstanceConstraint> constraints = new ArrayList<>();
if (rootNode.has(FIELD_CONSTRAINTS)) {
for (JsonNode constraint : rootNode.get(FIELD_CONSTRAINTS)) {
constraints.add(this.deserializeConstraint(components, constraint));
}
}
return new Pair<>(new ComponentRepository(components, constraints), paramConfigs);
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/serialization/ParameterDeserializer.java
|
package ai.libs.jaicore.components.serialization;
import java.io.IOException;
import java.util.LinkedList;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import ai.libs.jaicore.components.api.IParameterDomain;
import ai.libs.jaicore.components.model.CategoricalParameterDomain;
import ai.libs.jaicore.components.model.NumericParameterDomain;
import ai.libs.jaicore.components.model.Parameter;
public class ParameterDeserializer extends StdDeserializer<Parameter> {
/**
*
*/
private static final long serialVersionUID = 1L;
public ParameterDeserializer() {
this(null);
}
public ParameterDeserializer(final Class<Parameter> vc) {
super(vc);
}
@Override
public Parameter deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException {
JsonNode node = jp.getCodec().readTree(jp);
String name = node.get("name").asText();
boolean numeric = node.get("numeric").asBoolean();
boolean categorical = node.get("categorical").asBoolean();
boolean defaultValue = node.get("defaultValue").asBoolean();
IParameterDomain domain = null;
JsonNode domainNode = node.get("defaultDomain");
if (numeric) {
boolean isInteger = domainNode.get("integer").asBoolean();
double min = domainNode.get("min").asDouble();
double max = domainNode.get("max").asDouble();
domain = new NumericParameterDomain(isInteger, min, max);
} else if (categorical) {
LinkedList<String> values = new LinkedList<>();
JsonNode arrayNode = domainNode.get("values");
if (arrayNode.isArray()) {
for (final JsonNode valueNode : arrayNode) {
values.add(valueNode.asText());
}
}
domain = new CategoricalParameterDomain(values);
}
return new Parameter(name, domain, defaultValue);
}
}
|
0
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components
|
java-sources/ai/libs/jaicore-components/0.2.7/ai/libs/jaicore/components/serialization/ParameterDomainDeserializer.java
|
package ai.libs.jaicore.components.serialization;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.components.api.IParameter;
import ai.libs.jaicore.components.api.IParameterDomain;
import ai.libs.jaicore.components.model.Dependency;
public class ParameterDomainDeserializer extends StdDeserializer<Dependency> {
/**
*
*/
private static final long serialVersionUID = -3868917516989468264L;
public ParameterDomainDeserializer() {
this(null);
}
public ParameterDomainDeserializer(final Class<IParameterDomain> vc) {
super(vc);
}
@Override
public Dependency deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException {
List<Pair<IParameter, IParameterDomain>> collection1 = new LinkedList<>();
LinkedList<Collection<Pair<IParameter, IParameterDomain>>> collection2 = new LinkedList<>();
return new Dependency(collection2, collection1);
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/AEvolutionaryAlgorithm.java
|
package ai.libs.jaicore.ea.algorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithm;
public abstract class AEvolutionaryAlgorithm<P> extends AAlgorithm<IEvolutionaryAlgorithmProblem, IEvolutionaryAlgorithmResult<P>> {
protected AEvolutionaryAlgorithm(final IEvolutionaryAlgorithmConfig config, final IEvolutionaryAlgorithmProblem problem) {
super(config, problem);
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/IEvolutionaryAlgorithmConfig.java
|
package ai.libs.jaicore.ea.algorithm;
import ai.libs.jaicore.basic.IOwnerBasedAlgorithmConfig;
/**
* General properties of an evolutionary algorithm.
*
* @author wever
*/
public interface IEvolutionaryAlgorithmConfig extends IOwnerBasedAlgorithmConfig {
public static final String K_EVALUATIONS = "evaluations";
public static final String K_GENERATIONS = "generations";
public static final String K_POPULATION_SIZE = "population.size";
public static final String K_EARLY_TERMINATION_GENS = "earlytermination.generations";
public static final String K_EARLY_TERMINATION_EPSILON = "earlytermination.epsilon";
@Key(K_POPULATION_SIZE)
@DefaultValue("100")
public int populationSize();
@Key(K_GENERATIONS)
@DefaultValue("1000")
public int numberOfGenerations();
@Key(K_EVALUATIONS)
@DefaultValue("-1")
public int numberOfEvaluations();
@Key(K_EARLY_TERMINATION_EPSILON)
@DefaultValue("0.00001")
public double earlyTerminationEpsilon();
/**
* Number of generations after which early termination criterion evaluates to true.
* If it is set to -1, no early termination is applied.
*
* @return Number of generations with no change after which early termination becomes true.
*/
@Key(K_EARLY_TERMINATION_GENS)
@DefaultValue("-1")
public double earlyTerminationGenerations();
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/IEvolutionaryAlgorithmProblem.java
|
package ai.libs.jaicore.ea.algorithm;
public interface IEvolutionaryAlgorithmProblem {
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/IEvolutionaryAlgorithmResult.java
|
package ai.libs.jaicore.ea.algorithm;
public interface IEvolutionaryAlgorithmResult<P> {
public P getPopulation();
public P getResult();
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/AEvolutionaryAlgorithm.java
|
/* Copyright 2009-2016 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import java.io.NotSerializableException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.moeaframework.algorithm.AlgorithmInitializationException;
import org.moeaframework.core.EvolutionaryAlgorithm;
import org.moeaframework.core.Initialization;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.Population;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
/**
* Abstract class providing default implementations for several
* {@link EvolutionaryAlgorithm} methods. Primarily, the {@link #initialize()}
* method generates and evaluates the initial population, adding the solutions
* to the archive if available. The {@link #getResult()} method returns the
* non-dominated solutions from the population and, if available, the archive.
* The majority of evolutionary algorithms should only need to override the
* {@link #iterate()} method.
*/
public abstract class AEvolutionaryAlgorithm extends AbstractAlgorithm implements EvolutionaryAlgorithm {
/**
* The current population.
*/
protected final Population population;
/**
* The archive storing the non-dominated solutions.
*/
protected final NondominatedPopulation archive;
/**
* The initialization operator.
*/
protected final Initialization initialization;
/**
* Constructs an abstract evolutionary algorithm.
*
* @param problem the problem being solved
* @param population the population
* @param archive the archive storing the non-dominated solutions
* @param initialization the initialization operator
*/
protected AEvolutionaryAlgorithm(final Problem problem, final Population population, final NondominatedPopulation archive, final Initialization initialization) {
super(problem);
this.population = population;
this.archive = archive;
this.initialization = initialization;
}
@Override
public NondominatedPopulation getResult() {
Population resultPopulation = this.getPopulation();
NondominatedPopulation resultArchive = this.getArchive();
NondominatedPopulation result = new NondominatedPopulation();
result.addAll(resultPopulation);
if (resultArchive != null) {
result.addAll(resultArchive);
}
return result;
}
@Override
protected void initialize() {
super.initialize();
Population initPopulation = this.getPopulation();
NondominatedPopulation initArchive = this.getArchive();
Solution[] initialSolutions = this.initialization.initialize();
this.evaluateAll(initialSolutions);
initPopulation.addAll(initialSolutions);
if (initArchive != null) {
initArchive.addAll(initPopulation);
}
}
@Override
public NondominatedPopulation getArchive() {
return this.archive;
}
@Override
public Population getPopulation() {
return this.population;
}
@Override
public Serializable getState() throws NotSerializableException {
if (!this.isInitialized()) {
throw new AlgorithmInitializationException(this, "algorithm not initialized");
}
List<Solution> populationList = new ArrayList<>();
List<Solution> archiveList = new ArrayList<>();
for (Solution solution : this.population) {
populationList.add(solution);
}
if (this.archive != null) {
for (Solution solution : this.archive) {
archiveList.add(solution);
}
}
return new EvolutionaryAlgorithmState(this.getNumberOfEvaluations(), populationList, archiveList);
}
@Override
public void setState(final Object objState) throws NotSerializableException {
super.initialize();
EvolutionaryAlgorithmState state = (EvolutionaryAlgorithmState) objState;
this.numberOfEvaluations = state.getNumberOfEvaluations();
this.population.addAll(state.getPopulation());
if (this.archive != null) {
this.archive.addAll(state.getArchive());
}
}
/**
* Proxy for serializing and deserializing the state of an
* {@code AbstractEvolutionaryAlgorithm}. This proxy supports saving
* the {@code numberOfEvaluations}, {@code population} and {@code archive}.
*/
private static class EvolutionaryAlgorithmState implements Serializable {
private static final long serialVersionUID = -6186688380313335557L;
/**
* The number of objective function evaluations.
*/
private final int numberOfEvaluations;
/**
* The population stored in a serializable list.
*/
private final List<Solution> population;
/**
* The archive stored in a serializable list.
*/
private final List<Solution> archive;
/**
* Constructs a proxy to serialize and deserialize the state of an
* {@code AbstractEvolutionaryAlgorithm}.
*
* @param numberOfEvaluations the number of objective function
* evaluations
* @param population the population stored in a serializable list
* @param archive the archive stored in a serializable list
*/
public EvolutionaryAlgorithmState(final int numberOfEvaluations, final List<Solution> population, final List<Solution> archive) {
super();
this.numberOfEvaluations = numberOfEvaluations;
this.population = population;
this.archive = archive;
}
/**
* Returns the number of objective function evaluations.
*
* @return the number of objective function evaluations
*/
public int getNumberOfEvaluations() {
return this.numberOfEvaluations;
}
/**
* Returns the population stored in a serializable list.
*
* @return the population stored in a serializable list
*/
public List<Solution> getPopulation() {
return this.population;
}
/**
* Returns the archive stored in a serializable list.
*
* @return the archive stored in a serializable list
*/
public List<Solution> getArchive() {
return this.archive;
}
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/AbstractAlgorithm.java
|
/* Copyright 2009-2016 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import java.io.NotSerializableException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.moeaframework.algorithm.AlgorithmInitializationException;
import org.moeaframework.algorithm.AlgorithmTerminationException;
import org.moeaframework.core.Algorithm;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
/**
* Abstract class providing default implementations for several
* {@link Algorithm} methods. All method extending this class must use the
* {@link #evaluate} method to evaluate a solution. This is mandatory to ensure
* the {@link #getNumberOfEvaluations()} method returns the correct result.
* <p>
* Subclasses should avoid overriding the {@link #step()} method and instead
* override the {@link #initialize()} and {@link #iterate()} methods
* individually.
*/
public abstract class AbstractAlgorithm implements Algorithm {
/**
* The problem being solved.
*/
protected final Problem problem;
/**
* The number of times the {@link #evaluate} method was invoked.
*/
protected int numberOfEvaluations;
/**
* {@code true} if the {@link #initialize()} method has been invoked;
* {@code false} otherwise.
*/
protected boolean initialized;
/**
* {@code true} if the {@link #terminate()} method has been invoked;
* {@code false} otherwise.
*/
protected boolean terminated;
/**
* Constructs an abstract algorithm for solving the specified problem.
*
* @param problem the problem being solved
*/
protected AbstractAlgorithm(final Problem problem) {
super();
this.problem = problem;
}
/**
* Evaluates the specified solutions. This method calls
* {@link #evaluate(Solution)} on each of the solutions. Subclasses should
* prefer calling this method over {@code evaluate} whenever possible,
* as this ensures the solutions can be evaluated in parallel.
*
* @param solutions the solutions to evaluate
*/
public void evaluateAll(final Iterable<Solution> solutions) {
if (this.problem instanceof IBatchEvaluationProblem) {
List<Solution> solutionList = new LinkedList<>();
for (Solution solution : solutions) {
solutionList.add(solution);
}
((IBatchEvaluationProblem) this.problem).evaluateBatch(solutionList);
this.numberOfEvaluations += solutionList.size();
} else {
for (Solution solution : solutions) {
this.evaluate(solution);
}
}
}
/**
* Evaluates the specified solutions. This method is equivalent to
* {@code evaluateAll(Arrays.asList(solutions))}.
*
* @param solutions the solutions to evaluate
*/
public void evaluateAll(final Solution[] solutions) {
this.evaluateAll(Arrays.asList(solutions));
}
@Override
public void evaluate(final Solution solution) {
this.problem.evaluate(solution);
this.numberOfEvaluations++;
}
@Override
public int getNumberOfEvaluations() {
return this.numberOfEvaluations;
}
@Override
public Problem getProblem() {
return this.problem;
}
/**
* Performs any initialization that is required by this algorithm. This
* method is called automatically by the first invocation of
* {@link #step()}, but may also be called manually prior to any invocations
* of {@code step}. Implementations should always invoke
* {@code super.initialize()} to ensure the hierarchy is initialized
* correctly.
*
* @throws AlgorithmInitializationException if the algorithm has already
* been initialized
*/
protected void initialize() {
if (this.initialized) {
throw new AlgorithmInitializationException(this, "algorithm already initialized");
}
this.initialized = true;
}
/**
* Returns {@code true} if the {@link #initialize()} method has been
* invoked; {@code false} otherwise.
*
* @return {@code true} if the {@link #initialize()} method has been
* invoked; {@code false} otherwise
*/
public boolean isInitialized() {
return this.initialized;
}
/**
* This method first checks if the algorithm is initialized. If not, the
* {@link #initialize()} method is invoked. If initialized, all calls to
* {@code step} invoke {@link #iterate()}. Implementations should override
* the {@code initialize} and {@code iterate} methods in preference to
* modifying this method.
*
* @throws AlgorithmTerminationException if the algorithm has already
* terminated
*/
@Override
public void step() {
if (this.isTerminated()) {
throw new AlgorithmTerminationException(this, "algorithm already terminated");
} else if (!this.isInitialized()) {
this.initialize();
} else {
this.iterate();
}
}
/**
* Performs one iteration of the algorithm. This method should be
* overridden by implementations to perform each logical iteration of the
* algorithm.
*/
protected abstract void iterate();
@Override
public boolean isTerminated() {
return this.terminated;
}
/**
* Implementations should always invoke {@code super.terminate()} to ensure
* the hierarchy is terminated correctly. This method is automatically
* invoked during finalization, and need only be called directly if
* non-Java resources are in use.
*
* @throws AlgorithmTerminationException if the algorithm has already
* terminated
*/
@Override
public void terminate() {
if (this.terminated) {
throw new AlgorithmTerminationException(this, "algorithm already terminated");
}
this.terminated = true;
}
@Override
public Serializable getState() throws NotSerializableException {
throw new NotSerializableException(this.getClass().getName());
}
@Override
public void setState(final Object state) throws NotSerializableException {
throw new NotSerializableException(this.getClass().getName());
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/IBatchEvaluationProblem.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import java.util.List;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
public interface IBatchEvaluationProblem extends Problem {
/**
* Evaluates a batch of individuals.
* @param batch The batch of individuals to be evaluated.
*/
public void evaluateBatch(List<Solution> batch);
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/IMOEAFrameworkAlgorithmConfig.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import ai.libs.jaicore.ea.algorithm.IEvolutionaryAlgorithmConfig;
import ai.libs.jaicore.ea.algorithm.moea.moeaframework.util.EMOEAFrameworkAlgorithmName;
public interface IMOEAFrameworkAlgorithmConfig extends IEvolutionaryAlgorithmConfig {
public static final String K_MOEAFRAMEWORK_ALGORITHM_NAME = "moeaframework.algorithm";
public static final String K_CROSSOVER_RATE = "moeaframework.sbx.rate";
public static final String K_CROSSOVER_DIST_INDEX = "moeaframework.sbx.distributionIndex";
public static final String K_PERMUTATION_RATE = "moeaframework.pm.rate";
public static final String K_PERMUTATION_DIST_INDEX = "moeaframework.pm.distributionIndex";
public static final String K_WITH_REPLACEMENT = "moeaframework.withReplacement";
@Key(K_MOEAFRAMEWORK_ALGORITHM_NAME)
@DefaultValue("NSGAII")
public EMOEAFrameworkAlgorithmName algorithmName();
@Key(K_CROSSOVER_RATE)
@DefaultValue("0.9")
public double crossoverRate();
@Key(K_CROSSOVER_DIST_INDEX)
@DefaultValue("10")
public double crossoverDistIndex();
@Key(K_PERMUTATION_RATE)
@DefaultValue("0.1")
public double mutationRate();
@Key(K_PERMUTATION_DIST_INDEX)
@DefaultValue("10")
public double mutationDistIndex();
@Key(K_WITH_REPLACEMENT)
@DefaultValue("false")
public double withReplacement();
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/IMOEAFrameworkAlgorithmInput.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import org.moeaframework.problem.AbstractProblem;
import ai.libs.jaicore.ea.algorithm.IEvolutionaryAlgorithmProblem;
public interface IMOEAFrameworkAlgorithmInput extends IEvolutionaryAlgorithmProblem {
/**
* @return Returns a problem instance specific to the MOEAFramework.
*/
public AbstractProblem getProblem();
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/MOEAFrameworkAlgorithm.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.moeaframework.core.Algorithm;
import org.moeaframework.core.Initialization;
import org.moeaframework.core.NondominatedSortingPopulation;
import org.moeaframework.core.Population;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Variation;
import org.moeaframework.core.comparator.ChainedComparator;
import org.moeaframework.core.comparator.CrowdingComparator;
import org.moeaframework.core.comparator.ParetoDominanceComparator;
import org.moeaframework.core.operator.RandomInitialization;
import org.moeaframework.core.operator.TournamentSelection;
import org.moeaframework.core.spi.OperatorFactory;
import org.moeaframework.util.TypedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.EAlgorithmState;
import ai.libs.jaicore.ea.algorithm.AEvolutionaryAlgorithm;
import ai.libs.jaicore.ea.algorithm.moea.moeaframework.event.MOEAFrameworkAlgorithmResultEvent;
import ai.libs.jaicore.ea.algorithm.moea.moeaframework.util.MOEAFrameworkUtil;
public class MOEAFrameworkAlgorithm extends AEvolutionaryAlgorithm<Population> {
private Logger logger = LoggerFactory.getLogger(MOEAFrameworkAlgorithm.class);
private Algorithm algorithm;
private int numberOfGenerationsEvolved = 0;
private double bestFitness = 1.0;
private int numberOfGenerationsWOChange = 0;
public MOEAFrameworkAlgorithm(final IMOEAFrameworkAlgorithmConfig config, final IMOEAFrameworkAlgorithmInput input) {
super(config, input);
}
@Override
public IAlgorithmEvent nextWithException() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
this.checkAndConductTermination();
this.logger.info("{} step1: {}", this.getClass().getName(), this.getState());
switch (this.getState()) {
case CREATED:
try {
this.numberOfGenerationsEvolved = 0;
// initialize population
TypedProperties properties = new TypedProperties();
properties.setInt("populationSize", this.getConfig().populationSize());
properties.setDouble("sbx.rate", this.getConfig().crossoverRate());
properties.setDouble("pm.rate", this.getConfig().mutationRate());
Initialization initialization = new RandomInitialization(this.getInput().getProblem(), this.getConfig().populationSize());
NondominatedSortingPopulation population = new NondominatedSortingPopulation();
TournamentSelection selection = new TournamentSelection(2, new ChainedComparator(new ParetoDominanceComparator(), new CrowdingComparator()));
Variation variation = OperatorFactory.getInstance().getVariation(null, properties, this.getInput().getProblem());
this.algorithm = new NSGAII(this.getInput().getProblem(), population, null, selection, variation, initialization);
this.logger.info("{} step2", this.getClass().getName());
this.algorithm.step();
return super.activate();
} catch (Exception e) {
throw new AlgorithmException("Could not create the algorithm.", e);
}
case ACTIVE:
this.logger.info("{} step3", this.getClass().getName());
this.algorithm.step();
this.numberOfGenerationsWOChange++;
if (this.getCurrentResult().getResult().get(0).getObjective(0) + this.getConfig().earlyTerminationEpsilon() < this.bestFitness) {
this.bestFitness = this.getCurrentResult().getResult().get(0).getObjective(0);
this.numberOfGenerationsWOChange = 0;
}
return new MOEAFrameworkAlgorithmResultEvent(this, this.getCurrentResult());
default:
case INACTIVE:
throw new AlgorithmException("The current algorithm state is >inactive<.");
}
}
public void reset() {
this.setState(EAlgorithmState.CREATED);
}
public MOEAFrameworkAlgorithmResult getCurrentResult() throws AlgorithmException {
this.algorithm.getResult();
Population population = null;
try {
population = this.getPopulation();
} catch (IllegalAccessException | InvocationTargetException e) {
throw new AlgorithmException("Could not get the result!", e);
}
return new MOEAFrameworkAlgorithmResult(this.algorithm.getResult(), population);
}
public int getNumberOfGenerationsEvolved() {
return this.numberOfGenerationsEvolved;
}
public int getNumberOfEvaluations() {
if (this.algorithm == null) {
return 0;
} else {
return this.algorithm.getNumberOfEvaluations();
}
}
@Override
public MOEAFrameworkAlgorithmResult call() throws InterruptedException, AlgorithmExecutionCanceledException, AlgorithmTimeoutedException, AlgorithmException {
while ((this.getState() == EAlgorithmState.CREATED || this.getState() == EAlgorithmState.ACTIVE) && (this.getConfig().numberOfGenerations() <= 0 || this.numberOfGenerationsEvolved < this.getConfig().numberOfGenerations())
&& (this.getConfig().numberOfEvaluations() <= 0 || this.algorithm.getNumberOfEvaluations() < this.getConfig().numberOfEvaluations())) {
this.nextWithException();
if (this.logger.isInfoEnabled()) {
this.logger.info("\n=============\nCurrent Result:\n{}\nGen: {}/{}\nEvals: {}/{}\n=============", MOEAFrameworkUtil.populationToString(this.getCurrentResult().getResult()), this.numberOfGenerationsEvolved,
this.getConfig().numberOfGenerations(), this.getNumberOfEvaluations(), this.getConfig().numberOfEvaluations());
}
this.numberOfGenerationsEvolved++;
}
if (this.logger.isInfoEnabled()) {
this.logger.info("State: {} ", (this.getState() == EAlgorithmState.CREATED || this.getState() == EAlgorithmState.ACTIVE));
this.logger.info("Generations: {} {}", this.getConfig().numberOfGenerations() <= 0, this.numberOfGenerationsEvolved < this.getConfig().numberOfGenerations());
this.logger.info("Evaluations: {}", this.getConfig().numberOfEvaluations() <= 0 || this.algorithm.getNumberOfEvaluations() < this.getConfig().numberOfEvaluations());
this.logger.info("Gen: {}/{}", this.numberOfGenerationsEvolved, this.getConfig().numberOfGenerations());
this.logger.info("Evals: {}/{}", this.getNumberOfEvaluations(), this.getConfig().numberOfEvaluations());
}
return this.getCurrentResult();
}
public boolean terminateEvolution() {
boolean condition = this.getState() == EAlgorithmState.INACTIVE;
if (this.getConfig().numberOfEvaluations() > 0) {
condition = condition || this.getNumberOfEvaluations() >= this.getConfig().numberOfEvaluations();
}
if (this.getConfig().numberOfGenerations() > 0) {
condition = condition || this.getNumberOfGenerationsEvolved() >= this.getConfig().numberOfGenerations();
}
if (this.getConfig().earlyTerminationGenerations() >= 0) {
condition = condition || this.numberOfGenerationsWOChange >= this.getConfig().earlyTerminationGenerations();
}
return condition;
}
@Override
public IMOEAFrameworkAlgorithmConfig getConfig() {
return (IMOEAFrameworkAlgorithmConfig) super.getConfig();
}
@Override
public IMOEAFrameworkAlgorithmInput getInput() {
return (IMOEAFrameworkAlgorithmInput) super.getInput();
}
protected Algorithm getAlgorithm() {
return this.algorithm;
}
public Population getPopulation() throws IllegalAccessException, InvocationTargetException {
if (this.algorithm instanceof NSGAII) {
return ((NSGAII) this.algorithm).getPopulation();
}
Method getPopulationMethod = null;
try {
getPopulationMethod = this.getAlgorithm().getClass().getMethod("getPopulation", (Class<?>[]) null);
} catch (NoSuchMethodException | SecurityException e) {
this.logger.error("Encountered exception.", e);
}
if (getPopulationMethod == null) {
throw new UnsupportedOperationException("The method getPopulation is not available for " + this.getAlgorithm().getClass().getName());
} else {
return (Population) getPopulationMethod.invoke(this.getAlgorithm(), (Object[]) null);
}
}
public List<Solution> getPopulationAsList() throws IllegalAccessException, InvocationTargetException {
List<Solution> population = new LinkedList<>();
for (Solution solution : this.getPopulation()) {
population.add(solution);
}
return population;
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/MOEAFrameworkAlgorithmInput.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import org.moeaframework.problem.AbstractProblem;
public class MOEAFrameworkAlgorithmInput implements IMOEAFrameworkAlgorithmInput {
private AbstractProblem problem;
public MOEAFrameworkAlgorithmInput(final AbstractProblem problem) {
this.problem = problem;
}
@Override
public AbstractProblem getProblem() {
return this.problem;
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/MOEAFrameworkAlgorithmResult.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import org.moeaframework.core.NondominatedPopulation;
import org.moeaframework.core.Population;
import ai.libs.jaicore.ea.algorithm.IEvolutionaryAlgorithmResult;
public class MOEAFrameworkAlgorithmResult implements IEvolutionaryAlgorithmResult<Population> {
private final NondominatedPopulation result;
private final Population population;
public MOEAFrameworkAlgorithmResult(final NondominatedPopulation result, final Population population) {
this.result = result;
this.population = population;
}
@Override
public Population getPopulation() {
return this.population;
}
@Override
public Population getResult() {
return this.result;
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/NSGAII.java
|
/* Copyright 2009-2016 David Hadka
*
* This file is part of the MOEA Framework.
*
* The MOEA Framework is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* The MOEA Framework is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the MOEA Framework. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.libs.jaicore.ea.algorithm.moea.moeaframework;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.moeaframework.core.EpsilonBoxDominanceArchive;
import org.moeaframework.core.EpsilonBoxEvolutionaryAlgorithm;
import org.moeaframework.core.Initialization;
import org.moeaframework.core.NondominatedSortingPopulation;
import org.moeaframework.core.PRNG;
import org.moeaframework.core.Population;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Selection;
import org.moeaframework.core.Solution;
import org.moeaframework.core.Variation;
import org.moeaframework.core.comparator.ChainedComparator;
import org.moeaframework.core.comparator.CrowdingComparator;
import org.moeaframework.core.comparator.DominanceComparator;
import org.moeaframework.core.comparator.ParetoDominanceComparator;
import org.moeaframework.core.operator.TournamentSelection;
/**
* Implementation of NSGA-II, with the ability to attach an optional
* ε-dominance archive.
* <p>
* References:
* <ol>
* <li>Deb, K. et al. "A Fast Elitist Multi-Objective Genetic Algorithm:
* NSGA-II." IEEE Transactions on Evolutionary Computation, 6:182-197,
* 2000.
* <li>Kollat, J. B., and Reed, P. M. "Comparison of Multi-Objective
* Evolutionary Algorithms for Long-Term Monitoring Design." Advances in
* Water Resources, 29(6):792-807, 2006.
* </ol>
*/
public class NSGAII extends AEvolutionaryAlgorithm implements EpsilonBoxEvolutionaryAlgorithm {
/**
* The selection operator. If {@code null}, this algorithm uses binary
* tournament selection without replacement, replicating the behavior of the
* original NSGA-II implementation.
*/
private final Selection selection;
/**
* The variation operator.
*/
private final Variation variation;
/**
* Constructs the NSGA-II algorithm with the specified components.
*
* @param problem the problem being solved
* @param population the population used to store solutions
* @param archive the archive used to store the result; can be {@code null}
* @param selection the selection operator
* @param variation the variation operator
* @param initialization the initialization method
*/
public NSGAII(final Problem problem, final NondominatedSortingPopulation population, final EpsilonBoxDominanceArchive archive, final Selection selection, final Variation variation, final Initialization initialization) {
super(problem, population, archive, initialization);
this.selection = selection;
this.variation = variation;
}
@Override
public void iterate() {
NondominatedSortingPopulation population = this.getPopulation();
EpsilonBoxDominanceArchive archive = this.getArchive();
Population offspring = new Population();
int populationSize = population.size();
if (this.selection == null) {
// recreate the original NSGA-II implementation using binary
// tournament selection without replacement; this version works by
// maintaining a pool of candidate parents.
LinkedList<Solution> pool = new LinkedList<>();
DominanceComparator comparator = new ChainedComparator(new ParetoDominanceComparator(), new CrowdingComparator());
while (offspring.size() < populationSize) {
// ensure the pool has enough solutions
while (pool.size() < 2 * this.variation.getArity()) {
List<Solution> poolAdditions = new ArrayList<>();
for (Solution solution : population) {
poolAdditions.add(solution);
}
PRNG.shuffle(poolAdditions);
pool.addAll(poolAdditions);
}
// select the parents using a binary tournament
Solution[] parents = new Solution[this.variation.getArity()];
for (int i = 0; i < parents.length; i++) {
parents[i] = TournamentSelection.binaryTournament(pool.removeFirst(), pool.removeFirst(), comparator);
}
// evolve the children
offspring.addAll(this.variation.evolve(parents));
}
} else {
// run NSGA-II using selection with replacement; this version allows
// using custom selection operators
while (offspring.size() < populationSize) {
Solution[] parents = this.selection.select(this.variation.getArity(), population);
offspring.addAll(this.variation.evolve(parents));
}
}
this.evaluateAll(offspring);
if (archive != null) {
archive.addAll(offspring);
}
population.addAll(offspring);
population.truncate(populationSize);
}
@Override
public EpsilonBoxDominanceArchive getArchive() {
return (EpsilonBoxDominanceArchive) super.getArchive();
}
@Override
public NondominatedSortingPopulation getPopulation() {
return (NondominatedSortingPopulation) super.getPopulation();
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/event/MOEAFrameworkAlgorithmResultEvent.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework.event;
import org.api4.java.algorithm.IAlgorithm;
import ai.libs.jaicore.basic.algorithm.AAlgorithmEvent;
import ai.libs.jaicore.ea.algorithm.moea.moeaframework.MOEAFrameworkAlgorithmResult;
public class MOEAFrameworkAlgorithmResultEvent extends AAlgorithmEvent {
private final MOEAFrameworkAlgorithmResult result;
public MOEAFrameworkAlgorithmResultEvent(final IAlgorithm<?, ?> algorithm, final MOEAFrameworkAlgorithmResult result) {
super(algorithm);
this.result = result;
}
public MOEAFrameworkAlgorithmResult getResult() {
return this.result;
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/util/EMOEAFrameworkAlgorithmName.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework.util;
public enum EMOEAFrameworkAlgorithmName {
CMA_ES("CMA-ES"), DBEA("DBEA"), EMOEA("eMOEA"), ENSGAII("eNSGAII"), GDE3("GDE3"), IBEA("IBEA"), MOEAD("MOEAD"), MSOPS("MSOPS"), NSGAII("NSGAII"), NSGAIII("NSGAIII"), OMOPSO("OMOPSO"), PAES("PAES"), PESA2("PESA2"), RANDOM(
"Random"), RVEA("RVEA"), SMPSO("SMPSO"), SMS_EMOA("SMS-EMOA"), SPEA2("SPEA2"), VEGA("VEGA"), GA("GA"), ES("ES"), DE("DE");
private final String name;
private EMOEAFrameworkAlgorithmName(final String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/algorithm/moea/moeaframework/util/MOEAFrameworkUtil.java
|
package ai.libs.jaicore.ea.algorithm.moea.moeaframework.util;
import java.util.Arrays;
import org.moeaframework.core.Population;
import org.moeaframework.core.Solution;
import org.moeaframework.core.variable.EncodingUtils;
/**
* Some utils for getting along with the MOEAFramework.
*
* @author wever
*/
public class MOEAFrameworkUtil {
private MOEAFrameworkUtil() {
// intentionally do nothing.
}
public static String solutionGenotypeToString(final Solution solution) {
StringBuilder sb = new StringBuilder();
sb.append(Arrays.toString(EncodingUtils.getInt(solution)));
return sb.toString();
}
public static String solutionToString(final Solution solution) {
StringBuilder sb = new StringBuilder();
sb.append("Objectives: ");
sb.append(Arrays.toString(solution.getObjectives()));
sb.append("\t");
sb.append("Annotations: ");
sb.append(solution.getAttributes());
return sb.toString();
}
public static String populationToString(final Population population) {
StringBuilder sb = new StringBuilder();
int solutionCounter = 1;
for (Solution solution : population) {
sb.append("Solution ");
sb.append(solutionCounter++);
sb.append(": ");
sb.append(solutionToString(solution));
sb.append("\n");
}
return sb.toString();
}
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/evaluation/IAttributeFunction.java
|
package ai.libs.jaicore.ea.evaluation;
public interface IAttributeFunction<I> {
public String attribute(I individual);
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/evaluation/IFitnessFunction.java
|
package ai.libs.jaicore.ea.evaluation;
public interface IFitnessFunction<I> {
public double fitness(I individual);
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/population/IIndividual.java
|
package ai.libs.jaicore.ea.population;
public interface IIndividual {
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/population/IPopulation.java
|
package ai.libs.jaicore.ea.population;
import java.util.Collection;
public interface IPopulation<I extends IIndividual> extends Iterable<I> {
public Collection<I> getIndividuals();
}
|
0
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea
|
java-sources/ai/libs/jaicore-ea/0.2.7/ai/libs/jaicore/ea/population/Individual.java
|
package ai.libs.jaicore.ea.population;
public class Individual implements IIndividual {
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/AAlgorithmExperimentBuilder.java
|
package ai.libs.jaicore.experiments;
import ai.libs.jaicore.basic.IOwnerBasedRandomConfig;
import ai.libs.jaicore.experiments.configurations.IAlgorithmMaxIterConfig;
import ai.libs.jaicore.experiments.configurations.IAlgorithmNameConfig;
public abstract class AAlgorithmExperimentBuilder<B extends AAlgorithmExperimentBuilder<B>> extends AExperimentBuilder<B> {
protected AAlgorithmExperimentBuilder(final IExperimentSetConfig config) {
super(config);
}
public B withAlgorithmName(final String search) {
this.set(IAlgorithmNameConfig.K_ALGORITHM_NAME, search);
return this.getMe();
}
public B withMaxiter(final int maxIter) {
this.set(IAlgorithmMaxIterConfig.K_ALGORITHM_MAXITER, maxIter);
return this.getMe();
}
public B withAlgorithmSeed(final long seed) {
this.set(IOwnerBasedRandomConfig.K_SEED, seed);
return this.getMe();
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/AExperimentBuilder.java
|
package ai.libs.jaicore.experiments;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.experiments.exceptions.IllegalKeyDescriptorException;
import ai.libs.jaicore.logging.LoggerUtil;
public abstract class AExperimentBuilder<B extends AExperimentBuilder<B>> implements IExperimentBuilder {
protected Logger logger = LoggerFactory.getLogger("builder." + this.getClass().getName());
private int memory;
private int numCPUs;
private final Map<String, String> keyMap = new HashMap<>();
private final IExperimentSetConfig config;
private final Class<?> configClass;
private final ExperimentSetAnalyzer analyzer;
protected AExperimentBuilder(final IExperimentSetConfig config) {
super();
this.config = config;
/* determine config class (relevant for forks) */
Class<?> tmpConfigClass = null;
for (Class<?> c : this.config.getClass().getInterfaces()) {
if (IExperimentSetConfig.class.isAssignableFrom(c)) {
if (tmpConfigClass != null) {
throw new IllegalStateException("Config interface is not unique!");
}
tmpConfigClass = c;
}
}
if (tmpConfigClass == null) {
throw new IllegalArgumentException("Could not identify config interface of the given configuration");
}
this.configClass = tmpConfigClass;
this.analyzer = new ExperimentSetAnalyzer(config);
}
protected void set(final String key, final Object value) {
String valAsString = value.toString();
try {
if (!this.analyzer.isValueForKeyValid(key, valAsString)) {
throw new IllegalArgumentException("\"" + valAsString + "\" is not a valid value for key \"" + key + "\"");
}
} catch (IllegalKeyDescriptorException e) {
throw new IllegalArgumentException("\"" + key + "\" is not a valid key in this experiment setup.");
}
this.keyMap.put(key, valAsString);
}
protected abstract B getMe();
public B withMem(final int memoryInMB) {
this.memory = memoryInMB;
return this.getMe();
}
public B withCPUs(final int numCPUs) {
this.numCPUs = numCPUs;
return this.getMe();
}
public B fork() {
try {
B builder = (B) this.getMe().getClass().getConstructor(this.configClass).newInstance(this.config);
AExperimentBuilder<B> cBuilder = (builder);
cBuilder.keyMap.putAll(this.keyMap);
cBuilder.memory = this.memory;
cBuilder.numCPUs = this.numCPUs;
return builder;
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
this.logger.error(LoggerUtil.getExceptionInfo(e));
return null;
}
}
public B withExperiment(final Experiment experiment) {
this.keyMap.putAll(experiment.getValuesOfKeyFields());
this.memory = experiment.getMemoryInMB();
this.numCPUs = experiment.getNumCPUs();
return this.getMe();
}
@Override
public Experiment build() {
ExperimentSetAnalyzer ea = new ExperimentSetAnalyzer(this.config);
List<String> keyFieldNames = this.config.getKeyFields().stream().map(f -> ea.getNameTypeSplitForAttribute(f).getX()).collect(Collectors.toList());
if (!this.keyMap.keySet().containsAll(keyFieldNames)) {
throw new IllegalStateException("Cannot build experiment. Required fields have not been defined: " + SetUtil.difference(keyFieldNames, this.keyMap.keySet()));
}
this.preBuildHook();
return new Experiment(this.memory, this.numCPUs, this.keyMap);
}
/**
* This can be used to check whether everything is ok with the experiment
*/
protected void preBuildHook() {
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/AExperimentDecoder.java
|
package ai.libs.jaicore.experiments;
public abstract class AExperimentDecoder<I, A> implements IExperimentDecoder<I, A> {
private final IExperimentSetConfig config;
private final ExperimentSetAnalyzer analyzer;
protected AExperimentDecoder(final IExperimentSetConfig config) {
super();
this.config = config;
this.analyzer = new ExperimentSetAnalyzer(config);
}
public void checkThatAllKeyFieldsInExperimentAreDefined(final Experiment experiment) {
if (!this.analyzer.isExperimentInLineWithSetup(experiment)) {
throw new IllegalArgumentException("Experiment " + experiment.getValuesOfKeyFields() + " is not in line with the experiment set configuration!");
}
}
public IExperimentSetConfig getConfig() {
return this.config;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/AExperimentDomain.java
|
package ai.libs.jaicore.experiments;
import java.lang.reflect.InvocationTargetException;
import org.api4.java.algorithm.IAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.logging.LoggerUtil;
/**
*
* @author felix
*
* @param <B>
* class of the builder for problems in this domain
* @param <I>
* input class of concrete problem instances for the algorithm
* @param <A>
* class of the algorithms applied here
*/
public abstract class AExperimentDomain<B extends IExperimentBuilder, I, A extends IAlgorithm<? extends I, ?>> {
protected Logger logger = LoggerFactory.getLogger("experimentsdomain");
private final IExperimentSetConfig config;
private final IExperimentDecoder<I, A> decoder;
protected AExperimentDomain(final IExperimentSetConfig config, final IExperimentDecoder<I, A> decoder) {
super();
this.config = config;
this.decoder = decoder;
}
public IExperimentSetConfig getConfig() {
return this.config;
}
public IExperimentDecoder<I, A> getDecoder() {
return this.decoder;
}
public abstract Class<B> getBuilderClass();
public B newBuilder() {
try {
return this.getBuilderClass().getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
this.logger.error(LoggerUtil.getExceptionInfo(e));
return null;
}
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/AlgorithmBenchmarker.java
|
package ai.libs.jaicore.experiments;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;
import java.util.function.Function;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.experiments.exceptions.ExperimentEvaluationFailedException;
public class AlgorithmBenchmarker implements IExperimentSetEvaluator, ILoggingCustomizable {
private class Caps<I, A extends IAlgorithm<? extends I, ?>> {
private final IExperimentDecoder<I, A> decoder;
public Caps(final IExperimentDecoder<I, A> decoder) {
super();
this.decoder = decoder;
}
}
private final IExperimentRunController<?> controller;
private final Caps<?, ?> caps;
private Function<Experiment, Timeout> experimentSpecificTimeout;
private Timeout timeout;
private Logger logger = LoggerFactory.getLogger(AlgorithmBenchmarker.class);
private Thread eventThread;
private final List<Consumer<IAlgorithm<?, ?>>> preRunHooks = new ArrayList<>();
public <I, A extends IAlgorithm<? extends I, ?>> AlgorithmBenchmarker(final IExperimentDecoder<I, A> decoder, final IExperimentRunController<?> controller) {
this.caps = new Caps<>(decoder);
this.controller = controller;
}
@Override
public final void evaluate(final ExperimentDBEntry experimentEntry, final IExperimentIntermediateResultProcessor processor) throws ExperimentEvaluationFailedException, InterruptedException {
try {
this.logger.info("Starting evaluation of experiment entry with keys {}", experimentEntry.getExperiment().getValuesOfKeyFields());
/* get algorithm */
IAlgorithm<?, ?> algorithm = this.caps.decoder.getAlgorithm(experimentEntry.getExperiment());
this.logger.debug("Created algorithm {} of class {} for problem instance {}. Configuring logger name if possible.", algorithm, algorithm.getClass(), algorithm.getInput());
if (algorithm instanceof ILoggingCustomizable) {
((ILoggingCustomizable) algorithm).setLoggerName(this.getLoggerName() + ".algorithm");
}
/* set algorithm timeout */
if (this.experimentSpecificTimeout != null) {
Timeout to = this.experimentSpecificTimeout.apply(experimentEntry.getExperiment());
algorithm.setTimeout(to);
this.logger.info("Set algorithm timeout to experiment specific timeout: {}", to);
}
else if (this.timeout != null) {
algorithm.setTimeout(this.timeout);
this.logger.info("Set algorithm timeout to general timeout: {}", this.timeout);
}
final List<IEventBasedResultUpdater> resultUpdaters = this.controller.getResultUpdaterComputer(experimentEntry.getExperiment());
resultUpdaters.forEach(ru -> ru.setAlgorithm(algorithm));
final List<IExperimentTerminationCriterion> terminationCriteria = this.controller.getTerminationCriteria(experimentEntry.getExperiment());
/* create thread to process events */
BlockingQueue<IAlgorithmEvent> eventQueue = new LinkedBlockingQueue<>();
this.eventThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
IAlgorithmEvent e;
try {
e = eventQueue.take();
} catch (InterruptedException e1) {
break;
}
/* update result */
final Map<String, Object> results = new HashMap<>();
for (IEventBasedResultUpdater updater : resultUpdaters) {
updater.processEvent(e, results);
}
if (!results.isEmpty()) {
processor.processResults(results);
}
/* check whether one of the termination criteria is satisfied */
if (terminationCriteria.stream().anyMatch(c -> c.doesTerminate(e, algorithm))) {
this.logger.info("Stopping algorithm execution, because termination criterion fired.");
algorithm.cancel();
return;
}
}
}, "Experiment Event Processor");
this.eventThread.start();
algorithm.registerListener(new Object() {
@Subscribe
public void receiveEvent(final IAlgorithmEvent e) {
eventQueue.add(e);
}
});
/* running pre-run hooks */
this.preRunHooks.forEach(h -> h.accept(algorithm));
/* run algorithm */
this.logger.info("Running call method on {}", algorithm);
try { // this try block must be here, because timeouts are regular behavior but may throw an exception. One more reason to change this ...
algorithm.call();
}
catch (AlgorithmTimeoutedException e) {
this.logger.info("Algorithm timed out.");
}
/* finish updaters, and update ultimate results */
final Map<String, Object> results = new HashMap<>();
for (IEventBasedResultUpdater updater : resultUpdaters) {
updater.finish(results);
}
if (!results.isEmpty()) {
processor.processResults(results);
}
} catch (Throwable e1) { // we catch throwable here on purpose to be sure that this is logged to the database
throw new ExperimentEvaluationFailedException(e1);
} finally {
if (this.eventThread != null) {
this.eventThread.interrupt();
this.eventThread = null;
}
}
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Loggername is now {}", name);
}
public Timeout getTimeout() {
return this.timeout;
}
public void setTimeout(final Timeout timeout) {
this.timeout = timeout;
}
public Function<Experiment, Timeout> getExperimentSpecificTimeout() {
return this.experimentSpecificTimeout;
}
public void setExperimentSpecificTimeout(final Function<Experiment, Timeout> experimentSpecificTimeout) {
this.experimentSpecificTimeout = experimentSpecificTimeout;
}
public void addPreRunHook(final Consumer<IAlgorithm<?, ?>> hook) {
this.preRunHooks.add(hook);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/Experiment.java
|
package ai.libs.jaicore.experiments;
import java.util.HashMap;
import java.util.Map;
/**
* Basic experiment class that describes an experiment conceptually in terms of hardware information and semantic keys.
*
* @author fmohr
*
*/
public class Experiment {
private final int memoryInMB;
private final int numCPUs;
private Map<String, String> valuesOfKeyFields;
private Map<String, Object> valuesOfResultFields;
private final String error;
public Experiment(final Experiment experiment) {
this(experiment.getMemoryInMB(), experiment.getNumCPUs(), new HashMap<>(experiment.getValuesOfKeyFields()), experiment.getValuesOfResultFields() != null ? new HashMap<>(experiment.getValuesOfResultFields()) : null);
}
public Experiment(final int memoryInMB, final int numCPUs, final Map<String, String> valuesOfKeyFields) {
this(memoryInMB, numCPUs, valuesOfKeyFields, null);
}
public Experiment(final int memoryInMB, final int numCPUs, final Map<String, String> valuesOfKeyFields, final Map<String, Object> valuesOfResultFields) {
this(memoryInMB, numCPUs, valuesOfKeyFields, valuesOfResultFields, "");
}
public Experiment(final int memoryInMB, final int numCPUs, final Map<String, String> valuesOfKeyFields, final Map<String, Object> valuesOfResultFields, final String error) {
super();
this.memoryInMB = memoryInMB;
this.numCPUs = numCPUs;
this.valuesOfKeyFields = valuesOfKeyFields;
this.valuesOfResultFields = valuesOfResultFields;
this.error = error;
}
public Map<String, String> getValuesOfKeyFields() {
return this.valuesOfKeyFields;
}
public Map<String, Object> getValuesOfResultFields() {
return this.valuesOfResultFields;
}
public Map<String, Object> getJointMapOfKeysAndResults() {
Map<String, Object> map = new HashMap<>(this.valuesOfKeyFields);
map.putAll(this.valuesOfResultFields);
return map;
}
public void setValuesOfResultFields(final Map<String, Object> valuesOfResultFields) {
this.valuesOfResultFields = valuesOfResultFields;
}
public void setKeys(final Map<String, String> keys) {
this.valuesOfKeyFields = keys;
}
public int getMemoryInMB() {
return this.memoryInMB;
}
public int getNumCPUs() {
return this.numCPUs;
}
public String getError() {
return this.error;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.memoryInMB;
result = prime * result + this.numCPUs;
result = prime * result + ((this.valuesOfKeyFields == null) ? 0 : this.valuesOfKeyFields.hashCode());
result = prime * result + ((this.valuesOfResultFields == null) ? 0 : this.valuesOfResultFields.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Experiment other = (Experiment) obj;
if (this.memoryInMB != other.memoryInMB) {
return false;
}
if (this.numCPUs != other.numCPUs) {
return false;
}
if (this.valuesOfKeyFields == null) {
if (other.valuesOfKeyFields != null) {
return false;
}
} else if (!this.valuesOfKeyFields.equals(other.valuesOfKeyFields)) {
return false;
}
if (this.valuesOfResultFields == null) {
if (other.valuesOfResultFields != null) {
return false;
}
} else if (!this.valuesOfResultFields.equals(other.valuesOfResultFields)) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimentDBEntry.java
|
package ai.libs.jaicore.experiments;
/**
* This class describes concrete experiment entities contained in the database.
* Each ExperimentDBEntry has a unique id (for the context of the experiment setup) and is bound to a conceptual experiment description in form of an Experiment object.
*
* @author fmohr
*
*/
public class ExperimentDBEntry {
private final int id;
private final Experiment experiment;
public ExperimentDBEntry(final int id, final Experiment experiment) {
super();
if (experiment == null) {
throw new IllegalArgumentException("Experiment must not be null");
}
this.id = id;
this.experiment = experiment;
}
public int getId() {
return this.id;
}
public Experiment getExperiment() {
return this.experiment;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.experiment == null) ? 0 : this.experiment.hashCode());
result = prime * result + this.id;
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
ExperimentDBEntry other = (ExperimentDBEntry) obj;
if (this.experiment == null) {
if (other.experiment != null) {
return false;
}
} else if (!this.experiment.equals(other.experiment)) {
return false;
}
return this.id == other.id;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimentDatabasePreparer.java
|
package ai.libs.jaicore.experiments;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyExistsInDatabaseException;
import ai.libs.jaicore.experiments.exceptions.ExperimentDBInteractionFailedException;
import ai.libs.jaicore.experiments.exceptions.IllegalExperimentSetupException;
public class ExperimentDatabasePreparer implements ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(ExperimentDatabasePreparer.class);
private final IExperimentSetConfig experimentConfig;
private final ExperimentSetAnalyzer configAnalyzer;
private final IExperimentDatabaseHandle handle;
private final int memoryLimit;
private final int cpuLimit;
public ExperimentDatabasePreparer(final IExperimentSetConfig config, final IExperimentDatabaseHandle databaseHandle) {
if (config.getKeyFields() == null) {
throw new IllegalArgumentException("Configuration has not defined any key fields. Make sure to specify the " + IExperimentSetConfig.KEYFIELDS + " entry in the config file.");
}
/* check data base configuration */
if (config.getMemoryLimitInMB() == null) {
throw new IllegalArgumentException("Memory field (" + IExperimentSetConfig.MEM_MAX + ") must be set in configuration");
}
if (config.getNumberOfCPUs() == null) {
throw new IllegalArgumentException("Max CPU field (" + IExperimentSetConfig.CPU_MAX + ") must be set in configuration");
}
if (config.getKeyFields() == null) {
throw new IllegalArgumentException("Key fields (" + IExperimentSetConfig.KEYFIELDS + ") entry must be set in configuration!");
}
if (config.getResultFields() == null) {
throw new IllegalArgumentException("Result fields (" + IExperimentSetConfig.RESULTFIELDS + ") entry must be set in configuration!");
}
/* store most relevant information (since accessing the config object is costly) */
this.memoryLimit = config.getMemoryLimitInMB();
this.cpuLimit = config.getNumberOfCPUs();
/* create analyzer */
this.configAnalyzer = new ExperimentSetAnalyzer(config);
/* synchronize information with the database */
this.handle = databaseHandle;
this.experimentConfig = config;
this.logger.info("Successfully created and initialized ExperimentDatabasePreparer.");
}
/**
* Installs not all but only a sub-sample of the defined experiments.
* The experiments are sampled based on Latin Hypercube sampling.
*
* @param numberOfExperiments
* @return
* @throws AlgorithmExecutionCanceledException
* @throws InterruptedException
* @throws IllegalExperimentSetupException
* @throws AlgorithmTimeoutedException
* @throws ExperimentAlreadyExistsInDatabaseException
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> installSubGridOfExperiments(final int numberOfExperiments) throws AlgorithmTimeoutedException, IllegalExperimentSetupException, InterruptedException, AlgorithmExecutionCanceledException, ExperimentDBInteractionFailedException, ExperimentAlreadyExistsInDatabaseException {
/* setup the table */
this.logger.info("Creating experiment table if not existent.");
this.handle.setup(this.experimentConfig);
this.logger.info("Table ready. Now synchronizing experiments.");
List<List<String>> tmpPossibleKeyCombinations = this.configAnalyzer.getAllPossibleKeyCombinationsAsList();
Collection<List<String>> chosenExperiments = SetUtil.getSubGridRelationFromRelation(tmpPossibleKeyCombinations, numberOfExperiments);
Collection<Map<String, String>> experimentsAsMaps = this.configAnalyzer.mapListTuplesToKeyValueMap(chosenExperiments);
List<ExperimentDBEntry> entries = this.handle.createOrGetExperiments(experimentsAsMaps.stream().map(t -> new Experiment(this.memoryLimit, this.cpuLimit, t)).collect(Collectors.toList()));
this.logger.info("Ids of {} inserted entries: {}", entries.size(), entries.stream().map(ExperimentDBEntry::getId).collect(Collectors.toList()));
return entries;
}
/**
* Creates all experiments in the database that should exist with respect to the configuration but have not been created yet.
*
* @return
* @throws ExperimentDBInteractionFailedException
* @throws IllegalExperimentSetupException
* @throws ExperimentAlreadyExistsInDatabaseException
* @throws AlgorithmTimeoutedException
* @throws InterruptedException
* @throws AlgorithmExecutionCanceledException
*/
public List<ExperimentDBEntry> synchronizeExperiments()
throws ExperimentDBInteractionFailedException, IllegalExperimentSetupException, ExperimentAlreadyExistsInDatabaseException, AlgorithmTimeoutedException, InterruptedException, AlgorithmExecutionCanceledException {
/* setup the table */
this.logger.info("Creating experiment table if not existent.");
this.handle.setup(this.experimentConfig);
this.logger.info("Table ready. Now synchronizing experiments.");
/* get set of all POSSIBLE experiments and all CREATED experiments */
List<Map<String, String>> tmpPossibleKeyCombinations = new ArrayList<>(this.configAnalyzer.getAllPossibleKeyCombinations());
this.logger.debug("Determined {} possible combinations. Will now remove keys that are already contained.", tmpPossibleKeyCombinations.size());
Collection<ExperimentDBEntry> installedExperiments = this.handle.getAllExperiments();
this.logger.debug("Identified {} installed experiments. Removing these from the list of all possible experiments.", installedExperiments.size());
/* now determine the experiments that are currently missing and alert if there are created experiments that are not in line with the current config anymore */
int removed = 0;
for (ExperimentDBEntry experiment : installedExperiments) {
if (tmpPossibleKeyCombinations.contains(experiment.getExperiment().getValuesOfKeyFields())) {
tmpPossibleKeyCombinations.remove(experiment.getExperiment().getValuesOfKeyFields());
removed++;
} else {
this.logger.warn("Experiment with id {} and keys {} seems outdated. The reason can be an illegal key name or an outdated value for one of the keys. Enable DEBUG mode for more details.", experiment.getId(),
experiment.getExperiment().getValuesOfKeyFields());
}
}
this.logger.debug("{} experiments already exist. Number of experiments that will be created now is {}.", removed, tmpPossibleKeyCombinations.size());
/* add experiments that have not been created yet */
if (tmpPossibleKeyCombinations.isEmpty()) {
return new ArrayList<>(0);
}
List<ExperimentDBEntry> entries = this.handle.createOrGetExperiments(tmpPossibleKeyCombinations.stream().map(t -> new Experiment(this.memoryLimit, this.cpuLimit, t)).collect(Collectors.toList()));
this.logger.info("Ids of {} inserted entries: {}", entries.size(), entries.stream().map(ExperimentDBEntry::getId).collect(Collectors.toList()));
return entries;
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
if (this.handle instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.handle).setLoggerName(name + ".handle");
}
}
public ExperimentSetAnalyzer getConfigAnalyzer() {
return this.configAnalyzer;
}
public IExperimentDatabaseHandle getHandle() {
return this.handle;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimentRunner.java
|
package ai.libs.jaicore.experiments;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyStartedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentDBInteractionFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentEvaluationFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentFailurePredictionException;
import ai.libs.jaicore.experiments.exceptions.ExperimentUpdateFailedException;
import ai.libs.jaicore.logging.LoggerUtil;
/**
* This class is used to run experiments.
*
* @author fmohr
*
*/
public class ExperimentRunner implements ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(ExperimentRunner.class);
private static final double MAX_MEM_DEVIATION = .15;
private static final String MSG_STARTEXPS = "Starting to run up to {} experiments.";
private boolean checkMemory = true;
private final IExperimentSetConfig config;
private final IExperimentSetEvaluator evaluator;
private final IExperimentDatabaseHandle handle;
private final int availableMemoryInMB;
private final String executorInfo;
private final Runtime runtime = Runtime.getRuntime();
private boolean allExperimentsFinished = false;
public ExperimentRunner(final IExperimentSetConfig config, final IExperimentSetEvaluator evaluator, final IExperimentDatabaseHandle databaseHandle) throws ExperimentDBInteractionFailedException {
this(config, evaluator, databaseHandle, null);
}
public ExperimentRunner(final IExperimentSetConfig config, final IExperimentSetEvaluator evaluator, final IExperimentDatabaseHandle databaseHandle, final String executorInfo)
throws ExperimentDBInteractionFailedException {
if (databaseHandle == null) {
throw new IllegalArgumentException("Cannot create ExperimentRunner without database handle!");
}
/* check data base configuration */
this.config = config;
this.evaluator = evaluator;
this.handle = databaseHandle;
this.logger.debug("Created ExperimentRunner. Now updating its configuration from the database.");
this.logger.info("Successfully created and initialized ExperimentRunner.");
this.handle.setup(config);
this.availableMemoryInMB = (int) (Runtime.getRuntime().maxMemory() / 1024 / 1024);
this.executorInfo = executorInfo;
}
/**
* Copy constructor for making a (shallow) copy of an already existing experiment runner.
*
* @param other The experiment runner to be copied.
*/
public ExperimentRunner(final ExperimentRunner other) {
this.config = other.config;
this.evaluator = other.evaluator;
this.handle = other.handle;
this.checkMemory = other.checkMemory;
this.availableMemoryInMB = other.availableMemoryInMB;
this.executorInfo = other.executorInfo;
}
public void setCheckMemory(final boolean checkMemory) {
this.checkMemory = checkMemory;
}
/**
* Conducts a limited number of not yet conducted experiments randomly chosen from the grid.
*
* @param maxNumberOfExperiments
* Limit for the number of experiments
* @throws ExperimentDBInteractionFailedException
* @throws InterruptedException
*/
public void randomlyConductExperiments(final int maxNumberOfExperiments) throws ExperimentDBInteractionFailedException, InterruptedException {
if (this.logger.isInfoEnabled()) {
this.logger.info(MSG_STARTEXPS, maxNumberOfExperiments);
}
int numberOfConductedExperiments = 0;
while ((maxNumberOfExperiments <= 0 || numberOfConductedExperiments < maxNumberOfExperiments)) {
List<ExperimentDBEntry> openRandomExperiments = this.handle.getRandomOpenExperiments(maxNumberOfExperiments);
if (openRandomExperiments.isEmpty()) {
this.logger.info("No more open experiments found.");
this.allExperimentsFinished = true;
break;
}
/* if we WOULD conduct more experiments but are interrupted, throw an exception */
if (Thread.interrupted()) {
this.logger.info("Experimenter Thread is interrupted, throwing InterruptedException.");
throw new InterruptedException();
}
/* get experiment, create experiment thread, run the thread, and wait for its termination
* the dedicated thread is created in order to avoid that interrupts on it cause the main thread
* to be interrupted. */
ExperimentDBEntry exp = openRandomExperiments.get(0);
this.checkExperimentValidity(exp.getExperiment());
this.logger.info("Conduct experiment #{} with key values: {}. Memory statistics: {}MB allocated, {}MB free.", numberOfConductedExperiments + 1, exp.getExperiment().getValuesOfKeyFields(),
this.runtime.totalMemory() / (1024 * 1024), this.runtime.freeMemory() / (1024 * 1024));
Thread expThread = new Thread(() -> {
try {
this.handle.startExperiment(exp, this.executorInfo);
this.conductExperiment(exp);
} catch (InterruptedException e) {
this.logger.info("Experiment interrupted.");
Thread.currentThread().interrupt(); // interrupt myself to make Sonar happy
} catch (ExperimentDBInteractionFailedException | ExperimentAlreadyStartedException e) {
this.logger.error(LoggerUtil.getExceptionInfo(e));
}
}, "Thread of experiment id " + exp.getId());
expThread.start();
expThread.join();
numberOfConductedExperiments++;
this.logger.info("Finished experiment #{} with key values {}. Memory statistics: {}MB allocated, {}MB free. Now running GC.", numberOfConductedExperiments,
exp.getExperiment().getValuesOfKeyFields(), this.runtime.totalMemory() / (1024 * 1024), this.runtime.freeMemory() / (1024 * 1024));
System.gc(); // deliberately run the garbage collection to avoid memory accumulation. We found that the JVM is sometimes not able to reasonably clean up later! This is not a guarantee, but better than
this.logger.info("GC finished. Memory statistics: {}MB allocated, {}MB free.", this.runtime.totalMemory() / (1024 * 1024), this.runtime.freeMemory() / (1024 * 1024));
}
this.logger.info("Successfully finished {} experiments.", numberOfConductedExperiments);
}
/**
* Conducts a limited number of not yet conducted experiments randomly chosen from the grid.
*
* @param maxNumberOfExperiments
* Limit for the number of experiments
* @param numThreads Number of threads for running multiple copies of the experiment runner in parallel.
* @throws ExperimentDBInteractionFailedException
* @throws InterruptedException
*/
public void randomlyConductExperimentsInParallel(final int maxNumberOfExperiments, final int numThreads) throws InterruptedException, ExperimentDBInteractionFailedException {
this.logger.info(MSG_STARTEXPS, maxNumberOfExperiments);
// Calculate how many experiments need to be conducted per thread and how many threads are actually needed.
final int experimentsPerThread;
final int actualNumThreads;
if (maxNumberOfExperiments >= 0) {
experimentsPerThread = (int) Math.ceil((double) maxNumberOfExperiments / numThreads);
if (maxNumberOfExperiments < numThreads) {
actualNumThreads = maxNumberOfExperiments;
this.logger.info("Reducing the number of cores to {} as there are only {} many experiments to conduct.", actualNumThreads, maxNumberOfExperiments);
} else {
actualNumThreads = numThreads;
}
} else {
experimentsPerThread = maxNumberOfExperiments;
actualNumThreads = numThreads;
}
this.logger.info("Running {} experiments in parallel using {} threads and conducting {} experiments per thread", maxNumberOfExperiments, actualNumThreads, experimentsPerThread);
ExecutorService pool = Executors.newFixedThreadPool(numThreads);
Semaphore sem = new Semaphore(0);
List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<>());
IntStream.range(0, actualNumThreads).mapToObj(x -> new Runnable() {
@Override
public void run() {
if (ExperimentRunner.this.logger.isInfoEnabled()) {
ExperimentRunner.this.logger.info("Starting to run {} experiments in thread {}", experimentsPerThread, Thread.currentThread().getName());
}
try {
new ExperimentRunner(ExperimentRunner.this).randomlyConductExperiments(experimentsPerThread);
} catch (ExperimentDBInteractionFailedException | InterruptedException e) {
exceptions.add(e);
sem.release(actualNumThreads);
Thread.currentThread().interrupt();
} finally {
sem.release();
}
}}).forEach(pool::submit);
try {
sem.acquire(actualNumThreads);
} finally {
if (!pool.isShutdown()) {
pool.shutdownNow();
}
}
if (!exceptions.isEmpty()) {
Throwable e = exceptions.get(0);
if (e instanceof InterruptedException) {
throw (InterruptedException) e;
} else {
throw (ExperimentDBInteractionFailedException) e;
}
}
}
public void sequentiallyConductExperiments(final int maxNumberOfExperiments) throws ExperimentDBInteractionFailedException, InterruptedException {
this.logger.info(MSG_STARTEXPS, maxNumberOfExperiments);
int numberOfConductedExperiments = 0;
while ((maxNumberOfExperiments <= 0 || numberOfConductedExperiments < maxNumberOfExperiments)) {
Optional<ExperimentDBEntry> nextExperiment = this.handle.startNextExperiment(this.executorInfo);
if (!nextExperiment.isPresent()) {
this.logger.info("After running {}/{} experiments, no more un-started experiments were found.", numberOfConductedExperiments, maxNumberOfExperiments);
this.allExperimentsFinished = true;
break;
}
/* if we WOULD conduct more experiments but are interrupted, throw an exception */
if (Thread.interrupted()) {
this.logger.info("Experimenter Thread is interrupted, throwing InterruptedException.");
throw new InterruptedException();
}
/* get experiment, create experiment thread, run the thread, and wait for its termination
* the dedicated thread is created in order to avoid that interrupts on it cause the main thread
* to be interrupted. */
ExperimentDBEntry exp = nextExperiment.get();
this.checkExperimentValidity(exp.getExperiment());
this.logger.info("Conduct experiment #{} with key values: {}", numberOfConductedExperiments + 1, exp.getExperiment().getValuesOfKeyFields());
Thread expThread = new Thread(() -> {
try {
this.conductExperiment(exp);
} catch (InterruptedException e) {
this.logger.info("Experiment interrupted.");
Thread.currentThread().interrupt(); // interrupt myself to make Sonar happy
} catch (ExperimentDBInteractionFailedException e) {
this.logger.error(LoggerUtil.getExceptionInfo(e));
}
});
expThread.start();
expThread.join();
numberOfConductedExperiments++;
this.logger.info("Finished experiment #{} with key values {}", numberOfConductedExperiments, exp.getExperiment().getValuesOfKeyFields());
}
this.logger.info("Successfully finished {} experiments.", numberOfConductedExperiments);
}
/**
* Conducts an unbound number of randomly chosen experiments from the grid.
*
* @throws ExperimentDBInteractionFailedException
* @throws InterruptedException
*/
public void randomlyConductExperiments() throws ExperimentDBInteractionFailedException, InterruptedException {
this.randomlyConductExperiments(-1);
}
/**
* Conducts an unbound number of experiments from the grid.
*
* @throws ExperimentDBInteractionFailedException
* @throws InterruptedException
*/
public void sequentiallyConductExperiments() throws ExperimentDBInteractionFailedException, InterruptedException {
this.sequentiallyConductExperiments(-1);
}
/**
* Conducts a single experiment The experiment is expected to be marked as started already.
*
* @param expEntry
* the experiment to be conducted
* @throws ExperimentDBInteractionFailedException
* @throws ExperimentAlreadyStartedException
* @throws InterruptedException
* @throws Exception
* These are not the exceptions thrown by the experiment itself, because these are logged into the database. Exceptions thrown here are technical exceptions that occur when arranging the experiment
*/
protected void conductExperiment(final ExperimentDBEntry expEntry) throws ExperimentDBInteractionFailedException, InterruptedException {
/* run experiment */
if (expEntry == null) {
throw new IllegalArgumentException("Cannot conduct NULL experiment!");
}
assert this.handle.hasExperimentStarted(expEntry);
Throwable error = null;
try {
if (this.checkMemory) {
double memoryDeviation = Math.abs(expEntry.getExperiment().getMemoryInMB() - this.availableMemoryInMB) * 1f / expEntry.getExperiment().getMemoryInMB();
if (memoryDeviation > MAX_MEM_DEVIATION) {
this.logger.error("Cannot conduct experiment {}, because the available memory is {} where declared is {}. Deviation: {}", expEntry.getExperiment(), this.availableMemoryInMB,
expEntry.getExperiment().getMemoryInMB(), memoryDeviation);
return;
}
}
if (expEntry.getExperiment().getNumCPUs() > Runtime.getRuntime().availableProcessors()) {
this.logger.error("Cannot conduct experiment {}, because only {} CPU cores are available where declared is {}", expEntry.getExperiment(), Runtime.getRuntime().availableProcessors(),
expEntry.getExperiment().getNumCPUs());
return;
}
this.evaluator.evaluate(expEntry, m -> {
try {
this.logger.info("Updating experiment with id {} in the following entries (enable DEBUG for values): {}", expEntry.getId(), m.keySet());
this.logger.debug("Update map is: {}", m);
this.handle.updateExperiment(expEntry, m);
} catch (ExperimentUpdateFailedException e) {
this.logger.error("Error in updating experiment data. Message of {}: {}.\nStack trace:\n {}", e.getClass().getName(), e.getMessage(), LoggerUtil.getExceptionInfo(e));
}
});
} catch (ExperimentEvaluationFailedException e) {
error = e.getCause();
} catch (ExperimentFailurePredictionException | RuntimeException e) {
error = e;
}
if (error != null) {
this.logger.error("Experiment failed due to {}. Message: {}. Detail info: {}", error.getClass().getName(), error.getMessage(), LoggerUtil.getExceptionInfo(error));
}
this.handle.finishExperiment(expEntry, error);
}
private void checkExperimentValidity(final Experiment experiment) {
ExperimentSetAnalyzer analyzer = new ExperimentSetAnalyzer(this.config);
List<String> keyFields = this.config.getKeyFields().stream().map(k -> analyzer.getNameTypeSplitForAttribute(k).getX()).collect(Collectors.toList());
if (SetUtil.differenceNotEmpty(keyFields, experiment.getValuesOfKeyFields().keySet())) {
throw new IllegalArgumentException("The experiment " + experiment + " is invalid, because key fields have not been defined: "
+ SetUtil.difference(this.config.getKeyFields(), experiment.getValuesOfKeyFields().keySet()));
}
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
if (this.handle instanceof ILoggingCustomizable) {
((ILoggingCustomizable) this.handle).setLoggerName(name + ".handle");
}
}
public boolean mightHaveMoreExperiments() {
return !this.allExperimentsFinished;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimentSetAnalyzer.java
|
package ai.libs.jaicore.experiments;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.StringUtil;
import ai.libs.jaicore.basic.sets.LDSRelationComputer;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.RelationComputationProblem;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.experiments.exceptions.IllegalExperimentSetupException;
import ai.libs.jaicore.experiments.exceptions.IllegalKeyDescriptorException;
import ai.libs.jaicore.logging.LoggerUtil;
public class ExperimentSetAnalyzer {
private static final String PROTOCOL_JAVA = "java:";
private static final String LOGMESSAGE_CREATEINSTANCE = "Create a new instance of {} and ask it for the number of possible values.";
/**
* The ThreadLocal variable holds a unique instance of ScriptEngine for each thread that requests it.
* We use a ThreadLocal variable instead of a local variable to speed up the creation of the ScriptEngine.
* We use a ThreadLocal variable instead of a (static) instance variable because ScriptEngine generally isn't threadsafe
* and can cause problems if multiple threads operate on it.
*/
private static final ThreadLocal<ScriptEngine> scriptEngine = ThreadLocal.withInitial(() -> {
ScriptEngineManager mgr = new ScriptEngineManager();
return mgr.getEngineByName("JavaScript");
});
private final Logger logger = LoggerFactory.getLogger(ExperimentSetAnalyzer.class);
private final IExperimentSetConfig config;
private List<String> keyFields;
private Map<String, List<String>> valuesForKeyFieldsInConfig;
private List<Map<String, String>> possibleKeyCombinations;
private Map<String, IExperimentKeyGenerator<?>> valueGeneratorsPerKey = new HashMap<>();
private int numExperimentsTotal;
public ExperimentSetAnalyzer(final IExperimentSetConfig config) {
this.config = config;
this.reloadConfiguration();
scriptEngine.remove();
}
public void reloadConfiguration() {
/* reload configuration */
//FIXME this reload yields empty config object.
// this.config.reload();
/* erase laze fields */
synchronized (this.config) {
this.possibleKeyCombinations = null;
this.valueGeneratorsPerKey.clear();
/* update key fields */
this.keyFields = Collections.unmodifiableList(this.config.getKeyFields().stream().map(k -> this.getNameTypeSplitForAttribute(k).getX()).collect(Collectors.toList()));
/* create map of possible values for each key field */
this.numExperimentsTotal = 1;
this.valuesForKeyFieldsInConfig = new HashMap<>();
for (String key: this.keyFields) {
String propertyVals = this.config.removeProperty(key);
if (propertyVals == null) {
throw new IllegalArgumentException("Invalid experiment set configuration! No property values defined for key field \"" + key + "\"");
}
List<String> vals = Arrays.asList(StringUtil.explode(propertyVals, ",")).stream().map(String::trim).collect(Collectors.toList());
this.config.setProperty(key, propertyVals);
this.valuesForKeyFieldsInConfig.put(key, vals);
try {
this.numExperimentsTotal *= this.getNumberOfValuesForKey(key);
} catch (IllegalKeyDescriptorException e) {
this.logger.error(LoggerUtil.getExceptionInfo(e));
}
}
}
}
public boolean isValueForKeyValid(final String key, final String value) throws IllegalKeyDescriptorException {
if (!this.keyFields.contains(key)) {
throw new IllegalStateException("Key \"" + key + "\" is not defined in experiment setup.");
}
List<String> possibleValues = this.valuesForKeyFieldsInConfig.get(key);
if (possibleValues.isEmpty()) {
throw new IllegalStateException("No values specified for key " + key);
}
if (!possibleValues.get(0).startsWith(PROTOCOL_JAVA)) {
return possibleValues.contains(value);
}
this.checkThatKeyOnlyAllowsOneValue(key);
try {
Class<?> c = Class.forName(possibleValues.get(0).substring(PROTOCOL_JAVA.length()).trim());
this.checkKeyGenerator(c);
this.logger.trace(LOGMESSAGE_CREATEINSTANCE, c.getName());
return ((IExperimentKeyGenerator<?>) c.getConstructor().newInstance()).isValueValid(value);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new IllegalKeyDescriptorException(e);
}
}
public boolean isExperimentInLineWithSetup(final Experiment experiment) {
/* first check on the keys themselves (not the values) */
Collection<String> additionalKeys = SetUtil.difference(experiment.getValuesOfKeyFields().keySet(), this.keyFields);
Collection<String> missingKeys = SetUtil.difference(this.keyFields, experiment.getValuesOfKeyFields().keySet());
if (!additionalKeys.isEmpty() || !missingKeys.isEmpty()) {
return false;
}
/* now check the concrete values */
for (Entry<String, String> keyEntry : experiment.getValuesOfKeyFields().entrySet()) {
try {
if (!this.isValueForKeyValid(keyEntry.getKey(), keyEntry.getValue())) {
this.logger.debug("Experiment {} seems outdated. The value {} for key {} is not admissible anymore. Consider removing it.", experiment, keyEntry.getKey(), keyEntry.getValue());
return false;
}
} catch (IllegalKeyDescriptorException e) {
this.logger.debug("Experiment {} seems outdated. The key {} is not defined in the current setup.", experiment, keyEntry.getKey());
return false;
}
}
return true;
}
public List<List<String>> getAllPossibleKeyCombinationsAsList() throws IllegalExperimentSetupException, AlgorithmTimeoutedException, InterruptedException, AlgorithmExecutionCanceledException {
this.logger.debug("Computing all possible experiments.");
/* build cartesian product over all possible key-values */
List<List<String>> values = new ArrayList<>();
for (String key : this.keyFields) {
if (!this.valuesForKeyFieldsInConfig.containsKey(key)) {
throw new IllegalStateException("No values for key " + key + " have been defined!");
}
List<String> valuesForKey = this.getAllValuesForKey(key);
this.logger.debug("Retrieving {} values for key {}. Enable TRACE to see all values.", valuesForKey.size(), key);
this.logger.trace("Values for key {}: {}", key, valuesForKey);
values.add(valuesForKey);
}
/* get constraints */
List<List<String>> valuesSortedByConstraintRelevance;
List<Predicate<List<String>>> constraints = new ArrayList<>();
List<Integer> permutation;
if (this.config.getConstraints() != null) {
List<String> constraintsToParse = new ArrayList<>();
Map<String, Integer> constraintScorePerKeyword = new HashMap<>();
this.keyFields.forEach(k -> constraintScorePerKeyword.put(k, 0));
for (String p : this.config.getConstraints()) {
if (p.startsWith(PROTOCOL_JAVA)) {
try {
constraints.add((Predicate<List<String>>) Class.forName(p.substring(PROTOCOL_JAVA.length()).trim()).getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
this.logger.error("Error in loading constraint {}: {}", p, LoggerUtil.getExceptionInfo(e));
}
}
else {
this.logger.info("Parsing constraint {}", p);
constraintsToParse.add(p);
for (String keyword : this.keyFields) {
if (p.contains(keyword)) {
constraintScorePerKeyword.put(keyword, constraintScorePerKeyword.get(keyword) + 1);
}
}
}
}
final List<String> keyFieldsSortedByConstraintRelevance = this.keyFields.stream().sorted((f1, f2) -> Integer.compare(constraintScorePerKeyword.get(f2), constraintScorePerKeyword.get(f1))).collect(Collectors.toList());
permutation = SetUtil.getPermutation(this.keyFields, keyFieldsSortedByConstraintRelevance);
valuesSortedByConstraintRelevance = SetUtil.applyPermutation(values, permutation);
/* now create predicates from the constraints that require parsing */
for (String p : constraintsToParse) {
Predicate<List<String>> predicate = new Predicate<List<String>>() {
private final int highestRequiredIndex = keyFieldsSortedByConstraintRelevance.stream().filter(p::contains).map(keyFieldsSortedByConstraintRelevance::indexOf).max(Integer::compare).get();
@Override
public boolean test(final List<String> t) {
String evaluatedConstraint = p;
int n = t.size(); // n is the number of key fields considered in t (grows over time)
if (n <= this.highestRequiredIndex || n > this.highestRequiredIndex + 1) { // only apply the predicate for tuples of EXACTLY the length of the highest required variable (we assume that any larger tuple has already been tested implictly by a previously requested sub-tuple)
return true;
}
for (int i = 0; i < n; i++) {
evaluatedConstraint = evaluatedConstraint.replace(keyFieldsSortedByConstraintRelevance.get(i), t.get(i));
}
try {
ScriptEngine engine = scriptEngine.get();
Object evaluation = engine.eval(evaluatedConstraint);
if(evaluation instanceof Boolean) {
return (boolean) evaluation;
} else {
ExperimentSetAnalyzer.this.logger.error("The evaluation of constraint={} did not return a boolean but instead: {}. Predicate falls back to `false`."
+ " \nThe original constraint is: {}",
evaluatedConstraint, evaluation, p);
return false;
}
} catch (ScriptException e) {
ExperimentSetAnalyzer.this.logger.error(LoggerUtil.getExceptionInfo(e));
return false;
}
}
};
constraints.add(predicate);
}
}
else {
valuesSortedByConstraintRelevance = values;
permutation = null;
}
Predicate<List<String>> jointConstraints = t -> {
for (Predicate<List<String>> c : constraints) {
if (!c.test(t)) {
return false;
}
}
return true;
};
/* create one experiment object from every tuple */
if (this.logger.isDebugEnabled()) {
this.logger.debug("Building relation from {} cartesian product with {} constraints.", values.stream().map(l -> "" + l.size()).collect(Collectors.joining(" x ")), constraints.size());
}
RelationComputationProblem<String> problem = constraints.isEmpty() ? new RelationComputationProblem<>(values) : new RelationComputationProblem<>(valuesSortedByConstraintRelevance, jointConstraints);
LDSRelationComputer<String> lc = new LDSRelationComputer<>(problem);
lc.setLoggerName(this.logger.getName() + ".relationcomputer");
List<List<String>> entries = lc.call();
return permutation != null ? entries.stream().map(e -> SetUtil.applyInvertedPermutation(e, permutation)).collect(Collectors.toList()) : entries;
}
public List<Map<String, String>> getAllPossibleKeyCombinations() throws IllegalExperimentSetupException, AlgorithmTimeoutedException, InterruptedException, AlgorithmExecutionCanceledException {
if (this.possibleKeyCombinations == null) {
List<List<String>> combinationsAsList = this.getAllPossibleKeyCombinationsAsList();
this.logger.info("Obtained {} key combinations. Now building maps from these.", combinationsAsList.size());
this.possibleKeyCombinations = this.mapListTuplesToKeyValueMap(combinationsAsList);
}
return this.possibleKeyCombinations;
}
private Map<String, String> mapValuesToKeyValueMap(final List<String> values) {
Map<String, String> map = new HashMap<>();
int i = 0;
for (String key : this.keyFields) {
map.put(key, values.get(i++));
}
return map;
}
public List<Map<String, String>> mapListTuplesToKeyValueMap(final Collection<List<String>> tuples) {
return Collections.unmodifiableList(tuples.stream().map(c -> Collections.unmodifiableMap(this.mapValuesToKeyValueMap(c))).collect(Collectors.toList()));
}
public int getNumberOfValuesForKey(final String key) throws IllegalKeyDescriptorException {
List<String> possibleValues = this.valuesForKeyFieldsInConfig.get(key);
if (possibleValues.isEmpty()) {
return 0;
}
if (!possibleValues.get(0).startsWith(PROTOCOL_JAVA)) {
return possibleValues.size();
}
this.checkThatKeyOnlyAllowsOneValue(key);
try {
Class<?> c = Class.forName(possibleValues.get(0).substring(PROTOCOL_JAVA.length()).trim());
this.checkKeyGenerator(c);
this.logger.trace(LOGMESSAGE_CREATEINSTANCE, c.getName());
return ((IExperimentKeyGenerator<?>) c.getConstructor().newInstance()).getNumberOfValues();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new IllegalKeyDescriptorException(e);
}
}
public String getValueForKey(final String key, final int indexOfValue) {
List<String> possibleValues = this.valuesForKeyFieldsInConfig.get(key);
if (possibleValues.isEmpty()) {
throw new IllegalArgumentException("No values specified for key " + key);
}
if (!possibleValues.get(0).startsWith(PROTOCOL_JAVA)) {
return possibleValues.get(indexOfValue);
}
this.checkThatKeyOnlyAllowsOneValue(key);
/* determine the generator for this key if this has not happened before */
IExperimentKeyGenerator<?> keyGenerator = this.valueGeneratorsPerKey.computeIfAbsent(key, k -> {
try {
Class<?> c = Class.forName(possibleValues.get(0).substring(PROTOCOL_JAVA.length()).trim());
this.checkKeyGenerator(c);
this.logger.trace(LOGMESSAGE_CREATEINSTANCE, c.getName());
return (IExperimentKeyGenerator<?>) c.getConstructor().newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalKeyDescriptorException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new IllegalArgumentException(e);
}
});
Object value = keyGenerator.getValue(indexOfValue);
if (value == null) {
throw new NoSuchElementException("No value could be found for index " + indexOfValue + " in keyfield " + key);
}
return value.toString();
}
public List<String> getAllValuesForKey(final String key) throws IllegalKeyDescriptorException {
int n = this.getNumberOfValuesForKey(key);
List<String> vals = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
vals.add(this.getValueForKey(key, i));
}
return Collections.unmodifiableList(vals);
}
public int getNumExperimentsTotal() {
return this.numExperimentsTotal;
}
private void checkThatKeyOnlyAllowsOneValue(final String key) {
if (this.valuesForKeyFieldsInConfig.get(key).size() > 1) {
throw new UnsupportedOperationException("The value for key " + key + " seems to be a java class, but there are multiple values defined.");
}
}
private void checkKeyGenerator(final Class<?> c) throws IllegalKeyDescriptorException {
if (!IExperimentKeyGenerator.class.isAssignableFrom(c)) {
throw new IllegalKeyDescriptorException("The specified class " + c.getName() + " does not implement the " + IExperimentKeyGenerator.class.getName() + " interface.");
}
}
public Pair<String, String> getNameTypeSplitForAttribute(final String name) {
String[] parts = name.split(":");
String type = parts.length == 2 ? parts[1] : null;
return new Pair<>(parts[0], type);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimentUtil.java
|
package ai.libs.jaicore.experiments;
import java.util.ArrayList;
import java.util.List;
import ai.libs.jaicore.experiments.databasehandle.AExperimenterSQLHandle;
public class ExperimentUtil {
private ExperimentUtil() {
/* no instantiation desired */
}
public static String getProgressQuery(final String tablename) {
return getProgressQuery(tablename, 0);
}
public static String getProgressQuery(final String tablename, final int numberOfParallelJobs) {
/* create sub-queries */
List<String> subQueries = new ArrayList<>();
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as \"open\" FROM `" + tablename + "` WHERE time_started is null");
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as \"running\" FROM `" + tablename + "` WHERE time_started is not null and time_end is null");
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as finished, AVG(TIMESTAMPDIFF(SECOND, time_started, time_end)) as avgRuntimeFinished FROM `" + tablename + "` WHERE time_started is not null and time_end is not null");
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as successful FROM `" + tablename + "` where time_end is not null and exception is null");
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as failed FROM `" + tablename + "` where exception is not null");
subQueries.add("SELECT \"aux\" as pk, COUNT(*) as total FROM `" + tablename + "`");
/* create main query */
StringBuilder sb = new StringBuilder();
sb.append(
"SELECT total, open, CONCAT(ROUND(100 * open / total, 2), \"%\") as \"open (rel)\", running, CONCAT(ROUND(100 * running / total, 2), \"%\") as \"running (rel)\", finished, CONCAT(ROUND(100 * finished / total, 2), \"%\") as \"finished (rel)\", successful, failed, CONCAT(ROUND(100 * successful / (successful + failed), 2), \"%\") as \"success rate\", CONCAT(ROUND(avgRuntimeFinished), \"s\") as \"Average Time of Finished\", CONCAT(ROUND(avgRuntimeFinished * open / "
+ (numberOfParallelJobs > 0 ? numberOfParallelJobs : "running") + "), \"s\") as \"ETA\" FROM ");
for (int t = 1; t < subQueries.size(); t++) {
sb.append("(");
sb.append(subQueries.get(t - 1));
sb.append(") as t");
sb.append(t);
sb.append(" NATURAL JOIN ");
}
sb.append("(");
sb.append(subQueries.get(subQueries.size() - 1));
sb.append(") as t" + subQueries.size());
return sb.toString();
}
public static String getQueryToIdentifyCorruptRuns(final String tablename) {
return "SELECT * FROM (SELECT " + AExperimenterSQLHandle.FIELD_EXECUTOR + ", COUNT(*) as n FROM `" + tablename + "` WHERE time_started is not null and time_end is null group by " + AExperimenterSQLHandle.FIELD_EXECUTOR + ") as t where n > 1";
}
public static String getQueryToListAllCorruptJobRuns(final String tablename) {
return "SELECT t1.* FROM `" + tablename + "` as t1 join `" + tablename + "` as t2 USING(" + AExperimenterSQLHandle.FIELD_EXECUTOR + ") WHERE t1.time_started is not null and t1.time_end is null and t2.time_started > t1.time_started and t2.time_end is null";
}
public static String getQueryToListAllRunningExecutions(final String tablename) {
return "SELECT * FROM `" + tablename + "` WHERE time_started is not null and time_end is null";
}
public static String getQueryToListAllFailedExecutions(final String tablename) {
return "SELECT * FROM `" + tablename + "` WHERE exception is not null";
}
public static String getOccurredExceptions(final String tablename, final String... ignorePatterns) {
StringBuilder sb = new StringBuilder();
for (String p : ignorePatterns) {
sb.append(" AND `exception` NOT LIKE '%" + p + "%'");
}
return "SELECT exception, COUNT(*) FROM `" + tablename + "` WHERE exception is not null" + sb.toString() + " GROUP BY exception";
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/ExperimenterFrontend.java
|
package ai.libs.jaicore.experiments;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import org.aeonbits.owner.ConfigFactory;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.Timeout;
import org.api4.java.algorithm.exceptions.AlgorithmExecutionCanceledException;
import org.api4.java.algorithm.exceptions.AlgorithmTimeoutedException;
import org.api4.java.common.control.ILoggingCustomizable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.db.IDatabaseConfig;
import ai.libs.jaicore.db.sql.IRestDatabaseConfig;
import ai.libs.jaicore.experiments.databasehandle.ExperimenterMySQLHandle;
import ai.libs.jaicore.experiments.databasehandle.ExperimenterRestSQLHandle;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyExistsInDatabaseException;
import ai.libs.jaicore.experiments.exceptions.ExperimentDBInteractionFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentEvaluationFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentFailurePredictionException;
import ai.libs.jaicore.experiments.exceptions.IllegalExperimentSetupException;
public class ExperimenterFrontend implements ILoggingCustomizable {
private static final String MSG_NO_MORE_EXPERIMENTS = "No more experiments to conduct.";
private static final String MSG_NOTABLE = "No table set in the database configuration!";
private IExperimentSetConfig config;
private IExperimentDatabaseHandle databaseHandle;
private IExperimentSetEvaluator evaluator;
private AExperimentDomain<?, ?, ?> domain;
private IExperimentRunController<?> controller;
private String loggerNameForAlgorithm;
private ExperimentRunner runner;
private String executorInfo; // information about the job of the compute center executing this in order to ease tracking
private Timeout timeout;
private Function<Experiment, Timeout> experimentSpecificTimeout;
private final List<Consumer<IAlgorithm<?, ?>>> preRunHooks = new ArrayList<>();
private Logger logger = LoggerFactory.getLogger("expfe");
public ExperimenterFrontend withLoggerNameForAlgorithm(final String loggerName) {
this.loggerNameForAlgorithm = loggerName;
return this;
}
public ExperimenterFrontend withDatabaseConfig(final String databaseConfigFileName) {
return this.withDatabaseConfig(new File(databaseConfigFileName));
}
public ExperimenterFrontend withDatabaseConfig(final File... databaseConfigFiles) {
return this.withDatabaseConfig((IDatabaseConfig) ConfigFactory.create(IDatabaseConfig.class).loadPropertiesFromFileArray(databaseConfigFiles));
}
public ExperimenterFrontend withRestDatabaseConfig(final File... databaseConfigFiles) {
return this.withDatabaseConfig((IRestDatabaseConfig) ConfigFactory.create(IRestDatabaseConfig.class).loadPropertiesFromFileArray(databaseConfigFiles));
}
public ExperimenterFrontend withDatabaseConfig(final IRestDatabaseConfig databaseConfig) {
this.databaseHandle = new ExperimenterRestSQLHandle(databaseConfig);
if (databaseConfig.getTable() == null) {
throw new IllegalArgumentException(MSG_NOTABLE);
}
return this;
}
public ExperimenterFrontend withDatabaseConfig(final IDatabaseConfig databaseConfig) {
this.databaseHandle = new ExperimenterMySQLHandle(databaseConfig);
if (databaseConfig.getDBTableName() == null) {
throw new IllegalArgumentException(MSG_NOTABLE);
}
return this;
}
public ExperimenterFrontend withExperimentsConfig(final File configFile) {
return this.withExperimentsConfig((IExperimentSetConfig) ConfigFactory.create(IExperimentSetConfig.class).loadPropertiesFromFile(configFile));
}
public ExperimenterFrontend withExperimentsConfig(final IExperimentSetConfig config) {
this.config = config;
return this;
}
public ExperimenterFrontend withTimeout(final Timeout to) {
this.timeout = to;
return this;
}
public ExperimenterFrontend withExperimentSpecificTimeout(final Function<Experiment, Timeout> timeoutFunction) {
this.experimentSpecificTimeout = timeoutFunction;
return this;
}
public ExperimenterFrontend clearDatabase() throws ExperimentDBInteractionFailedException {
this.databaseHandle.deleteDatabase();
return this;
}
public ExperimenterFrontend withEvaluator(final IExperimentSetEvaluator evaluator) {
this.evaluator = evaluator;
return this;
}
public ExperimenterFrontend withExecutorInfo(final String executorInfo) {
this.executorInfo = executorInfo;
return this;
}
public String getExecutorInfo() {
return this.executorInfo;
}
public <B extends IExperimentBuilder, I, A extends IAlgorithm<? extends I, ?>> ExperimenterFrontend withDomain(final AExperimentDomain<B, I, A> domain) {
this.evaluator = null;
this.withExperimentsConfig(domain.getConfig());
this.domain = domain;
return this;
}
public ExperimenterFrontend withController(final IExperimentRunController<?> controller) {
this.controller = controller;
return this;
}
public ExperimenterFrontend synchronizeDatabase()
throws ExperimentDBInteractionFailedException, AlgorithmTimeoutedException, IllegalExperimentSetupException, ExperimentAlreadyExistsInDatabaseException, InterruptedException, AlgorithmExecutionCanceledException {
ExperimentDatabasePreparer preparer = new ExperimentDatabasePreparer(this.config, this.databaseHandle);
preparer.setLoggerName(this.getLoggerName() + ".preparer");
preparer.synchronizeExperiments();
return this;
}
private void prepareEvaluator() {
if (this.evaluator != null) {
throw new IllegalStateException("An evaluator has already been set manually. Preparing a domain specific one afterwards and overriding the manually set is not allowed!");
}
if (this.controller == null) {
throw new IllegalStateException("Cannot prepare evaluator, because no experiment controller has been set!");
}
if (this.domain != null) {
this.evaluator = new AlgorithmBenchmarker(this.domain.getDecoder(), this.controller);
((AlgorithmBenchmarker) this.evaluator).setLoggerName(this.loggerNameForAlgorithm != null ? this.loggerNameForAlgorithm : (this.getLoggerName() + ".evaluator"));
if (this.timeout != null) {
((AlgorithmBenchmarker) this.evaluator).setTimeout(this.timeout);
}
if (this.experimentSpecificTimeout != null) {
((AlgorithmBenchmarker) this.evaluator).setExperimentSpecificTimeout(this.experimentSpecificTimeout);
}
}
this.preRunHooks.forEach(((AlgorithmBenchmarker)this.evaluator)::addPreRunHook);
}
private ExperimentRunner getExperimentRunner() throws ExperimentDBInteractionFailedException {
if (this.runner == null) {
if (this.config == null) {
throw new IllegalStateException("Cannot conduct experiments. No experiment config has been set, yet.");
}
if (this.databaseHandle == null) {
throw new IllegalStateException("Cannot conduct experiments. No database handle has been set, yet.");
}
if (this.evaluator == null) {
this.prepareEvaluator();
}
this.runner = new ExperimentRunner(this.config, this.evaluator, this.databaseHandle, this.executorInfo);
this.runner.setLoggerName(this.getLoggerName() + ".runner");
}
return this.runner;
}
public void conductExperiment(final int id) throws ExperimentDBInteractionFailedException, InterruptedException {
this.getExperimentRunner().conductExperiment(this.databaseHandle.getExperimentWithId(id));
}
public void randomlyConductExperiments() throws ExperimentDBInteractionFailedException, InterruptedException {
if (!this.getExperimentRunner().mightHaveMoreExperiments()) {
throw new IllegalStateException(MSG_NO_MORE_EXPERIMENTS);
}
this.getExperimentRunner().randomlyConductExperiments();
}
public void sequentiallyConductExperiments() throws ExperimentDBInteractionFailedException, InterruptedException {
if (!this.getExperimentRunner().mightHaveMoreExperiments()) {
throw new IllegalStateException(MSG_NO_MORE_EXPERIMENTS);
}
this.getExperimentRunner().sequentiallyConductExperiments();
}
public ExperimenterFrontend randomlyConductExperiments(final int limit) throws ExperimentDBInteractionFailedException, InterruptedException {
if (!this.getExperimentRunner().mightHaveMoreExperiments()) {
throw new IllegalStateException(MSG_NO_MORE_EXPERIMENTS);
}
this.getExperimentRunner().randomlyConductExperiments(limit);
return this;
}
public ExperimenterFrontend randomlyConductExperiments(final Timeout to, final int maxExperimentRuntime) throws ExperimentDBInteractionFailedException, InterruptedException {
long deadline = System.currentTimeMillis() + to.milliseconds();
while (System.currentTimeMillis() + maxExperimentRuntime < deadline) {
this.logger.info("We have time for more experiments. Conducting next.");
this.randomlyConductExperiments(1);
this.logger.info("Finished experiment.");
}
return this;
}
public boolean mightHaveMoreExperiments() throws ExperimentDBInteractionFailedException {
return this.getExperimentRunner().mightHaveMoreExperiments();
}
public <O> O simulateExperiment(final Experiment experiment, final IExperimentRunController<O> controller) throws ExperimentEvaluationFailedException, InterruptedException, ExperimentFailurePredictionException {
Objects.requireNonNull(controller, "A controller must be provided to simulate an experiment.");
this.withController(controller);
this.prepareEvaluator();
ExperimentDBEntry experimentEntry = new ExperimentDBEntry(-1, experiment);
Map<String, Object> results = new HashMap<>();
this.evaluator.evaluate(experimentEntry, results::putAll);
Experiment expCopy = new Experiment(experiment);
expCopy.setValuesOfResultFields(results);
return controller.getExperimentEncoding(expCopy);
}
public void simulateExperiment(final int id, final IExperimentRunController<?> controller) throws ExperimentEvaluationFailedException, InterruptedException, ExperimentFailurePredictionException, ExperimentDBInteractionFailedException {
Objects.requireNonNull(this.databaseHandle, "Not database handle has been set.");
this.databaseHandle.setup(this.config);
this.simulateExperiment(this.databaseHandle.getExperimentWithId(id).getExperiment(), controller);
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
}
public void addPreRunHook(final Consumer<IAlgorithm<?, ?>> hook) {
this.preRunHooks.add(hook);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IEventBasedResultUpdater.java
|
package ai.libs.jaicore.experiments;
import java.util.Map;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
public interface IEventBasedResultUpdater {
public void setAlgorithm(IAlgorithm<?, ?> algorithm);
public void processEvent(IAlgorithmEvent e, Map<String, Object> currentResults);
public void finish(Map<String, Object> currentResults);
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentBuilder.java
|
package ai.libs.jaicore.experiments;
public interface IExperimentBuilder {
public Experiment build();
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentDatabaseHandle.java
|
package ai.libs.jaicore.experiments;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyExistsInDatabaseException;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyStartedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentDBInteractionFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentUpdateFailedException;
/**
* This interface is used by the ExperimentRunner to get, create, and update experiment entries.
*
* @author fmohr
*
*/
public interface IExperimentDatabaseHandle {
/**
* Prepares everything so that upcoming calls for create and update will be managed according to the specified configuration.
*
* @param config
* Description of the experiment setup
* @throws ExperimentDBInteractionFailedException
*/
public void setup(final IExperimentSetConfig config) throws ExperimentDBInteractionFailedException;
/**
*
* @param key
* The key attribute
* @throws ExperimentDBInteractionFailedException
*/
public Collection<String> getConsideredValuesForKey(final String key) throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database
*
* @return List of all experiments
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getAllExperiments() throws ExperimentDBInteractionFailedException;
/**
* Returns the number of all experiments contained in the database
*
* @throws ExperimentDBInteractionFailedException
*/
public int getNumberOfAllExperiments() throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database marked as being conducted.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getConductedExperiments() throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database marked as being conducted and with the attribute values specified as in the map.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getConductedExperiments(Map<String, Object> fieldFilter) throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database marked as being conducted and with an exception.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getFailedExperiments() throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database marked as being conducted and with an exception and with the attribute values specified as in the map.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getFailedExperiments(Map<String, Object> fieldFilter) throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database that have not been started yet.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getOpenExperiments() throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments contained in the database that have not been started yet.
*
* @param limit
* Maximum number of open experiments that should be returned
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getRandomOpenExperiments(int limit) throws ExperimentDBInteractionFailedException;
/**
* Picks an unstarted experiment, marks it as started and returns it. These operations happen atomically, so if a experiment is returned, then ownership on it can be assumed.
*
* If no experiment is returned, i.e. an empty optional, then no experiment is remaining.
*
* @param executorInfo
* The identifier of the executor who evaluates this experiment; important for tracking of experiments in compute centers
* @return A started experiment if there are any left, or else an empty optional.
* @throws ExperimentDBInteractionFailedException
*/
public Optional<ExperimentDBEntry> startNextExperiment(String executorInfo) throws ExperimentDBInteractionFailedException;
/**
* Returns a list of all experiments that are currently being conducted.
*
* @return List of all experiments conducted so far
* @throws ExperimentDBInteractionFailedException
*/
public List<ExperimentDBEntry> getRunningExperiments() throws ExperimentDBInteractionFailedException;
/**
* Gets the experiment with the given id.
*
* @param id
* @return
* @throws ExperimentDBInteractionFailedException
*/
public ExperimentDBEntry getExperimentWithId(int id) throws ExperimentDBInteractionFailedException;
/**
* Creates a new experiment entry and returns it.
*
* @param experiment
* @return The id of the created experiment
* @throws ExperimentDBInteractionFailedException
* @throws ExperimentAlreadyExistsInDatabaseException
*/
public ExperimentDBEntry createAndGetExperiment(final Experiment experiment) throws ExperimentDBInteractionFailedException, ExperimentAlreadyExistsInDatabaseException;
/**
* Creates or fetches the experiment entries from the database. The "or" is exclusive, i.e. that if any entry exist it won't be created. In comparison to other createAndGet methods, this doesn't throw a
* ExperimentAlreadyExistsInDatabaseException.
*
* @param experiments
* the experiments to be created
* @return The id of the created experiment
* @throws ExperimentDBInteractionFailedException
* @throws ExperimentAlreadyExistsInDatabaseException
*/
public List<ExperimentDBEntry> createOrGetExperiments(final List<Experiment> experiments) throws ExperimentDBInteractionFailedException, ExperimentAlreadyExistsInDatabaseException;
/**
* Starts the given experiment
*
* @param exp
* The experiment that is started on the current machine
* @param executorInfo
* The identifier of the executor who evaluates this experiment; important for tracking of experiments in compute centers
* @throws ExperimentUpdateFailedException
*/
public void startExperiment(final ExperimentDBEntry exp, String executorInfo) throws ExperimentAlreadyStartedException, ExperimentUpdateFailedException;
/**
* Updates non-keyfield values of the experiment.
*
* @param exp
* The experiment entry in the database
* @param values
* A key-value store where keys are names of result fields. The values will be associated to each key in the database.
* @throws ExperimentUpdateFailedException
*/
public void updateExperiment(final ExperimentDBEntry exp, final Map<String, ? extends Object> values) throws ExperimentUpdateFailedException;
public boolean updateExperimentConditionally(final ExperimentDBEntry exp, final Map<String, String> conditions, final Map<String, ? extends Object> values) throws ExperimentUpdateFailedException;
/**
* Signals that an experiment has been finished successfully. A corresponding timestamp will be attached to the experiment entry.
*
* @param exp
* @throws ExperimentDBInteractionFailedException
*/
public void finishExperiment(final ExperimentDBEntry exp) throws ExperimentDBInteractionFailedException;
/**
* Signals that an experiment has failed with an exception. The timestamp and the exception will be stored with the experiment.
*
* @param exp
* Experiment to be marked as finished
* @param errror
* If not null, the experiment
* @throws ExperimentDBInteractionFailedException
*/
public void finishExperiment(final ExperimentDBEntry exp, final Throwable errror) throws ExperimentDBInteractionFailedException;
/**
* Deletes an experiment from the database
*
* @param exp
* Experiment to be deleted
* @throws ExperimentDBInteractionFailedException
*/
public void deleteExperiment(final ExperimentDBEntry exp) throws ExperimentDBInteractionFailedException;
/**
* Deletes everything known to the experiment database. Note that database is understood as an abstract term. In a true database, this could just be a table.
*
* @throws ExperimentDBInteractionFailedException
*/
public void deleteDatabase() throws ExperimentDBInteractionFailedException;
/**
* Checks if the given experiment has been started already.
*
* @param exp
* Experiment used for the query.
* @return true iff experiment has been marked as started.
* @throws ExperimentDBInteractionFailedException
*/
public boolean hasExperimentStarted(final ExperimentDBEntry exp) throws ExperimentDBInteractionFailedException;
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentDecoder.java
|
package ai.libs.jaicore.experiments;
import ai.libs.jaicore.experiments.exceptions.ExperimentDecodingException;
public interface IExperimentDecoder<I, A> {
public I getProblem(Experiment experiment) throws ExperimentDecodingException;
public A getAlgorithm(Experiment experiment) throws ExperimentDecodingException;
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentIntermediateResultProcessor.java
|
package ai.libs.jaicore.experiments;
import java.util.Map;
/**
* A result processor is used to push new result values to the database when they arrive.
* The result processor internally knows to which experiment the pushed values belong.
*
* @author fmohr
*
*/
public interface IExperimentIntermediateResultProcessor {
/**
* The result fields and the values that should be pushed for them.
* @param results
*/
public void processResults(Map<String,Object> results);
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentJSONKeyGenerator.java
|
package ai.libs.jaicore.experiments;
import com.fasterxml.jackson.databind.JsonNode;
public interface IExperimentJSONKeyGenerator extends IExperimentKeyGenerator<JsonNode> {
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentKeyGenerator.java
|
package ai.libs.jaicore.experiments;
/**
* An IExperimentKeyGenerator generates and validates values for a computed key field.
*
*
* @author fmohr
*
* @param <T>
*/
public interface IExperimentKeyGenerator<T> {
/**
* @return The cardinality of the set of values that may be assigned to this key field
*/
public int getNumberOfValues();
/**
* Deterministically computes the i-th value in the (totally ordered) set of values for this key
*
* @param i The index for the value
* @return
*/
public T getValue(int i);
/**
* Tries to cast the given String to an object of the value domain and checks whether any entry in the set corresponds to it.
*
* @param value
* @return True iff there is one entity in the value set whose toString method evaluates to the given string.
*/
public boolean isValueValid(String value);
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentRunController.java
|
package ai.libs.jaicore.experiments;
import java.util.List;
public interface IExperimentRunController<O> {
public O getExperimentEncoding(Experiment map);
public List<IEventBasedResultUpdater> getResultUpdaterComputer(final Experiment experiment);
public List<IExperimentTerminationCriterion> getTerminationCriteria(final Experiment experiment);
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentSetConfig.java
|
package ai.libs.jaicore.experiments;
import java.util.List;
import org.aeonbits.owner.Reloadable;
import ai.libs.jaicore.basic.IOwnerBasedConfig;
public interface IExperimentSetConfig extends IOwnerBasedConfig, Reloadable {
public static final String MEM_MAX = "mem.max";
public static final String MEM_OPP = "mem.opp";
public static final String CPU_MAX = "cpu.max";
/* the key fields define the semantics of a single experiment */
public static final String KEYFIELDS = "keyfields";
/* the result fields define fields for results of each run */
public static final String RESULTFIELDS = "resultfields";
public static final String CONSTRAINTS = "constraints";
/* the fields for ignoring time and memory information */
public static final String IGNORE_TIME = "ignore.time";
public static final String IGNORE_MEMORY = "ignore.memory";
@Key(MEM_MAX)
public Integer getMemoryLimitInMB();
@Key(MEM_OPP)
public Integer getAssumedMemoryOverheadPerProcess();
@Key(CPU_MAX)
public Integer getNumberOfCPUs();
@Key(KEYFIELDS)
public List<String> getKeyFields();
@Key(RESULTFIELDS)
public List<String> getResultFields();
@Key(CONSTRAINTS)
public List<String> getConstraints();
@Key(IGNORE_TIME)
public List<String> getFieldsForWhichToIgnoreTime();
@Key(IGNORE_MEMORY)
public List<String> getFieldsForWhichToIgnoreMemory();
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentSetEvaluator.java
|
package ai.libs.jaicore.experiments;
import ai.libs.jaicore.experiments.exceptions.ExperimentEvaluationFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentFailurePredictionException;
public interface IExperimentSetEvaluator {
/**
* Method to compute a single point of the experiment set
*
* @param experimentEntry The point of the experiment set
* @param processor A handle to return intermediate results to the experiment runner routine
* @throws Exception
*/
public void evaluate(ExperimentDBEntry experimentEntry, IExperimentIntermediateResultProcessor processor) throws ExperimentEvaluationFailedException, ExperimentFailurePredictionException, InterruptedException;
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/IExperimentTerminationCriterion.java
|
package ai.libs.jaicore.experiments;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
/**
* Decides, based on a new incoming event, whether the experiment should be stopped.
*
* @author Felix Mohr
*
*/
public interface IExperimentTerminationCriterion {
public boolean doesTerminate(IAlgorithmEvent e, IAlgorithm<?, ?> algorithm);
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/MaxNumberOfEventsTerminationCriterion.java
|
package ai.libs.jaicore.experiments;
import java.util.Arrays;
import java.util.List;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
public class MaxNumberOfEventsTerminationCriterion implements IExperimentTerminationCriterion {
private final int maxNumberOfEvents;
private final List<Class<? extends IAlgorithmEvent>> matchedClasses;
private int numOfSeenEvents = 0;
public MaxNumberOfEventsTerminationCriterion(final int maxNumberOfEvents, final Class<? extends IAlgorithmEvent> matchedClass) {
this(maxNumberOfEvents, Arrays.asList(matchedClass));
}
public MaxNumberOfEventsTerminationCriterion(final int maxNumberOfEvents, final List<Class<? extends IAlgorithmEvent>> matchedClasses) {
super();
this.maxNumberOfEvents = maxNumberOfEvents;
this.matchedClasses = matchedClasses;
}
@Override
public boolean doesTerminate(final IAlgorithmEvent e, final IAlgorithm<?, ?> algorithm) {
if (this.matchedClasses.stream().anyMatch(c -> c.isInstance(e))) {
this.numOfSeenEvents ++;
if (this.numOfSeenEvents >= this.maxNumberOfEvents) {
return true;
}
}
return false;
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/configurations/IAlgorithmMaxIterConfig.java
|
package ai.libs.jaicore.experiments.configurations;
import org.aeonbits.owner.Reloadable;
import ai.libs.jaicore.basic.IOwnerBasedConfig;
public interface IAlgorithmMaxIterConfig extends IOwnerBasedConfig, Reloadable {
public static final String K_ALGORITHM_MAXITER = "maxiter";
@Key(K_ALGORITHM_MAXITER)
public String getMaxIterations();
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/configurations/IAlgorithmNameConfig.java
|
package ai.libs.jaicore.experiments.configurations;
import org.aeonbits.owner.Reloadable;
import ai.libs.jaicore.basic.IOwnerBasedConfig;
public interface IAlgorithmNameConfig extends IOwnerBasedConfig, Reloadable {
public static final String K_ALGORITHM_NAME = "algorithmname";
@Key(K_ALGORITHM_NAME)
public String getAlgorithmName();
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/databasehandle/AExperimenterSQLHandle.java
|
package ai.libs.jaicore.experiments.databasehandle;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.api4.java.common.control.ILoggingCustomizable;
import org.api4.java.datastructure.kvstore.IKVStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.sets.Pair;
import ai.libs.jaicore.basic.sets.SetUtil;
import ai.libs.jaicore.db.IDatabaseAdapter;
import ai.libs.jaicore.db.IDatabaseConfig;
import ai.libs.jaicore.db.sql.DatabaseAdapterFactory;
import ai.libs.jaicore.experiments.Experiment;
import ai.libs.jaicore.experiments.ExperimentDBEntry;
import ai.libs.jaicore.experiments.ExperimentSetAnalyzer;
import ai.libs.jaicore.experiments.IExperimentDatabaseHandle;
import ai.libs.jaicore.experiments.IExperimentSetConfig;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyExistsInDatabaseException;
import ai.libs.jaicore.experiments.exceptions.ExperimentAlreadyStartedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentDBInteractionFailedException;
import ai.libs.jaicore.experiments.exceptions.ExperimentUpdateFailedException;
import ai.libs.jaicore.logging.LoggerUtil;
public abstract class AExperimenterSQLHandle implements IExperimentDatabaseHandle, ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(AExperimenterSQLHandle.class);
private static final String ERROR_NOSETUP = "No key fields defined. Setup the handler before using it.";
private static final String FIELD_ID = "experiment_id";
private static final String FIELD_MEMORY = "memory";
private static final String FIELD_MEMORY_MAX = FIELD_MEMORY + "_max";
public static final String FIELD_HOST = "host";
public static final String FIELD_EXECUTOR = "executor";
public static final String FIELD_NUMCPUS = "cpus";
private static final String FIELD_TIME = "time";
private static final String FIELD_TIME_START = FIELD_TIME + "_started";
private static final String FIELD_TIME_END = FIELD_TIME + "_end";
private static final String FIELD_EXCEPTION = "exception";
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String Q_AND = " AND ";
private static final String Q_FROM = " FROM ";
private final String cachedHost;
{
String hostName;
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
this.logger.error("Couldn't retrieve Host name. No experiment can be started.", e);
hostName = null;
}
this.cachedHost = hostName;
}
protected final IDatabaseAdapter adapter;
protected final String tablename;
private IExperimentSetConfig config;
private ExperimentSetAnalyzer analyzer;
private String[] keyFields;
private String[] resultFields;
protected AExperimenterSQLHandle(final IDatabaseAdapter adapter, final String tablename) {
super();
this.adapter = adapter;
this.tablename = tablename;
}
protected AExperimenterSQLHandle(final IDatabaseConfig config) {
if (config.getDBDriver() == null) {
throw new IllegalArgumentException("DB driver must not be null in experiment config.");
}
if (config.getDBHost() == null) {
throw new IllegalArgumentException("DB host must not be null in experiment config.");
}
if (config.getDBUsername() == null) {
throw new IllegalArgumentException("DB user must not be null in experiment config.");
}
if (config.getDBPassword() == null) {
config.setProperty(IDatabaseConfig.DB_PASS, "");
}
if (config.getDBDatabaseName() == null) {
throw new IllegalArgumentException("DB database name must not be null in experiment config.");
}
if (config.getDBTableName() == null) {
throw new IllegalArgumentException("DB table must not be null in experiment config.");
}
this.adapter = DatabaseAdapterFactory.get(config);
this.tablename = config.getDBTableName();
}
protected String getSetupCreateTableQuery() {
StringBuilder sqlMainTable = new StringBuilder();
StringBuilder keyFieldsSB = new StringBuilder();
sqlMainTable.append("CREATE TABLE IF NOT EXISTS `" + this.tablename + "` (");
sqlMainTable.append("`" + FIELD_ID + "` int(10) NOT NULL AUTO_INCREMENT,");
for (String key : this.keyFields) {
Pair<String, String> decomposition = this.analyzer.getNameTypeSplitForAttribute(key);
String fieldName = decomposition.getX();
String fieldType = decomposition.getY();
if (fieldType == null) {
fieldType = "varchar(500)";
this.logger.warn("No type definition given for field {}. Using varchar(500)", fieldName);
}
sqlMainTable.append("`" + fieldName + "` " + fieldType + " NOT NULL,");
keyFieldsSB.append("`" + fieldName + "`,");
}
sqlMainTable.append("`" + FIELD_NUMCPUS + "` int(2) NOT NULL,");
sqlMainTable.append("`" + FIELD_MEMORY + "_max` int(6) NOT NULL,");
sqlMainTable.append("`" + FIELD_TIME + "_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,");
sqlMainTable.append("`" + FIELD_HOST + "` varchar(255) NULL,");
sqlMainTable.append("`" + FIELD_EXECUTOR + "` varchar(100) NULL,");
sqlMainTable.append("`" + FIELD_TIME + "_started` TIMESTAMP NULL,");
/* add columns for result fields */
List<String> fieldsForWhichToIgnoreTime = this.config.getFieldsForWhichToIgnoreTime();
List<String> fieldsForWhichToIgnoreMemory = this.config.getFieldsForWhichToIgnoreMemory();
for (String result : this.resultFields) {
Pair<String, String> decomposition = this.analyzer.getNameTypeSplitForAttribute(result);
String fieldName = decomposition.getX();
String fieldType = decomposition.getY();
if (fieldType == null) {
fieldType = "varchar(500)";
this.logger.warn("No type definition given for field {}. Using varchar(500)", fieldName);
}
sqlMainTable.append("`" + fieldName + "` " + fieldType + " NULL,");
if (this.config.getFieldsForWhichToIgnoreTime() == null || fieldsForWhichToIgnoreTime.stream().noneMatch(fieldName::matches)) {
sqlMainTable.append("`" + fieldName + "_" + FIELD_TIME + "` TIMESTAMP NULL,");
}
if (this.config.getFieldsForWhichToIgnoreMemory() == null || fieldsForWhichToIgnoreMemory.stream().noneMatch(fieldName::matches)) {
sqlMainTable.append("`" + fieldName + "_" + FIELD_MEMORY + "` int(6) NULL,");
}
}
/* exception field and keys */
sqlMainTable.append("`exception` TEXT NULL,");
sqlMainTable.append("`" + FIELD_TIME + "_end` TIMESTAMP NULL,");
sqlMainTable.append("PRIMARY KEY (`" + FIELD_ID + "`)");
sqlMainTable.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
return sqlMainTable.toString();
}
/**
* Checks if this instance has been configured.
* That is it throws an exception iff the setup method hasn't been successfully called yet.
* @throws IllegalStateException thrown if setup wasn't called.
*/
protected void assertSetup() {
if (this.config == null || this.keyFields == null) {
throw new IllegalStateException(ERROR_NOSETUP);
}
}
@Override
public void setup(final IExperimentSetConfig config) throws ExperimentDBInteractionFailedException {
if (this.config != null) {
if (this.config.equals(config)) {
this.logger.info("Setup was called repeatedly with the same configuration. Ignoring the subsequent call.", new IllegalStateException());
return;
} else {
throw new IllegalStateException("Setup was called a second time with an alternative experiment set configuration.");
}
}
this.logger.info("Setting up the experiment table {}", this.tablename);
this.config = config;
this.analyzer = new ExperimentSetAnalyzer(this.config);
this.keyFields = config.getKeyFields().toArray(new String[] {}); // redundant to increase performance
this.resultFields = config.getResultFields().toArray(new String[] {}); // redundant to increase performance
/* creates basic table creation statement */
String createTableQuery = this.getSetupCreateTableQuery();
try {
this.logger.debug("Sending table creation query: {}", createTableQuery);
this.adapter.update(createTableQuery, new String[] {});
} catch (SQLException e) {
this.logger.error("An SQL exception occured with the following query: {}", createTableQuery);
throw new ExperimentDBInteractionFailedException(e);
}
}
private String buildWhereClause(final Map<String, ?> map) {
return map.entrySet().stream().map(e -> "`" + e.getKey() + "` = '" + e.getValue().toString() + "'").collect(Collectors.joining(Q_AND));
}
protected String getSQLPrefixForKeySelectQuery() {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT `" + FIELD_ID + "`, `" + FIELD_MEMORY_MAX + "`, `" + FIELD_NUMCPUS + "`, " + Arrays.stream(this.keyFields).map(this::getDatabaseFieldnameForConfigEntry).collect(Collectors.joining(", ")));
queryStringSB.append(this.getSQLFromTable());
return queryStringSB.toString();
}
protected String getSQLFromTable() {
return Q_FROM + " `" + this.tablename + "` ";
}
protected String getSQLPrefixForSelectQuery() {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT * ");
queryStringSB.append(this.getSQLFromTable());
return queryStringSB.toString();
}
@Override
public Collection<String> getConsideredValuesForKey(final String key) throws ExperimentDBInteractionFailedException {
if (this.config == null || this.keyFields == null) {
throw new IllegalStateException(ERROR_NOSETUP);
}
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT DISTINCT(`" + key + "`) as d ");
queryStringSB.append(this.getSQLFromTable());
try {
List<IKVStore> res = this.adapter.getRowsOfTable(queryStringSB.toString());
return res.stream().map(x -> x.getAsString("d")).collect(Collectors.toList());
} catch (Exception e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public int getNumberOfAllExperiments() throws ExperimentDBInteractionFailedException {
if (this.config == null || this.keyFields == null) {
throw new IllegalStateException(ERROR_NOSETUP);
}
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT COUNT(*) as c ");
queryStringSB.append(this.getSQLFromTable());
try {
List<IKVStore> res = this.adapter.getResultsOfQuery(queryStringSB.toString());
return res.get(0).getAsInt("c");
} catch (Exception e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public List<ExperimentDBEntry> getAllExperiments() throws ExperimentDBInteractionFailedException {
try {
return this.getExperimentsForSQLQuery(this.getSQLPrefixForSelectQuery());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public List<ExperimentDBEntry> getOpenExperiments() throws ExperimentDBInteractionFailedException {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append(this.getSQLPrefixForKeySelectQuery());
queryStringSB.append("WHERE time_started IS NULL");
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public List<ExperimentDBEntry> getRandomOpenExperiments(int limit) throws ExperimentDBInteractionFailedException {
if (limit == -1) {
// select a feasible limit:
limit = 10;
}
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT * FROM ("); // open sub-query
queryStringSB.append(this.getSQLPrefixForKeySelectQuery());
queryStringSB.append("WHERE time_started IS NULL LIMIT " + (limit * 100)); // basic pool
queryStringSB.append(") as t ORDER BY RAND() LIMIT " + limit); // close sub-query and order results
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public Optional<ExperimentDBEntry> startNextExperiment(final String executorInfo) throws ExperimentDBInteractionFailedException {
if (this.cachedHost == null) {
// failed to retrieve host information.
throw new ExperimentUpdateFailedException(new IllegalStateException("Host information is unavailable."));
}
/*
* Build a query to update a random unstarted experiment and fetch the updated id:
*/
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ");
sb.append(this.tablename);
sb.append(" AS target_table ");
// Fields to be updated are `time_started`=(now) and `host`=(host name of this machine):
sb.append("SET target_table.");
sb.append(FIELD_TIME_START);
sb.append(" = '");
sb.append(new SimpleDateFormat(DATE_FORMAT).format(new Date()));
sb.append("', target_table.");
sb.append(FIELD_HOST);
sb.append(" = '");
sb.append(this.cachedHost);
sb.append("', target_table.");
sb.append(FIELD_EXECUTOR);
sb.append(" = '");
sb.append(executorInfo);
sb.append("' ");
// We need the id of the updated row.
// The trick is to tell mysql to update the last insert id with the single affected row:
// See: https://stackoverflow.com/questions/1388025
// This is a MySQL specific solution.
sb.append(" WHERE target_table.time_started IS NULL" + " AND last_insert_id(target_table.experiment_id)" + " LIMIT 1");
int startedExperimentId;
try {
// Update and get the affected rows
// Use insert because we are interested in the `last_insert_id` field that is returned as a generated key.
int[] affectedKeys = this.adapter.insert(sb.toString(), new String[0]);
if (affectedKeys == null) {
throw new IllegalStateException("The database adapter did not return the id of the updated experiment. The sql query executed was: \n" + sb.toString());
} else if (affectedKeys.length > 1) {
throw new IllegalStateException("BUG: The sql query affected more than one row. It is supposed to only update a single row: \n" + sb.toString());
} else if (affectedKeys.length == 0) {
this.logger.info("No experiment with time_started=null could be found. So no experiment could be started.");
return Optional.empty();
} else {
startedExperimentId = affectedKeys[0];
}
} catch (Exception ex) {
throw new ExperimentDBInteractionFailedException(ex);
}
ExperimentDBEntry experimentWithId = this.getExperimentWithId(startedExperimentId);
if (experimentWithId == null) {
throw new ExperimentDBInteractionFailedException(new RuntimeException(String.format("BUG: The updated experiment with id, `%d`, could not be fetched. ", startedExperimentId)));
}
return Optional.of(experimentWithId);
}
@Override
public List<ExperimentDBEntry> getRunningExperiments() throws ExperimentDBInteractionFailedException {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append(this.getSQLPrefixForKeySelectQuery());
queryStringSB.append("WHERE time_started IS NOT NULL AND time_end IS NULL");
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public List<ExperimentDBEntry> getConductedExperiments() throws ExperimentDBInteractionFailedException {
return this.getConductedExperiments(new HashMap<>());
}
@Override
public List<ExperimentDBEntry> getConductedExperiments(final Map<String, Object> fieldFilter) throws ExperimentDBInteractionFailedException {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append(this.getSQLPrefixForSelectQuery());
queryStringSB.append("WHERE time_started IS NOT NULL");
if (!fieldFilter.isEmpty()) {
queryStringSB.append(Q_AND);
queryStringSB.append(this.buildWhereClause(fieldFilter));
}
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException("Given query was:\n" + queryStringSB.toString(), e);
}
}
@Override
public List<ExperimentDBEntry> getFailedExperiments() throws ExperimentDBInteractionFailedException {
return this.getFailedExperiments(new HashMap<>());
}
@Override
public List<ExperimentDBEntry> getFailedExperiments(final Map<String, Object> fieldFilter) throws ExperimentDBInteractionFailedException {
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append(
"SELECT " + FIELD_ID + ", " + FIELD_MEMORY_MAX + ", " + FIELD_NUMCPUS + ", " + Arrays.stream(this.keyFields).map(k -> this.analyzer.getNameTypeSplitForAttribute(k).getX()).collect(Collectors.joining(", ")) + ", exception");
queryStringSB.append(this.getSQLFromTable());
queryStringSB.append("WHERE exception IS NOT NULL");
if (!fieldFilter.isEmpty()) {
queryStringSB.append(Q_AND);
queryStringSB.append(this.buildWhereClause(fieldFilter));
}
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString());
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException("Given query was:\n" + queryStringSB.toString(), e);
}
}
protected List<ExperimentDBEntry> getExperimentsForSQLQuery(final String sql) throws SQLException {
if (this.config == null || this.keyFields == null) {
throw new IllegalStateException(ERROR_NOSETUP);
}
this.logger.debug("Executing query {}", sql);
List<IKVStore> res = this.adapter.getResultsOfQuery(sql);
this.logger.debug("Obtained results, now building experiment objects.");
List<ExperimentDBEntry> experimentEntries = new ArrayList<>();
int i = 0;
long startAll = System.currentTimeMillis();
for (IKVStore store : res) {
long start = System.currentTimeMillis();
/* get key values for experiment */
Map<String, String> keyValues = new HashMap<>();
for (String key : this.keyFields) {
String dbKey = this.getDatabaseFieldnameForConfigEntry(key);
keyValues.put(dbKey, store.getAsString(dbKey));
}
/* get result values for experiment */
Map<String, Object> resultValues = new HashMap<>();
for (String key : this.resultFields) {
String dbKey = this.getDatabaseFieldnameForConfigEntry(key);
resultValues.put(dbKey, store.getAsString(dbKey));
}
String error = store.getAsString(FIELD_EXCEPTION);
ExperimentDBEntry entry = new ExperimentDBEntry(store.getAsInt(FIELD_ID), new Experiment(store.getAsInt(FIELD_MEMORY_MAX), store.getAsInt(FIELD_NUMCPUS), keyValues, resultValues, error));
this.logger.trace("Building {}-th object took {}ms.", ++i, System.currentTimeMillis() - start);
experimentEntries.add(entry);
if (i % 1000 == 0) {
this.logger.debug("{} objects have been built within {}ms.", i, System.currentTimeMillis() - startAll);
}
}
return experimentEntries;
}
public ExperimentDBEntry createAndGetExperiment(final Map<String, String> values) throws ExperimentDBInteractionFailedException, ExperimentAlreadyExistsInDatabaseException {
return this.createAndGetExperiment(new Experiment(this.config.getMemoryLimitInMB(), this.config.getNumberOfCPUs(), values));
}
@Override
public ExperimentDBEntry createAndGetExperiment(final Experiment experiment) throws ExperimentDBInteractionFailedException, ExperimentAlreadyExistsInDatabaseException {
try {
/* first check whether exactly the same experiment (with the same seed) has been conducted previously */
Optional<?> existingExperiment = this.getConductedExperiments().stream().filter(e -> e.getExperiment().equals(experiment)).findAny();
if (existingExperiment.isPresent()) {
throw new ExperimentAlreadyExistsInDatabaseException();
}
Map<String, Object> valuesToInsert = new HashMap<>(experiment.getValuesOfKeyFields());
valuesToInsert.put(FIELD_MEMORY_MAX, experiment.getMemoryInMB());
valuesToInsert.put(FIELD_NUMCPUS, experiment.getNumCPUs());
this.logger.debug("Inserting mem: {}, cpus: {}, host: {}, and key fields: {}", experiment.getMemoryInMB(), experiment.getNumCPUs(), valuesToInsert.get(FIELD_HOST), experiment.getValuesOfKeyFields());
int id = this.adapter.insert(this.tablename, valuesToInsert)[0];
return new ExperimentDBEntry(id, experiment);
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public List<ExperimentDBEntry> createOrGetExperiments(final List<Experiment> experiments) throws ExperimentDBInteractionFailedException {
Objects.requireNonNull(this.keyFields, "No key fields set!");
if (experiments == null || experiments.isEmpty()) {
throw new IllegalArgumentException();
}
/* derive input for insertion */
List<String> keys = new ArrayList<>();
keys.add(FIELD_MEMORY_MAX);
keys.add(FIELD_NUMCPUS);
keys.addAll(Arrays.stream(this.keyFields).map(this::getDatabaseFieldnameForConfigEntry).collect(Collectors.toList()));
List<List<?>> values = new ArrayList<>();
for (Experiment exp : experiments) {
List<String> datarow = new ArrayList<>(keys.size());
datarow.add("" + exp.getMemoryInMB());
datarow.add("" + exp.getNumCPUs());
Map<String, String> expKeys = exp.getValuesOfKeyFields();
for (String key : this.keyFields) {
datarow.add(expKeys.get(this.getDatabaseFieldnameForConfigEntry(key)));
}
values.add(datarow);
}
/* conduct insertion */
try {
this.logger.debug("Inserting {} entries", values.size());
int[] ids = this.adapter.insertMultiple(this.tablename, keys, values);
this.logger.debug("Inserted {} entries", ids.length);
int n = ids.length;
List<ExperimentDBEntry> entries = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
entries.add(new ExperimentDBEntry(ids[i], experiments.get(i)));
}
return entries;
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public void updateExperiment(final ExperimentDBEntry exp, final Map<String, ? extends Object> values) throws ExperimentUpdateFailedException {
this.updateExperimentConditionally(exp, new HashMap<>(), values);
}
@Override
public boolean updateExperimentConditionally(final ExperimentDBEntry exp, final Map<String, String> conditions, final Map<String, ? extends Object> values) throws ExperimentUpdateFailedException {
if (values == null || values.isEmpty()) {
throw new IllegalArgumentException("No values provided for experiment update of experiment " + exp);
}
Collection<String> resultFieldsAsList = Arrays.stream(this.resultFields).map(k -> this.analyzer.getNameTypeSplitForAttribute(k).getX()).collect(Collectors.toList());
Collection<String> writableFields = new ArrayList<>(resultFieldsAsList);
writableFields.add(FIELD_HOST);
writableFields.add(FIELD_EXECUTOR);
writableFields.add(FIELD_TIME_START);
writableFields.add(FIELD_EXCEPTION);
writableFields.add(FIELD_TIME_END);
if (!writableFields.containsAll(values.keySet())) {
throw new IllegalArgumentException("The value set contains non-result fields: " + SetUtil.difference(values.keySet(), writableFields));
}
String now = new SimpleDateFormat(DATE_FORMAT).format(new Date());
String memoryUsageInMB = String.valueOf((int) Runtime.getRuntime().totalMemory() / 1024 / 1024);
Map<String, String> valuesToWrite = new HashMap<>();
values.keySet().forEach(k -> valuesToWrite.put(k, values.get(k) != null ? values.get(k).toString() : null));
List<String> fieldsForWhichToIgnoreTime = this.config.getFieldsForWhichToIgnoreTime();
List<String> fieldsForWhichToIgnoreMemory = this.config.getFieldsForWhichToIgnoreMemory();
for (String result : values.keySet()) {
if (resultFieldsAsList.contains(result)) {
if (this.config.getFieldsForWhichToIgnoreTime() == null || fieldsForWhichToIgnoreTime.stream().noneMatch(result::matches)) {
valuesToWrite.put(result + "_" + FIELD_TIME, now);
}
if (this.config.getFieldsForWhichToIgnoreMemory() == null || fieldsForWhichToIgnoreMemory.stream().noneMatch(result::matches)) {
valuesToWrite.put(result + "_" + FIELD_MEMORY, memoryUsageInMB);
}
}
}
Map<String, String> where = new HashMap<>();
where.putAll(conditions);
where.put(FIELD_ID, String.valueOf(exp.getId()));
try {
return this.adapter.update(this.tablename, valuesToWrite, where) >= 1;
} catch (SQLException e) {
throw new ExperimentUpdateFailedException("Could not update " + this.tablename + " with values " + valuesToWrite, e);
}
}
@Override
public void finishExperiment(final ExperimentDBEntry expEntry, final Throwable error) throws ExperimentDBInteractionFailedException {
Map<String, Object> valuesToAddAfterRun = new HashMap<>();
if (error != null) {
valuesToAddAfterRun.put(FIELD_EXCEPTION, LoggerUtil.getExceptionInfo(error));
}
valuesToAddAfterRun.put(FIELD_TIME_END, new SimpleDateFormat(DATE_FORMAT).format(new Date()));
this.updateExperiment(expEntry, valuesToAddAfterRun);
}
@Override
public void finishExperiment(final ExperimentDBEntry expEntry) throws ExperimentDBInteractionFailedException {
this.finishExperiment(expEntry, null);
}
protected String getDatabaseFieldnameForConfigEntry(final String configKey) {
return this.analyzer.getNameTypeSplitForAttribute(configKey).getX().replace("\\.", "_");
}
@Override
public void deleteExperiment(final ExperimentDBEntry exp) throws ExperimentDBInteractionFailedException {
String deleteExperimentQuery = "DELETE " + this.getSQLFromTable() + " WHERE experiment_id = " + exp.getId();
try {
this.adapter.update(deleteExperimentQuery);
} catch (Exception e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public void deleteDatabase() throws ExperimentDBInteractionFailedException {
String dropTableQuery = "DROP TABLE `" + this.tablename + "`";
try {
this.adapter.insert(dropTableQuery, new String[0]);
} catch (Exception e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
@Override
public boolean hasExperimentStarted(final ExperimentDBEntry exp) throws ExperimentDBInteractionFailedException {
this.assertSetup();
StringBuilder queryStringSB = new StringBuilder();
int expId = exp.getId();
queryStringSB.append("SELECT ").append(FIELD_TIME_START);
queryStringSB.append(this.getSQLFromTable());
queryStringSB.append(" WHERE `experiment_id` = ").append(expId);
try {
List<IKVStore> selectResult = this.adapter.query(queryStringSB.toString());
if (selectResult.isEmpty()) {
throw new IllegalArgumentException("The given experiment was not found: " + exp);
}
if (selectResult.size() > 1) {
throw new IllegalStateException("The experiment with primary id " + exp.getId() + " exists multiple times.");
}
IKVStore selectedRow = selectResult.get(0);
if (selectedRow.get(FIELD_TIME_START) != null) {
return true;
}
} catch (SQLException | IOException ex) {
throw new ExperimentDBInteractionFailedException(ex);
}
return false;
}
@Override
public void startExperiment(final ExperimentDBEntry exp, final String executorInfo) throws ExperimentUpdateFailedException, ExperimentAlreadyStartedException {
this.assertSetup();
Map<String, Object> initValues = new HashMap<>();
initValues.put(FIELD_TIME_START, new SimpleDateFormat(DATE_FORMAT).format(new Date()));
initValues.put(FIELD_HOST, this.cachedHost);
initValues.put(FIELD_EXECUTOR, executorInfo);
Map<String, String> condition = new HashMap<>();
condition.put(FIELD_TIME_START, null);
if (!this.updateExperimentConditionally(exp, condition, initValues)) {
throw new ExperimentAlreadyStartedException();
}
}
@Override
public String getLoggerName() {
return this.logger.getName();
}
@Override
public void setLoggerName(final String name) {
this.logger = LoggerFactory.getLogger(name);
this.adapter.setLoggerName(name + ".adapter");
}
@Override
public ExperimentDBEntry getExperimentWithId(final int id) throws ExperimentDBInteractionFailedException {
this.assertSetup();
StringBuilder queryStringSB = new StringBuilder();
queryStringSB.append("SELECT * ");
queryStringSB.append(this.getSQLFromTable());
queryStringSB.append(" WHERE `experiment_id` = " + id);
try {
return this.getExperimentsForSQLQuery(queryStringSB.toString()).get(0);
} catch (SQLException e) {
throw new ExperimentDBInteractionFailedException(e);
}
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/databasehandle/ExperimenterMySQLHandle.java
|
package ai.libs.jaicore.experiments.databasehandle;
import ai.libs.jaicore.db.IDatabaseAdapter;
import ai.libs.jaicore.db.IDatabaseConfig;
public class ExperimenterMySQLHandle extends AExperimenterSQLHandle {
public ExperimenterMySQLHandle(final IDatabaseAdapter adapter, final String tablename) {
super(adapter, tablename);
}
public ExperimenterMySQLHandle(final IDatabaseConfig config) {
super(config);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/databasehandle/ExperimenterRestSQLHandle.java
|
package ai.libs.jaicore.experiments.databasehandle;
import ai.libs.jaicore.db.IDatabaseAdapter;
import ai.libs.jaicore.db.sql.DatabaseAdapterFactory;
import ai.libs.jaicore.db.sql.IRestDatabaseConfig;
public class ExperimenterRestSQLHandle extends AExperimenterSQLHandle {
public ExperimenterRestSQLHandle(final IRestDatabaseConfig config) {
this (DatabaseAdapterFactory.get(config), config.getTable());
}
public ExperimenterRestSQLHandle(final IDatabaseAdapter adapter, final String tablename) {
super (adapter, tablename);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentAlreadyExistsInDatabaseException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentAlreadyExistsInDatabaseException extends Exception {
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentAlreadyStartedException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentAlreadyStartedException extends Exception {
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentDBInteractionFailedException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentDBInteractionFailedException extends Exception {
public ExperimentDBInteractionFailedException(final String message, final Exception e) {
super(message, e);
}
public ExperimentDBInteractionFailedException(final Exception e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentDecodingException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentDecodingException extends Exception {
private static final long serialVersionUID = 6800781691160306725L;
public ExperimentDecodingException(final String message) {
super(message);
}
public ExperimentDecodingException(final String message, final Exception e) {
super(message, e);
}
public ExperimentDecodingException(final Exception e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentEvaluationFailedException.java
|
package ai.libs.jaicore.experiments.exceptions;
@SuppressWarnings("serial")
public class ExperimentEvaluationFailedException extends Exception {
public ExperimentEvaluationFailedException(final String s) {
super(s);
}
public ExperimentEvaluationFailedException(final Throwable e) {
super(e);
}
public ExperimentEvaluationFailedException(final String message, final Throwable e) {
super(message, e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentFailurePredictionException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentFailurePredictionException extends Exception {
public ExperimentFailurePredictionException() {
super();
}
public ExperimentFailurePredictionException(final String msg) {
super(msg);
}
public ExperimentFailurePredictionException(final String msg, final Throwable t) {
super(msg, t);
}
public ExperimentFailurePredictionException(final Throwable t) {
super(t);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/ExperimentUpdateFailedException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class ExperimentUpdateFailedException extends ExperimentDBInteractionFailedException {
private static final long serialVersionUID = 662503302081674486L;
public ExperimentUpdateFailedException(final String message, final Exception e) {
super(message, e);
}
public ExperimentUpdateFailedException(final Exception e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/IllegalExperimentSetupException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class IllegalExperimentSetupException extends Exception {
public IllegalExperimentSetupException(final String message) {
super(message);
}
public IllegalExperimentSetupException(final Exception e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/exceptions/IllegalKeyDescriptorException.java
|
package ai.libs.jaicore.experiments.exceptions;
public class IllegalKeyDescriptorException extends IllegalExperimentSetupException {
public IllegalKeyDescriptorException(final String message) {
super(message);
}
public IllegalKeyDescriptorException(final Exception e) {
super(e);
}
}
|
0
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments
|
java-sources/ai/libs/jaicore-experiments/0.2.7/ai/libs/jaicore/experiments/resultcomputers/SolutionPerformanceHistoryComputer.java
|
package ai.libs.jaicore.experiments.resultcomputers;
import java.util.Map;
import org.api4.java.algorithm.IAlgorithm;
import org.api4.java.algorithm.events.IAlgorithmEvent;
import org.api4.java.algorithm.events.result.IScoredSolutionCandidateFoundEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import ai.libs.jaicore.basic.MathExt;
import ai.libs.jaicore.experiments.IEventBasedResultUpdater;
public class SolutionPerformanceHistoryComputer implements IEventBasedResultUpdater {
private ArrayNode observations = new ObjectMapper().createArrayNode();
private final long start = System.currentTimeMillis();
private final int saveRate;
public SolutionPerformanceHistoryComputer(final int saveRate) {
super(); this.saveRate = saveRate;
}
@Override
public void processEvent(final IAlgorithmEvent e, final Map<String, Object> currentResults) {
if (e instanceof IScoredSolutionCandidateFoundEvent) {
@SuppressWarnings("rawtypes")
double score = (double) ((IScoredSolutionCandidateFoundEvent) e).getScore();
ArrayNode observation = new ObjectMapper().createArrayNode();
observation.insert(0, System.currentTimeMillis() - this.start); // relative time
observation.insert(1, MathExt.round(score, 5)); // score
this.observations.add(observation);
if (this.observations.size() % this.saveRate == 0) {
currentResults.put("history", this.observations);
}
}
}
@Override
public void finish(final Map<String, Object> currentResults) {
currentResults.put("history", this.observations);
}
@Override
public void setAlgorithm(final IAlgorithm<?, ?> algorithm) {
/* this computer does not need the algorithm for its computations */
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/IntegerAxisFormatter.java
|
package ai.libs.jaicore.graphvisualizer;
import ai.libs.jaicore.basic.MathExt;
import javafx.util.StringConverter;
public class IntegerAxisFormatter extends StringConverter<Number> {
@Override
public String toString(final Number object) {
Double val = MathExt.round(object.doubleValue(), 8);
if (val.intValue() == val) { // consider all numbers that are close to an integer by 10^-8 as ints
String str = String.valueOf(val);
str = str.substring(0, str.indexOf('.'));
return str;
} else {
return "";
}
}
@Override
public Number fromString(final String string) {
return null; // not needed
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/GraphEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
public interface GraphEvent extends AlgorithmEvent {
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/GraphInitializedEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AAlgorithmEvent;
public class GraphInitializedEvent<T> extends AAlgorithmEvent implements GraphEvent {
private T root;
public GraphInitializedEvent(final String algorithmId, final T root) {
super(algorithmId);
this.root = root;
}
public T getRoot() {
return this.root;
}
public void setRoot(final T root) {
this.root = root;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/NodeAddedEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AAlgorithmEvent;
public class NodeAddedEvent<T> extends AAlgorithmEvent implements GraphEvent {
private final T parent;
private final T node;
private final String type;
public NodeAddedEvent(final String algorithmId, final T parent, final T node, final String type) {
super(algorithmId);
this.parent = parent;
this.node = node;
this.type = type;
}
public T getParent() {
return this.parent;
}
public T getNode() {
return this.node;
}
public String getType() {
return this.type;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/NodeParentSwitchEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AAlgorithmEvent;
public class NodeParentSwitchEvent<T> extends AAlgorithmEvent implements GraphEvent {
private final T node;
private final T oldParent;
private final T newParent;
public NodeParentSwitchEvent(final String algorithmEvent, final T node, final T oldParent, final T newParent) {
super(algorithmEvent);
this.node = node;
this.oldParent = oldParent;
this.newParent = newParent;
}
public T getNode() {
return this.node;
}
public T getOldParent() {
return this.oldParent;
}
public T getNewParent() {
return this.newParent;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/NodeRemovedEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AAlgorithmEvent;
public class NodeRemovedEvent<T> extends AAlgorithmEvent implements GraphEvent {
private final T node;
public NodeRemovedEvent(final String algorithmId, final T node) {
super(algorithmId);
this.node = node;
}
public T getNode() {
return this.node;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/NodeTypeSwitchEvent.java
|
package ai.libs.jaicore.graphvisualizer.events.graph;
import ai.libs.jaicore.basic.algorithm.events.AAlgorithmEvent;
public class NodeTypeSwitchEvent<T> extends AAlgorithmEvent implements GraphEvent {
private final T node;
private final String type;
public NodeTypeSwitchEvent(final String algorithmId, final T node, final String type) {
super(algorithmId);
this.node = node;
this.type = type;
}
public T getNode() {
return this.node;
}
public String getType() {
return this.type;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/bus/AlgorithmEventBus.java
|
package ai.libs.jaicore.graphvisualizer.events.graph.bus;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
public interface AlgorithmEventBus extends AlgorithmEventSource {
public void postEvent(AlgorithmEvent algorithmEvent);
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/graph/bus/AlgorithmEventListener.java
|
package ai.libs.jaicore.graphvisualizer.events.graph.bus;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
public interface AlgorithmEventListener {
@Subscribe
public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException;
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/gui/DefaultGUIEventBus.java
|
package ai.libs.jaicore.graphvisualizer.events.gui;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultGUIEventBus implements GUIEventBus {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGUIEventBus.class);
private static DefaultGUIEventBus singletonInstance;
private List<GUIEventListener> guiEventListeners;
private DefaultGUIEventBus() {
guiEventListeners = Collections.synchronizedList(new LinkedList<>());
}
@Override
public void registerListener(GUIEventListener graphEventListener) {
guiEventListeners.add(graphEventListener);
}
@Override
public void unregisterListener(GUIEventListener graphEventListener) {
guiEventListeners.remove(graphEventListener);
}
@Override
public void postEvent(GUIEvent guiEvent) {
synchronized (this) {
for (GUIEventListener listener : guiEventListeners) {
passEventToListener(guiEvent, listener);
}
}
}
private void passEventToListener(GUIEvent guiEvent, GUIEventListener listener) {
try {
listener.handleGUIEvent(guiEvent);
} catch (Exception exception) {
LOGGER.error("Error while passing GUIEvent {} to handler {}.", guiEvent, listener, exception);
}
}
public static synchronized GUIEventBus getInstance() {
if (singletonInstance == null) {
singletonInstance = new DefaultGUIEventBus();
}
return singletonInstance;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/gui/GUIEventBus.java
|
package ai.libs.jaicore.graphvisualizer.events.gui;
public interface GUIEventBus extends GUIEventSource {
public void postEvent(GUIEvent guiEvent);
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistory.java
|
package ai.libs.jaicore.graphvisualizer.events.recorder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.ILoggingCustomizable;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
public class AlgorithmEventHistory implements ILoggingCustomizable {
private Logger logger = LoggerFactory.getLogger(AlgorithmEventHistory.class);
private String loggerName;
private List<AlgorithmEventHistoryEntry> events;
public AlgorithmEventHistory() {
this.events = Collections.synchronizedList(new ArrayList<>());
}
public void addEvent(final AlgorithmEvent algorithmEvent) {
AlgorithmEventHistoryEntry entry = this.generateHistoryEntry(algorithmEvent);
this.events.add(entry);
this.logger.debug("Added entry {} for algorithm event {} to history at position {}.", entry, algorithmEvent, this.events.size() - 1);
}
private AlgorithmEventHistoryEntry generateHistoryEntry(final AlgorithmEvent algorithmEvent) {
return new AlgorithmEventHistoryEntry(algorithmEvent, this.getCurrentReceptionTime());
}
private long getCurrentReceptionTime() {
long currentTime = System.currentTimeMillis();
return Math.max(0, currentTime - this.getReceptionTimeOfFirstEvent());
}
private long getReceptionTimeOfFirstEvent() {
Optional<AlgorithmEventHistoryEntry> firstHistoryEntryOptional = this.events.stream().findFirst();
if (!firstHistoryEntryOptional.isPresent()) {
return -1;
}
return firstHistoryEntryOptional.get().getTimeEventWasReceived();
}
public AlgorithmEventHistoryEntry getEntryAtTimeStep(final int timestep) {
return this.events.get(timestep);
}
public long getLength() {
return this.events.size();
}
@Override
public String getLoggerName() {
return this.loggerName;
}
@Override
public void setLoggerName(final String name) {
this.loggerName = name;
this.logger.info("Switching logger name to {}", name);
this.logger = LoggerFactory.getLogger(name);
this.logger.info("Switched logger name to {}", name);
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryEntry.java
|
package ai.libs.jaicore.graphvisualizer.events.recorder;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
public class AlgorithmEventHistoryEntry {
private AlgorithmEvent algorithmEvent;
private long timeEventWasReceived;
public AlgorithmEventHistoryEntry(AlgorithmEvent algorithmEvent, long timeEventWasReceived) {
this.algorithmEvent = algorithmEvent;
this.timeEventWasReceived = timeEventWasReceived;
}
public AlgorithmEvent getAlgorithmEvent() {
return algorithmEvent;
}
public long getTimeEventWasReceived() {
return timeEventWasReceived;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryEntryDeliverer.java
|
package ai.libs.jaicore.graphvisualizer.events.recorder;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventListener;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException;
import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent;
import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventListener;
import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PauseEvent;
import ai.libs.jaicore.graphvisualizer.plugin.controlbar.PlayEvent;
import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent;
import ai.libs.jaicore.graphvisualizer.plugin.speedslider.ChangeSpeedEvent;
import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent;
/**
* The {@link AlgorithmEventHistoryEntryDeliverer} is {@link Thread} constantly pulling events from a given {@link AlgorithmEventHistory} and sending these to all registered {@link AlgorithmEventListener}s.
*
* @author ahetzer
*
*/
public class AlgorithmEventHistoryEntryDeliverer extends Thread implements AlgorithmEventSource, GUIEventListener {
private Logger logger = LoggerFactory.getLogger(AlgorithmEventHistoryEntryDeliverer.class);
private Set<AlgorithmEventListener> algorithmEventListeners;
private AlgorithmEventHistory eventHistory;
private int maximumSleepTimeInMilliseconds;
private int timestep;
private boolean paused;
private double sleepTimeMultiplier;
public AlgorithmEventHistoryEntryDeliverer(final AlgorithmEventHistory eventHistory, final int maximumSleepTimeInMilliseconds) {
this.eventHistory = eventHistory;
this.maximumSleepTimeInMilliseconds = maximumSleepTimeInMilliseconds;
this.timestep = 0;
this.paused = true;
this.algorithmEventListeners = ConcurrentHashMap.newKeySet();
this.sleepTimeMultiplier = 1;
this.setDaemon(true);
this.logger.info("{} started with thread {}", this.getClass().getSimpleName(), this.getName());
}
public AlgorithmEventHistoryEntryDeliverer(final AlgorithmEventHistory eventHistory) {
this(eventHistory, 30);
}
@Override
public void registerListener(final AlgorithmEventListener algorithmEventListener) {
this.algorithmEventListeners.add(algorithmEventListener);
}
@Override
public void unregisterListener(final AlgorithmEventListener algorithmEventListener) {
this.algorithmEventListeners.remove(algorithmEventListener);
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (!this.paused && this.timestep < this.eventHistory.getLength()) {
AlgorithmEventHistoryEntry historyEntry = this.eventHistory.getEntryAtTimeStep(this.timestep);
AlgorithmEvent algorithmEvent = historyEntry.getAlgorithmEvent();
this.logger.debug("Pulled event entry {} associated with event {} at position {}.", historyEntry, algorithmEvent, this.timestep);
this.sendAlgorithmEventToListeners(algorithmEvent);
this.timestep++;
} else if (this.paused) {
this.logger.debug("Not processing events since visualization is paused.");
} else if (this.timestep >= this.eventHistory.getLength()) {
this.logger.debug("Not processing events since no unpublished events are known.");
}
try {
this.goToSleep();
} catch (InterruptedException e) {
this.logger.info("{} has been interrupted: {}.", this.getClass().getSimpleName(), e);
Thread.currentThread().interrupt();
}
}
}
private void goToSleep() throws InterruptedException {
int sleepTime = (int) (this.sleepTimeMultiplier * this.maximumSleepTimeInMilliseconds);
this.logger.trace("Sleeping {}ms.", sleepTime);
sleep(sleepTime);
}
private void sendAlgorithmEventToListeners(final AlgorithmEvent algorithmEvent) {
for (AlgorithmEventListener eventListener : this.algorithmEventListeners) {
try {
this.sendAlgorithmEventToListener(algorithmEvent, eventListener);
} catch (Exception e) {
this.logger.error("Error in dispatching event {} due to error.", algorithmEvent, e);
}
}
this.logger.info("Pulled and sent event {} as entry at time step {}.", algorithmEvent, this.timestep);
}
private void sendAlgorithmEventToListener(final AlgorithmEvent algorithmEvent, final AlgorithmEventListener eventListener) throws HandleAlgorithmEventException {
this.logger.debug("Sending event {} to listener {}.", algorithmEvent, eventListener);
long startTime = System.currentTimeMillis();
eventListener.handleAlgorithmEvent(algorithmEvent);
long dispatchTime = System.currentTimeMillis() - startTime;
if (dispatchTime > 10) {
this.logger.warn("Dispatch time for event {} to listener {} took {}ms!", algorithmEvent, eventListener, dispatchTime);
}
}
@Override
public void handleGUIEvent(final GUIEvent guiEvent) {
if (guiEvent instanceof PauseEvent) {
this.pause();
} else if (guiEvent instanceof PlayEvent) {
this.unpause();
} else if (guiEvent instanceof ResetEvent) {
this.handleResetEvent();
} else if (guiEvent instanceof GoToTimeStepEvent) {
this.handleGoToTimeStepEvent(guiEvent);
} else if (guiEvent instanceof ChangeSpeedEvent) {
this.handleChangeSpeedEvent(guiEvent);
}
}
private void pause() {
this.paused = true;
}
private void unpause() {
this.paused = false;
}
private void handleResetEvent() {
this.resetTimeStep();
this.pause();
}
private void resetTimeStep() {
this.timestep = 0;
}
private void handleGoToTimeStepEvent(final GUIEvent guiEvent) {
this.resetTimeStep();
GoToTimeStepEvent goToTimeStepEvent = (GoToTimeStepEvent) guiEvent;
while (this.timestep < goToTimeStepEvent.getNewTimeStep() && this.timestep < this.eventHistory.getLength()) {
AlgorithmEvent algorithmEvent = this.eventHistory.getEntryAtTimeStep(this.timestep).getAlgorithmEvent();
this.sendAlgorithmEventToListeners(algorithmEvent);
this.timestep++;
}
}
private void handleChangeSpeedEvent(final GUIEvent guiEvent) {
ChangeSpeedEvent changeSpeedEvent = (ChangeSpeedEvent) guiEvent;
this.sleepTimeMultiplier = 1 - changeSpeedEvent.getNewSpeedPercentage() / 100.0;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/events/recorder/AlgorithmEventHistoryRecorder.java
|
package ai.libs.jaicore.graphvisualizer.events.recorder;
import com.google.common.eventbus.Subscribe;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventListener;
public class AlgorithmEventHistoryRecorder implements AlgorithmEventListener {
private AlgorithmEventHistory algorithmEventHistory;
public AlgorithmEventHistoryRecorder() {
algorithmEventHistory = new AlgorithmEventHistory();
}
@Subscribe
@Override
public void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) {
synchronized (this) {
algorithmEventHistory.addEvent(algorithmEvent);
}
}
public AlgorithmEventHistory getHistory() {
return algorithmEventHistory;
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPlugin.java
|
package ai.libs.jaicore.graphvisualizer.plugin;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.AlgorithmEventSource;
import ai.libs.jaicore.graphvisualizer.events.gui.GUIEventSource;
public abstract class ASimpleMVCPlugin<M extends ASimpleMVCPluginModel<V, C>, V extends ASimpleMVCPluginView<M, C, ?>, C extends ASimpleMVCPluginController<M, V>> implements IGUIPlugin {
private final Logger logger = LoggerFactory.getLogger(ASimpleMVCPlugin.class);
private final M model;
private final V view;
private final C controller;
@SuppressWarnings("unchecked")
public ASimpleMVCPlugin() {
super();
Type[] mvcPatternClasses = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
M myModel;
V myView;
C myController;
try {
if (this.logger.isDebugEnabled()) {
this.logger.debug(mvcPatternClasses[0].getTypeName().replaceAll("(<.*>)", ""));
}
Class<M> modelClass = ((Class<M>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[0].getTypeName())));
Class<V> viewClass = ((Class<V>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[1].getTypeName())));
Class<C> controllerClass = ((Class<C>) Class.forName(this.getClassNameWithoutGenerics(mvcPatternClasses[2].getTypeName())));
myModel = modelClass.newInstance();
myView = viewClass.getDeclaredConstructor(modelClass).newInstance(myModel);
myController = controllerClass.getDeclaredConstructor(modelClass, viewClass).newInstance(myModel, myView);
myController.setDaemon(true);
myController.start();
} catch (Exception e) {
this.logger.error("Could not initialize {} due to exception in building MVC.", this, e);
this.model = null;
this.view = null;
this.controller = null;
return;
}
this.model = myModel;
this.view = myView;
this.controller = myController;
this.model.setController(myController);
this.model.setView(myView);
this.view.setController(myController);
}
@Override
public C getController() {
return this.controller;
}
@Override
public M getModel() {
return this.view.getModel();
}
@Override
public V getView() {
return this.view;
}
@Override
public void setAlgorithmEventSource(final AlgorithmEventSource graphEventSource) {
graphEventSource.registerListener(this.controller);
}
@Override
public void setGUIEventSource(final GUIEventSource guiEventSource) {
guiEventSource.registerListener(this.controller);
}
private String getClassNameWithoutGenerics(final String className) {
return className.replaceAll("(<.*>)", "");
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginController.java
|
package ai.libs.jaicore.graphvisualizer.plugin;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.libs.jaicore.basic.algorithm.events.AlgorithmEvent;
import ai.libs.jaicore.graphvisualizer.events.graph.bus.HandleAlgorithmEventException;
import ai.libs.jaicore.graphvisualizer.events.gui.GUIEvent;
import ai.libs.jaicore.graphvisualizer.plugin.controlbar.ResetEvent;
import ai.libs.jaicore.graphvisualizer.plugin.timeslider.GoToTimeStepEvent;
public abstract class ASimpleMVCPluginController<M extends ASimpleMVCPluginModel<?, ?>, V extends ASimpleMVCPluginView<?, ?, ?>> extends Thread implements IGUIPluginController {
private static final Logger LOGGER = LoggerFactory.getLogger(ASimpleMVCPluginController.class);
private final Queue<AlgorithmEvent> eventQueue;
private final V view;
private final M model;
public ASimpleMVCPluginController(M model, V view) {
super();
this.model = model;
this.view = view;
eventQueue = new ConcurrentLinkedQueue<>();
}
public M getModel() {
return model;
}
public V getView() {
return view;
}
@Override
public final void handleAlgorithmEvent(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException {
eventQueue.add(algorithmEvent);
}
@Override
public void run() {
while (true) {
AlgorithmEvent event = eventQueue.poll();
if (event != null) {
try {
handleAlgorithmEventInternally(event);
} catch (HandleAlgorithmEventException e) {
LOGGER.error("An error occurred while handling event {}.", event, e);
}
}
}
}
protected abstract void handleAlgorithmEventInternally(AlgorithmEvent algorithmEvent) throws HandleAlgorithmEventException;
@Override
public void handleGUIEvent(GUIEvent guiEvent) {
if (guiEvent instanceof ResetEvent || guiEvent instanceof GoToTimeStepEvent) {
getModel().clear();
getView().clear();
}
}
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginModel.java
|
package ai.libs.jaicore.graphvisualizer.plugin;
/**
*
* @author fmohr
*
*/
public abstract class ASimpleMVCPluginModel<V extends ASimpleMVCPluginView<?, ?, ?>, C extends ASimpleMVCPluginController<?,?>> implements IGUIPluginModel {
private V view;
private C controller;
public void setView(V view) {
this.view = view;
}
public V getView() {
return view;
}
public C getController() {
return controller;
}
public void setController(C controller) {
this.controller = controller;
}
public abstract void clear();
}
|
0
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer
|
java-sources/ai/libs/jaicore-graphvisualizer/0.1.4/ai/libs/jaicore/graphvisualizer/plugin/ASimpleMVCPluginView.java
|
package ai.libs.jaicore.graphvisualizer.plugin;
import javafx.scene.Node;
/**
*
* @author fmohr
*
*/
public abstract class ASimpleMVCPluginView<M extends IGUIPluginModel, C extends IGUIPluginController, N extends Node> implements IGUIPluginView {
private final N node;
private final M model;
private C controller;
public ASimpleMVCPluginView(M model, N node) {
this.model = model;
this.node = node;
}
public M getModel() {
return model;
}
public C getController() {
return controller;
}
public void setController(C controller) {
this.controller = controller;
}
public abstract void clear();
/**
* Gets the node that represents this view
*/
public N getNode() {
return node;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.