repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterManagerConfiguration.java
|
package org.infinispan.counter.configuration;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.util.Collections;
import java.util.Map;
import org.infinispan.commons.configuration.attributes.AttributeDefinition;
import org.infinispan.commons.configuration.attributes.AttributeSet;
import org.infinispan.commons.configuration.attributes.ConfigurationElement;
import org.infinispan.configuration.serializing.SerializedWith;
/**
* The {@link org.infinispan.counter.api.CounterManager} configuration.
* <p>
* It configures the number of owners (number of copies in the cluster) of a counter and the {@link Reliability} mode.
*
* @author Pedro Ruivo
* @since 9.0
*/
@SerializedWith(CounterConfigurationSerializer.class)
public class CounterManagerConfiguration extends ConfigurationElement<CounterManagerConfiguration> {
static final AttributeDefinition<Reliability> RELIABILITY = AttributeDefinition
.builder("reliability", Reliability.AVAILABLE)
.validator(value -> {
if (value == null) {
throw CONTAINER.invalidReliabilityMode();
}
})
.immutable().build();
static final AttributeDefinition<Integer> NUM_OWNERS = AttributeDefinition.builder(Attribute.NUM_OWNERS, 2)
.validator(value -> {
if (value < 1) {
throw CONTAINER.invalidNumOwners(value);
}
})
.immutable().build();
private final Map<String, AbstractCounterConfiguration> counters;
CounterManagerConfiguration(AttributeSet attributes, Map<String, AbstractCounterConfiguration> counters) {
super(Element.COUNTERS, attributes);
this.counters = counters;
}
static AttributeSet attributeDefinitionSet() {
return new AttributeSet(CounterManagerConfiguration.class, NUM_OWNERS, RELIABILITY);
}
public int numOwners() {
return attributes.attribute(NUM_OWNERS).get();
}
public Reliability reliability() {
return attributes.attribute(RELIABILITY).get();
}
public Map<String, AbstractCounterConfiguration> counters() {
return Collections.unmodifiableMap(counters);
}
}
| 2,167
| 34.540984
| 118
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/configuration/CounterConfigurationParser.java
|
package org.infinispan.counter.configuration;
import static org.infinispan.counter.configuration.CounterConfigurationParser.NAMESPACE;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.infinispan.commons.configuration.io.ConfigurationFormatFeature;
import org.infinispan.commons.configuration.io.ConfigurationReader;
import org.infinispan.commons.util.Util;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ConfigurationParser;
import org.infinispan.configuration.parsing.Namespace;
import org.infinispan.configuration.parsing.ParseUtils;
import org.infinispan.configuration.parsing.ParserScope;
import org.kohsuke.MetaInfServices;
/**
* Counters configuration parser
*
* @author Pedro Ruivo
* @since 13.0
*/
@MetaInfServices(ConfigurationParser.class)
@Namespace(root = "counters")
@Namespace(uri = NAMESPACE + "*", root = "counters", since = "9.0")
public class CounterConfigurationParser extends CounterParser {
@Override
public void readElement(ConfigurationReader reader, ConfigurationBuilderHolder holder) {
if (!holder.inScope(ParserScope.CACHE_CONTAINER)) {
throw CONTAINER.invalidScope(holder.getScope());
}
GlobalConfigurationBuilder builder = holder.getGlobalConfigurationBuilder();
Element element = Element.forName(reader.getLocalName());
if (element != Element.COUNTERS) {
throw ParseUtils.unexpectedElement(reader);
}
parseCountersElement(reader, builder.addModule(CounterManagerConfigurationBuilder.class));
}
@Override
public Namespace[] getNamespaces() {
return ParseUtils.getNamespaceAnnotations(getClass());
}
/**
* Reads a list of counter's configuration from an {@link InputStream}.
*
* @param is the {@link InputStream} to read.
* @return a {@link List} of {@link AbstractCounterConfiguration} read.
*/
public Map<String, AbstractCounterConfiguration> parseConfigurations(InputStream is) throws IOException {
BufferedInputStream input = new BufferedInputStream(is);
ConfigurationReader reader = ConfigurationReader.from(input).build();
CounterManagerConfigurationBuilder builder = new CounterManagerConfigurationBuilder(null);
try {
reader.require(ConfigurationReader.ElementType.START_DOCUMENT);
reader.nextElement();
reader.require(ConfigurationReader.ElementType.START_ELEMENT);
Element element = Element.forName(reader.getLocalName());
if (element != Element.COUNTERS) {
throw ParseUtils.unexpectedElement(reader);
}
parseCountersElement(reader, builder);
} finally {
Util.close(reader);
}
return builder.create().counters();
}
private void parseCountersElement(ConfigurationReader reader, CounterManagerConfigurationBuilder builder) {
for (int i = 0; i < reader.getAttributeCount(); i++) {
ParseUtils.requireNoNamespaceAttribute(reader, i);
String value = reader.getAttributeValue(i);
Attribute attribute = Attribute.forName(reader.getAttributeName(i));
switch (attribute) {
case NUM_OWNERS:
builder.numOwner(Integer.parseInt(value));
break;
case RELIABILITY:
builder.reliability(Reliability.valueOf(value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
}
if (reader.hasFeature(ConfigurationFormatFeature.MIXED_ELEMENTS)) {
while (reader.inTag()) {
Map.Entry<String, String> item = reader.getMapItem(Attribute.NAME);
readElement(reader, builder, Element.forName(item.getValue()), item.getKey());
reader.endMapItem();
}
} else {
reader.nextElement();
reader.require(ConfigurationReader.ElementType.START_ELEMENT, null, Element.COUNTERS);
while (reader.inTag()) {
Map.Entry<String, String> item = reader.getMapItem(Attribute.NAME);
readElement(reader, builder, Element.forName(item.getValue()), item.getKey());
reader.endMapItem();
}
reader.nextElement();
reader.require(ConfigurationReader.ElementType.END_ELEMENT, null, Element.COUNTERS);
}
}
}
| 4,580
| 39.539823
| 110
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/logging/Log.java
|
package org.infinispan.counter.logging;
import java.io.File;
import org.infinispan.counter.exception.CounterConfigurationException;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.counter.exception.CounterNotFoundException;
import org.infinispan.util.ByteString;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
/**
* range: 29501 - 30000
*
* @author Pedro Ruivo
* @since 9.0
*/
@MessageLogger(projectCode = "ISPN")
public interface Log extends BasicLogger {
String LOG_ROOT = "org.infinispan.";
Log CONTAINER = Logger.getMessageLogger(Log.class, LOG_ROOT + "CONTAINER");
//29501 is in commons log
// @Message(value = "The counter was deleted.", id = 29502)
// CounterException counterDeleted();
@Message(value = "The counter name is missing.", id = 29503)
CounterConfigurationException missingCounterName();
@Message(value = "Invalid storage mode. It must be non-null", id = 29504)
CounterConfigurationException invalidStorageMode();
@Message(value = "Invalid storage mode. PERSISTENT is not allowed without global state enabled in cache container.", id = 29505)
CounterConfigurationException invalidPersistentStorageMode();
@Message(value = "Invalid number of owner. It must be higher than zero but it was %s", id = 29506)
CounterConfigurationException invalidNumOwners(int value);
@Message(value = "Invalid reliability mode. It must be non-null", id = 29507)
CounterConfigurationException invalidReliabilityMode();
@Message(value = "Invalid initial value for counter. It must be between %s and %s (inclusive) but was %s", id = 29508)
CounterConfigurationException invalidInitialValueForBoundedCounter(long lower, long upper, long value);
@Message(value = "Invalid concurrency-level. It must be higher than zero but it was %s", id = 29509)
CounterConfigurationException invalidConcurrencyLevel(int value);
// @LogMessage(level = WARN)
// @Message(value = "Unable to add(%s) to non-existing counter '%s'.", id = 29510)
// void noSuchCounterAdd(long value, ByteString counterName);
// @LogMessage(level = WARN)
// @Message(value = "Unable to reset non-existing counter '%s'.", id = 29511)
// void noSuchCounterReset(ByteString counterName);
// @LogMessage(level = WARN)
// @Message(value = "Interrupted while waiting for the counter manager caches.", id = 29512)
// void interruptedWhileWaitingForCaches();
// @LogMessage(level = ERROR)
// @Message(value = "Exception while waiting for counter manager caches.", id = 29513)
// void exceptionWhileWaitingForCached(@Cause Throwable cause);
@Message(value = "Invalid counter type. Expected=%s but got %s", id = 29514)
CounterException invalidCounterType(String expected, String actual);
@Message(value = "Unable to fetch counter manager caches.", id = 29515)
CounterException unableToFetchCaches();
@Message(value = "Counter '%s' is not defined.", id = 29516)
CounterNotFoundException undefinedCounter(String name);
@Message(value = "Duplicated counter name found. Counter '%s' already exists.", id = 29517)
CounterConfigurationException duplicatedCounterName(String counter);
@Message(value = "Metadata not found but counter exists. Counter=%s", id = 29518)
IllegalStateException metadataIsMissing(ByteString counterName);
// @LogMessage(level = WARN)
// @Message(value = "Unable to compare-and-set(%d, %d) non-existing counter '%s'.", id = 29519)
// void noSuchCounterCAS(long expected, long value, ByteString counterName);
@Message(value = "Invalid scope for tag <counter>. Expected CACHE_CONTAINER but was %s", id = 29520)
CounterConfigurationException invalidScope(String scope);
// @Message(value = "Clustered counters only available with clustered cache manager.", id = 29521)
// CounterException expectedClusteredEnvironment();
//29522 is in commons log
//29523 is in hot rod log
@Message(value = "Lower bound (%s) and upper bound (%s) can't be the same.", id = 29524)
CounterConfigurationException invalidSameLowerAndUpperBound(long lower, long upper);
@Message(value = "Cannot rename file %s to %s", id = 29525)
CounterConfigurationException cannotRenamePersistentFile(String absolutePath, File persistentFile, @Cause Throwable cause);
@Message(value = "Error while persisting counter's configurations", id = 29526)
CounterConfigurationException errorPersistingCountersConfiguration(@Cause Throwable cause);
@Message(value = "Error while reading counter's configurations", id = 29527)
CounterConfigurationException errorReadingCountersConfiguration(@Cause Throwable cause);
@Message(value = "CounterManager hasn't started yet or has been stopped.", id = 29528)
CounterException counterManagerNotStarted();
@Message(value = "MBean registration failed", id = 29529)
CounterException jmxRegistrationFailed(@Cause Throwable cause);
}
| 5,087
| 43.243478
| 131
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/CounterModuleLifecycle.java
|
package org.infinispan.counter.impl;
import static java.util.EnumSet.of;
import static org.infinispan.registry.InternalCacheRegistry.Flag.EXCLUSIVE;
import static org.infinispan.registry.InternalCacheRegistry.Flag.PERSISTENT;
import java.util.Map;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.configuration.CounterManagerConfiguration;
import org.infinispan.counter.configuration.CounterManagerConfigurationBuilder;
import org.infinispan.counter.configuration.Reliability;
import org.infinispan.counter.impl.function.AddFunction;
import org.infinispan.counter.impl.function.CompareAndSwapFunction;
import org.infinispan.counter.impl.function.CreateAndAddFunction;
import org.infinispan.counter.impl.function.CreateAndCASFunction;
import org.infinispan.counter.impl.function.CreateAndSetFunction;
import org.infinispan.counter.impl.function.InitializeCounterFunction;
import org.infinispan.counter.impl.function.ReadFunction;
import org.infinispan.counter.impl.function.RemoveFunction;
import org.infinispan.counter.impl.function.ResetFunction;
import org.infinispan.counter.impl.function.SetFunction;
import org.infinispan.counter.impl.interceptor.CounterInterceptor;
import org.infinispan.counter.impl.manager.EmbeddedCounterManager;
import org.infinispan.counter.impl.persistence.PersistenceContextInitializerImpl;
import org.infinispan.counter.logging.Log;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.annotations.InfinispanModule;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.impl.ComponentRef;
import org.infinispan.interceptors.AsyncInterceptorChain;
import org.infinispan.interceptors.impl.EntryWrappingInterceptor;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.lifecycle.ModuleLifecycle;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.marshall.protostream.impl.SerializationContextRegistry;
import org.infinispan.partitionhandling.PartitionHandling;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.util.logging.LogFactory;
/**
* It registers a {@link EmbeddedCounterManager} to each {@link EmbeddedCacheManager} started and starts the cache on
* it.
*
* @author Pedro Ruivo
* @since 9.0
*/
@InfinispanModule(name = "clustered-counter", requiredModules = "core")
public class CounterModuleLifecycle implements ModuleLifecycle {
public static final String COUNTER_CACHE_NAME = "org.infinispan.COUNTER";
private static final Log log = LogFactory.getLog(CounterModuleLifecycle.class, Log.class);
private static Configuration createCounterCacheConfiguration(CounterManagerConfiguration config) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.DIST_SYNC)
.hash().numOwners(config.numOwners())
.stateTransfer().fetchInMemoryState(true)
.l1().disable()
.partitionHandling().whenSplit(config.reliability() == Reliability.CONSISTENT ?
PartitionHandling.DENY_READ_WRITES :
PartitionHandling.ALLOW_READ_WRITES)
.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
return builder.build();
}
private static Configuration createLocalCounterCacheConfiguration() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.LOCAL)
.l1().disable()
.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL);
return builder.build();
}
private static void addAdvancedExternalizer(Map<Integer, AdvancedExternalizer<?>> map, AdvancedExternalizer<?> ext) {
map.put(ext.getId(), ext);
}
private static CounterManagerConfiguration extractConfiguration(GlobalConfiguration globalConfiguration) {
CounterManagerConfiguration config = globalConfiguration.module(CounterManagerConfiguration.class);
return config == null ? CounterManagerConfigurationBuilder.defaultConfiguration() : config;
}
private static void registerCounterCache(InternalCacheRegistry registry, CounterManagerConfiguration config) {
registry.registerInternalCache(COUNTER_CACHE_NAME, createCounterCacheConfiguration(config),
of(EXCLUSIVE, PERSISTENT));
}
private static void registerLocalCounterCache(InternalCacheRegistry registry) {
registry.registerInternalCache(COUNTER_CACHE_NAME, createLocalCounterCacheConfiguration(),
of(EXCLUSIVE, PERSISTENT));
}
@Override
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) {
log.debug("Initialize counter module lifecycle");
Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalConfiguration.serialization().advancedExternalizers();
// Only required by GlobalMarshaller
addAdvancedExternalizer(externalizerMap, ResetFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, ReadFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, InitializeCounterFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, AddFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, CompareAndSwapFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, CreateAndCASFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, CreateAndAddFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, RemoveFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, SetFunction.EXTERNALIZER);
addAdvancedExternalizer(externalizerMap, CreateAndSetFunction.EXTERNALIZER);
BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class);
InternalCacheRegistry internalCacheRegistry = bcr.getComponent(InternalCacheRegistry.class).running();
SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class);
ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, new PersistenceContextInitializerImpl());
log.debugf("Register counter's cache %s", COUNTER_CACHE_NAME);
CounterManagerConfiguration counterManagerConfiguration = extractConfiguration(globalConfiguration);
if (gcr.getGlobalConfiguration().isClustered()) {
//only attempts to create the caches if the cache manager is clustered.
registerCounterCache(internalCacheRegistry, counterManagerConfiguration);
} else {
//local only cache manager.
registerLocalCounterCache(internalCacheRegistry);
}
log.debug("Register EmbeddedCounterManager");
// required to instantiate and start the EmbeddedCounterManager.
ComponentRef<CounterManager> component = bcr.getComponent(CounterManager.class);
if (component == null) {
return;
}
CounterManager cm = component.wired();
if (globalConfiguration.jmx().enabled()) {
try {
CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running();
jmxRegistration.registerMBean(cm);
} catch (Exception e) {
throw log.jmxRegistrationFailed(e);
}
}
}
@Override
public void cacheStarting(ComponentRegistry cr, Configuration configuration, String cacheName) {
if (COUNTER_CACHE_NAME.equals(cacheName) && configuration.clustering().cacheMode().isClustered()) {
log.debugf("Starting counter's cache %s", cacheName);
BasicComponentRegistry bcr = cr.getComponent(BasicComponentRegistry.class);
CounterInterceptor counterInterceptor = new CounterInterceptor();
bcr.registerComponent(CounterInterceptor.class, counterInterceptor, true);
bcr.addDynamicDependency(AsyncInterceptorChain.class.getName(), CounterInterceptor.class.getName());
bcr.getComponent(AsyncInterceptorChain.class).wired()
.addInterceptorAfter(counterInterceptor, EntryWrappingInterceptor.class);
}
}
}
| 8,553
| 50.842424
| 138
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/Utils.java
|
package org.infinispan.counter.impl;
import static org.infinispan.counter.logging.Log.CONTAINER;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.exception.CounterConfigurationException;
import org.infinispan.functional.Param;
/**
* Utility methods.
*
* @author Pedro Ruivo
* @since 9.0
*/
public final class Utils {
private Utils() {
}
/**
* Validates the lower and upper bound for a strong counter.
* <p>
* It throws a {@link CounterConfigurationException} is not valid.
*
* @param lowerBound The counter's lower bound value.
* @param initialValue The counter's initial value.
* @param upperBound The counter's upper bound value.
* @throws CounterConfigurationException if the upper or lower bound aren't valid.
*/
public static void validateStrongCounterBounds(long lowerBound, long initialValue, long upperBound) {
if (lowerBound > initialValue || initialValue > upperBound) {
throw CONTAINER.invalidInitialValueForBoundedCounter(lowerBound, upperBound, initialValue);
} else if (lowerBound == upperBound) {
throw CONTAINER.invalidSameLowerAndUpperBound(lowerBound, upperBound);
}
}
/**
* Calculates the {@link CounterState} to use based on the value and the boundaries.
* <p>
* If the value is less than the lower bound, {@link CounterState#LOWER_BOUND_REACHED} is returned. On other hand, if
* the value is higher than the upper bound, {@link CounterState#UPPER_BOUND_REACHED} is returned. Otherwise, {@link
* CounterState#VALID} is returned.
*
* @param value the value to check.
* @param lowerBound the lower bound.
* @param upperBound the upper bound.
* @return the {@link CounterState}.
*/
public static CounterState calculateState(long value, long lowerBound, long upperBound) {
if (value < lowerBound) {
return CounterState.LOWER_BOUND_REACHED;
} else if (value > upperBound) {
return CounterState.UPPER_BOUND_REACHED;
}
return CounterState.VALID;
}
public static Param.PersistenceMode getPersistenceMode(Storage storage) {
switch (storage) {
case PERSISTENT:
return Param.PersistenceMode.LOAD_PERSIST;
case VOLATILE:
return Param.PersistenceMode.SKIP;
default:
throw new IllegalStateException("[should never happen] unknown storage " + storage);
}
}
}
| 2,519
| 35
| 120
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/SyncWeakCounterAdapter.java
|
package org.infinispan.counter.impl;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import java.util.Objects;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.SyncWeakCounter;
import org.infinispan.counter.api.WeakCounter;
/**
* A {@link WeakCounter} decorator that waits for the operation to complete.
*
* @author Pedro Ruivo
* @see WeakCounter
* @since 9.2
*/
public class SyncWeakCounterAdapter implements SyncWeakCounter {
private final WeakCounter counter;
public SyncWeakCounterAdapter(WeakCounter counter) {
this.counter = Objects.requireNonNull(counter);
}
/**
* @see WeakCounter#getName()
*/
@Override
public String getName() {
return counter.getName();
}
/**
* @see WeakCounter#getValue()
*/
@Override
public long getValue() {
return counter.getValue();
}
/**
* @see WeakCounter#add(long)
*/
@Override
public void add(long delta) {
awaitCounterOperation(counter.add(delta));
}
/**
* @see WeakCounter#reset()
*/
@Override
public void reset() {
awaitCounterOperation(counter.reset());
}
/**
* @see WeakCounter#getConfiguration()
*/
@Override
public CounterConfiguration getConfiguration() {
return counter.getConfiguration();
}
/**
* @see WeakCounter#remove()
*/
@Override
public void remove() {
awaitCounterOperation(counter.remove());
}
@Override
public String toString() {
return "SyncWeakCounter{" +
"counter=" + counter +
'}';
}
}
| 1,639
| 19.246914
| 76
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/SyncStrongCounterAdapter.java
|
package org.infinispan.counter.impl;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import java.util.Objects;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.api.SyncStrongCounter;
/**
* A {@link StrongCounter} decorator that waits for the operation to complete.
*
* @author Pedro Ruivo
* @see StrongCounter
* @since 9.2
*/
public class SyncStrongCounterAdapter implements SyncStrongCounter {
private final StrongCounter counter;
public SyncStrongCounterAdapter(StrongCounter counter) {
this.counter = Objects.requireNonNull(counter);
}
/**
* @see StrongCounter#addAndGet(long)
*/
@Override
public long addAndGet(long delta) {
return awaitCounterOperation(counter.addAndGet(delta));
}
/**
* @see StrongCounter#reset()
*/
@Override
public void reset() {
awaitCounterOperation(counter.reset());
}
/**
* @see StrongCounter#decrementAndGet()
*/
@Override
public long getValue() {
return awaitCounterOperation(counter.getValue());
}
@Override
public long compareAndSwap(long expect, long update) {
return awaitCounterOperation(counter.compareAndSwap(expect, update));
}
/**
* @see StrongCounter#getName()
*/
@Override
public String getName() {
return counter.getName();
}
/**
* @see StrongCounter#getConfiguration()
*/
@Override
public CounterConfiguration getConfiguration() {
return counter.getConfiguration();
}
/**
* @see StrongCounter#remove()
*/
@Override
public void remove() {
awaitCounterOperation(counter.remove());
}
/**
* @see StrongCounter#getAndSet(long)
*/
@Override
public long getAndSet(long value) {
return awaitCounterOperation(counter.getAndSet(value));
}
@Override
public String toString() {
return "SyncStrongCounter{" +
"counter=" + counter +
'}';
}
}
| 2,052
| 20.840426
| 78
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/Util.java
|
package org.infinispan.counter.impl;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import org.infinispan.counter.exception.CounterException;
import org.infinispan.util.concurrent.CompletionStages;
/**
* Utility methods.
*
* @author Pedro Ruivo
* @since 9.2
*/
public final class Util {
private Util() {
}
/**
* Returns a {@link CounterException} with the throwable.
*/
private static CounterException rethrowAsCounterException(Throwable throwable) {
//make it public if needed.
if (throwable instanceof CounterException) {
return (CounterException) throwable;
} else if (throwable instanceof ExecutionException || throwable instanceof CompletionException) {
return rethrowAsCounterException(throwable.getCause());
} else {
return new CounterException(throwable);
}
}
/**
* Awaits for the counter operation and throws any exception as {@link CounterException}.
*/
public static <T> T awaitCounterOperation(CompletionStage<T> stage) {
try {
return CompletionStages.await(stage);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw rethrowAsCounterException(e);
} catch (ExecutionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
throw rethrowAsCounterException(e.getCause());
}
}
}
| 1,553
| 28.884615
| 103
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/CacheBasedStrongCounterFactory.java
|
package org.infinispan.counter.impl.factory;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
import org.infinispan.counter.impl.strong.AbstractStrongCounter;
import org.infinispan.counter.impl.strong.BoundedStrongCounter;
import org.infinispan.counter.impl.strong.StrongCounterKey;
import org.infinispan.counter.impl.strong.UnboundedStrongCounter;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* Created bounded and unbounded {@link StrongCounter} stored in a {@link Cache}.
*
* @since 14.0
*/
@Scope(Scopes.GLOBAL)
public class CacheBasedStrongCounterFactory extends CacheBaseCounterFactory<StrongCounterKey> implements StrongCounterFactory {
@Override
public CompletionStage<InternalCounterAdmin> createStrongCounter(String name, CounterConfiguration configuration) {
assert configuration.type() != CounterType.WEAK;
return cache(configuration)
.thenCompose(cache -> {
AbstractStrongCounter counter = configuration.type() == CounterType.BOUNDED_STRONG ?
new BoundedStrongCounter(name, cache, configuration, notificationManager) :
new UnboundedStrongCounter(name, cache, configuration, notificationManager);
return counter.init();
});
}
@Override
public CompletionStage<Void> removeStrongCounter(String name) {
return getCounterCacheAsync().thenCompose(cache -> AbstractStrongCounter.removeStrongCounter(cache, name));
}
}
| 1,760
| 39.953488
| 127
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/CounterComponentsFactory.java
|
package org.infinispan.counter.impl.factory;
import static org.infinispan.util.logging.Log.CONTAINER;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
import org.infinispan.counter.impl.manager.CounterConfigurationManager;
import org.infinispan.counter.impl.manager.CounterConfigurationStorage;
import org.infinispan.counter.impl.manager.EmbeddedCounterManager;
import org.infinispan.counter.impl.manager.PersistedCounterConfigurationStorage;
import org.infinispan.counter.impl.manager.VolatileCounterConfigurationStorage;
import org.infinispan.factories.AbstractComponentFactory;
import org.infinispan.factories.AutoInstantiableFactory;
import org.infinispan.factories.ComponentFactory;
import org.infinispan.factories.annotations.DefaultFactoryFor;
import org.infinispan.factories.impl.ComponentAlias;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* {@link ComponentFactory} for counters.
*
* @since 14.0
*/
@DefaultFactoryFor(classes = {
WeakCounterFactory.class,
StrongCounterFactory.class,
CounterManagerNotificationManager.class,
CounterConfigurationManager.class,
CounterConfigurationStorage.class,
CounterManager.class,
EmbeddedCounterManager.class
})
@Scope(Scopes.GLOBAL)
public class CounterComponentsFactory extends AbstractComponentFactory implements AutoInstantiableFactory {
@Override
public Object construct(String name) {
if (name.equals(WeakCounterFactory.class.getName())) {
return new CacheBasedWeakCounterFactory();
} else if (name.equals(StrongCounterFactory.class.getName())) {
return new CacheBasedStrongCounterFactory();
} else if (name.equals(CounterManagerNotificationManager.class.getName())) {
return new CounterManagerNotificationManager();
} else if (name.equals(CounterConfigurationManager.class.getName())) {
return new CounterConfigurationManager(globalConfiguration);
} else if (name.equals(CounterManager.class.getName())) {
return new EmbeddedCounterManager();
} else if (name.equals(EmbeddedCounterManager.class.getName())) {
return ComponentAlias.of(CounterManager.class);
} else if (name.equals(CounterConfigurationStorage.class.getName())) {
return globalConfiguration.globalState().enabled() ?
new PersistedCounterConfigurationStorage(globalConfiguration) :
VolatileCounterConfigurationStorage.INSTANCE;
}
throw CONTAINER.factoryCannotConstructComponent(name);
}
}
| 2,644
| 43.830508
| 107
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/WeakCounterFactory.java
|
package org.infinispan.counter.impl.factory;
import java.util.concurrent.CompletionStage;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
/**
* Factory to create and remove {@link WeakCounter}.
*
* @since 14.0
*/
public interface WeakCounterFactory {
/**
* Removes the {@link WeakCounter} state.
*
* @param counterName The counter's name.
* @return A {@link CompletionStage} that is completed after the counter is removed.
*/
CompletionStage<Void> removeWeakCounter(String counterName, CounterConfiguration configuration);
/**
* Creates a {@link WeakCounter}.
*
* @param counterName The counter's name.
* @param configuration The counter's configuration.
* @return A {@link CompletionStage} that is completed after the counter is created.
*/
CompletionStage<InternalCounterAdmin> createWeakCounter(String counterName, CounterConfiguration configuration);
}
| 1,045
| 29.764706
| 115
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/CacheBasedWeakCounterFactory.java
|
package org.infinispan.counter.impl.factory;
import java.util.concurrent.CompletionStage;
import org.infinispan.Cache;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
import org.infinispan.counter.impl.weak.WeakCounterImpl;
import org.infinispan.counter.impl.weak.WeakCounterKey;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.util.concurrent.CompletionStages;
/**
* Creates {@link WeakCounter} stored in a {@link Cache}.
*
* @since 14.0
*/
@Scope(Scopes.GLOBAL)
public class CacheBasedWeakCounterFactory extends CacheBaseCounterFactory<WeakCounterKey> implements WeakCounterFactory {
@Override
public CompletionStage<InternalCounterAdmin> createWeakCounter(String name, CounterConfiguration configuration) {
assert configuration.type() == CounterType.WEAK;
return cache(configuration).thenCompose(cache -> {
WeakCounterImpl counter = new WeakCounterImpl(name, cache, configuration, notificationManager);
return registerListeners(cache).thenCompose(___ -> counter.init());
});
}
@Override
public CompletionStage<Void> removeWeakCounter(String name, CounterConfiguration configuration) {
return getCounterCacheAsync().thenCompose(cache -> WeakCounterImpl.removeWeakCounter(cache, configuration, name));
}
private CompletionStage<Void> registerListeners(Cache<? extends CounterKey, CounterValue> cache) {
// topology listener is used to compute the keys where this node is the primary owner
// adds are made on these keys to avoid contention and improve performance
CompletionStage<Void> topologyStage = notificationManager.registerTopologyListener(cache);
// the weak counter keeps a local value and, on each event, the local value is updated (reads are always local)
CompletionStage<Void> valueStage = notificationManager.registerCounterValueListener(cache);
return CompletionStages.allOf(topologyStage, valueStage);
}
}
| 2,281
| 44.64
| 121
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/StrongCounterFactory.java
|
package org.infinispan.counter.impl.factory;
import java.util.concurrent.CompletionStage;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
/**
* Factory to create and remove bounded and unbounded {@link StrongCounter}.
*
* @since 14.0
*/
public interface StrongCounterFactory {
/**
* Removes the {@link StrongCounter} state.
*
* @param counterName The counter's name.
* @return A {@link CompletionStage} that is completed after the counter is removed.
*/
CompletionStage<Void> removeStrongCounter(String counterName);
/**
* Creates a (un)bounded {@link StrongCounter}.
*
* @param counterName The counter's name.
* @param configuration The counter's configuration.
* @return A {@link CompletionStage} that is completed after the counter is created.
*/
CompletionStage<InternalCounterAdmin> createStrongCounter(String counterName, CounterConfiguration configuration);
}
| 1,057
| 30.117647
| 117
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/factory/CacheBaseCounterFactory.java
|
package org.infinispan.counter.impl.factory;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.context.Flag;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.impl.CounterModuleLifecycle;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.util.concurrent.BlockingManager;
/**
* Base class to create counters stored in a {@link Cache}.
*
* @since 14.0
*/
@Scope(Scopes.NONE)
public abstract class CacheBaseCounterFactory<K extends CounterKey> {
@Inject BlockingManager blockingManager;
@Inject EmbeddedCacheManager cacheManager;
@Inject CounterManagerNotificationManager notificationManager;
protected CompletionStage<AdvancedCache<K, CounterValue>> cache(CounterConfiguration configuration) {
return configuration.storage() == Storage.VOLATILE ?
getCounterCacheAsync().thenApply(this::transformCacheToVolatile) :
getCounterCacheAsync();
}
CompletionStage<AdvancedCache<K, CounterValue>> getCounterCacheAsync() {
return blockingManager.supplyBlocking(this::getCounterCacheSync, "get-counter-cache");
}
private AdvancedCache<K, CounterValue> getCounterCacheSync() {
Cache<K, CounterValue> cache = cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME);
return cache.getAdvancedCache();
}
private AdvancedCache<K, CounterValue> transformCacheToVolatile(AdvancedCache<K, CounterValue> cache) {
return cache.withFlags(Flag.SKIP_CACHE_LOAD, Flag.SKIP_CACHE_STORE);
}
}
| 1,994
| 37.365385
| 106
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/ResetFunction.java
|
package org.infinispan.counter.impl.function;
import static org.infinispan.counter.impl.entries.CounterValue.newCounterValue;
import java.io.IOException;
import java.io.ObjectInput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.functional.EntryView;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.exts.NoStateExternalizer;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.counter.logging.Log;
/**
* Reset function that sets the counter's delta to it's initial delta.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class ResetFunction<K extends CounterKey> extends BaseFunction<K, Void> {
public static final AdvancedExternalizer<ResetFunction> EXTERNALIZER = new Externalizer();
private static final Log log = LogFactory.getLog(ResetFunction.class, Log.class);
private static final ResetFunction INSTANCE = new ResetFunction();
private ResetFunction() {
}
public static <K extends CounterKey> ResetFunction<K> getInstance() {
//noinspection unchecked
return INSTANCE;
}
@Override
Void apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterConfigurationMetaParam metadata) {
entryView.set(newCounterValue(metadata.get()), metadata);
return null;
}
@Override
protected Log getLog() {
return log;
}
@Override
public String toString() {
return "ResetFunction{}";
}
private static class Externalizer extends NoStateExternalizer<ResetFunction> {
@Override
public ResetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return ResetFunction.getInstance();
}
@Override
public Set<Class<? extends ResetFunction>> getTypeClasses() {
return Collections.singleton(ResetFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.RESET_FUNCTION;
}
}
}
| 2,247
| 28.973333
| 112
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/InitializeCounterFunction.java
|
package org.infinispan.counter.impl.function;
import static org.infinispan.counter.impl.entries.CounterValue.newCounterValue;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import org.infinispan.functional.EntryView;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
/**
* Function that initializes the {@link CounterValue} and {@link CounterConfigurationMetaParam} if they don't exists.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class InitializeCounterFunction<K extends CounterKey> implements
Function<EntryView.ReadWriteEntryView<K, CounterValue>, CounterValue> {
public static final AdvancedExternalizer<InitializeCounterFunction> EXTERNALIZER = new Externalizer();
private final CounterConfiguration counterConfiguration;
public InitializeCounterFunction(CounterConfiguration counterConfiguration) {
this.counterConfiguration = counterConfiguration;
}
@Override
public CounterValue apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView) {
Optional<CounterValue> currentValue = entryView.find();
if (currentValue.isPresent()) {
return currentValue.get();
}
CounterValue newValue = newCounterValue(counterConfiguration);
entryView.set(newValue, new CounterConfigurationMetaParam(counterConfiguration));
return newValue;
}
@Override
public String toString() {
return "InitializeCounterFunction{" +
"counterConfiguration=" + counterConfiguration +
'}';
}
private static class Externalizer implements AdvancedExternalizer<InitializeCounterFunction> {
@Override
public void writeObject(ObjectOutput output, InitializeCounterFunction object) throws IOException {
output.writeObject(object.counterConfiguration);
}
@Override
public InitializeCounterFunction<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new InitializeCounterFunction<>((CounterConfiguration) input.readObject());
}
@Override
public Set<Class<? extends InitializeCounterFunction>> getTypeClasses() {
return Collections.singleton(InitializeCounterFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.INITIALIZE_FUNCTION;
}
}
}
| 2,781
| 34.666667
| 117
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/BaseCreateFunction.java
|
package org.infinispan.counter.impl.function;
import java.util.function.Function;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.EntryView;
/**
* A base function to update a counter, even if it doesn't exist.
* <p>
* If the counter doesn't exist, it is created based on the configuration.
*
* @author Pedro Ruivo
* @since 9.2
*/
abstract class BaseCreateFunction<K extends CounterKey, R> implements
Function<EntryView.ReadWriteEntryView<K, CounterValue>, R> {
final CounterConfiguration configuration;
BaseCreateFunction(CounterConfiguration configuration) {
this.configuration = configuration;
}
@Override
public final R apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView) {
return entryView.find().isPresent() ?
checkMetadataAndApply(entryView) :
createAndApply(entryView);
}
private R checkMetadataAndApply(EntryView.ReadWriteEntryView<K, CounterValue> entryView) {
CounterConfigurationMetaParam metadata = entryView.findMetaParam(CounterConfigurationMetaParam.class)
.orElseGet(this::createMetadata);
return apply(entryView, entryView.get(), metadata);
}
private R createAndApply(EntryView.ReadWriteEntryView<K, CounterValue> entryView) {
CounterValue value = CounterValue.newCounterValue(configuration);
return apply(entryView, value, createMetadata());
}
abstract R apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterValue currentValue,
CounterConfigurationMetaParam metadata);
private CounterConfigurationMetaParam createMetadata() {
return new CounterConfigurationMetaParam(configuration);
}
}
| 1,906
| 34.981132
| 107
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/AddFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.counter.logging.Log;
import org.infinispan.functional.EntryView.ReadWriteEntryView;
/**
* The adding function to update the {@link CounterValue}.
*
* @author Pedro Ruivo
* @since 9.0
*/
public final class AddFunction<K extends CounterKey> extends BaseFunction<K, CounterValue> {
public static final AdvancedExternalizer<AddFunction> EXTERNALIZER = new Externalizer();
private static final Log log = LogFactory.getLog(AddFunction.class, Log.class);
private final long delta;
public AddFunction(long delta) {
this.delta = delta;
}
@Override
CounterValue apply(ReadWriteEntryView<K, CounterValue> entry, CounterConfigurationMetaParam metadata) {
return FunctionHelper.add(entry, entry.get(), metadata, delta);
}
@Override
protected Log getLog() {
return log;
}
private static class Externalizer implements AdvancedExternalizer<AddFunction> {
@Override
public Set<Class<? extends AddFunction>> getTypeClasses() {
return Collections.singleton(AddFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.ADD_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, AddFunction object) throws IOException {
output.writeLong(object.delta);
}
@Override
public AddFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new AddFunction(input.readLong());
}
}
}
| 2,062
| 29.338235
| 106
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/ReadFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.util.Collections;
import java.util.Set;
import java.util.function.Function;
import org.infinispan.functional.EntryView;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.exts.NoStateExternalizer;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
/**
* Read function that returns the current counter's delta.
* <p>
* Singleton class. Use {@link ReadFunction#getInstance()} to retrieve it.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class ReadFunction<K> implements Function<EntryView.ReadEntryView<K, CounterValue>, Long> {
public static final AdvancedExternalizer<ReadFunction> EXTERNALIZER = new Externalizer();
private static final ReadFunction INSTANCE = new ReadFunction();
private ReadFunction() {
}
public static <K> ReadFunction<K> getInstance() {
//noinspection unchecked
return INSTANCE;
}
@Override
public String toString() {
return "ReadFunction{}";
}
@Override
public Long apply(EntryView.ReadEntryView<K, CounterValue> view) {
return view.find().map(CounterValue::getValue).orElse(null);
}
private static class Externalizer extends NoStateExternalizer<ReadFunction> {
private Externalizer() {
}
@Override
public Set<Class<? extends ReadFunction>> getTypeClasses() {
return Collections.singleton(ReadFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.READ_FUNCTION;
}
@Override
public ReadFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return INSTANCE;
}
}
}
| 1,854
| 26.686567
| 100
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/FunctionHelper.java
|
package org.infinispan.counter.impl.function;
import static org.infinispan.counter.impl.entries.CounterValue.newCounterValue;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.functional.MetaParam;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.EntryView;
/**
* A helper with the function logic.
* <p>
* It avoids duplicate code between the functions and the create-functions.
*
* @author Pedro Ruivo
* @since 9.2
*/
final class FunctionHelper {
private FunctionHelper() {
}
/**
* Performs a compare-and-swap and return the previous value.
* <p>
* The compare-and-swap is successful if the return value is equals to the {@code expected}.
*
* @return the previous value or {@link CounterState#UPPER_BOUND_REACHED}/{@link CounterState#LOWER_BOUND_REACHED} if
* it reaches the boundaries of a bounded counter.
*/
static Object compareAndSwap(EntryView.ReadWriteEntryView<?, CounterValue> entry,
CounterValue value, CounterConfigurationMetaParam metadata, long expected, long update) {
long retVal = value.getValue();
if (expected == retVal) {
if (metadata.get().type() == CounterType.BOUNDED_STRONG) {
if (update < metadata.get().lowerBound()) {
return CounterState.LOWER_BOUND_REACHED;
} else if (update > metadata.get().upperBound()) {
return CounterState.UPPER_BOUND_REACHED;
}
}
setInEntry(entry, newCounterValue(update, CounterState.VALID), metadata);
}
return retVal;
}
static Object set(EntryView.ReadWriteEntryView<?, CounterValue> entry, CounterValue value,
CounterConfigurationMetaParam metadata, long update) {
long retVal = value.getValue();
CounterValue newValue;
if (metadata.get().type() == CounterType.BOUNDED_STRONG && update < metadata.get().lowerBound()) {
return CounterState.LOWER_BOUND_REACHED;
} else if (metadata.get().type() == CounterType.BOUNDED_STRONG && update > metadata.get().upperBound()) {
return CounterState.UPPER_BOUND_REACHED;
} else {
newValue = newCounterValue(update, CounterState.VALID);
}
setInEntry(entry, newValue, metadata);
return retVal;
}
static CounterValue add(EntryView.ReadWriteEntryView<?, CounterValue> entry,
CounterValue value, CounterConfigurationMetaParam metadata, long delta) {
if (delta == 0) {
return value;
}
if (metadata.get().type() == CounterType.BOUNDED_STRONG) {
if (delta > 0) {
return addAndCheckUpperBound(entry, value, metadata, delta);
} else {
return addAndCheckLowerBound(entry, value, metadata, delta);
}
} else {
return addUnbounded(entry, value, metadata, delta);
}
}
private static CounterValue addAndCheckUpperBound(EntryView.ReadWriteEntryView<?, CounterValue> entry,
CounterValue value, CounterConfigurationMetaParam metadata, long delta) {
if (value.getState() == CounterState.UPPER_BOUND_REACHED) {
return value;
}
CounterValue newValue;
long upperBound = metadata.get().upperBound();
try {
long addedValue = Math.addExact(value.getValue(), delta);
if (addedValue > upperBound) {
newValue = newCounterValue(upperBound, CounterState.UPPER_BOUND_REACHED);
} else {
newValue = newCounterValue(addedValue, CounterState.VALID);
}
} catch (ArithmeticException e) {
//overflow!
newValue = newCounterValue(Long.MAX_VALUE, CounterState.UPPER_BOUND_REACHED);
}
setInEntry(entry, newValue, metadata);
return newValue;
}
private static CounterValue addAndCheckLowerBound(EntryView.ReadWriteEntryView<?, CounterValue> entry,
CounterValue value, CounterConfigurationMetaParam metadata, long delta) {
if (value.getState() == CounterState.LOWER_BOUND_REACHED) {
return value;
}
CounterValue newValue;
long lowerBound = metadata.get().lowerBound();
try {
long addedValue = Math.addExact(value.getValue(), delta);
if (addedValue < lowerBound) {
newValue = newCounterValue(lowerBound, CounterState.LOWER_BOUND_REACHED);
} else {
newValue = newCounterValue(addedValue, CounterState.VALID);
}
} catch (ArithmeticException e) {
//overflow!
newValue = newCounterValue(Long.MIN_VALUE, CounterState.LOWER_BOUND_REACHED);
}
setInEntry(entry, newValue, metadata);
return newValue;
}
private static CounterValue addUnbounded(EntryView.ReadWriteEntryView<?, CounterValue> entry, CounterValue value,
CounterConfigurationMetaParam metadata, long delta) {
if (noChange(value.getValue(), delta)) {
return value;
}
CounterValue newValue;
try {
newValue = newCounterValue(Math.addExact(value.getValue(), delta));
} catch (ArithmeticException e) {
//overflow!
newValue = newCounterValue(delta > 0 ? Long.MAX_VALUE : Long.MIN_VALUE);
}
setInEntry(entry, newValue, metadata);
return newValue;
}
private static boolean noChange(long currentValue, long delta) {
return currentValue == Long.MAX_VALUE && delta > 0 ||
currentValue == Long.MIN_VALUE && delta < 0;
}
private static void setInEntry(EntryView.ReadWriteEntryView<?, CounterValue> entry, CounterValue value, CounterConfigurationMetaParam metadata) {
CounterConfiguration configuration = metadata.get();
if (configuration.type() != CounterType.WEAK && configuration.lifespan() > 0) {
entry.set(value, metadata, new MetaParam.MetaLifespan(configuration.lifespan()), new MetaParam.MetaUpdateCreationTime(false));
} else {
entry.set(value, metadata);
}
}
}
| 6,339
| 39.903226
| 148
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/SetFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.counter.logging.Log;
import org.infinispan.functional.EntryView;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
/**
* The function to set the {@link CounterValue}.
*
* @author Dipanshu Gupta
* @since 15.0
*/
public final class SetFunction<K extends CounterKey> extends BaseFunction<K, Object> implements Serializable {
public static final AdvancedExternalizer<SetFunction> EXTERNALIZER = new Externalizer();
private static final Log log = LogFactory.getLog(SetFunction.class, Log.class);
private final long value;
public SetFunction(long value) {
this.value = value;
}
@Override
Object apply(EntryView.ReadWriteEntryView<K, CounterValue> entry, CounterConfigurationMetaParam metadata) {
return FunctionHelper.set(entry, entry.get(), metadata, value);
}
@Override
protected Log getLog() {
return log;
}
private static class Externalizer implements AdvancedExternalizer<SetFunction> {
@Override
public Set<Class<? extends SetFunction>> getTypeClasses() {
return Collections.singleton(SetFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.SET_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, SetFunction object) throws IOException {
output.writeLong(object.value);
}
@Override
public SetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new SetFunction(input.readLong());
}
}
}
| 2,087
| 29.705882
| 110
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/RemoveFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.util.Collections;
import java.util.Set;
import java.util.function.Function;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.exts.NoStateExternalizer;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.EntryView;
/**
* It removes the {@link CounterValue} from the cache.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class RemoveFunction<K extends CounterKey> implements
Function<EntryView.ReadWriteEntryView<K, CounterValue>, Void> {
public static final AdvancedExternalizer<RemoveFunction> EXTERNALIZER = new Externalizer();
private static final RemoveFunction INSTANCE = new RemoveFunction();
private RemoveFunction() {
}
public static <K extends CounterKey> RemoveFunction<K> getInstance() {
//noinspection unchecked
return INSTANCE;
}
@Override
public String toString() {
return "RemoveFunction{}";
}
@Override
public Void apply(EntryView.ReadWriteEntryView<K, CounterValue> entry) {
if (entry.find().isPresent()) {
entry.remove();
}
return null;
}
private static class Externalizer extends NoStateExternalizer<RemoveFunction> {
@Override
public RemoveFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return RemoveFunction.getInstance();
}
@Override
public Set<Class<? extends RemoveFunction>> getTypeClasses() {
return Collections.singleton(RemoveFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.REMOVE_FUNCTION;
}
}
}
| 1,907
| 26.652174
| 102
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/CreateAndCASFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.EntryView;
/**
* The compare-and-swap function to update the {@link CounterValue}.
* <p>
* It has the same semantic as {@link CompareAndSwapFunction} but it creates the {@link CounterValue} if it doesn't
* exist.
*
* @author Pedro Ruivo
* @see CompareAndSwapFunction
* @since 9.2
*/
public class CreateAndCASFunction<K extends CounterKey> extends BaseCreateFunction<K, Object> {
public static final AdvancedExternalizer<CreateAndCASFunction> EXTERNALIZER = new Externalizer();
private final long expect;
private final long value;
public CreateAndCASFunction(CounterConfiguration configuration, long expect, long value) {
super(configuration);
this.expect = expect;
this.value = value;
}
@Override
Object apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterValue currentValue,
CounterConfigurationMetaParam metadata) {
return FunctionHelper.compareAndSwap(entryView, currentValue, metadata, expect, value);
}
private static class Externalizer implements AdvancedExternalizer<CreateAndCASFunction> {
@Override
public Set<Class<? extends CreateAndCASFunction>> getTypeClasses() {
return Collections.singleton(CreateAndCASFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CREATE_CAS_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, CreateAndCASFunction object) throws IOException {
output.writeObject(object.configuration);
output.writeLong(object.expect);
output.writeLong(object.value);
}
@Override
public CreateAndCASFunction<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CreateAndCASFunction<>((CounterConfiguration) input.readObject(), input.readLong(), input.readLong());
}
}
}
| 2,475
| 34.371429
| 122
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/BaseFunction.java
|
package org.infinispan.counter.impl.function;
import java.util.Optional;
import java.util.function.Function;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.counter.logging.Log;
import org.infinispan.functional.EntryView;
/**
* A base function to update an existing counter.
*
* @author Pedro Ruivo
* @since 9.0
*/
abstract class BaseFunction<K extends CounterKey, R> implements
Function<EntryView.ReadWriteEntryView<K, CounterValue>, R> {
@Override
public final R apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView) {
Optional<CounterValue> value = entryView.find();
if (!value.isPresent()) {
return null;
}
Optional<CounterConfigurationMetaParam> metadata = entryView.findMetaParam(CounterConfigurationMetaParam.class);
if (!metadata.isPresent()) {
throw getLog().metadataIsMissing(entryView.key().getCounterName());
}
return apply(entryView, metadata.get());
}
abstract R apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterConfigurationMetaParam metadata);
protected abstract Log getLog();
}
| 1,272
| 32.5
| 118
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/CreateAndSetFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.EntryView;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
public class CreateAndSetFunction<K extends CounterKey> extends BaseCreateFunction<K, Object> {
public static final AdvancedExternalizer<CreateAndSetFunction> EXTERNALIZER = new Externalizer();
private final long value;
public CreateAndSetFunction(CounterConfiguration configuration, long value) {
super(configuration);
this.value = value;
}
@Override
Object apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterValue currentValue, CounterConfigurationMetaParam metadata) {
return FunctionHelper.set(entryView, currentValue, metadata, value);
}
private static class Externalizer implements AdvancedExternalizer<CreateAndSetFunction> {
@Override
public Set<Class<? extends CreateAndSetFunction>> getTypeClasses() {
return Collections.singleton(CreateAndSetFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CREATE_AND_SET_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, CreateAndSetFunction object) throws IOException {
output.writeObject(object.configuration);
output.writeLong(object.value);
}
@Override
public CreateAndSetFunction<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CreateAndSetFunction<>((CounterConfiguration) input.readObject(), input.readLong());
}
}
}
| 2,038
| 36.072727
| 141
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/CompareAndSwapFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.counter.logging.Log;
import org.infinispan.functional.EntryView;
/**
* The compare-and-swap function to update the {@link CounterValue}.
* <p>
* It returns the previous value and it is considered successful when the return value is the {@code expect}ed.
* <p>
* For a bounded counter (if the current value is equal to the {@code expect}ed), if the {@code value} is outside the
* bounds, it returns {@link CounterState#LOWER_BOUND_REACHED} or {@link CounterState#UPPER_BOUND_REACHED} if the lower
* bound or upper bound is violated.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CompareAndSwapFunction<K extends CounterKey> extends BaseFunction<K, Object> {
public static final AdvancedExternalizer<CompareAndSwapFunction> EXTERNALIZER = new Externalizer();
private static final Log log = LogFactory.getLog(CompareAndSwapFunction.class, Log.class);
private final long expect;
private final long value;
public CompareAndSwapFunction(long expect, long value) {
this.expect = expect;
this.value = value;
}
@Override
Object apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterConfigurationMetaParam metadata) {
return FunctionHelper.compareAndSwap(entryView, entryView.get(), metadata, expect, value);
}
@Override
protected Log getLog() {
return log;
}
private static class Externalizer implements AdvancedExternalizer<CompareAndSwapFunction> {
@Override
public Set<Class<? extends CompareAndSwapFunction>> getTypeClasses() {
return Collections.singleton(CompareAndSwapFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CAS_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, CompareAndSwapFunction object) throws IOException {
output.writeLong(object.expect);
output.writeLong(object.value);
}
@Override
public CompareAndSwapFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CompareAndSwapFunction(input.readLong(), input.readLong());
}
}
}
| 2,765
| 34.922078
| 119
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/function/CreateAndAddFunction.java
|
package org.infinispan.counter.impl.function;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Collections;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.externalizers.ExternalizerIds;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.EntryView;
/**
* The adding function to update the {@link CounterValue}.
* <p>
* If the {@link CounterValue} doesn't exist, it is created. This is a difference between {@link AddFunction} and this
* class.
*
* @author Pedro Ruivo
* @since 9.2
*/
public class CreateAndAddFunction<K extends CounterKey> extends BaseCreateFunction<K, CounterValue> {
public static final AdvancedExternalizer<CreateAndAddFunction> EXTERNALIZER = new Externalizer();
private final long delta;
public CreateAndAddFunction(CounterConfiguration configuration, long delta) {
super(configuration);
this.delta = delta;
}
@Override
CounterValue apply(EntryView.ReadWriteEntryView<K, CounterValue> entryView, CounterValue currentValue,
CounterConfigurationMetaParam metadata) {
return FunctionHelper.add(entryView, currentValue, metadata, delta);
}
private static class Externalizer implements AdvancedExternalizer<CreateAndAddFunction> {
@Override
public Set<Class<? extends CreateAndAddFunction>> getTypeClasses() {
return Collections.singleton(CreateAndAddFunction.class);
}
@Override
public Integer getId() {
return ExternalizerIds.CREATE_ADD_FUNCTION;
}
@Override
public void writeObject(ObjectOutput output, CreateAndAddFunction object) throws IOException {
output.writeObject(object.configuration);
output.writeLong(object.delta);
}
@Override
public CreateAndAddFunction<?> readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return new CreateAndAddFunction<>((CounterConfiguration) input.readObject(), input.readLong());
}
}
}
| 2,299
| 33.848485
| 118
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/interceptor/CounterInterceptor.java
|
package org.infinispan.counter.impl.interceptor;
import java.util.Collection;
import java.util.EnumSet;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.EnumUtil;
import org.infinispan.container.entries.CacheEntry;
import org.infinispan.context.Flag;
import org.infinispan.context.InvocationContext;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.logging.Log;
import org.infinispan.functional.impl.CounterConfigurationMetaParam;
import org.infinispan.functional.impl.MetaParamsInternalMetadata;
import org.infinispan.interceptors.BaseCustomAsyncInterceptor;
import org.infinispan.metadata.Metadata;
/**
* Interceptor for the counters cache.
* <p>
* Since the state transfer doesn't know about the {@link Flag#SKIP_CACHE_STORE} and {@link Flag#SKIP_CACHE_LOAD} flags,
* all the counters are persisted. However, we only want the {@link Storage#PERSISTENT} configurations to be persisted.
* <p>
* This interceptor checks the configuration's {@link Storage} and sets the {@link Flag#SKIP_CACHE_LOAD} and {@link
* Flag#SKIP_CACHE_STORE} flags.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class CounterInterceptor extends BaseCustomAsyncInterceptor {
private static final Log log = LogFactory.getLog(CounterInterceptor.class, Log.class);
private static final Collection<Flag> FLAGS_TO_SKIP_PERSISTENCE = EnumSet
.of(Flag.SKIP_CACHE_LOAD, Flag.SKIP_CACHE_STORE);
private static CounterConfigurationMetaParam extract(Metadata metadata) {
return metadata instanceof MetaParamsInternalMetadata ?
((MetaParamsInternalMetadata) metadata).findMetaParam(CounterConfigurationMetaParam.class).orElse(null) :
null;
}
private static boolean isVolatile(CounterConfigurationMetaParam metadata) {
return metadata != null && metadata.get().storage() == Storage.VOLATILE;
}
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command)
throws Throwable {
//State Transfer puts doesn't use the skip_cache_load/store and the volatile counters are stored.
//interceptor should be between the entry wrapping and the cache loader/writer interceptors.
CacheEntry entry = ctx.lookupEntry(command.getKey());
CounterConfigurationMetaParam entryMetadata = entry == null ? null : extract(entry.getMetadata());
CounterConfigurationMetaParam commandMetadata = extract(command.getMetadata());
if (isVolatile(entryMetadata) || isVolatile(commandMetadata)) {
if (log.isTraceEnabled()) {
log.tracef("Setting skip persistence for %s", command.getKey());
}
command.setFlagsBitSet(EnumUtil.setEnums(command.getFlagsBitSet(), FLAGS_TO_SKIP_PERSISTENCE));
}
return invokeNext(ctx, command);
}
}
| 2,895
| 44.25
| 120
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/CounterConfigurationStorage.java
|
package org.infinispan.counter.impl.manager;
import java.util.Map;
import org.infinispan.counter.api.CounterConfiguration;
/**
* A local storage to persist counter's {@link CounterConfiguration}.
*
* @author Pedro Ruivo
* @since 9.2
*/
public interface CounterConfigurationStorage {
/**
* Invoked when starts, it returns all the persisted counter's.
*
* @return all the persisted counter's name and configurations.
*/
Map<String, CounterConfiguration> loadAll();
/**
* Persists the counter's configuration.
*
* @param name the counter's name.
* @param configuration the counter's {@link CounterConfiguration}.
*/
void store(String name, CounterConfiguration configuration);
/**
* Remove a counter configuration
*
* @param name the counter's name.
*/
void remove(String name);
/**
* Validates if the {@link CounterConfiguration} has a valid {@link org.infinispan.counter.api.Storage}.
* <p>
* It throws an exception if the implementation doesn't support one or more {@link org.infinispan.counter.api.Storage} modes.
*
* @param configuration the {@link CounterConfiguration} to check.
*/
void validatePersistence(CounterConfiguration configuration);
}
| 1,271
| 26.652174
| 128
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/CounterConfigurationManager.java
|
package org.infinispan.counter.impl.manager;
import static org.infinispan.counter.configuration.ConvertUtil.parsedConfigToConfig;
import static org.infinispan.counter.impl.Utils.validateStrongCounterBounds;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.configuration.AbstractCounterConfiguration;
import org.infinispan.counter.configuration.CounterManagerConfiguration;
import org.infinispan.counter.impl.CounterModuleLifecycle;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.globalstate.ScopeFilter;
import org.infinispan.globalstate.ScopedState;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.event.Event;
import org.infinispan.security.actions.SecurityActions;
import org.infinispan.stream.CacheCollectors;
import org.infinispan.util.concurrent.BlockingManager;
/**
* Stores all the defined counter's configuration.
* <p>
* It uses the state-{@link Cache} to distribute the counter's configuration among the nodes in the cluster, and the
* {@link CounterConfigurationStorage} to persist persistent configurations.
* <p>
* Note that the {@link Cache} doesn't persist anything.
*
* @author Pedro Ruivo
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public class CounterConfigurationManager {
public static final String COUNTER_SCOPE = "counter";
@Inject EmbeddedCacheManager cacheManager;
@Inject CounterConfigurationStorage storage;
private final AtomicBoolean counterCacheStarted = new AtomicBoolean(false);
private final Map<String, AbstractCounterConfiguration> configuredCounters;
private volatile AdvancedCache<ScopedState, CounterConfiguration> stateCache;
private volatile CounterConfigurationListener listener;
public CounterConfigurationManager(GlobalConfiguration globalConfiguration) {
CounterManagerConfiguration counterManagerConfig = globalConfiguration.module(CounterManagerConfiguration.class);
configuredCounters = counterManagerConfig == null ?
Collections.emptyMap() :
counterManagerConfig.counters();
}
private static ScopedState stateKey(String counterName) {
return new ScopedState(COUNTER_SCOPE, counterName);
}
/**
* It checks for existing defined configurations in {@link CounterConfigurationStorage} and in the {@link Cache}.
* <p>
* If any is found, it starts the counter's {@link Cache}.
*/
@Start
public void start() {
stateCache = cacheManager
.<ScopedState, CounterConfiguration>getCache(GlobalConfigurationManager.CONFIG_STATE_CACHE_NAME)
.getAdvancedCache();
listener = new CounterConfigurationListener();
Map<String, CounterConfiguration> persisted = storage.loadAll();
persisted.forEach((name, cfg) -> stateCache.putIfAbsent(stateKey(name), cfg));
counterCacheStarted.set(false);
stateCache.addListener(listener, new ScopeFilter(COUNTER_SCOPE), null);
if (!persisted.isEmpty() || stateCache.keySet().stream()
.anyMatch(scopedState -> COUNTER_SCOPE.equals(scopedState.getScope()))) {
//we have counter defined
startCounterCache();
}
}
/**
* Removes the listener for new coming defined counter's.
* <p>
* The persistence is done on the fly when the configuration is defined.
*/
@Stop
public void stop() {
counterCacheStarted.set(true); //avoid starting the counter cache if it hasn't started yet
if (listener != null && stateCache != null) {
stateCache.removeListener(listener);
}
listener = null;
stateCache = null;
}
/**
* It defines a new counter with the {@link CounterConfiguration}.
*
* @param name the counter's name.
* @param configuration the counter's {@link CounterConfiguration}.
* @return {@code true} if the counter doesn't exist. {@code false} otherwise.
*/
public CompletableFuture<Boolean> defineConfiguration(String name, CounterConfiguration configuration) {
//first, check if valid.
validateConfiguration(configuration);
return checkGlobalConfiguration(name)
.thenCompose(fileConfig -> {
if (fileConfig != null) {
//counter configuration exists in configuration file!
return CompletableFuture.completedFuture(Boolean.FALSE);
}
//put configuration in cache
return stateCache.putIfAbsentAsync(stateKey(name), configuration)
.thenCompose(cfg -> {
if (cfg == null) {
BlockingManager blockingManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(BlockingManager.class);
//the counter was created. we need to persist it (if the counter is persistent)
return blockingManager.supplyBlocking(() -> {
storage.store(name, configuration);
return Boolean.TRUE;
}, name);
} else {
//already defined.
return CompletableFutures.completedFalse();
}
});
});
}
/**
* Remove a configuration
*
* @param name the name of the counter
* @return true if the configuration was removed
*/
CompletableFuture<Boolean> removeConfiguration(String name) {
return stateCache.removeAsync(stateKey(name)).thenApply(Objects::nonNull);
}
/**
* @return all the defined counter's name, even the one in Infinispan's configuration.
*/
public Collection<String> getCounterNames() {
Collection<String> countersName = stateCache.keySet().stream()
.filter(new ScopeFilter(COUNTER_SCOPE))
.map(ScopedState::getName)
.collect(CacheCollectors.serializableCollector(Collectors::toSet));
countersName.addAll(configuredCounters.keySet());
return Collections.unmodifiableCollection(countersName);
}
/**
* Returns the counter's configuration.
*
* @param name the counter's name.
* @return the counter's {@link CounterConfiguration} or {@code null} if not defined.
*/
CompletableFuture<CounterConfiguration> getConfiguration(String name) {
return stateCache.getAsync(stateKey(name)).thenCompose(existingConfiguration -> {
if (existingConfiguration == null) {
return checkGlobalConfiguration(name);
} else {
return CompletableFuture.completedFuture(existingConfiguration);
}
});
}
/**
* Checks if the counter is defined in the Infinispan's configuration file.
*
* @param name the counter's name.
* @return {@code null} if the counter isn't defined yet. {@link CounterConfiguration} if it is defined.
*/
private CompletableFuture<CounterConfiguration> checkGlobalConfiguration(String name) {
for (AbstractCounterConfiguration config : configuredCounters.values()) {
if (config.name().equals(name)) {
CounterConfiguration cConfig = parsedConfigToConfig(config);
return stateCache.putIfAbsentAsync(stateKey(name), cConfig)
.thenApply(configuration -> {
if (configuration == null) {
storage.store(name, cConfig);
return cConfig;
}
return configuration;
});
}
}
return CompletableFutures.completedNull();
}
/**
* Invoked when a new configuration is stored in the state-cache, it boots the counter's cache.
*/
private void createCounter() {
if (stateCache.getStatus() == ComponentStatus.RUNNING) {
startCounterCache();
}
}
/**
* Validates the counter's configuration.
*
* @param configuration the {@link CounterConfiguration} to be validated.
*/
private void validateConfiguration(CounterConfiguration configuration) {
storage.validatePersistence(configuration);
switch (configuration.type()) {
case BOUNDED_STRONG:
validateStrongCounterBounds(configuration.lowerBound(), configuration.initialValue(),
configuration.upperBound());
break;
case WEAK:
if (configuration.concurrencyLevel() < 1) {
throw CONTAINER.invalidConcurrencyLevel(configuration.concurrencyLevel());
}
break;
}
}
private void startCounterCache() {
if (counterCacheStarted.compareAndSet(false, true)) {
BlockingManager blockingManager = SecurityActions.getGlobalComponentRegistry(cacheManager)
.getComponent(BlockingManager.class);
blockingManager.runBlocking(() -> {
String oldName = Thread.currentThread().getName();
try {
GlobalConfiguration configuration = SecurityActions.getCacheManagerConfiguration(cacheManager);
String threadName = "CounterCacheStartThread," + configuration.transport().nodeName();
Thread.currentThread().setName(threadName);
cacheManager.getCache(CounterModuleLifecycle.COUNTER_CACHE_NAME);
} finally {
Thread.currentThread().setName(oldName);
}
}, CounterModuleLifecycle.COUNTER_CACHE_NAME);
}
}
//can be async!
@Listener(observation = Listener.Observation.POST, sync = false)
private class CounterConfigurationListener {
@CacheEntryModified
@CacheEntryCreated
public void onNewCounterConfiguration(Event<ScopedState, CounterConfiguration> event) {
createCounter();
}
}
}
| 10,886
| 39.173432
| 154
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/EmbeddedCounterManager.java
|
package org.infinispan.counter.impl.manager;
import static org.infinispan.commons.util.concurrent.CompletableFutures.completedNull;
import static org.infinispan.commons.util.concurrent.CompletableFutures.toNullFunction;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.PropertyFormatter;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.factory.StrongCounterFactory;
import org.infinispan.counter.impl.factory.WeakCounterFactory;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
import org.infinispan.counter.logging.Log;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Start;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.util.concurrent.CompletionStages;
/**
* A {@link CounterManager} implementation for embedded cache manager.
*
* @author Pedro Ruivo
* @since 9.0
*/
@Scope(Scopes.GLOBAL)
@MBean(objectName = EmbeddedCounterManager.OBJECT_NAME, description = "Component to manage counters")
public class EmbeddedCounterManager implements CounterManager {
public static final String OBJECT_NAME = "CounterManager";
private static final Log log = LogFactory.getLog(EmbeddedCounterManager.class, Log.class);
private final Map<String, CompletableFuture<InternalCounterAdmin>> counters;
private volatile boolean stopped = true;
@Inject CounterConfigurationManager configurationManager;
@Inject CounterManagerNotificationManager notificationManager;
@Inject StrongCounterFactory strongCounterFactory;
@Inject WeakCounterFactory weakCounterFactory;
public EmbeddedCounterManager() {
counters = new ConcurrentHashMap<>(32);
}
@Start
public void start() {
if (log.isTraceEnabled()) {
log.trace("Starting EmbeddedCounterManager");
}
stopped = false;
}
@Stop(priority = 9) //lower than default priority to avoid creating the counters cache.
public void stop() {
if (log.isTraceEnabled()) {
log.trace("Stopping EmbeddedCounterManager");
}
stopped = true;
}
@ManagedOperation(
description = "Removes the counter's value from the cluster. The counter will be re-created when access next time.",
displayName = "Remove Counter",
name = "remove"
)
@Override
public void remove(String counterName) {
awaitCounterOperation(removeAsync(counterName, true));
}
public CompletionStage<Void> removeAsync(String counterName, boolean keepConfig) {
CompletionStage<Void> removeStage = getConfigurationAsync(counterName)
.thenCompose(config -> {
// check if the counter is defined
if (config == null) {
return completedNull();
}
CompletionStage<InternalCounterAdmin> existingCounter = counters.remove(counterName);
// if counter instance exists, invoke destroy()
if (existingCounter != null) {
return existingCounter.thenCompose(InternalCounterAdmin::destroy);
}
if (config.type() == CounterType.WEAK) {
return weakCounterFactory.removeWeakCounter(counterName, config);
} else {
return strongCounterFactory.removeStrongCounter(counterName);
}
});
if (keepConfig) {
return removeStage;
}
return removeStage.thenCompose(unused -> configurationManager.removeConfiguration(counterName))
.thenApply(toNullFunction());
}
@Override
public void undefineCounter(String counterName) {
awaitCounterOperation(removeAsync(counterName, false));
}
@Override
public StrongCounter getStrongCounter(String name) {
return awaitCounterOperation(getStrongCounterAsync(name));
}
public CompletionStage<StrongCounter> getStrongCounterAsync(String counterName) {
return getOrCreateAsync(counterName).thenApply(InternalCounterAdmin::asStrongCounter);
}
@Override
public WeakCounter getWeakCounter(String name) {
return awaitCounterOperation(getWeakCounterAsync(name));
}
public CompletionStage<WeakCounter> getWeakCounterAsync(String counterName) {
return getOrCreateAsync(counterName).thenApply(InternalCounterAdmin::asWeakCounter);
}
public CompletionStage<InternalCounterAdmin> getOrCreateAsync(String counterName) {
if (stopped) {
return CompletableFuture.failedFuture(CONTAINER.counterManagerNotStarted());
}
CompletableFuture<InternalCounterAdmin> stage = counters.computeIfAbsent(counterName, this::createCounter);
if (CompletionStages.isCompletedSuccessfully(stage)) {
// avoid invoking "exceptionally()" every time
return stage;
}
// remove if it fails
stage.exceptionally(throwable -> {
counters.remove(counterName, stage);
return null;
});
return stage;
}
@ManagedOperation(
description = "Returns a collection of defined counter's name.",
displayName = "Get Defined Counters",
name = "counters")
@Override
public Collection<String> getCounterNames() {
return configurationManager.getCounterNames();
}
public CompletableFuture<Boolean> defineCounterAsync(String name, CounterConfiguration configuration) {
return configurationManager.defineConfiguration(name, configuration);
}
@Override
public boolean defineCounter(String name, CounterConfiguration configuration) {
return awaitCounterOperation(defineCounterAsync(name, configuration));
}
@Override
public boolean isDefined(String name) {
return awaitCounterOperation(isDefinedAsync(name));
}
@Override
public CounterConfiguration getConfiguration(String counterName) {
return awaitCounterOperation(getConfigurationAsync(counterName));
}
public CompletableFuture<CounterConfiguration> getConfigurationAsync(String name) {
return configurationManager.getConfiguration(name);
}
@ManagedOperation(
description = "Returns the current counter's value",
displayName = "Get Counter' Value",
name = "value"
)
public long getValue(String counterName) {
return awaitCounterOperation(getOrCreateAsync(counterName).thenCompose(InternalCounterAdmin::value));
}
@ManagedOperation(
description = "Resets the counter's value",
displayName = "Reset Counter",
name = "reset"
)
public void reset(String counterName) {
awaitCounterOperation(getOrCreateAsync(counterName).thenCompose(InternalCounterAdmin::reset));
}
@ManagedOperation(
description = "Returns the counter's configuration",
displayName = "Counter Configuration",
name = "configuration"
)
public Properties getCounterConfiguration(String counterName) {
CounterConfiguration configuration = getConfiguration(counterName);
if (configuration == null) {
throw CONTAINER.undefinedCounter(counterName);
}
return PropertyFormatter.getInstance().format(configuration);
}
public CompletableFuture<Boolean> isDefinedAsync(String name) {
return getConfigurationAsync(name).thenApply(Objects::nonNull);
}
private CompletableFuture<InternalCounterAdmin> createCounter(String counterName) {
return getConfigurationAsync(counterName)
.thenCompose(config -> {
if (config == null) {
return CompletableFuture.failedFuture(CONTAINER.undefinedCounter(counterName));
}
switch (config.type()) {
case WEAK:
return weakCounterFactory.createWeakCounter(counterName, config);
case BOUNDED_STRONG:
case UNBOUNDED_STRONG:
return strongCounterFactory.createStrongCounter(counterName, config);
default:
return CompletableFuture.failedFuture(new IllegalStateException("[should never happen] unknown counter type: " + config.type()));
}
});
}
}
| 9,015
| 36.410788
| 150
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/InternalCounterAdmin.java
|
package org.infinispan.counter.impl.manager;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.util.concurrent.CompletionStage;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.exception.CounterException;
/**
* Internal interface which abstract the {@link StrongCounter} and {@link WeakCounter}.
*
* @since 14.0
*/
public interface InternalCounterAdmin {
/**
* @return The {@link StrongCounter} instance or throws an {@link CounterException} if the counter is not a {@link
* StrongCounter}.
*/
default StrongCounter asStrongCounter() {
throw CONTAINER.invalidCounterType(StrongCounter.class.getSimpleName(), getClass().getSimpleName());
}
/**
* @return The {@link WeakCounter} instance or throws an {@link CounterException} if the counter is not a {@link
* WeakCounter}.
*/
default WeakCounter asWeakCounter() {
throw CONTAINER.invalidCounterType(WeakCounter.class.getSimpleName(), getClass().getSimpleName());
}
/**
* Destroys the counter.
* <p>
* It drops the counter's value and all listeners registered.
*
* @return A {@link CompletionStage} instance which is completed when the operation finishes.
*/
CompletionStage<Void> destroy();
/**
* Resets the counter to its initial value.
*
* @return A {@link CompletionStage} instance which is completed when the operation finishes.
*/
CompletionStage<Void> reset();
/**
* Returns the counter's value.
*
* @return A {@link CompletionStage} instance which is completed when the operation finishes.
*/
CompletionStage<Long> value();
/**
* Checks if the counter is a {@link WeakCounter}.
* <p>
* If {@code true}, ensures {@link #asWeakCounter()} never throws an {@link CounterException}. Otherwise, it ensures
* {@link #asStrongCounter()} never throws an {@link CounterException}.
*
* @return {@code true} if the counter is {@link WeakCounter}.
*/
boolean isWeakCounter();
}
| 2,096
| 29.838235
| 119
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/VolatileCounterConfigurationStorage.java
|
package org.infinispan.counter.impl.manager;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.util.Collections;
import java.util.Map;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.Storage;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
/**
* A volatile implementation of {@link CounterConfigurationStorage}.
* <p>
* It throws an exception if it tries to store a {@link Storage#PERSISTENT} counter.
*
* @author Pedro Ruivo
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public enum VolatileCounterConfigurationStorage implements CounterConfigurationStorage {
INSTANCE;
@Override
public Map<String, CounterConfiguration> loadAll() {
return Collections.emptyMap();
}
@Override
public void store(String name, CounterConfiguration configuration) {
}
@Override
public void remove(String name) {
}
@Override
public void validatePersistence(CounterConfiguration configuration) {
if (configuration.storage() == Storage.PERSISTENT) {
throw CONTAINER.invalidPersistentStorageMode();
}
}
}
| 1,165
| 23.808511
| 88
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/manager/PersistedCounterConfigurationStorage.java
|
package org.infinispan.counter.impl.manager;
import static org.infinispan.commons.util.Util.renameTempFile;
import static org.infinispan.counter.configuration.ConvertUtil.parsedConfigToConfig;
import static org.infinispan.counter.logging.Log.CONTAINER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalStateConfiguration;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.Storage;
import org.infinispan.counter.configuration.AbstractCounterConfiguration;
import org.infinispan.counter.configuration.ConvertUtil;
import org.infinispan.counter.configuration.CounterConfigurationParser;
import org.infinispan.counter.configuration.CounterConfigurationSerializer;
import org.infinispan.counter.logging.Log;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.util.logging.LogFactory;
/**
* A persistent implementation of {@link CounterConfigurationStorage}.
* <p>
* The counter's configuration will be stored (as xml format) in {@code counters.xml} file in {@link
* GlobalStateConfiguration#sharedPersistentLocation()}
*
* @author Pedro Ruivo
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public class PersistedCounterConfigurationStorage implements CounterConfigurationStorage {
private static final Log log = LogFactory.getLog(PersistedCounterConfigurationStorage.class, Log.class);
private final Map<String, CounterConfiguration> storage;
private final CounterConfigurationSerializer serializer;
private final CounterConfigurationParser parser;
private final String sharedDirectory;
public PersistedCounterConfigurationStorage(GlobalConfiguration globalConfiguration) {
storage = new ConcurrentHashMap<>(32);
serializer = new CounterConfigurationSerializer();
parser = new CounterConfigurationParser();
sharedDirectory = globalConfiguration.globalState().sharedPersistentLocation();
}
private static AbstractCounterConfiguration fromEntry(Map.Entry<String, CounterConfiguration> entry) {
return ConvertUtil.configToParsedConfig(entry.getKey(), entry.getValue());
}
@Override
public Map<String, CounterConfiguration> loadAll() {
try {
doLoadAll();
} catch (IOException e) {
throw CONTAINER.errorReadingCountersConfiguration(e);
}
return storage;
}
@Override
public void store(String name, CounterConfiguration configuration) {
if (configuration.storage() == Storage.VOLATILE) {
//don't store volatile counters!
return;
}
storage.put(name, configuration);
try {
doStoreAll();
} catch (IOException e) {
throw CONTAINER.errorPersistingCountersConfiguration(e);
}
}
@Override
public void remove(String name) {
storage.remove(name);
}
@Override
public void validatePersistence(CounterConfiguration configuration) {
//nothing to validate
}
private void doStoreAll() throws IOException {
File directory = getSharedDirectory();
File temp = File.createTempFile("counters", null, directory);
try (FileOutputStream f = new FileOutputStream(temp)) {
serializer.serializeConfigurations(f, convertToList());
}
File persistentFile = getPersistentFile();
try {
renameTempFile(temp, getFileLock(), persistentFile);
} catch (Exception e) {
throw CONTAINER.cannotRenamePersistentFile(temp.getAbsolutePath(), persistentFile, e);
}
}
private void doLoadAll() throws IOException {
File file = getPersistentFile();
try (FileInputStream fis = new FileInputStream(file)) {
convertToMap(parser.parseConfigurations(fis));
} catch (FileNotFoundException e) {
if (log.isTraceEnabled()) {
log.tracef("File '%s' does not exist. Skip loading.", file.getAbsolutePath());
}
}
}
private List<AbstractCounterConfiguration> convertToList() {
return storage.entrySet().stream()
.map(PersistedCounterConfigurationStorage::fromEntry)
.collect(Collectors.toList());
}
private void convertToMap(Map<String, AbstractCounterConfiguration> configs) {
configs.forEach((n, c) -> storage.put(n, parsedConfigToConfig(c)));
}
private File getSharedDirectory() {
File directory = new File(sharedDirectory);
if (!directory.exists()) {
boolean created = directory.mkdirs();
if (log.isTraceEnabled()) {
log.tracef("Shared directory created? %s", created);
}
}
return directory;
}
private File getPersistentFile() {
return new File(sharedDirectory, "counters.xml");
}
private File getFileLock() {
return new File(sharedDirectory, "counters.xml.lck");
}
}
| 5,173
| 34.197279
| 107
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/weak/WeakCounterKey.java
|
package org.infinispan.counter.impl.weak;
import java.util.Objects;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.util.ByteString;
/**
* The key to store in the {@link org.infinispan.Cache} used by {@link WeakCounter}.
* <p>
* The weak consistent counters splits the counter's value in multiple keys. This class contains the index.
*
* @author Pedro Ruivo
* @since 9.0
*/
@ProtoTypeId(ProtoStreamTypeIds.WEAK_COUNTER_KEY)
public class WeakCounterKey implements CounterKey {
private final ByteString counterName;
private final int index;
@ProtoFactory
WeakCounterKey(ByteString counterName, int index) {
this.counterName = Objects.requireNonNull(counterName);
this.index = requirePositive(index);
}
private static int requirePositive(int i) {
if (i < 0) {
throw new IllegalArgumentException("Requires positive index");
}
return i;
}
@Override
@ProtoField(1)
public ByteString getCounterName() {
return counterName;
}
@ProtoField(number = 2, defaultValue = "0")
int getIndex() {
return index;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WeakCounterKey that = (WeakCounterKey) o;
return index == that.index &&
counterName.equals(that.counterName);
}
@Override
public int hashCode() {
int result = counterName.hashCode();
result = 31 * result + index;
return result;
}
@Override
public String toString() {
return "WeakCounterKey{" +
"counterName=" + counterName +
", index=" + index +
'}';
}
}
| 2,067
| 24.530864
| 107
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/weak/WeakCounterImpl.java
|
package org.infinispan.counter.impl.weak;
import static org.infinispan.counter.impl.Utils.getPersistenceMode;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.api.SyncWeakCounter;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.SyncWeakCounterAdapter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.function.AddFunction;
import org.infinispan.counter.impl.function.CreateAndAddFunction;
import org.infinispan.counter.impl.function.ReadFunction;
import org.infinispan.counter.impl.function.RemoveFunction;
import org.infinispan.counter.impl.function.ResetFunction;
import org.infinispan.counter.impl.listener.CounterEventGenerator;
import org.infinispan.counter.impl.listener.CounterEventImpl;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
import org.infinispan.counter.impl.listener.TopologyChangeListener;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
import org.infinispan.distribution.LocalizedCacheTopology;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.AggregateCompletionStage;
import org.infinispan.util.concurrent.CompletionStages;
/**
* A weak consistent counter implementation.
* <p>
* Implementation: The counter is split in multiple keys and they are stored in the cache.
* <p>
* Write: A write operation will pick a key to update. If the node is a primary owner of one of the key, that key is
* chosen based on thread-id. This will take advantage of faster write operations. If the node is not a primary owner,
* one of the key in key set is chosen.
* <p>
* Read: A read operation needs to read all the key set (including the remote keys). This is slower than atomic
* counter.
* <p>
* Weak Read: A snapshot of all the keys values is kept locally and they are updated via cluster listeners.
* <p>
* Reset: The reset operation is <b>not</b> atomic and intermediate results may be observed.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class WeakCounterImpl implements WeakCounter, CounterEventGenerator, TopologyChangeListener, InternalCounterAdmin {
private static final AtomicReferenceFieldUpdater<Entry, Long> SNAPSHOT_UPDATER = AtomicReferenceFieldUpdater.newUpdater(Entry.class, Long.class, "snapshot");
private final Entry[] entries;
private final AdvancedCache<WeakCounterKey, CounterValue> cache;
private final FunctionalMap.ReadWriteMap<WeakCounterKey, CounterValue> readWriteMap;
private final CounterManagerNotificationManager notificationManager;
private final FunctionalMap.ReadOnlyMap<WeakCounterKey, CounterValue> readOnlyMap;
private final CounterConfiguration configuration;
private final CounterConfiguration zeroConfiguration;
private final KeySelector selector;
public WeakCounterImpl(String counterName, AdvancedCache<WeakCounterKey, CounterValue> cache,
CounterConfiguration configuration, CounterManagerNotificationManager notificationManager) {
this.cache = cache;
this.notificationManager = notificationManager;
FunctionalMapImpl<WeakCounterKey, CounterValue> functionalMap = FunctionalMapImpl.create(cache)
.withParams(getPersistenceMode(configuration.storage()));
this.readWriteMap = ReadWriteMapImpl.create(functionalMap);
this.readOnlyMap = ReadOnlyMapImpl.create(functionalMap);
this.entries = initKeys(counterName, configuration.concurrencyLevel());
this.selector = cache.getCacheConfiguration().clustering().cacheMode().isClustered() ?
new ClusteredKeySelector(entries) :
new LocalKeySelector(entries);
this.configuration = configuration;
this.zeroConfiguration = CounterConfiguration.builder(CounterType.WEAK)
.concurrencyLevel(configuration.concurrencyLevel()).storage(configuration.storage()).initialValue(0)
.build();
}
private static <T> T get(int hash, T[] array) {
return array[hash & (array.length - 1)];
}
private static Entry[] initKeys(String counterName, int concurrencyLevel) {
ByteString name = ByteString.fromString(counterName);
int size = Util.findNextHighestPowerOfTwo(concurrencyLevel);
Entry[] entries = new Entry[size];
for (int i = 0; i < size; ++i) {
entries[i] = new Entry(new WeakCounterKey(name, i));
}
return entries;
}
/**
* It removes a weak counter from the {@code cache}, identified by the {@code counterName}.
*
* @param cache The {@link Cache} to remove the counter from.
* @param configuration The counter's configuration.
* @param counterName The counter's name.
*/
public static CompletionStage<Void> removeWeakCounter(Cache<WeakCounterKey, CounterValue> cache,
CounterConfiguration configuration, String counterName) {
ByteString counterNameByteString = ByteString.fromString(counterName);
AggregateCompletionStage<Void> stage = CompletionStages.aggregateCompletionStage();
for (int i = 0; i < configuration.concurrencyLevel(); ++i) {
stage.dependsOn(cache.removeAsync(new WeakCounterKey(counterNameByteString, i)));
}
return stage.freeze();
}
/**
* Initializes the key set.
* <p>
* Only one key will have the initial value and the remaining is zero.
*/
public CompletionStage<InternalCounterAdmin> init() {
registerListener();
AggregateCompletionStage<InternalCounterAdmin> stage = CompletionStages.aggregateCompletionStage(this);
for (int i = 0; i < entries.length; ++i) {
int index = i;
stage.dependsOn(readOnlyMap.eval(entries[index].key, ReadFunction.getInstance())
.thenAccept(value -> initEntry(index, value)));
}
selector.updatePreferredKeys();
return stage.freeze();
}
@Override
public String getName() {
return counterName().toString();
}
@Override
public long getValue() {
//return the initial value if it doesn't have a valid snapshot!
Long snapshot = getCachedValue();
return snapshot == null ? configuration.initialValue() : snapshot;
}
@Override
public CompletableFuture<Void> add(long delta) {
WeakCounterKey key = findKey();
return readWriteMap.eval(key, new AddFunction<>(delta))
.thenCompose(counterValue -> handleAddResult(key, counterValue, delta));
}
@Override
public WeakCounter asWeakCounter() {
return this;
}
@Override
public CompletionStage<Void> destroy() {
removeListener();
return remove();
}
@Override
public CompletableFuture<Void> reset() {
AggregateCompletionStage<Void> stage = CompletionStages.aggregateCompletionStage();
for (Entry entry : entries) {
stage.dependsOn(readWriteMap.eval(entry.key, ResetFunction.getInstance()));
}
return stage.freeze().toCompletableFuture();
}
@Override
public CompletionStage<Long> value() {
return CompletableFuture.completedFuture(getValue());
}
@Override
public boolean isWeakCounter() {
return true;
}
@Override
public <T extends CounterListener> Handle<T> addListener(T listener) {
return notificationManager.registerUserListener(counterName(), listener);
}
@Override
public CounterConfiguration getConfiguration() {
return configuration;
}
@Override
public synchronized CounterEvent generate(CounterKey key, CounterValue value) {
//we need to synchronize this.
//if it receives 2 events concurrently (e.g. 2 increments), it can generate duplicated events!
assert key instanceof WeakCounterKey;
int index = ((WeakCounterKey) key).getIndex();
long newValue = value == null ?
defaultValueOfIndex(index) :
value.getValue();
Long base = getCachedValue(index);
Long oldValue = entries[index].update(newValue);
return base == null || oldValue == null || oldValue == newValue ?
null :
CounterEventImpl.create(base + oldValue, base + newValue);
}
@Override
public CompletableFuture<Void> remove() {
AggregateCompletionStage<Void> stage = CompletionStages.aggregateCompletionStage();
for (Entry entry : entries) {
stage.dependsOn(readWriteMap.eval(entry.key, RemoveFunction.getInstance()));
}
return stage.freeze().toCompletableFuture();
}
@Override
public SyncWeakCounter sync() {
return new SyncWeakCounterAdapter(this);
}
@Override
public void topologyChanged() {
selector.updatePreferredKeys();
}
/**
* Debug only!
*/
public WeakCounterKey[] getPreferredKeys() {
return selector.getPreferredKeys();
}
/**
* Debug only!
*/
public WeakCounterKey[] getKeys() {
WeakCounterKey[] keys = new WeakCounterKey[entries.length];
for (int i = 0; i < keys.length; ++i) {
keys[i] = entries[i].key;
}
return keys;
}
@Override
public String toString() {
return "WeakCounter{" +
"counterName=" + counterName() +
'}';
}
private long defaultValueOfIndex(int index) {
return index == 0 ? configuration.initialValue() : 0;
}
private void initEntry(int index, Long value) {
if (value == null) {
value = defaultValueOfIndex(index);
}
entries[index].init(value);
}
private Long getCachedValue() {
long value = 0;
int index = 0;
try {
for (; index < entries.length; ++index) {
Long toAdd = entries[index].snapshot;
if (toAdd == null) {
//we don't have a valid snapshot
return null;
}
value = Math.addExact(value, toAdd);
}
} catch (ArithmeticException e) {
return getCachedValue0(index, value, -1);
}
return value;
}
private Long getCachedValue(int skipIndex) {
long value = 0;
int index = 0;
try {
for (; index < entries.length; ++index) {
if (index == skipIndex) {
continue;
}
Long toAdd = entries[index].snapshot;
if (toAdd == null) {
//we don't have a valid snapshot
return null;
}
value = Math.addExact(value, toAdd);
}
} catch (ArithmeticException e) {
return getCachedValue0(index, value, skipIndex);
}
return value;
}
private Long getCachedValue0(int index, long value, int skipIndex) {
BigInteger currentValue = BigInteger.valueOf(value);
do {
Long toAdd = entries[index++].snapshot;
if (toAdd == null) {
//we don't have a valid snapshot
return null;
}
currentValue = currentValue.add(BigInteger.valueOf(toAdd));
if (index == skipIndex) {
index++;
}
} while (index < entries.length);
try {
return currentValue.longValue();
} catch (ArithmeticException e) {
return currentValue.signum() > 0 ? Long.MAX_VALUE : Long.MIN_VALUE;
}
}
private CompletableFuture<Void> handleAddResult(WeakCounterKey key, CounterValue value, long delta) {
if (value == null) {
//first time
CounterConfiguration createConfiguration = key.getIndex() == 0 ?
configuration :
zeroConfiguration;
return readWriteMap.eval(key, new CreateAndAddFunction<>(createConfiguration, delta))
.thenApply(value1 -> null);
} else {
return CompletableFutures.completedNull();
}
}
private void registerListener() {
notificationManager.registerCounter(counterName(), this, this);
}
private void removeListener() {
notificationManager.removeCounter(counterName());
}
private WeakCounterKey findKey() {
return selector.findKey((int) Thread.currentThread().getId());
}
private ByteString counterName() {
return entries[0].key.getCounterName();
}
private static final class Entry {
final WeakCounterKey key;
volatile Long snapshot;
private Entry(WeakCounterKey key) {
this.key = key;
}
void init(long initialValue) {
SNAPSHOT_UPDATER.compareAndSet(this, null, initialValue);
}
Long update(long value) {
return SNAPSHOT_UPDATER.getAndSet(this, value);
}
}
private interface KeySelector {
WeakCounterKey findKey(int hash);
void updatePreferredKeys();
WeakCounterKey[] getPreferredKeys();
}
private static final class LocalKeySelector implements KeySelector {
private final Entry[] entries;
private LocalKeySelector(Entry[] entries) {
this.entries = entries;
}
@Override
public WeakCounterKey findKey(int hash) {
return get(hash, entries).key;
}
@Override
public void updatePreferredKeys() {
//no-op, everything is local
}
@Override
public WeakCounterKey[] getPreferredKeys() {
return Arrays.stream(entries).map(entry -> entry.key).toArray(WeakCounterKey[]::new);
}
}
private final class ClusteredKeySelector implements KeySelector {
private final Entry[] entries;
private volatile WeakCounterKey[] preferredKeys; //null when no keys available
private ClusteredKeySelector(Entry[] entries) {
this.entries = entries;
}
@Override
public WeakCounterKey findKey(int hash) {
WeakCounterKey[] copy = preferredKeys;
if (copy == null) {
return get(hash, entries).key;
} else if (copy.length == 1) {
return copy[0];
} else {
return get(hash, copy);
}
}
@Override
public void updatePreferredKeys() {
ArrayList<WeakCounterKey> preferredKeys = new ArrayList<>(entries.length);
LocalizedCacheTopology topology = cache.getDistributionManager().getCacheTopology();
for (Entry entry : entries) {
if (topology.getDistribution(entry.key).isPrimary()) {
preferredKeys.add(entry.key);
}
}
this.preferredKeys = preferredKeys.isEmpty() ?
null :
preferredKeys.toArray(new WeakCounterKey[preferredKeys.size()]);
}
@Override
public WeakCounterKey[] getPreferredKeys() {
return preferredKeys;
}
}
}
| 15,551
| 33.48337
| 160
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/persistence/PersistenceContextInitializer.java
|
package org.infinispan.counter.impl.persistence;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.strong.StrongCounterKey;
import org.infinispan.counter.impl.weak.WeakCounterKey;
import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl;
import org.infinispan.protostream.SerializationContextInitializer;
import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder;
/**
* Interface used to initialise the {@link PersistenceMarshallerImpl}'s {@link org.infinispan.protostream.SerializationContext}
* using the specified Pojos, Marshaller implementations and provided .proto schemas.
*
* @author Ryan Emerson
* @since 10.0
*/
@AutoProtoSchemaBuilder(
dependsOn = {
org.infinispan.marshall.persistence.impl.PersistenceContextInitializer.class,
org.infinispan.commons.marshall.PersistenceContextInitializer.class,
},
includeClasses = {
CounterValue.class,
StrongCounterKey.class,
WeakCounterKey.class
},
schemaFileName = "persistence.counters.proto",
schemaFilePath = "proto/generated",
schemaPackageName = "org.infinispan.persistence.counters",
service = false
)
interface PersistenceContextInitializer extends SerializationContextInitializer {
}
| 1,322
| 37.911765
| 127
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/strong/AbstractStrongCounter.java
|
package org.infinispan.counter.impl.strong;
import static org.infinispan.counter.impl.Util.awaitCounterOperation;
import static org.infinispan.counter.impl.Utils.getPersistenceMode;
import static org.infinispan.counter.impl.entries.CounterValue.newCounterValue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commons.util.concurrent.CompletableFutures;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.api.SyncStrongCounter;
import org.infinispan.counter.impl.SyncStrongCounterAdapter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.function.AddFunction;
import org.infinispan.counter.impl.function.CompareAndSwapFunction;
import org.infinispan.counter.impl.function.CreateAndAddFunction;
import org.infinispan.counter.impl.function.CreateAndCASFunction;
import org.infinispan.counter.impl.function.CreateAndSetFunction;
import org.infinispan.counter.impl.function.ReadFunction;
import org.infinispan.counter.impl.function.RemoveFunction;
import org.infinispan.counter.impl.function.ResetFunction;
import org.infinispan.counter.impl.function.SetFunction;
import org.infinispan.counter.impl.listener.CounterEventGenerator;
import org.infinispan.counter.impl.listener.CounterEventImpl;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
import org.infinispan.counter.impl.manager.InternalCounterAdmin;
import org.infinispan.functional.FunctionalMap;
import org.infinispan.functional.impl.FunctionalMapImpl;
import org.infinispan.functional.impl.ReadOnlyMapImpl;
import org.infinispan.functional.impl.ReadWriteMapImpl;
import net.jcip.annotations.GuardedBy;
/**
* A base strong consistent counter implementation.
* <p>
* Implementation: The value is stored in a single key and it uses the Infinispan's concurrency control and distribution
* to apply the write and reads. It uses the functional API.
* <p>
* Writes: The writes are performed by the functional API in order. The single key approach allows us to provide atomic
* properties for the counter value.
* <p>
* Reads: The reads read the value from the cache and it can go remotely.
* <p>
* Weak Reads: This implementation supports weak cached reads. It uses clustered listeners to receive the notifications
* of the actual value to store it locally.
*
* @author Pedro Ruivo
* @since 9.0
*/
public abstract class AbstractStrongCounter implements StrongCounter, CounterEventGenerator, InternalCounterAdmin {
final StrongCounterKey key;
private final FunctionalMap.ReadWriteMap<StrongCounterKey, CounterValue> readWriteMap;
private final FunctionalMap.ReadOnlyMap<StrongCounterKey, CounterValue> readOnlyMap;
private final CounterManagerNotificationManager notificationManager;
private final CounterConfiguration configuration;
@GuardedBy("this")
private CounterValue weakCounter;
AbstractStrongCounter(String counterName, AdvancedCache<StrongCounterKey, CounterValue> cache,
CounterConfiguration configuration, CounterManagerNotificationManager notificationManager) {
this.notificationManager = notificationManager;
FunctionalMapImpl<StrongCounterKey, CounterValue> functionalMap = FunctionalMapImpl.create(cache)
.withParams(getPersistenceMode(configuration.storage()));
key = new StrongCounterKey(counterName);
readWriteMap = ReadWriteMapImpl.create(functionalMap);
readOnlyMap = ReadOnlyMapImpl.create(functionalMap);
weakCounter = null;
this.configuration = configuration;
}
/**
* It removes a strong counter from the {@code cache}, identified by the {@code counterName}.
*
* @param cache The {@link Cache} to remove the counter from.
* @param counterName The counter's name.
*/
public static CompletionStage<Void> removeStrongCounter(Cache<StrongCounterKey, CounterValue> cache, String counterName) {
return cache.removeAsync(new StrongCounterKey(counterName)).thenApply(CompletableFutures.toNullFunction());
}
public final CompletionStage<InternalCounterAdmin> init() {
registerListener();
return readOnlyMap.eval(key, ReadFunction.getInstance()).thenAccept(this::initCounterState).thenApply(unused -> this);
}
@Override
public StrongCounter asStrongCounter() {
return this;
}
@Override
public CompletionStage<Void> destroy() {
removeListener();
return remove();
}
@Override
public CompletionStage<Long> value() {
return getValue();
}
@Override
public boolean isWeakCounter() {
return false;
}
@Override
public final String getName() {
return key.getCounterName().toString();
}
@Override
public final CompletableFuture<Long> getValue() {
return readOnlyMap.eval(key, ReadFunction.getInstance()).thenApply(this::handleReadResult);
}
@Override
public final CompletableFuture<Long> addAndGet(long delta) {
return readWriteMap.eval(key, new AddFunction<>(delta)).thenCompose(value -> checkAddResult(value, delta));
}
@Override
public final CompletableFuture<Void> reset() {
return readWriteMap.eval(key, ResetFunction.getInstance());
}
@Override
public final <T extends CounterListener> Handle<T> addListener(T listener) {
awaitCounterOperation(notificationManager.registerCounterValueListener(readWriteMap.cache()));
return notificationManager.registerUserListener(key.getCounterName(), listener);
}
@Override
public CompletableFuture<Long> compareAndSwap(long expect, long update) {
return readWriteMap.eval(key, new CompareAndSwapFunction<>(expect, update))
.thenCompose(result -> checkCasResult(result, expect, update));
}
@Override
public CompletableFuture<Long> getAndSet(long value) {
return readWriteMap.eval(key, new SetFunction<>(value))
.thenCompose(result -> checkSetResult(result, value));
}
@Override
public synchronized CounterEvent generate(CounterKey key, CounterValue value) {
CounterValue newValue = value == null ?
newCounterValue(configuration) :
value;
if (weakCounter == null || weakCounter.equals(newValue)) {
weakCounter = newValue;
return null;
} else {
CounterEvent event = CounterEventImpl.create(weakCounter, newValue);
weakCounter = newValue;
return event;
}
}
public CompletableFuture<Void> remove() {
return readWriteMap.eval(key, RemoveFunction.getInstance());
}
@Override
public final CounterConfiguration getConfiguration() {
return configuration;
}
@Override
public SyncStrongCounter sync() {
return new SyncStrongCounterAdapter(this);
}
protected abstract Long handleCASResult(Object state);
/**
* Extracts and validates the value after a read.
* <p>
* Any exception should be thrown using {@link CompletionException}.
*
* @param counterValue The new {@link CounterValue}.
* @return The new value stored in {@link CounterValue}.
*/
protected abstract long handleAddResult(CounterValue counterValue);
protected abstract Long handleSetResult(Object state);
/**
* Registers this instance as a cluster listener.
* <p>
* Note: It must be invoked when initialize the instance.
*/
private void registerListener() {
notificationManager.registerCounter(key.getCounterName(), this, null);
}
/**
* Removes this counter from the notification manager.
*/
private void removeListener() {
notificationManager.removeCounter(key.getCounterName());
}
/**
* Initializes the weak value.
*
* @param currentValue The current value.
*/
private synchronized void initCounterState(Long currentValue) {
if (weakCounter == null) {
weakCounter = currentValue == null ?
newCounterValue(configuration) :
newCounterValue(currentValue, configuration);
}
}
/**
* Retrieves and validate the value after a read.
*
* @param value The current value.
* @return The current value.
*/
private long handleReadResult(Long value) {
return value == null ?
configuration.initialValue() :
value;
}
private CompletableFuture<Long> checkAddResult(CounterValue value, long delta) {
if (value == null) {
//key doesn't exist in the cache. create and add.
return readWriteMap.eval(key, new CreateAndAddFunction<>(configuration, delta))
.thenApply(this::handleAddResult);
} else {
return CompletableFuture.completedFuture(handleAddResult(value));
}
}
private CompletionStage<Long> checkCasResult(Object result, long expect, long update) {
if (result == null) {
//key doesn't exist in the cache. create and CAS
return readWriteMap.eval(key, new CreateAndCASFunction<>(configuration, expect, update))
.thenApply(this::handleCASResult);
} else {
return CompletableFuture.completedFuture(handleCASResult(result));
}
}
private CompletionStage<Long> checkSetResult(Object result, long update) {
if (result == null) {
return readWriteMap.eval(key, new CreateAndSetFunction<>(configuration, update))
.thenApply(this::handleSetResult);
} else {
return CompletableFuture.completedFuture(handleSetResult(result));
}
}
}
| 9,962
| 36.037175
| 125
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/strong/BoundedStrongCounter.java
|
package org.infinispan.counter.impl.strong;
import static org.infinispan.counter.exception.CounterOutOfBoundsException.LOWER_BOUND;
import static org.infinispan.counter.exception.CounterOutOfBoundsException.UPPER_BOUND;
import java.util.concurrent.CompletionException;
import org.infinispan.AdvancedCache;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.exception.CounterOutOfBoundsException;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
/**
* A bounded strong consistent counter.
* <p>
* When the boundaries are reached, a {@link CounterOutOfBoundsException} is thrown. Use {@link
* CounterOutOfBoundsException#isUpperBoundReached()} or {@link CounterOutOfBoundsException#isLowerBoundReached()} to
* check if upper or lower bound has been reached, respectively.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class BoundedStrongCounter extends AbstractStrongCounter {
private static final Log log = LogFactory.getLog(BoundedStrongCounter.class, Log.class);
public BoundedStrongCounter(String counterName, AdvancedCache<StrongCounterKey, CounterValue> cache,
CounterConfiguration configuration, CounterManagerNotificationManager notificationManager) {
super(counterName, cache, configuration, notificationManager);
}
@Override
protected long handleAddResult(CounterValue counterValue) {
throwOutOfBoundExceptionIfNeeded(counterValue.getState());
return counterValue.getValue();
}
@Override
protected Long handleSetResult(Object state) {
if (state instanceof CounterState) {
throwOutOfBoundExceptionIfNeeded((CounterState) state);
}
assert state instanceof Long;
return (Long) state;
}
protected Long handleCASResult(Object state) {
if (state instanceof CounterState) {
throwOutOfBoundExceptionIfNeeded((CounterState) state);
}
assert state instanceof Long;
return (Long) state;
}
private void throwOutOfBoundExceptionIfNeeded(CounterState state) {
switch (state) {
case LOWER_BOUND_REACHED:
throw new CompletionException(log.counterOurOfBounds(LOWER_BOUND));
case UPPER_BOUND_REACHED:
throw new CompletionException(log.counterOurOfBounds(UPPER_BOUND));
default:
}
}
@Override
public String toString() {
return "BoundedStrongCounter{" +
"counterName=" + key.getCounterName() +
'}';
}
}
| 2,731
| 34.947368
| 123
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/strong/StrongCounterKey.java
|
package org.infinispan.counter.impl.strong;
import java.util.Objects;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.counter.api.StrongCounter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import org.infinispan.util.ByteString;
/**
* The key to store in the {@link org.infinispan.Cache} used by {@link StrongCounter}.
*
* @author Pedro Ruivo
* @see StrongCounter
* @since 9.0
*/
@ProtoTypeId(ProtoStreamTypeIds.STRONG_COUNTER_KEY)
public class StrongCounterKey implements CounterKey {
private final ByteString counterName;
StrongCounterKey(String counterName) {
this(ByteString.fromString(counterName));
}
@ProtoFactory
StrongCounterKey(ByteString counterName) {
this.counterName = Objects.requireNonNull(counterName);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StrongCounterKey that = (StrongCounterKey) o;
return counterName.equals(that.counterName);
}
@Override
public int hashCode() {
return counterName.hashCode();
}
@Override
public String toString() {
return "CounterKey{" +
"counterName=" + counterName +
'}';
}
@Override
@ProtoField(1)
public ByteString getCounterName() {
return counterName;
}
}
| 1,608
| 23.378788
| 86
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/strong/UnboundedStrongCounter.java
|
package org.infinispan.counter.impl.strong;
import org.infinispan.AdvancedCache;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.impl.listener.CounterManagerNotificationManager;
/**
* An unbounded strong consistent counter.
*
* @author Pedro Ruivo
* @see AbstractStrongCounter
* @since 9.0
*/
public class UnboundedStrongCounter extends AbstractStrongCounter {
public UnboundedStrongCounter(String counterName, AdvancedCache<StrongCounterKey, CounterValue> cache,
CounterConfiguration configuration, CounterManagerNotificationManager notificationManager) {
super(counterName, cache, configuration, notificationManager);
}
@Override
protected Long handleCASResult(Object state) {
assert state instanceof Long;
return (Long) state;
}
@Override
protected long handleAddResult(CounterValue counterValue) {
return counterValue.getValue();
}
@Override
protected Long handleSetResult(Object state) {
assert state instanceof Long;
return (Long) state;
}
@Override
public String toString() {
return "UnboundedStrongCounter{" +
"counterName=" + key.getCounterName() +
'}';
}
}
| 1,316
| 27.630435
| 125
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/listener/CounterEventGenerator.java
|
package org.infinispan.counter.impl.listener;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
/**
* A interface to generate {@link CounterEvent} from the current {@link CounterValue}.
*
* @author Pedro Ruivo
* @since 9.2
*/
@FunctionalInterface
public interface CounterEventGenerator {
/**
* It generates the {@link CounterEvent}.
* <p>
* The {@code value} is the new value of {@link CounterEvent}.
*
* @param key The counter's key.
* @param value The counter's most recent {@link CounterValue}.
* @return The {@link CounterEvent} with the updated value.
*/
CounterEvent generate(CounterKey key, CounterValue value);
}
| 780
| 26.892857
| 86
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/listener/TopologyChangeListener.java
|
package org.infinispan.counter.impl.listener;
/**
* The listener to be invoked when the cache topology changes.
*
* @author Pedro Ruivo
* @since 9.2
*/
@FunctionalInterface
public interface TopologyChangeListener {
/**
* It notifies the cache topology change.
*/
void topologyChanged();
}
| 311
| 16.333333
| 62
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/listener/CounterManagerNotificationManager.java
|
package org.infinispan.counter.impl.listener;
import static org.infinispan.commons.util.concurrent.CompletableFutures.completedNull;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import org.infinispan.Cache;
import org.infinispan.commons.util.ByRef;
import org.infinispan.configuration.cache.ClusteringConfiguration;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterListener;
import org.infinispan.counter.api.Handle;
import org.infinispan.counter.api.WeakCounter;
import org.infinispan.counter.impl.entries.CounterKey;
import org.infinispan.counter.impl.entries.CounterValue;
import org.infinispan.counter.logging.Log;
import org.infinispan.factories.annotations.Inject;
import org.infinispan.factories.annotations.Stop;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.notifications.Listener;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified;
import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved;
import org.infinispan.notifications.cachelistener.annotation.TopologyChanged;
import org.infinispan.notifications.cachelistener.event.CacheEntryEvent;
import org.infinispan.notifications.cachelistener.event.TopologyChangedEvent;
import org.infinispan.util.ByteString;
import org.infinispan.util.concurrent.BlockingManager;
import org.infinispan.util.logging.LogFactory;
/**
* It manages all the caches events and handles them. Also, it handles the user-specific {@link CounterListener}.
* <p>
* When a particular key is updated, its update is send to the counter, via {@link
* CounterEventGenerator#generate(CounterKey, CounterValue)}, and the result {@link CounterEvent} is used to notify the
* users {@link CounterListener}.
* <p>
* Also listens to topology changes in the cache to update the {@link WeakCounter} preferred keys, via {@link
* TopologyChangeListener#topologyChanged()}.
* <p>
* An user's {@link CounterListener} is invoked in sequence (i.e. only the next update is invoked when the previous one
* is handled) but it can be invoked in different thread.
*
* @author Pedro Ruivo
* @since 9.2
*/
@Scope(Scopes.GLOBAL)
public class CounterManagerNotificationManager {
private static final Log log = LogFactory.getLog(CounterManagerNotificationManager.class, Log.class);
private final Map<ByteString, Holder> counters;
private final CounterValueListener valueListener;
private final TopologyListener topologyListener;
private volatile BlockingManager.BlockingExecutor userListenerExecutor;
public CounterManagerNotificationManager() {
counters = new ConcurrentHashMap<>(32);
valueListener = new CounterValueListener();
topologyListener = new TopologyListener();
}
@Inject
public void inject(BlockingManager blockingManager) {
userListenerExecutor = blockingManager.limitedBlockingExecutor("counter-listener", 1);
}
@Stop
public void stop() {
// do not try to remove the listeners; the counter cache is already stopped at this point
counters.clear();
}
/**
* It registers a new counter created locally.
*
* @param counterName The counter's name.
* @param generator The counter's {@link CounterEvent} generator.
* @param topologyChangeListener The counter's listener to topology change. It can be {@code null}.
* @throws IllegalStateException If the counter with that name is already registered.
*/
public void registerCounter(ByteString counterName, CounterEventGenerator generator,
TopologyChangeListener topologyChangeListener) {
if (counters.putIfAbsent(counterName, new Holder(generator, topologyChangeListener)) != null) {
throw new IllegalStateException();
}
}
/**
* It registers a user's {@link CounterListener} for a specific counter.
*
* @param counterName The counter's name to listen.
* @param userListener The {@link CounterListener} to be invoked.
* @return The {@link Handle} for the {@link CounterListener}.
*/
public <T extends CounterListener> Handle<T> registerUserListener(ByteString counterName, T userListener) {
ByRef<Handle<T>> handleByRef = new ByRef<>(null);
counters.computeIfPresent(counterName, (name, holder) -> holder.addListener(userListener, handleByRef));
return handleByRef.get();
}
/**
* It registers the clustered cache listener if they aren't already registered.
* <p>
* This listener receives notification when a counter's value is updated.
*
* @param cache The {@link Cache} to listen to cluster events.
*/
public CompletionStage<Void> registerCounterValueListener(Cache<? extends CounterKey, CounterValue> cache) {
return valueListener.register(cache);
}
/**
* It registers the topology cache listener if they aren't already registered.
*
* @param cache The {@link Cache} to listen to cluster events.
*/
public CompletionStage<Void> registerTopologyListener(Cache<? extends CounterKey, CounterValue> cache) {
return topologyListener.register(cache);
}
/**
* It removes and stops sending notification to the counter.
*
* @param counterName The counter's name to remove.
*/
public void removeCounter(ByteString counterName) {
counters.remove(counterName);
}
/**
* A holder for a counter that container the {@link CounterEventGenerator}, the {@link TopologyChangeListener} and
* the user's {@link CounterListener}.
*/
private static class Holder {
private final CounterEventGenerator generator;
private final List<CounterListenerResponse<?>> userListeners;
private final TopologyChangeListener topologyChangeListener;
private Holder(CounterEventGenerator generator, TopologyChangeListener topologyChangeListener) {
this.generator = generator;
this.topologyChangeListener = topologyChangeListener;
userListeners = new CopyOnWriteArrayList<>();
}
<T extends CounterListener> Holder addListener(T userListener,
ByRef<Handle<T>> handleByRef) {
CounterListenerResponse<T> handle = new CounterListenerResponse<>(userListener, this);
userListeners.add(handle);
handleByRef.set(handle);
return this;
}
<T extends CounterListener> void removeListener(CounterListenerResponse<T> userListener) {
userListeners.remove(userListener);
}
TopologyChangeListener getTopologyChangeListener() {
return topologyChangeListener;
}
}
/**
* The {@link Handle} implementation for a specific {@link CounterListener}.
*/
private static class CounterListenerResponse<T extends CounterListener> implements Handle<T>, CounterListener {
private final T listener;
private final Holder holder;
private CounterListenerResponse(T listener, Holder holder) {
this.listener = listener;
this.holder = holder;
}
@Override
public T getCounterListener() {
return listener;
}
@Override
public void remove() {
holder.removeListener(this);
}
@Override
public void onUpdate(CounterEvent event) {
try {
listener.onUpdate(event);
} catch (Throwable t) {
log.warnf(t, "Exception while invoking listener %s", listener);
}
}
@Override
public int hashCode() {
return listener.hashCode();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CounterListenerResponse<?> that = (CounterListenerResponse<?>) o;
return listener.equals(that.listener);
}
}
/**
* The listener that register counter's value change.
*/
@Listener(clustered = true, observation = Listener.Observation.POST)
private class CounterValueListener {
final AtomicBoolean registered = new AtomicBoolean(false);
@CacheEntryCreated
@CacheEntryModified
@CacheEntryRemoved
public void updateState(CacheEntryEvent<? extends CounterKey, CounterValue> event) {
CounterKey key = event.getKey();
Holder holder = counters.get(key.getCounterName());
if (holder == null) {
return;
}
synchronized (holder.generator) {
//weak counter events execute the updateState method in parallel.
//if we don't synchronize, we can have events reordered.
triggerUserListener(holder.userListeners, holder.generator.generate(key, event.getValue()));
}
}
private void triggerUserListener(List<CounterListenerResponse<?>> userListeners, CounterEvent event) {
if (userListeners.isEmpty() || event == null) {
return;
}
userListenerExecutor.execute(() -> userListeners.forEach(l -> l.onUpdate(event)), event);
}
CompletionStage<Void> register(Cache<? extends CounterKey, CounterValue> cache) {
if (registered.compareAndSet(false, true)) {
return cache.addListenerAsync(this);
}
return completedNull();
}
}
/**
* The listener that registers topology changes.
*/
@Listener(sync = false)
private class TopologyListener {
final AtomicBoolean registered = new AtomicBoolean(false);
@TopologyChanged
public void topologyChanged(TopologyChangedEvent<?, ?> event) {
counters.values().stream()
.map(Holder::getTopologyChangeListener)
.filter(Objects::nonNull)
.forEach(TopologyChangeListener::topologyChanged);
}
private CompletionStage<Void> register(Cache<?, ?> cache) {
ClusteringConfiguration config = cache.getCacheConfiguration().clustering();
if (config.cacheMode().isClustered() && registered.compareAndSet(false, true)) {
return cache.addListenerAsync(this);
}
return completedNull();
}
}
}
| 10,543
| 36.257951
| 119
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/listener/CounterEventImpl.java
|
package org.infinispan.counter.impl.listener;
import org.infinispan.counter.api.CounterEvent;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.impl.entries.CounterValue;
import static java.util.Objects.requireNonNull;
/**
* The {@link CounterEvent} implementation.
*
* @author Pedro Ruivo
* @since 9.0
*/
public class CounterEventImpl implements CounterEvent {
private final long oldValue;
private final CounterState oldState;
private final long newValue;
private final CounterState newState;
private CounterEventImpl(long oldValue, CounterState oldState, long newValue, CounterState newState) {
this.oldValue = oldValue;
this.oldState = requireNonNull(oldState);
this.newValue = newValue;
this.newState = requireNonNull(newState);
}
public static CounterEvent create(long oldValue, long newValue) {
return new CounterEventImpl(oldValue, CounterState.VALID, newValue, CounterState.VALID);
}
public static CounterEvent create(CounterValue oldValue, CounterValue newValue) {
if (oldValue == null) {
return new CounterEventImpl(newValue.getValue(), newValue.getState(), newValue.getValue(), newValue.getState());
}
return new CounterEventImpl(oldValue.getValue(), oldValue.getState(), newValue.getValue(), newValue.getState());
}
@Override
public long getOldValue() {
return oldValue;
}
@Override
public CounterState getOldState() {
return oldState;
}
@Override
public long getNewValue() {
return newValue;
}
@Override
public CounterState getNewState() {
return newState;
}
@Override
public String toString() {
return "CounterEventImpl{" +
"oldValue=" + oldValue +
", oldState=" + oldState +
", newValue=" + newValue +
", newState=" + newState +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CounterEventImpl that = (CounterEventImpl) o;
return oldValue == that.oldValue &&
newValue == that.newValue &&
oldState == that.oldState &&
newState == that.newState;
}
@Override
public int hashCode() {
int result = (int) (oldValue ^ (oldValue >>> 32));
result = 31 * result + oldState.hashCode();
result = 31 * result + (int) (newValue ^ (newValue >>> 32));
result = 31 * result + newState.hashCode();
return result;
}
}
| 2,584
| 26.795699
| 121
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/externalizers/ExternalizerIds.java
|
package org.infinispan.counter.impl.externalizers;
/**
* Ids range: 2000 - 2050
*
* @author Pedro Ruivo
* @since 9.0
*/
public interface ExternalizerIds {
//2000 CounterConfiguration in commons
//2001 CounterState in commons
Integer RESET_FUNCTION = 2002;
Integer CONVERTER_AND_FILTER = 2003;
Integer STRONG_COUNTER_KEY = 2004;
Integer WEAK_COUNTER_KEY = 2005;
Integer READ_FUNCTION = 2006;
Integer COUNTER_VALUE = 2007;
Integer COUNTER_METADATA = 2008;
Integer INITIALIZE_FUNCTION = 2009;
Integer ADD_FUNCTION = 2010;
Integer CAS_FUNCTION = 2011;
Integer CREATE_CAS_FUNCTION = 2012;
Integer CREATE_ADD_FUNCTION = 2013;
Integer REMOVE_FUNCTION = 2014;
Integer SET_FUNCTION = 2015;
Integer CREATE_AND_SET_FUNCTION = 2016;
}
| 781
| 25.965517
| 50
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/entries/CounterValue.java
|
package org.infinispan.counter.impl.entries;
import static org.infinispan.counter.impl.Utils.calculateState;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterState;
import org.infinispan.counter.api.CounterType;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
import org.infinispan.protostream.annotations.ProtoTypeId;
import net.jcip.annotations.Immutable;
/**
* Stores the counter's value and {@link CounterState}.
* <p>
* If the counter isn't bounded, the state is always {@link CounterState#VALID}.
*
* @author Pedro Ruivo
* @since 9.0
*/
@Immutable
@ProtoTypeId(ProtoStreamTypeIds.COUNTER_VALUE)
public class CounterValue {
//A valid zero value
private static final CounterValue ZERO = new CounterValue(0, CounterState.VALID);
private final long value;
private final CounterState state;
@ProtoFactory
CounterValue(long value, CounterState state) {
this.value = value;
this.state = state;
}
/**
* Creates a new valid {@link CounterValue} with the value.
*
* @param value the counter's value.
* @return the {@link CounterValue}.
*/
public static CounterValue newCounterValue(long value) {
return value == 0 ?
ZERO :
new CounterValue(value, CounterState.VALID);
}
/**
* Creates a new {@link CounterValue} with the value and state based on the boundaries.
*
* @param value the counter's value.
* @param lowerBound the counter's lower bound.
* @param upperBound the counter's upper bound.
* @return the {@link CounterValue}.
*/
public static CounterValue newCounterValue(long value, long lowerBound, long upperBound) {
return new CounterValue(value, calculateState(value, lowerBound, upperBound));
}
/**
* Creates a new {@link CounterValue} with the value and state.
*
* @param value the counter's value.
* @param state the counter's state.
* @return the {@link CounterValue}.
*/
public static CounterValue newCounterValue(long value, CounterState state) {
return new CounterValue(value, state);
}
/**
* Creates the initial {@link CounterValue} based on {@link CounterConfiguration}.
*
* @param configuration the configuration.
* @return the {@link CounterValue}.
*/
public static CounterValue newCounterValue(CounterConfiguration configuration) {
return configuration.type() == CounterType.BOUNDED_STRONG ?
newCounterValue(configuration.initialValue(), configuration.lowerBound(), configuration.upperBound()) :
newCounterValue(configuration.initialValue());
}
/**
* Creates the initial {@link CounterValue} based on {@code currentValue} and the {@link CounterConfiguration}.
*
* @param currentValue the current counter's value.
* @param configuration the configuration.
* @return the {@link CounterValue}.
*/
public static CounterValue newCounterValue(long currentValue, CounterConfiguration configuration) {
return configuration.type() == CounterType.BOUNDED_STRONG ?
newCounterValue(currentValue, configuration.lowerBound(), configuration.upperBound()) :
newCounterValue(currentValue);
}
/**
* @return the counter's value.
*/
@ProtoField(number = 1, defaultValue = "0")
public long getValue() {
return value;
}
/**
* @return the counter's state.
*/
@ProtoField(2)
public CounterState getState() {
return state;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CounterValue that = (CounterValue) o;
return value == that.value && state == that.state;
}
@Override
public int hashCode() {
int result = (int) (value ^ (value >>> 32));
result = 31 * result + state.hashCode();
return result;
}
@Override
public String toString() {
return "CounterValue{" +
"value=" + value +
", state=" + state +
'}';
}
}
| 4,291
| 29.439716
| 115
|
java
|
null |
infinispan-main/counter/src/main/java/org/infinispan/counter/impl/entries/CounterKey.java
|
package org.infinispan.counter.impl.entries;
import org.infinispan.util.ByteString;
/**
* Interface that represents the key stored in the cache.
*
* @author Pedro Ruivo
* @since 9.0
*/
public interface CounterKey {
/**
* @return The counter name.
*/
ByteString getCounterName();
}
| 304
| 15.052632
| 57
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/StationPackingTestUtils.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/StationPackingTestUtils.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
/**
* Created by newmanne on 21/04/15.
*/
public class StationPackingTestUtils {
public static StationPackingInstance getSimpleInstance() {
return new StationPackingInstance(ImmutableMap.of(new Station(1), ImmutableSet.of(2)));
}
public static Map<Integer, Set<Station>> getSimpleInstanceAnswer() {
return ImmutableMap.of(2, ImmutableSet.of(new Station(1)));
}
public static StationPackingInstance instanceFromSpecs(Converter.StationPackingProblemSpecs specs, IStationManager stationManager) {
final Map<Station, Set<Integer>> domains = new HashMap<>();
for (Integer stationID : specs.getDomains().keySet()) {
Station station = stationManager.getStationfromID(stationID);
Set<Integer> domain = specs.getDomains().get(stationID);
Set<Integer> stationDomain = stationManager.getDomain(station);
Set<Integer> truedomain = Sets.intersection(domain, stationDomain);
domains.put(station, truedomain);
}
final Map<Station, Integer> previousAssignment = new HashMap<>();
for (Station station : domains.keySet()) {
Integer previousChannel = specs.getPreviousAssignment().get(station.getID());
if (previousChannel != null && previousChannel > 0) {
previousAssignment.put(station, previousChannel);
}
}
return new StationPackingInstance(domains, previousAssignment);
}
}
| 2,791
| 36.226667
| 136
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/TestConstraintManager.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/TestConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
/**
* Created by newmanne on 08/07/15.
*/
public class TestConstraintManager extends AMapBasedConstraintManager {
public TestConstraintManager(List<TestConstraint> constraints) throws FileNotFoundException {
super(null, "");
constraints.stream().forEach(c -> {
final Map<Station, Map<Integer, Set<Station>>> map = c.getKey().equals(ConstraintKey.CO) ? fCOConstraints : c.getKey().equals(ConstraintKey.ADJp1) ? fADJp1Constraints : fADJp2Constraints;
map.putIfAbsent(c.getReference(), new HashMap<>());
map.get(c.getReference()).putIfAbsent(c.getChannel(), new HashSet<>());
map.get(c.getReference()).get(c.getChannel()).addAll(c.getInterfering());
});
}
@Override
protected void loadConstraints(IStationManager stationManager, String fileName) throws FileNotFoundException {
}
}
| 2,027
| 36.555556
| 199
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ConstraintManagerTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ConstraintManagerTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
public abstract class ConstraintManagerTest {
final static protected String DOMAIN_PATH = Resources.getResource("data/testInterference/" + DataManager.DOMAIN_FILE).getPath();
protected abstract IConstraintManager getConstraintManager() throws Exception;
protected IStationManager getDomainManager() throws Exception {
return new DomainStationManager(DOMAIN_PATH);
}
public static class ChannelSpecificConstraintManagerTest extends ConstraintManagerTest {
@Override
protected IConstraintManager getConstraintManager() throws Exception {
final String interferencePath = Resources.getResource("data/testInterference").getPath();
return new ChannelSpecificConstraintManager(getDomainManager(), interferencePath + File.separator + "channelspecific" + File.separator + DataManager.INTERFERENCES_FILE);
}
}
public static class UnabridgedConstraintManagerTest extends ConstraintManagerTest {
@Override
protected IConstraintManager getConstraintManager() throws Exception {
final String interferencePath = Resources.getResource("data/testInterference").getPath();
return new UnabridgedFormatConstraintManager(getDomainManager(), interferencePath + File.separator + "unabridged" + File.separator + DataManager.INTERFERENCES_FILE);
}
@Test
public void testUnabridgedFormat() throws Exception {
final String interferencePath = Resources.getResource("data/testInterference/unabridged").getPath() + "/Interference_Paired_ADJm1_ADJm2.csv";
final IStationManager dm = new DomainStationManager(DOMAIN_PATH);
final IConstraintManager constraintManager = new UnabridgedFormatConstraintManager(dm, interferencePath);
// Test ADJ-1 and ADJ-2 constraints
assertEquals(Sets.newHashSet(s(dm, 9)), constraintManager.getADJplusOneInterferingStations(s(dm, 10), 9));
assertEquals(Sets.newHashSet(s(dm, 10)), constraintManager.getCOInterferingStations(s(dm, 9), 9));
assertEquals(Sets.newHashSet(s(dm, 10)), constraintManager.getCOInterferingStations(s(dm, 9), 10));
// Test ADJ-2 constraints
assertEquals(Sets.newHashSet(s(dm, 9)), constraintManager.getADJplusTwoInterferingStations(s(dm, 10), 98));
assertEquals(Sets.newHashSet(s(dm, 10)), constraintManager.getCOInterferingStations(s(dm, 9), 98));
assertEquals(Sets.newHashSet(s(dm, 10)), constraintManager.getCOInterferingStations(s(dm, 9), 99));
assertEquals(Sets.newHashSet(s(dm, 10)), constraintManager.getCOInterferingStations(s(dm, 9), 100));
assertEquals(Sets.newHashSet(s(dm, 9)), constraintManager.getADJplusOneInterferingStations(s(dm, 10), 99));
assertEquals(Sets.newHashSet(s(dm, 9)), constraintManager.getADJplusOneInterferingStations(s(dm, 10), 98));
}
}
@Test
public void testConstraints() throws Exception {
IConstraintManager cm = getConstraintManager();
IStationManager dm = getDomainManager();
// simple CO
assertEquals(Sets.newHashSet(s(dm, 2), s(dm, 3)), cm.getCOInterferingStations(s(dm, 1), 1));
// adj+1 and implied CO
assertEquals(Sets.newHashSet(s(dm, 2)), cm.getCOInterferingStations(s(dm, 1), 7));
assertEquals(Sets.newHashSet(s(dm, 2)), cm.getCOInterferingStations(s(dm, 1), 8));
assertEquals(Sets.newHashSet(s(dm, 2)), cm.getADJplusOneInterferingStations(s(dm, 1), 7));
// adj+2 and implied adj+2 and implied CO
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getCOInterferingStations(s(dm, 5), 99));
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getCOInterferingStations(s(dm, 5), 100));
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getCOInterferingStations(s(dm, 5), 101));
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getADJplusOneInterferingStations(s(dm, 5), 99));
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getADJplusOneInterferingStations(s(dm, 5), 100));
assertEquals(Sets.newHashSet(s(dm, 6)), cm.getADJplusTwoInterferingStations(s(dm, 5), 99));
// test some negative examples
assertEquals(new HashSet<Station>(), cm.getCOInterferingStations(s(dm, 2), 1));
assertEquals(new HashSet<Station>(), cm.getCOInterferingStations(s(dm, 2), 777));
assertEquals(new HashSet<Station>(), cm.getADJplusTwoInterferingStations(s(dm, 5), 100));
}
@Test
public void testIsSatisfyingAssignment() throws Exception {
IConstraintManager cm = getConstraintManager();
IStationManager dm = getDomainManager();
final ImmutableMap<Integer, Set<Station>> badAssignmentViolatesCo = ImmutableMap.<Integer, Set<Station>>builder()
.put(1, Sets.newHashSet(s(dm, 1), s(dm, 2))).build();
assertFalse(cm.isSatisfyingAssignment(badAssignmentViolatesCo));
final ImmutableMap<Integer, Set<Station>> goodAssignment = ImmutableMap.<Integer, Set<Station>>builder()
.put(1, Sets.newHashSet(s(dm, 1)))
.put(2, Sets.newHashSet(s(dm, 2)))
.build();
assertTrue(cm.isSatisfyingAssignment(goodAssignment));
}
@Test
public void testGetRelevantConstraints() throws Exception {
IConstraintManager cm = getConstraintManager();
IStationManager dm = getDomainManager();
final ImmutableMap<Station, Set<Integer>> oneAndTwoAdj = ImmutableMap.<Station, Set<Integer>>builder()
.put(s(dm, 1), Sets.newHashSet(7, 8))
.put(s(dm, 2), Sets.newHashSet(7, 8))
.build();
final ArrayList<Constraint> constraints = Lists.newArrayList(cm.getAllRelevantConstraints(oneAndTwoAdj));
assertEquals(3, constraints.size());
assertTrue(constraints.contains(new Constraint(s(dm, 1), s(dm, 2), 7, 7)));
assertTrue(constraints.contains(new Constraint(s(dm, 1), s(dm, 2), 8, 8)));
assertTrue(constraints.contains(new Constraint(s(dm, 1), s(dm, 2), 7, 8)));
final ImmutableMap<Station, Set<Integer>> oneAndTwoNoIssue = ImmutableMap.<Station, Set<Integer>>builder()
.put(s(dm, 1), Sets.newHashSet(7, 8))
.put(s(dm, 2), Sets.newHashSet(1))
.build();
final ArrayList<Constraint> constraints2 = Lists.newArrayList(cm.getAllRelevantConstraints(oneAndTwoNoIssue));
assertTrue(constraints2.isEmpty());
final ImmutableMap<Station, Set<Integer>> fiveSixAdjTwo = ImmutableMap.<Station, Set<Integer>>builder()
.put(s(dm, 5), Sets.newHashSet(99))
.put(s(dm, 6), Sets.newHashSet(101))
.build();
final ArrayList<Constraint> constraints3 = Lists.newArrayList(cm.getAllRelevantConstraints(fiveSixAdjTwo));
assertEquals(1, constraints3.size());
assertTrue(constraints3.contains(new Constraint(s(dm, 5), s(dm, 6), 99, 101)));
}
protected static Station s(IStationManager stationManager, int id) {
return stationManager.getStationfromID(id);
}
}
| 8,711
| 50.247059
| 181
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/TestConstraint.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/TestConstraint.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.Data;
/**
* Created by newmanne on 08/07/15.
*/
@Data
public class TestConstraint {
private final ConstraintKey key;
private final int channel;
private final Station reference;
private final Set<Station> interfering;
}
| 1,204
| 29.897436
| 86
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/GraphBackedConstraintManager.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/GraphBackedConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.util.Collections;
import java.util.Set;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* A mock ConstraintManager useful for running tests where the focus is on the shape of interference constraint graphs
* between stations.
* @author pcernek
*/
public class GraphBackedConstraintManager extends AConstraintManager {
private final NeighborIndex<Station, DefaultEdge> coInterferingStationNeighborIndex;
private final NeighborIndex<Station, DefaultEdge> adjInterferingStationNeighborIndex;
private final SimpleGraph<Station, DefaultEdge> coInterferingStationGraph;
private final SimpleGraph<Station, DefaultEdge> adjInterferingStationGraph;
/**
* Creates a constraint manager backed by the given interference graphs.
* @param coInterferingStationGraph - the graph representing CO interfering stations.
* @param adjInterferingStationGraph - the graph representing ADJ interfering stations.
*/
public GraphBackedConstraintManager(SimpleGraph<Station, DefaultEdge> coInterferingStationGraph,
SimpleGraph<Station, DefaultEdge> adjInterferingStationGraph) {
this.coInterferingStationGraph = coInterferingStationGraph;
this.adjInterferingStationGraph = adjInterferingStationGraph;
this.coInterferingStationNeighborIndex = new NeighborIndex<>(coInterferingStationGraph);
this.adjInterferingStationNeighborIndex = new NeighborIndex<>(adjInterferingStationGraph);
}
public GraphBackedConstraintManager(SimpleGraph<Station, DefaultEdge> coInterferingStationGraph) {
this(coInterferingStationGraph, new SimpleGraph<Station, DefaultEdge>(DefaultEdge.class));
}
/**
* Returns the set of all stations neighboring the given station in the underlying graph representing interference
* constraints between stations on the same channel.
* @param aStation -the station for which to return the set of CO-interfering stations.
* @param aChannel - this parameter is ignored, since the constraint graph has been defined explicitly in the construction
* of this constraint manager. It is retained for compatibility with the interface.
* @return the set of stations which, if they were on the same channel as the given station, would interfere with it.
*/
@Override
public Set<Station> getCOInterferingStations(Station aStation, int aChannel) {
if (this.coInterferingStationGraph.containsVertex(aStation)) {
return this.coInterferingStationNeighborIndex.neighborsOf(aStation);
}
return Collections.emptySet();
}
/**
* Returns the set of all stations neighboring the given station in the underlying graph representing interference
* constraints between stations on adjacent channels.
* @param aStation -the station for which to return the set of ADJ-interfering stations.
* @param aChannel - this parameter is ignored, since the constraint graph has been defined explicitly in the construction
* of this constraint manager. It is retained for compatibility with the interface.
* @return the set of stations which, if they were on a channel adjacent to the channel of the given station,
* would interfere with it.
*/
@Override
public Set<Station> getADJplusOneInterferingStations(Station aStation, int aChannel) {
if (this.adjInterferingStationGraph.containsVertex(aStation)) {
return this.adjInterferingStationNeighborIndex.neighborsOf(aStation);
}
return Collections.emptySet();
}
@Override
public Set<Station> getADJplusTwoInterferingStations(Station aStation, int aChannel) {
return Collections.emptySet();
}
@Override
public String getConstraintHash() {
throw new UnsupportedOperationException();
}
}
| 4,844
| 42.648649
| 126
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/GraphBackedConstraintManagerTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/GraphBackedConstraintManagerTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Collections2;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.test.GraphLoader;
public class GraphBackedConstraintManagerTest {
GraphLoader graphLoader;
int ARBITRARY_CHANNEL = 42;
@Before
public void setUp() throws Exception {
graphLoader = new GraphLoader();
graphLoader.loadAllGraphs();
}
/**
* Ensure that a station with no neighbors has no interfering stations.
*/
@Test
public void testNoNeighborsHasNoInterferingStations () throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getNoNeighbors(), graphLoader.getNoNeighbors());
assertTrue(cm.getCOInterferingStations(new Station(0), ARBITRARY_CHANNEL).isEmpty());
assertTrue(cm.getADJplusOneInterferingStations(new Station(0), ARBITRARY_CHANNEL).isEmpty());
}
@Test
public void testGetCOInterferingStations() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getBigConnectedGraph(), graphLoader.getBigConnectedGraph());
// Ensure that output is what we expect for a toy example
Set<Station> neighbors = new HashSet<>(Arrays.asList(new Station(6), new Station(8), new Station(0)));
assertTrue(cm.getCOInterferingStations(new Station(2), ARBITRARY_CHANNEL).equals(neighbors));
// Ensure that the empty set is correctly returned
// for stations that are not in the interference graph being queried
assertTrue(cm.getCOInterferingStations(new Station(99), ARBITRARY_CHANNEL).isEmpty());
}
@Test
public void testGetADJInterferingStations() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getBigConnectedGraph(), graphLoader.getBigConnectedGraph());
// Ensure that output is what we expect for a toy example
Set<Station> neighbors = new HashSet<>(Arrays.asList(new Station(6), new Station(8), new Station(0)));
assertTrue(cm.getADJplusOneInterferingStations(new Station(2), ARBITRARY_CHANNEL).equals(neighbors));
// Ensure that the empty set is correctly returned
// for stations that are not in the interference graph being queried
assertTrue(cm.getADJplusOneInterferingStations(new Station(99), ARBITRARY_CHANNEL).isEmpty());
}
/**
* CO graph only: In the most basic case, an assignment that puts two neighbors on the same channel is not SAT.
*/
@Test
public void testNeighborsOnSameChannel() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getHubAndSpoke(), graphLoader.getEmptyGraph());
Map<Integer, Set<Station>> assignment = new HashMap<>();
HashSet<Station> interferingStations = new HashSet<>(Arrays.asList(new Station(0), new Station(1)));
HashSet<Station> nonInterferingStations = new HashSet<>(Arrays.asList(new Station(2), new Station(3), new Station(4), new Station(5)));
assignment.put(13, interferingStations);
assignment.put(14, nonInterferingStations);
assertTrue(!cm.isSatisfyingAssignment(assignment));
}
/**
* Even when the CO graph is fully connected, if each station is on a separate channel, then the assignment is SAT.
*/
@Test
public void testAllDifferentChannels() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getClique(), graphLoader.getEmptyGraph());
Map<Integer, Set<Station>> assignment = new HashMap<>();
assignment.put(11, Collections.singleton(new Station(0)));
assignment.put(12, Collections.singleton(new Station(1)));
assignment.put(13, Collections.singleton(new Station(2)));
assignment.put(14, Collections.singleton(new Station(3)));
assignment.put(15, Collections.singleton(new Station(4)));
assignment.put(16, Collections.singleton(new Station(5)));
assertTrue(cm.isSatisfyingAssignment(assignment));
}
/**
* CO graph only: Two non-neighbors on the same channel should be SAT.
*/
@Test
public void testNoNeighborsOnSameChannel() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getHubAndSpoke(), graphLoader.getEmptyGraph());
Map<Integer, Set<Station>> assignment = new HashMap<>();
HashSet<Station> sameChannelButNotNeighbors = new HashSet<>(Arrays.asList(new Station(1), new Station(2)));
assignment.put(13, sameChannelButNotNeighbors);
assignment.put(11, Collections.singleton(new Station(0)));
assignment.put(14, Collections.singleton(new Station(3)));
assignment.put(15, Collections.singleton(new Station(4)));
assignment.put(16, Collections.singleton(new Station(5)));
assertTrue(cm.isSatisfyingAssignment(assignment));
}
/**
* ADJ graph only: Neighbors assigned to the bottom channel and the next channel up should fail.
*/
@Test
public void testNeighborsOnBottomTwoChannels() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getEmptyGraph(), graphLoader.getHubAndSpoke());
Map<Integer, Set<Station>> assignment = new HashMap<>();
assignment.put(11, Collections.singleton(new Station(0)));
assignment.put(12, Collections.singleton(new Station(1)));
assignment.put(14, Collections.singleton(new Station(2)));
assignment.put(16, Collections.singleton(new Station(3)));
assignment.put(18, Collections.singleton(new Station(4)));
assignment.put(20, Collections.singleton(new Station(5)));
assertTrue(!cm.isSatisfyingAssignment(assignment));
}
/**
* ADJ graph only: Neighbors assigned to the top channel and the next channel down should fail.
*/
@Test
public void testNeighborsOnTopTwoChannels() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getEmptyGraph(), graphLoader.getHubAndSpoke());
Map<Integer, Set<Station>> assignment = new HashMap<>();
assignment.put(22, Collections.singleton(new Station(0)));
assignment.put(23, Collections.singleton(new Station(1)));
assignment.put(14, Collections.singleton(new Station(2)));
assignment.put(16, Collections.singleton(new Station(3)));
assignment.put(18, Collections.singleton(new Station(4)));
assignment.put(20, Collections.singleton(new Station(5)));
assertTrue(!cm.isSatisfyingAssignment(assignment));
}
/**
* ADJ graph only: Even in a fully connected graph, if all neighbors are at least two channels apart,
* then the assignment is SAT.
*/
@Test
public void testNeighborsTwoChannelsApart() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getEmptyGraph(), graphLoader.getClique());
Map<Integer, Set<Station>> assignment = new HashMap<>();
assignment.put(10, Collections.singleton(new Station(0)));
assignment.put(12, Collections.singleton(new Station(1)));
assignment.put(14, Collections.singleton(new Station(2)));
assignment.put(16, Collections.singleton(new Station(3)));
assignment.put(18, Collections.singleton(new Station(4)));
assignment.put(20, Collections.singleton(new Station(5)));
assertTrue(cm.isSatisfyingAssignment(assignment));
}
/**
* An edgeless graph should recognize every assignment as SAT, even when every station is on the same channel.
*/
@Test
public void edgelessGraphOnSameChannel() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getNoNeighbors(), graphLoader.getNoNeighbors());
Map<Integer, Set<Station>> assignment = new HashMap<>();
Station station0 = new Station(0);
Station station1 = new Station(1);
Station station2 = new Station(2);
Station station3 = new Station(3);
assignment.put(11, new HashSet<>(Arrays.asList(station0, station1, station2, station3)));
assertTrue(cm.isSatisfyingAssignment(assignment));
}
/**
* An edgeless graph should always be SAT, even when the stations are all 1 channel apart.
* This method tests every possible configuration of 4 stations being 1 channel apart.
*/
@Test
public void edgelessGraphOnSameChannelPlus() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getNoNeighbors(), graphLoader.getNoNeighbors());
List<Station> stations = new ArrayList<>(Arrays.asList(new Station(0), new Station(1), new Station(2), new Station(3)));
List<Integer> channels = new ArrayList<>(Arrays.asList(11,12,13,14));
for (List<Integer> channelPermutation : Collections2.orderedPermutations(channels)) {
Map<Integer, Set<Station>> assignment = new HashMap<>();
for (int i=0; i < 4; i++) {
assignment.put(channelPermutation.get(i), Collections.singleton(stations.get(i)));
}
assertTrue(cm.isSatisfyingAssignment(assignment));
}
}
/**
* An empty assignment should pass trivially, regardless of the graph
*/
@Test
public void testEmptyAssignment() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getBigConnectedGraph(), graphLoader.getDisconnectedComponents());
Map<Integer, Set<Station>> assignment = new HashMap<>();
assertTrue(cm.isSatisfyingAssignment(assignment));
}
/**
* An empty graph should pass any assignment trivially, even when all stations are on same channel.
*/
@Test
public void emptyConstraintGraph() throws Exception {
GraphBackedConstraintManager cm = new GraphBackedConstraintManager(graphLoader.getEmptyGraph(), graphLoader.getEmptyGraph());
Map<Integer, Set<Station>> assignment = new HashMap<>();
Station station0 = new Station(0);
Station station1 = new Station(1);
Station station2 = new Station(2);
Station station3 = new Station(3);
assignment.put(11, new HashSet<>(Arrays.asList(station0, station1, station2, station3)));
assertTrue(cm.isSatisfyingAssignment(assignment));
}
}
| 10,947
| 40.003745
| 146
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/SatisfiabilityCacheTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/SatisfiabilityCacheTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.SatisfiabilityCacheFactory;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import containmentcache.util.PermutationUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SatisfiabilityCacheTest {
final Station s1 = new Station(1);
final Station s2 = new Station(2);
final Station s3 = new Station(3);
final Set<Station> UNIVERSE = Sets.newHashSet(s1, s2, s3);
@Test
public void testProveSATBySuperset() throws Exception {
final SatisfiabilityCacheFactory factory = new SatisfiabilityCacheFactory(3, 0);
final ImmutableBiMap<Station, Integer> permutation = PermutationUtils.makePermutation(UNIVERSE);
final ISatisfiabilityCache satisfiabilityCache = factory.create(permutation);
satisfiabilityCache.add(new ContainmentCacheSATEntry(ImmutableMap.of(1, UNIVERSE), permutation));
// Expected superset
final StationPackingInstance instance = new StationPackingInstance(ImmutableMap.of(s1, Sets.newHashSet(1), s2, Sets.newHashSet(1)));
final ContainmentCacheSATResult containmentCacheSATResult = satisfiabilityCache.proveSATBySuperset(instance);
assertTrue(containmentCacheSATResult.isValid());
assertEquals(ImmutableMap.of(1, Sets.newHashSet(s1, s2, s3)), containmentCacheSATResult.getResult());
// No expected superset
final StationPackingInstance instance2 = new StationPackingInstance(ImmutableMap.of(s1, Sets.newHashSet(1), s2, Sets.newHashSet(2)));
final ContainmentCacheSATResult containmentCacheSATResult2 = satisfiabilityCache.proveSATBySuperset(instance2);
assertFalse(containmentCacheSATResult2.isValid());
}
@Test
public void testProveUNSATBySubset() throws Exception {
final SatisfiabilityCacheFactory factory = new SatisfiabilityCacheFactory(3, 0);
final ImmutableBiMap<Station, Integer> permutation = PermutationUtils.makePermutation(UNIVERSE);
final ISatisfiabilityCache satisfiabilityCache = factory.create(permutation);
satisfiabilityCache.add(new ContainmentCacheUNSATEntry(ImmutableMap.of(s1, Sets.newHashSet(15), s2, Sets.newHashSet(15)), permutation));
// Expected subset
final StationPackingInstance instance = new StationPackingInstance(ImmutableMap.of(s1, Sets.newHashSet(15), s2, Sets.newHashSet(15), s3, Sets.newHashSet(15)));
final ContainmentCacheUNSATResult result = satisfiabilityCache.proveUNSATBySubset(instance);
assertTrue(result.isValid());
// No expected subset
final StationPackingInstance instance2 = new StationPackingInstance(ImmutableMap.of(s1, Sets.newHashSet(15)));
final ContainmentCacheUNSATResult result2 = satisfiabilityCache.proveUNSATBySubset(instance2);
assertFalse(result2.isValid());
}
@Test
public void testFilterSAT() throws Exception {
final SatisfiabilityCacheFactory factory = new SatisfiabilityCacheFactory(1, 0);
final ImmutableBiMap<Station, Integer> permutation = PermutationUtils.makePermutation(UNIVERSE);
final ISatisfiabilityCache satisfiabilityCache = factory.create(permutation);
final ContainmentCacheSATEntry c1 = new ContainmentCacheSATEntry(ImmutableMap.of(2, Sets.newHashSet(s1), 3, Sets.newHashSet(s2)), permutation);
final ContainmentCacheSATEntry c2 = new ContainmentCacheSATEntry(ImmutableMap.of(1, UNIVERSE), permutation);
c1.setKey("k1");
c2.setKey("k2");
satisfiabilityCache.add(c1);
satisfiabilityCache.add(c2);
final IStationManager stationManager = new IStationManager() {
@Override
public Set<Station> getStations() {
return UNIVERSE;
}
@Override
public Station getStationfromID(Integer aID) throws IllegalArgumentException {
return new Station(aID);
}
@Override
public Set<Integer> getDomain(Station aStation) {
return Sets.newHashSet(1,2,3);
}
@Override
public String getDomainHash() {
return "whocares";
}
};
List<ContainmentCacheSATEntry> containmentCacheSATEntries = satisfiabilityCache.filterSAT(stationManager, true);
assertEquals(Iterables.getOnlyElement(containmentCacheSATEntries), c1);
containmentCacheSATEntries = satisfiabilityCache.filterSAT(stationManager, true);
assertEquals(containmentCacheSATEntries.size(), 0);
}
}
| 6,051
| 45.553846
| 167
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATEntryTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATEntryTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.ImmutableBiMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Created by emily404 on 5/12/15.
*/
public class ContainmentCacheUNSATEntryTest {
final ImmutableBiMap<Station, Integer> permutation = ImmutableBiMap.of(new Station(1), 1, new Station(2), 2);
/**
* the same entry is not considered less restrictive
*/
@Test
public void isLessRestrictiveSameEntriesTest(){
Map<Station, Set<Integer>> domains = new HashMap<>();
ContainmentCacheUNSATEntry entry = new ContainmentCacheUNSATEntry(domains, permutation);
Assert.assertFalse(entry.isLessRestrictive(entry));
}
/**
* Good case when an entry is truly less restrictive than another entry
*/
@Test
public void lessStationsMoreChannelsTest(){
Map<Station, Set<Integer>> lesResDomains = new HashMap<>();
lesResDomains.put(new Station(1), new HashSet<>(Arrays.asList(19,20)));
ContainmentCacheUNSATEntry lessResEntry = new ContainmentCacheUNSATEntry(lesResDomains, permutation);
Map<Station, Set<Integer>> moreResDomains = new HashMap<>();
moreResDomains.put(new Station(1), new HashSet<>(Arrays.asList(19)));
moreResDomains.put(new Station(2), new HashSet<>(Arrays.asList(19)));
ContainmentCacheUNSATEntry moreResEntry = new ContainmentCacheUNSATEntry(moreResDomains, permutation);
Assert.assertTrue(lessResEntry.isLessRestrictive(moreResEntry));
}
/**
* more stations to pack means it is more restrictive
*/
@Test
public void moreStationTest(){
Map<Station, Set<Integer>> moreStationDomains = new HashMap<>();
moreStationDomains.put(new Station(1), new HashSet<>(Arrays.asList(19,20)));
moreStationDomains.put(new Station(2), new HashSet<>(Arrays.asList(19, 20)));
ContainmentCacheUNSATEntry moreStationEntry = new ContainmentCacheUNSATEntry(moreStationDomains, permutation);
Map<Station, Set<Integer>> lessStationDomains = new HashMap<>();
lessStationDomains.put(new Station(1), new HashSet<>(Arrays.asList(19, 20)));
ContainmentCacheUNSATEntry lessStationEntry = new ContainmentCacheUNSATEntry(lessStationDomains, permutation);
Assert.assertFalse(moreStationEntry.isLessRestrictive(lessStationEntry));
}
/**
* same stations to pack but at least one station has less candidate channels still indicates more restriction
*/
@Test
public void sameStationLessChannelTest(){
Map<Station, Set<Integer>> lessChannelDomains = new HashMap<>();
lessChannelDomains.put(new Station(1), new HashSet<>(Arrays.asList(19)));
ContainmentCacheUNSATEntry moreChannelEntry = new ContainmentCacheUNSATEntry(lessChannelDomains, permutation);
Map<Station, Set<Integer>> moreChannelDomains = new HashMap<>();
moreChannelDomains.put(new Station(1), new HashSet<>(Arrays.asList(19, 20)));
ContainmentCacheUNSATEntry lessChannelEntry = new ContainmentCacheUNSATEntry(moreChannelDomains, permutation);
Assert.assertFalse(moreChannelEntry.isLessRestrictive(lessChannelEntry));
}
/**
* one station contains more candidate channel while the other contains less candidate channels,
* this does not indicate less restrictive
*/
@Test
public void overlapDomainTest(){
Map<Station, Set<Integer>> firstDomains = new HashMap<>();
firstDomains.put(new Station(1), new HashSet<>(Arrays.asList(19,20)));
firstDomains.put(new Station(2), new HashSet<>(Arrays.asList(21)));
ContainmentCacheUNSATEntry firstEntry = new ContainmentCacheUNSATEntry(firstDomains, permutation);
Map<Station, Set<Integer>> secondDomains = new HashMap<>();
secondDomains.put(new Station(1), new HashSet<>(Arrays.asList(19)));
secondDomains.put(new Station(2), new HashSet<>(Arrays.asList(21, 22)));
ContainmentCacheUNSATEntry secondEntry = new ContainmentCacheUNSATEntry(secondDomains, permutation);
Assert.assertFalse(firstEntry.isLessRestrictive(secondEntry));
}
}
| 5,174
| 40.733871
| 118
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATEntryTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATEntryTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.ImmutableBiMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Created by emily404 on 5/12/15.
*/
public class ContainmentCacheSATEntryTest {
// stations and channels
private Station s1 = new Station(1);
private Station s2 = new Station(2);
private Integer c1 = 1;
private Integer c2 = 2;
private Integer c3 = 3;
private ImmutableBiMap<Station, Integer> permutation = ImmutableBiMap.of(s1, 1, s2, 2);
/**
* an entry with same key is not considered the superset
*/
@Test
public void isSupersetSameKeyTest(){
Map<Integer, Set<Station>> asgmnt = new HashMap<>();
ContainmentCacheSATEntry entry = new ContainmentCacheSATEntry(asgmnt, permutation);
Assert.assertFalse(entry.hasMoreSolvingPower(entry));
}
/**
* Good case when an entry is truly superset of than another entry
*/
@Test
public void isSupersetTest(){
Map<Integer, Set<Station>> asgmnt1 = new HashMap<>();
asgmnt1.put(c1, new HashSet<>(Arrays.asList(s1)));
ContainmentCacheSATEntry subsetEntry = new ContainmentCacheSATEntry(asgmnt1, permutation);
Map<Integer, Set<Station>> asgmnt2 = new HashMap<>();
asgmnt2.put(c1, new HashSet<>(Arrays.asList(s1)));
asgmnt2.put(c2, new HashSet<>(Arrays.asList(s2)));
ContainmentCacheSATEntry supersetEntry = new ContainmentCacheSATEntry(asgmnt2, permutation);
Assert.assertTrue(supersetEntry.hasMoreSolvingPower(subsetEntry));
}
/**
* When the assignments are identical, as long as the key differs, they are superset of each other
*/
@Test
public void isSupersetSameAssignmentTest(){
Map<Integer, Set<Station>> asgmnt1 = new HashMap<>();
asgmnt1.put(c1, new HashSet<>(Arrays.asList(s1)));
ContainmentCacheSATEntry e1 = new ContainmentCacheSATEntry(asgmnt1, permutation);
Map<Integer, Set<Station>> asgmnt2 = new HashMap<>();
asgmnt2.put(c1, new HashSet<>(Arrays.asList(s1)));
ContainmentCacheSATEntry e2 = new ContainmentCacheSATEntry(asgmnt2, permutation);
Assert.assertTrue(e1.hasMoreSolvingPower(e2));
Assert.assertTrue(e2.hasMoreSolvingPower(e1));
}
/**
* The assignments don't align at all, they are not superset of each other
*/
@Test
public void isNotSupersetTest(){
Map<Integer, Set<Station>> asgmnt1 = new HashMap<>();
asgmnt1.put(c1, new HashSet<>(Arrays.asList(s1)));
ContainmentCacheSATEntry e1 = new ContainmentCacheSATEntry(asgmnt1, permutation);
Map<Integer, Set<Station>> asgmnt2 = new HashMap<>();
asgmnt2.put(c1, new HashSet<>(Arrays.asList(s2)));
ContainmentCacheSATEntry e2 = new ContainmentCacheSATEntry(asgmnt2, permutation);
Assert.assertFalse(e1.hasMoreSolvingPower(e2));
Assert.assertFalse(e2.hasMoreSolvingPower(e1));
}
/**
* The channels in assignments do not align, they are not supersets of each other
*/
@Test
public void offChannelTest(){
Map<Integer, Set<Station>> asgmnt1 = new HashMap<>();
asgmnt1.put(c1, new HashSet<>(Arrays.asList(s1)));
asgmnt1.put(c2, new HashSet<>(Arrays.asList(s2)));
ContainmentCacheSATEntry e1 = new ContainmentCacheSATEntry(asgmnt1, permutation);
Map<Integer, Set<Station>> asgmnt2 = new HashMap<>();
asgmnt2.put(c1, new HashSet<>(Arrays.asList(s1)));
asgmnt2.put(c3, new HashSet<>(Arrays.asList(s2)));
ContainmentCacheSATEntry e2 = new ContainmentCacheSATEntry(asgmnt2, permutation);
Assert.assertFalse(e1.hasMoreSolvingPower(e2));
Assert.assertFalse(e2.hasMoreSolvingPower(e1));
}
}
| 4,801
| 35.378788
| 102
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/SimpleStationGraphParser.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/SimpleStationGraphParser.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* <p>
* Reads a text file that represents a simple graph, where each line in the file represents an edge
* between two nodes, and each node is designated by an integer. Nodes are separated by a space.
* Nodes are interpreted to represent stations; each numerical node is used to construct a Station,
* where Stations are defined completely by a single integer. Lines starting with '//' are interpreted
* as comments. Blank lines are also ignored.
* </p>
*
* <p>
* Note that in certain situations, one station needs to be designated as a starting point in a search.
* For such cases, node number 0 is reserved to represent this node.
* </p>
*
* <p> Example contents of a simple graph file:
* <pre>
* // The first line of this graph file is commented out.
* 1 0
* 3
*
* 1 2
* </pre></p>
*
* <p>
* This example graph file represents a graph consisting of stations 0, 1, 2, and 3, with edges between
* stations 1 and 0, and between stations 1 and 2. Station 3 is not connected to any other station.
* </p>
*
* @author pcernek
*/
public class SimpleStationGraphParser implements IStationGraphFileParser {
private final SimpleGraph<Station, DefaultEdge> stationGraph;
/**
* Returns a SimpleGraphBuilder that reads from a file that specifies a graph of the interference
* constraints between stations. The SimpleGraphBuilder tries to build a graph from the specified file
* immediately upon construction.
*
* @param graphFilePath - path to the graph file, relative to the project's resources directory.
* @throws IOException - if an error occurs when trying to read from the graph file, either due to
* a bad file path or due to a graph file whose contents are malformed.
*/
public SimpleStationGraphParser(Path graphFilePath) throws IOException {
this.stationGraph = parseGraphFile(graphFilePath);
}
/**
* Parse the given graph file and produce a simple graph.
* @param graphPath - the file containing a representation of a simple undirected graph.
* @return - the simple graph.
*/
private SimpleGraph<Station, DefaultEdge> parseGraphFile(Path graphPath) throws IOException {
SimpleGraph<Station, DefaultEdge> stationGraph = new SimpleGraph<>(DefaultEdge.class);
for (String line: Files.readAllLines(graphPath)) {
// Filter out comment lines.
if (line.startsWith("//") || line.isEmpty()) {
continue;
}
// Make stations from current line.
List<Station> currentStations = Stream.of(line.split(" ")) // stations on the same line are space-separated
.map(Integer::new)
.map(Station::new)
.collect(Collectors.toList());
// Make sure line contains no more than two stations.
if (currentStations.size() <= 2) {
currentStations.forEach(stationGraph::addVertex);
if (currentStations.size() == 2)
stationGraph.addEdge(currentStations.get(0), currentStations.get(1));
}
else {
throw new IOException("Graph file is malformed, each line should contain no more than two integers");
}
}
return stationGraph;
}
@Override
public SimpleGraph<Station, DefaultEdge> getStationGraph() {
return this.stationGraph;
}
}
| 4,639
| 35.825397
| 120
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/StationWholeSetSATCertifier.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/StationWholeSetSATCertifier.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jgrapht.alg.ConnectivityInspector;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.IStationSubsetCertifier;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Returns SAT when (and only when) all the stations in the instance of a station packing problem are contained in the
* "toPackStations" parameter (i.e. when the group of neighbors around a starting point has extended to include every
* station in the instance).
* @author pcernek
*/
public class StationWholeSetSATCertifier implements IStationSubsetCertifier {
private int numberOfTimesCalled;
private final Map < ConnectivityInspector<Station, DefaultEdge> ,
SimpleGraph<Station,DefaultEdge> > inspectorGraphMap;
private final Set<Station> startingStations;
public StationWholeSetSATCertifier(List<SimpleGraph<Station, DefaultEdge>> graphs, Set<Station> startingStations) {
this.numberOfTimesCalled = 0;
this.inspectorGraphMap = new HashMap<>();
for (SimpleGraph<Station, DefaultEdge> graph : graphs) {
this.inspectorGraphMap.put(new ConnectivityInspector<>(graph), graph);
}
this.startingStations = startingStations;
}
@Override
public SolverResult certify(StationPackingInstance aInstance, Set<Station> aToPackStations, ITerminationCriterion aTerminationCriterion, long aSeed) {
numberOfTimesCalled ++;
boolean allNeighborsIncluded = true;
for(Station station: startingStations) {
for (ConnectivityInspector<Station, DefaultEdge> inspector: inspectorGraphMap.keySet()) {
if (inspectorGraphMap.get(inspector).containsVertex(station)) {
allNeighborsIncluded &= aToPackStations.containsAll(inspector.connectedSetOf(station));
}
}
}
if (allNeighborsIncluded) {
return new SolverResult(SATResult.SAT, 0, new HashMap<>(), SolvedBy.UNKNOWN);
}
// We return TIMEOUT rather than UNSAT in keeping with the behavior of {@link: StationSubsetSATCertifier}
return SolverResult.createTimeoutResult(0);
}
public int getNumberOfTimesCalled() {
return numberOfTimesCalled;
}
}
| 3,601
| 39.931818
| 154
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/AugmentIntegrationTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/AugmentIntegrationTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.Pair;
import org.junit.Ignore;
import org.junit.Test;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.SATFCFacadeTests;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.CSVStationDB;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.base.InstanceParameters;
import ca.ubc.cs.beta.stationpacking.facade.AutoAugmentOptions;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacade;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.SATFCResult;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 29/06/15.
*/
@Slf4j
public class AugmentIntegrationTest {
final int clearingTarget = 38;
final int numStartingStations = 670;
final String interference = "/ubc/cs/research/arrow/satfc/public/interference/021814SC3M";
final String popFile = "/ubc/cs/research/arrow/satfc/public/interference/021814SC3M/Station_Info.csv";
@Test
@Ignore
public void driver() throws Exception {
final SATFCFacadeBuilder b = new SATFCFacadeBuilder();
try (SATFCFacade facade = b.build()) {
final IStationManager manager = new DomainStationManager(interference + File.separator + DataManager.DOMAIN_FILE);
log.info("Finding starting state with {} stations", numStartingStations);
final SATFCAugmentState state = getState(manager, facade);
facade.augment(getDomains(manager), state.getAssignment(), new CSVStationDB(popFile), interference, 60.0);
}
}
@Ignore
@Test
public void testAutoAugment() throws Exception {
final SATFCFacadeBuilder b = new SATFCFacadeBuilder();
b.setServerURL("http://localhost:8040/satfcserver");
b.setAutoAugmentOptions(AutoAugmentOptions.builder()
.augment(true)
.augmentCutoff(15.0)
.augmentStationConfigurationFolder(interference)
.idleTimeBeforeAugmentation(10.0)
.pollingInterval(1.0)
.build());
try (SATFCFacade facade = b.build()) {
TimeUnit.MINUTES.sleep(2);
int i = 0;
for (Map.Entry<InstanceParameters, Pair<SATResult, Double>> entry : SATFCFacadeTests.TEST_CASES.entrySet()) {
i++;
log.info("Starting problem " + i);
InstanceParameters testCase = entry.getKey();
Pair<SATResult, Double> expectedResult = entry.getValue();
SATFCResult result = facade.solve(testCase.getDomains(), testCase.getPreviousAssignment(), testCase.Cutoff, testCase.Seed, testCase.fDataFoldername);
assertEquals(expectedResult.getFirst(), result.getResult());
if (result.getRuntime() > expectedResult.getSecond()) {
log.warn("[WARNING] Test case " + testCase.toString() + " took more time (" + result.getRuntime() + ") than expected (" + expectedResult.getSecond() + ").");
}
}
}
TimeUnit.MINUTES.sleep(1);
}
Map<Integer, Set<Integer>> getDomains(IStationManager manager) {
final Map<Integer, Set<Integer>> domains = new HashMap<>();
manager.getStations().stream().forEach(s -> {
final Set<Integer> collect = manager.getDomain(s).stream().filter(c -> c >= StationPackingUtils.UHFmin && c <= clearingTarget).collect(Collectors.toSet());
if (!collect.isEmpty()) {
domains.put(s.getID(), collect);
}
});
return domains;
}
private SATFCAugmentState getState(IStationManager manager, SATFCFacade facade) {
while (true) {
List<Station> stations = new ArrayList<>(manager.getStations());
Collections.shuffle(stations);
final List<Integer> stationsInStartingState = stations.subList(0, numStartingStations).stream().map(Station::getID).collect(Collectors.toList());
// Solve the initial problem
final Map<Integer, Set<Integer>> integerSetMap = Maps.filterKeys(getDomains(manager), new Predicate<Integer>() {
@Override
public boolean apply(Integer input) {
return stationsInStartingState.contains(input);
}
});
final SATFCResult solve = facade.solve(integerSetMap, new HashMap<>(), 60.0, 1, interference);
if (solve.getResult().equals(SATResult.SAT)) {
log.info("Can use this as starting state");
return new SATFCAugmentState(integerSetMap, solve.getWitnessAssignment());
} else {
log.info("Do over");
}
}
}
@Data
public static class SATFCAugmentState {
private final Map<Integer, Set<Integer>> domains;
private final Map<Integer, Integer> assignment;
}
}
| 6,574
| 41.419355
| 177
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/IStationGraphFileParser.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/IStationGraphFileParser.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.test;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* <p>
* Builds a graph that represents a set of stations, where an edge between two stations
* indicates an interference constraint between them.
* </p>
* @author pcernek
*/
public interface IStationGraphFileParser {
/**
* Provide a graph of stations that represents the interference constraints between them.
* @return - a graph of stations.
*/
SimpleGraph<Station, DefaultEdge> getStationGraph();
}
| 1,433
| 30.866667
| 93
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/GraphLoader.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/test/GraphLoader.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.test;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* A class that lazily loads graphs to make them accessible to any other class.
* @author pcernek
*
*/
public class GraphLoader {
private SimpleGraph <Station,DefaultEdge> noNeighbors;
private SimpleGraph <Station,DefaultEdge> bigConnectedGraph;
private SimpleGraph <Station,DefaultEdge> clique;
private SimpleGraph <Station,DefaultEdge> hubAndSpoke;
private SimpleGraph <Station,DefaultEdge> longChainOfNeighbors;
private SimpleGraph <Station,DefaultEdge> bipartiteGraph;
private SimpleGraph <Station,DefaultEdge> disconnectedComponents;
private SimpleGraph<Station, DefaultEdge> emptyGraph = new SimpleGraph<>(DefaultEdge.class);
public SimpleGraph<Station, DefaultEdge> getNoNeighbors() throws IOException, URISyntaxException {
return loadSimpleGraph(noNeighbors, "graphs/noNeighbors.txt");
}
public SimpleGraph<Station, DefaultEdge> getBigConnectedGraph() throws IOException, URISyntaxException {
return loadSimpleGraph(bigConnectedGraph, "graphs/bigConnectedGraph.txt");
}
public SimpleGraph<Station, DefaultEdge> getClique() throws IOException, URISyntaxException {
return loadSimpleGraph(clique, "graphs/clique.txt");
}
public SimpleGraph<Station, DefaultEdge> getHubAndSpoke() throws IOException, URISyntaxException {
return loadSimpleGraph(hubAndSpoke, "graphs/hubAndSpoke.txt");
}
public SimpleGraph<Station, DefaultEdge> getLongChainOfNeighbors() throws IOException, URISyntaxException {
return loadSimpleGraph(longChainOfNeighbors, "graphs/longChainOfNeighbors.txt");
}
public SimpleGraph<Station, DefaultEdge> getBipartiteGraph() throws IOException, URISyntaxException {
return loadSimpleGraph(bipartiteGraph, "graphs/bipartiteGraph.txt");
}
public SimpleGraph<Station, DefaultEdge> getDisconnectedComponents() throws IOException, URISyntaxException {
return loadSimpleGraph(disconnectedComponents, "graphs/disconnectedComponents.txt");
}
public SimpleGraph<Station, DefaultEdge> getEmptyGraph() {
return emptyGraph;
}
private static SimpleGraph<Station, DefaultEdge> loadSimpleGraph(SimpleGraph<Station, DefaultEdge> graph, String relativePath)
throws IOException, URISyntaxException
{
if(graph == null)
graph = new SimpleStationGraphParser(GraphLoader.resourceLocationToPath(relativePath)).getStationGraph();
return graph;
}
/**
* Loads all the graphs accessible to this GraphLoader. Convenient for ensuring all overhead
* incurred by file I/O happens at one time.
*
* If any graph is ever added to this class, it would be preferable to add a call to a getter for it to this method.
* @throws IOException
* @throws URISyntaxException
*/
public void loadAllGraphs() throws IOException, URISyntaxException
{
getNoNeighbors();
getBigConnectedGraph();
getClique();
getHubAndSpoke();
getLongChainOfNeighbors();
getBipartiteGraph();
getDisconnectedComponents();
}
/**
* Convert a string, specifying a path to a resource file, into a java Path object, suited to file I/O.
* The path is assumed to be relative to the "resources" folder.
* highest directory
* @param resourceLocationString - the relative path to a resource contained in a resource folder.
* @return - a Path object corresponding to the location of that resource file.
* @throws URISyntaxException - if the string passed as an argument cannot be parsed as a valid path.
*/
private static Path resourceLocationToPath(String resourceLocationString) throws URISyntaxException {
return Paths.get(Resources.getResource(resourceLocationString).toURI());
}
}
| 4,904
| 38.878049
| 130
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/consistency/AC3EnforcerTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/consistency/AC3EnforcerTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.consistency;
import static ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ConstraintKey.ADJp1;
import static ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ConstraintKey.CO;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraint;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraintManager;
public class AC3EnforcerTest {
final Station s1 = new Station(1);
final Station s2 = new Station(2);
final Station s3 = new Station(3);
@Test
public void testAC3() throws Exception {
final StationPackingInstance instance = new StationPackingInstance(
ImmutableMap.of(
s1, ImmutableSet.of(1),
s2, ImmutableSet.of(1, 2, 3),
s3, ImmutableSet.of(1, 2, 3)
)
);
List<TestConstraint> constraints = new ArrayList<>();
constraints.add(new TestConstraint(CO, 1, s1, ImmutableSet.of(s2, s3))); // CO,1,1,s1,s2,s3
constraints.add(new TestConstraint(ADJp1, 1, s1, ImmutableSet.of(s2, s3))); // ADJ+1,1,2,s1,s2,s3
IConstraintManager constraintManager = new TestConstraintManager(constraints);
final AC3Enforcer ac3 = new AC3Enforcer(constraintManager);
final AC3Output ac3Output = ac3.AC3(instance);
assertFalse(ac3Output.isNoSolution());
assertEquals(4, ac3Output.getNumReducedChannels());
final Map<Station, Set<Integer>> reducedDomains = ac3Output.getReducedDomains();
assertEquals(ImmutableSet.of(3), reducedDomains.get(s2));
assertEquals(ImmutableSet.of(3), reducedDomains.get(s3));
}
@Test
public void testNoSolution() throws Exception {
final StationPackingInstance instance = new StationPackingInstance(
ImmutableMap.of(
s1, ImmutableSet.of(1),
s2, ImmutableSet.of(1, 2)
)
);
List<TestConstraint> constraints = new ArrayList<>();
constraints.add(new TestConstraint(CO, 1, s1, ImmutableSet.of(s2)));
constraints.add(new TestConstraint(ADJp1, 1, s1, ImmutableSet.of(s2)));
IConstraintManager constraintManager = new TestConstraintManager(constraints);
final AC3Enforcer ac3 = new AC3Enforcer(constraintManager);
final AC3Output ac3Output = ac3.AC3(instance);
assertTrue(ac3Output.isNoSolution());
}
}
| 3,847
| 41.285714
| 105
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/execution/SATFCFacadeTests.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/execution/SATFCFacadeTests.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.execution;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.junit.Test;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.base.InstanceParameters;
import ca.ubc.cs.beta.stationpacking.facade.InterruptibleSATFCResult;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacade;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.SATFCResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SATFCFacadeTests {
//A map taking a (data foldername, domains) pair of string to its expected result in the form of a (SAT result, runtime double) pair.
public final static Map<InstanceParameters, Pair<SATResult, Double>> TEST_CASES = new HashMap<InstanceParameters, Pair<SATResult, Double>>();
//Add in some test cases.
static {
//Non-trivial SAT test case.
TEST_CASES.put(getInstance(new String[]{
"-DATA-FOLDERNAME",
"./src/test/resources/data/021814SC3M",
"-DOMAINS",
"243:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;659:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;770:2,3,4,5,6,7,8,9,10,11,12,13;510:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1867:7,8,9,10,11,12,13;647:7,8,9,10,11,12,13;372:7,8,9,10,11,12,13;1557:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;384:2,3,4,5,6;64:7,8,9,10,11,12,13;1641:7,8,9,10,11,12,13;1086:7,8,9,10,11,12,13;1835:7,8,9,10,11,12,13;684:2,3,4,5,6;626:7,8,9,10,11,12,13;137:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;569:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;522:7,8,9,10,11,12,13;1045:7,8,9,10,11,12,13;1592:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;78:2,3,4,5,6,7,8,9,10,11,12,13;2044:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;528:7,8,9,10,11,12,13;320:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;71:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1356:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;864:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1443:7,8,9,10,11,12,13;1180:7,8,9,10,11,12,13;690:2,3,4,5,6,7,8,9,10,11,12,13;1260:7,8,9,10,11,12,13;1461:7,8,9,10,11,12,13;1310:2,3,4,5,6,7,8,9,10,11,12,13;324:7,8,9,10,11,12,13;59:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;599:7,8,9,10,11,12,13;1268:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;541:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;480:7,8,9,10,11,12,13;815:7,8,9,10,11,12,13;228:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1069:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;949:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;565:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1482:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;840:7,8,9,10,11,12,13;275:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2133:7,8,9,10,11,12,13;646:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1162:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1237:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;84:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;897:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;297:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;19:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1864:7,8,9,10,11,12,13;100:7,8,9,10,11,12,13;1907:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1862:7,8,9,10,11,12,13;1620:7,8,9,10,11,12,13;955:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1373:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1890:7,8,9,10,11,12,13;1752:7,8,9,10,11,12,13;1390:2,3,4,5,6,7,8,9,10,11,12,13;1496:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1510:7,8,9,10,11,12,13;1546:2,3,4,5,6,7,8,9,10,11,12,13;1095:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1100:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;680:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1431:2,3,4,5,6,7,8,9,10,11,12,13;518:7,8,9,10,11,12,13;1657:7,8,9,10,11,12,13;1925:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1340:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1474:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2082:7,8,9,10,11,12,13;1696:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;48:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1729:2,3,4,5,6,7,8,9,10,11,12,13;651:7,8,9,10,11,12,13;263:7,8,9,10,11,12,13;1689:7,8,9,10,11,12,13;505:7,8,9,10,11,12,13;968:7,8,9,10,11,12,13;673:7,8,9,10,11,12,13;2055:7,8,9,10,11,12,13;970:7,8,9,10,11,12,13;2029:2,3,4,5,6,7,8,9,10,11,12,13;170:7,8,9,10,11,12,13;1115:7,8,9,10,11,12,13;728:7,8,9,10,11,12,13;507:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;63:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;439:2,3,4,5,6;1172:7,8,9,10,11,12,13;341:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2113:7,8,9,10,11,12,13;1111:7,8,9,10,11,12,13;449:7,8,9,10,11,12,13;986:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2165:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;379:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2072:7,8,9,10,11,12,13;490:7,8,9,10,11,12,13;1975:7,8,9,10,11,12,13;1783:7,8,9,10,11,12,13;1150:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2060:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1193:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;890:7,8,9,10,11,12,13;1266:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;775:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1247:7,8,9,10,11,12,13;392:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1072:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;784:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1377:7,8,9,10,11,12,13;2010:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1176:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;205:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;845:7,8,9,10,11,12,13;1976:2,3,4,5,6;298:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;352:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2068:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;387:7,8,9,10,11,12,13;1234:7,8,9,10,11,12,13;1587:7,8,9,10,11,12,13;966:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;154:7,8,9,10,11,12,13;459:2,3,4,5,6,7,8,9,10,11,12,13;1651:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2130:7,8,9,10,11,12,13;1566:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;828:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;118:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;994:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1132:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;271:7,8,9,10,11,12,13;918:7,8,9,10,11,12,13;441:7,8,9,10,11,12,13;1667:7,8,9,10,11,12,13;766:7,8,9,10,11,12,13;512:7,8,9,10,11,12,13;1997:2,3,4,5,6;1081:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1358:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1099:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;846:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;533:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;487:7,8,9,10,11,12,13;281:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1413:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;430:7,8,9,10,11,12,13;508:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1188:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1486:2,3,4,5,6,7,8,9,10,11,12,13;279:7,8,9,10,11,12,13;882:7,8,9,10,11,12,13;1882:7,8,9,10,11,12,13;1256:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1019:7,8,9,10,11,12,13;148:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;725:7,8,9,10,11,12,13;1974:7,8,9,10,11,12,13;470:7,8,9,10,11,12,13;867:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;469:7,8,9,10,11,12,13;285:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1929:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2046:7,8,9,10,11,12,13;52:7,8,9,10,11,12,13;915:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1866:7,8,9,10,11,12,13;1263:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2097:7,8,9,10,11,12,13;332:7,8,9,10,11,12,13;422:7,8,9,10,11,12,13;236:7,8,9,10,11,12,13;600:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;328:2,3,4,5,6;1055:7,8,9,10,11,12,13;1982:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1847:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1672:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;254:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1678:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;546:7,8,9,10,11,12,13;1311:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1840:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;374:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;560:7,8,9,10,11,12,13;665:7,8,9,10,11,12,13;2092:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;16:7,8,9,10,11,12,13;708:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1470:7,8,9,10,11,12,13;1030:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1466:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1834:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;6:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;715:7,8,9,10,11,12,13;1653:7,8,9,10,11,12,13;2116:7,8,9,10,11,12,13;107:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1297:2,3,4,5,6,7,8,9,10,11,12,13;942:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1918:2,3,4,5,6,7,8,9,10,11,12,13;1154:7,8,9,10,11,12,13;1769:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;283:7,8,9,10,11,12,13;906:7,8,9,10,11,12,13;577:7,8,9,10,11,12,13;1159:2,3,4,5,6;532:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;950:7,8,9,10,11,12,13;538:7,8,9,10,11,12,13;1582:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1414:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2056:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1198:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1995:7,8,9,10,11,12,13;181:2,3,4,5,6;1556:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;511:7,8,9,10,11,12,13;2140:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1264:7,8,9,10,11,12,13;817:7,8,9,10,11,12,13;81:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2024:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;23:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1151:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;819:2,3,4,5,6;1353:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1865:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;767:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;317:7,8,9,10,11,12,13;1190:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;927:7,8,9,10,11,12,13;1859:7,8,9,10,11,12,13;884:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;645:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;937:7,8,9,10,11,12,13;1758:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1192:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;975:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1547:7,8,9,10,11,12,13;1426:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;603:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1322:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;911:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1451:7,8,9,10,11,12,13;1327:2,3,4,5,6,7,8,9,10,11,12,13;1841:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;891:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1258:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;879:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1318:7,8,9,10,11,12,13;616:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1108:7,8,9,10,11,12,13;2128:7,8,9,10,11,12,13;489:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2170:7,8,9,10,11,12,13;952:2,3,4,5,6,7,8,9,10,11,12,13;1071:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2074:7,8,9,10,11,12,13;42:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1144:2,3,4,5,6;1497:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1585:2,3,4,5,6;1255:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;901:7,8,9,10,11,12,13;591:7,8,9,10,11,12,13;550:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;453:7,8,9,10,11,12,13;58:7,8,9,10,11,12,13;1495:7,8,9,10,11,12,13;400:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;323:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;13:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1521:7,8,9,10,11,12,13;1203:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;98:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1911:7,8,9,10,11,12,13;91:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1683:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;839:7,8,9,10,11,12,13;931:7,8,9,10,11,12,13;523:7,8,9,10,11,12,13;397:2,3,4,5,6,7,8,9,10,11,12,13;408:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;842:7,8,9,10,11,12,13;2005:7,8,9,10,11,12,13;940:7,8,9,10,11,12,13;2096:7,8,9,10,11,12,13;1350:7,8,9,10,11,12,13;2163:2,3,4,5,6,7,8,9,10,11,12,13;1362:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;735:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1594:7,8,9,10,11,12,13;200:7,8,9,10,11,12,13;978:7,8,9,10,11,12,13;1816:7,8,9,10,11,12,13;2038:7,8,9,10,11,12,13;2091:7,8,9,10,11,12,13;1308:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1998:7,8,9,10,11,12,13;1336:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1291:2,3,4,5,6;553:7,8,9,10,11,12,13;92:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;800:7,8,9,10,11,12,13;1406:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;530:7,8,9,10,11,12,13;1183:7,8,9,10,11,12,13;1035:7,8,9,10,11,12,13;1622:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1617:7,8,9,10,11,12,13;935:7,8,9,10,11,12,13;810:7,8,9,10,11,12,13;1947:7,8,9,10,11,12,13;1057:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;75:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;695:2,3,4,5,6,7,8,9,10,11,12,13;1457:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1664:7,8,9,10,11,12,13;1675:7,8,9,10,11,12,13;1775:7,8,9,10,11,12,13;109:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1477:7,8,9,10,11,12,13;1774:7,8,9,10,11,12,13;2158:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1401:7,8,9,10,11,12,13;478:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1004:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1518:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;883:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;7:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;824:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1844:2,3,4,5,6,7,8,9,10,11,12,13;111:7,8,9,10,11,12,13;1378:7,8,9,10,11,12,13;1951:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1942:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;923:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;930:7,8,9,10,11,12,13;801:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1117:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1052:2,3,4,5,6,7,8,9,10,11,12,13;1409:7,8,9,10,11,12,13;2119:7,8,9,10,11,12,13;1550:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;554:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1033:7,8,9,10,11,12,13;2064:7,8,9,10,11,12,13;1643:2,3,4,5,6;1579:7,8,9,10,11,12,13;605:2,3,4,5,6,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;925:2,3,4,5,6;1924:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1363:7,8,9,10,11,12,13;1014:7,8,9,10,11,12,13;1500:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;131:7,8,9,10,11,12,13;1094:7,8,9,10,11,12,13;685:2,3,4,5,6;501:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;77:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2011:7,8,9,10,11,12,13;496:7,8,9,10,11,12,13;1777:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1952:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1627:7,8,9,10,11,12,13;1039:7,8,9,10,11,12,13;1416:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;230:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1647:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;417:7,8,9,10,11,12,13;971:7,8,9,10,11,12,13;1562:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1088:7,8,9,10,11,12,13;1435:2,3,4,5,6;1087:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1139:7,8,9,10,11,12,13;1996:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;468:2,3,4,5,6,7,8,9,10,11,12,13;850:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1803:7,8,9,10,11,12,13;768:7,8,9,10,11,12,13;953:7,8,9,10,11,12,13;1127:7,8,9,10,11,12,13;1059:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1374:7,8,9,10,11,12,13;1166:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2070:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;140:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2030:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1288:7,8,9,10,11,12,13;1748:7,8,9,10,11,12,13;1492:7,8,9,10,11,12,13;873:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1807:7,8,9,10,11,12,13;524:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2047:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;492:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;247:7,8,9,10,11,12,13;545:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2085:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1236:2,3,4,5,6,7,8,9,10,11,12,13;190:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1638:7,8,9,10,11,12,13;957:7,8,9,10,11,12,13;1209:7,8,9,10,11,12,13;403:7,8,9,10,11,12,13;1779:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;437:7,8,9,10,11,12,13;246:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;809:7,8,9,10,11,12,13;1945:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2169:7,8,9,10,11,12,13;2017:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2090:2,3,4,5,6;1174:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;499:7,8,9,10,11,12,13;1493:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;41:7,8,9,10,11,12,13;262:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;450:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;110:7,8,9,10,11,12,13;1104:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1958:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1719:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;836:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;256:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;705:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2168:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;207:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1345:7,8,9,10,11,12,13;1233:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;18:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;936:7,8,9,10,11,12,13;1754:7,8,9,10,11,12,13;87:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1677:7,8,9,10,11,12,13;169:7,8,9,10,11,12,13;1191:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;516:7,8,9,10,11,12,13;1170:7,8,9,10,11,12,13;1330:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1823:7,8,9,10,11,12,13;1633:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;574:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1760:7,8,9,10,11,12,13;1271:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2028:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1354:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1636:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1621:7,8,9,10,11,12,13;1902:2,3,4,5,6,7,8,9,10,11,12,13;675:7,8,9,10,11,12,13;293:7,8,9,10,11,12,13;795:2,3,4,5,6;557:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1694:7,8,9,10,11,12,13;1098:7,8,9,10,11,12,13;1455:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;233:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;814:7,8,9,10,11,12,13;1686:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;756:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1450:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1830:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;976:7,8,9,10,11,12,13;926:2,3,4,5,6;241:7,8,9,10,11,12,13;1282:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;979:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;62:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;83:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1141:7,8,9,10,11,12,13;264:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2089:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1519:7,8,9,10,11,12,13;580:7,8,9,10,11,12,13;862:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1682:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;696:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1580:7,8,9,10,11,12,13;722:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;106:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;826:7,8,9,10,11,12,13;1875:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;25:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;991:7,8,9,10,11,12,13;1734:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;309:7,8,9,10,11,12,13;1910:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;993:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1597:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1376:2,3,4,5,6,7,8,9,10,11,12,13;683:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1831:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2019:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1619:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2080:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;172:7,8,9,10,11,12,13;1423:7,8,9,10,11,12,13;1877:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;881:7,8,9,10,11,12,13;353:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;956:7,8,9,10,11,12,13;2032:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;751:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1444:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;821:7,8,9,10,11,12,13;904:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1855:2,3,4,5,6;644:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1440:2,3,4,5,6,7,8,9,10,11,12,13;1407:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1464:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1228:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2156:7,8,9,10,11,12,13;390:7,8,9,10,11,12,13;1871:7,8,9,10,11,12,13;120:2,3,4,5,6,7,8,9,10,11,12,13;196:7,8,9,10,11,12,13;1761:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1523:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;791:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1250:7,8,9,10,11,12,13;471:2,3,4,5,6,7,8,9,10,11,12,13;1281:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;484:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1421:7,8,9,10,11,12,13;1079:7,8,9,10,11,12,13;248:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;370:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1375:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;399:7,8,9,10,11,12,13;1317:7,8,9,10,11,12,13;45:7,8,9,10,11,12,13;1892:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1299:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1765:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;943:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1802:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;151:7,8,9,10,11,12,13;796:2,3,4,5,6,7,8,9,10,11,12,13;1909:7,8,9,10,11,12,13;649:7,8,9,10,11,12,13;133:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2150:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2131:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;472:7,8,9,10,11,12,13;2127:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1142:7,8,9,10,11,12,13;330:7,8,9,10,11,12,13;1611:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1883:7,8,9,10,11,12,13;1392:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;431:7,8,9,10,11,12,13;1737:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1077:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2094:2,3,4,5,6;1819:2,3,4,5,6;1644:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1824:7,8,9,10,11,12,13;1483:7,8,9,10,11,12,13;284:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2053:7,8,9,10,11,12,13;339:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;395:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;96:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;694:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2118:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1697:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1371:2,3,4,5,6,7,8,9,10,11,12,13;1848:7,8,9,10,11,12,13;491:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;568:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1442:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;3:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1436:7,8,9,10,11,12,13;1815:7,8,9,10,11,12,13;209:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;638:7,8,9,10,11,12,13;674:7,8,9,10,11,12,13;820:7,8,9,10,11,12,13;1293:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2059:7,8,9,10,11,12,13;216:7,8,9,10,11,12,13;729:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;539:7,8,9,10,11,12,13;237:7,8,9,10,11,12,13;40:7,8,9,10,11,12,13;1845:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;481:2,3,4,5,6;1437:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1016:7,8,9,10,11,12,13;1490:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1776:7,8,9,10,11,12,13;1604:7,8,9,10,11,12,13;231:2,3,4,5,6,7,8,9,10,11,12,13;198:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1804:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;833:7,8,9,10,11,12,13;1290:2,3,4,5,6,7,8,9,10,11,12,13;1109:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;701:2,3,4,5,6;1278:7,8,9,10,11,12,13;234:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1164:7,8,9,10,11,12,13;723:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1481:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1333:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;601:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1427:7,8,9,10,11,12,13;878:7,8,9,10,11,12,13;2009:7,8,9,10,11,12,13;983:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1537:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2067:7,8,9,10,11,12,13;946:7,8,9,10,11,12,13;1287:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;870:7,8,9,10,11,12,13;113:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;939:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1948:7,8,9,10,11,12,13;1606:7,8,9,10,11,12,13;1125:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1113:2,3,4,5,6,7,8,9,10,11,12,13;155:7,8,9,10,11,12,13;1028:7,8,9,10,11,12,13;1155:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;33:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;718:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;802:2,3,4,5,6;635:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;592:7,8,9,10,11,12,13;1140:2,3,4,5,6,7,8,9,10,11,12,13;1826:7,8,9,10,11,12,13;404:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1565:7,8,9,10,11,12,13;423:7,8,9,10,11,12,13;899:7,8,9,10,11,12,13;1445:7,8,9,10,11,12,13;2083:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1027:7,8,9,10,11,12,13;1980:2,3,4,5,6,7,8,9,10,11,12,13;1957:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;594:7,8,9,10,11,12,13;1618:7,8,9,10,11,12,13;1720:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;419:7,8,9,10,11,12,13;1917:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1177:7,8,9,10,11,12,13;807:7,8,9,10,11,12,13;335:2,3,4,5,6,7,8,9,10,11,12,13;1858:7,8,9,10,11,12,13;811:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;653:7,8,9,10,11,12,13;1420:7,8,9,10,11,12,13;761:7,8,9,10,11,12,13;365:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1944:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2173:2,3,4,5,6;920:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;834:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1106:7,8,9,10,11,12,13;218:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;299:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;168:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2006:7,8,9,10,11,12,13;147:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1749:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2050:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;929:7,8,9,10,11,12,13;183:7,8,9,10,11,12,13;396:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1799:2,3,4,5,6,7,8,9,10,11,12,13;562:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31"
}),
new Pair<SATResult, Double>(SATResult.SAT, 5.0));
//Non-trivial UNSAT test case.
TEST_CASES.put(getInstance(new String[]{
"-DATA-FOLDERNAME",
"./src/test/resources/data/021814SC3M",
"-DOMAINS",
"243:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;659:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;770:2,3,4,5,6,7,8,9,10,11,12,13;510:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1867:7,8,9,10,11,12,13;647:7,8,9,10,11,12,13;372:7,8,9,10,11,12,13;606:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1557:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;384:2,3,4,5,6;64:7,8,9,10,11,12,13;1641:7,8,9,10,11,12,13;1086:7,8,9,10,11,12,13;1835:7,8,9,10,11,12,13;684:2,3,4,5,6;626:7,8,9,10,11,12,13;137:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;569:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;522:7,8,9,10,11,12,13;1045:7,8,9,10,11,12,13;1592:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;78:2,3,4,5,6,7,8,9,10,11,12,13;2044:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;528:7,8,9,10,11,12,13;320:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;71:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1356:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;864:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1443:7,8,9,10,11,12,13;1180:7,8,9,10,11,12,13;690:2,3,4,5,6,7,8,9,10,11,12,13;1260:7,8,9,10,11,12,13;1461:7,8,9,10,11,12,13;1310:2,3,4,5,6,7,8,9,10,11,12,13;324:7,8,9,10,11,12,13;1188:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;599:7,8,9,10,11,12,13;1268:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;541:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;480:7,8,9,10,11,12,13;815:7,8,9,10,11,12,13;1069:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;565:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1482:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;840:7,8,9,10,11,12,13;275:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2133:7,8,9,10,11,12,13;646:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1162:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;950:7,8,9,10,11,12,13;84:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;897:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;19:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1864:7,8,9,10,11,12,13;100:7,8,9,10,11,12,13;1907:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1862:7,8,9,10,11,12,13;1620:7,8,9,10,11,12,13;955:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1373:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1890:7,8,9,10,11,12,13;1752:7,8,9,10,11,12,13;1390:2,3,4,5,6,7,8,9,10,11,12,13;1510:7,8,9,10,11,12,13;1546:2,3,4,5,6,7,8,9,10,11,12,13;1095:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1100:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;680:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1431:2,3,4,5,6,7,8,9,10,11,12,13;518:7,8,9,10,11,12,13;1657:7,8,9,10,11,12,13;1925:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1340:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1474:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2082:7,8,9,10,11,12,13;1696:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;48:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1729:2,3,4,5,6,7,8,9,10,11,12,13;651:2,3,4,5,6,7,8,9,10,11,12,13;263:7,8,9,10,11,12,13;1689:7,8,9,10,11,12,13;505:7,8,9,10,11,12,13;968:7,8,9,10,11,12,13;673:2,3,4,5,6,7,8,9,10,11,12,13;2055:7,8,9,10,11,12,13;970:7,8,9,10,11,12,13;2029:2,3,4,5,6,7,8,9,10,11,12,13;170:7,8,9,10,11,12,13;1115:7,8,9,10,11,12,13;728:7,8,9,10,11,12,13;507:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;63:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;439:2,3,4,5,6;1172:7,8,9,10,11,12,13;2113:7,8,9,10,11,12,13;1111:7,8,9,10,11,12,13;449:7,8,9,10,11,12,13;986:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2165:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;379:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2072:7,8,9,10,11,12,13;490:7,8,9,10,11,12,13;1975:7,8,9,10,11,12,13;1783:7,8,9,10,11,12,13;1150:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1193:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;890:7,8,9,10,11,12,13;775:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1247:7,8,9,10,11,12,13;392:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1072:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;784:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1377:7,8,9,10,11,12,13;2010:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1176:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;205:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;845:7,8,9,10,11,12,13;1976:2,3,4,5,6;352:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2068:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;387:7,8,9,10,11,12,13;1234:7,8,9,10,11,12,13;1587:7,8,9,10,11,12,13;966:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;154:7,8,9,10,11,12,13;459:2,3,4,5,6,7,8,9,10,11,12,13;1651:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2130:7,8,9,10,11,12,13;1566:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;828:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;118:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;994:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1132:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;271:7,8,9,10,11,12,13;918:7,8,9,10,11,12,13;441:7,8,9,10,11,12,13;1667:7,8,9,10,11,12,13;766:7,8,9,10,11,12,13;512:7,8,9,10,11,12,13;1997:2,3,4,5,6;1081:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1358:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1099:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;846:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;533:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;487:7,8,9,10,11,12,13;281:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1413:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;430:7,8,9,10,11,12,13;508:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;59:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1486:2,3,4,5,6,7,8,9,10,11,12,13;279:7,8,9,10,11,12,13;882:7,8,9,10,11,12,13;1882:7,8,9,10,11,12,13;1256:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1019:7,8,9,10,11,12,13;148:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;725:7,8,9,10,11,12,13;1974:7,8,9,10,11,12,13;470:7,8,9,10,11,12,13;867:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;469:7,8,9,10,11,12,13;285:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1929:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2046:7,8,9,10,11,12,13;52:7,8,9,10,11,12,13;915:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1866:7,8,9,10,11,12,13;1263:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2097:7,8,9,10,11,12,13;332:7,8,9,10,11,12,13;422:7,8,9,10,11,12,13;236:7,8,9,10,11,12,13;600:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;328:2,3,4,5,6;1055:7,8,9,10,11,12,13;1982:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1847:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1672:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;254:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1678:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;546:7,8,9,10,11,12,13;1311:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1840:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;374:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;560:7,8,9,10,11,12,13;665:7,8,9,10,11,12,13;2092:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;16:7,8,9,10,11,12,13;708:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1470:7,8,9,10,11,12,13;1030:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1466:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1834:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;6:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;715:7,8,9,10,11,12,13;1653:7,8,9,10,11,12,13;2116:7,8,9,10,11,12,13;107:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1297:2,3,4,5,6,7,8,9,10,11,12,13;942:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1918:2,3,4,5,6,7,8,9,10,11,12,13;1154:7,8,9,10,11,12,13;1769:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;283:7,8,9,10,11,12,13;906:7,8,9,10,11,12,13;577:7,8,9,10,11,12,13;1159:2,3,4,5,6;532:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1237:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;538:7,8,9,10,11,12,13;1582:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1414:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2056:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1198:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1995:7,8,9,10,11,12,13;181:2,3,4,5,6;1556:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;511:7,8,9,10,11,12,13;2140:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1264:7,8,9,10,11,12,13;817:7,8,9,10,11,12,13;2024:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;23:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1151:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;819:2,3,4,5,6;1353:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1865:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;767:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;317:7,8,9,10,11,12,13;1190:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;927:7,8,9,10,11,12,13;1859:7,8,9,10,11,12,13;884:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;645:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;937:7,8,9,10,11,12,13;1758:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1192:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;975:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1547:7,8,9,10,11,12,13;1426:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;603:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1322:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;911:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1451:7,8,9,10,11,12,13;1327:2,3,4,5,6,7,8,9,10,11,12,13;1841:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1258:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;879:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1318:7,8,9,10,11,12,13;616:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1108:7,8,9,10,11,12,13;2128:7,8,9,10,11,12,13;489:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2170:7,8,9,10,11,12,13;952:2,3,4,5,6,7,8,9,10,11,12,13;1071:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2074:7,8,9,10,11,12,13;1144:2,3,4,5,6;1497:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1585:2,3,4,5,6;1255:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;901:7,8,9,10,11,12,13;591:7,8,9,10,11,12,13;550:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;453:7,8,9,10,11,12,13;58:7,8,9,10,11,12,13;1495:7,8,9,10,11,12,13;400:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;323:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;13:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1521:7,8,9,10,11,12,13;1203:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;98:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1911:7,8,9,10,11,12,13;91:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1683:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;839:7,8,9,10,11,12,13;931:7,8,9,10,11,12,13;523:2,3,4,5,6,7,8,9,10,11,12,13;397:2,3,4,5,6,7,8,9,10,11,12,13;408:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;842:7,8,9,10,11,12,13;2005:7,8,9,10,11,12,13;940:7,8,9,10,11,12,13;2096:7,8,9,10,11,12,13;1350:7,8,9,10,11,12,13;2163:2,3,4,5,6,7,8,9,10,11,12,13;1362:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;735:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1594:7,8,9,10,11,12,13;200:7,8,9,10,11,12,13;978:7,8,9,10,11,12,13;1816:7,8,9,10,11,12,13;2038:7,8,9,10,11,12,13;2091:7,8,9,10,11,12,13;1308:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1998:7,8,9,10,11,12,13;1336:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1291:2,3,4,5,6;553:7,8,9,10,11,12,13;92:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;800:7,8,9,10,11,12,13;1406:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;530:7,8,9,10,11,12,13;1183:7,8,9,10,11,12,13;1035:7,8,9,10,11,12,13;1622:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1617:7,8,9,10,11,12,13;935:7,8,9,10,11,12,13;810:7,8,9,10,11,12,13;1947:7,8,9,10,11,12,13;1057:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;75:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;695:2,3,4,5,6,7,8,9,10,11,12,13;1457:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1664:7,8,9,10,11,12,13;1675:7,8,9,10,11,12,13;1775:7,8,9,10,11,12,13;109:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1477:7,8,9,10,11,12,13;1774:7,8,9,10,11,12,13;2158:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1401:7,8,9,10,11,12,13;478:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1004:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1518:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;883:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;7:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1844:2,3,4,5,6,7,8,9,10,11,12,13;111:7,8,9,10,11,12,13;1378:7,8,9,10,11,12,13;1951:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1942:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;923:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;930:7,8,9,10,11,12,13;801:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1117:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1052:2,3,4,5,6,7,8,9,10,11,12,13;1409:7,8,9,10,11,12,13;2119:7,8,9,10,11,12,13;1550:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;554:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1033:7,8,9,10,11,12,13;2064:7,8,9,10,11,12,13;1643:2,3,4,5,6;1579:7,8,9,10,11,12,13;605:2,3,4,5,6,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;925:2,3,4,5,6;1924:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1363:7,8,9,10,11,12,13;1014:7,8,9,10,11,12,13;1500:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;131:7,8,9,10,11,12,13;1094:7,8,9,10,11,12,13;685:2,3,4,5,6;501:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;77:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2011:7,8,9,10,11,12,13;496:7,8,9,10,11,12,13;1952:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1627:7,8,9,10,11,12,13;1039:7,8,9,10,11,12,13;1416:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;230:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1647:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;417:7,8,9,10,11,12,13;971:7,8,9,10,11,12,13;1562:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1088:7,8,9,10,11,12,13;1435:2,3,4,5,6;1087:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1139:7,8,9,10,11,12,13;1996:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;468:2,3,4,5,6,7,8,9,10,11,12,13;850:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1803:7,8,9,10,11,12,13;768:7,8,9,10,11,12,13;953:7,8,9,10,11,12,13;1127:7,8,9,10,11,12,13;1059:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1374:7,8,9,10,11,12,13;1166:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2070:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;140:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2030:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1288:2,3,4,5,6,7,8,9,10,11,12,13;1748:7,8,9,10,11,12,13;1492:7,8,9,10,11,12,13;873:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1807:7,8,9,10,11,12,13;524:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;492:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;247:7,8,9,10,11,12,13;545:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2085:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;190:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1638:7,8,9,10,11,12,13;957:7,8,9,10,11,12,13;1209:7,8,9,10,11,12,13;403:7,8,9,10,11,12,13;1779:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;437:7,8,9,10,11,12,13;246:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;809:7,8,9,10,11,12,13;1945:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2169:7,8,9,10,11,12,13;2017:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2090:2,3,4,5,6;1174:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;499:7,8,9,10,11,12,13;1493:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;41:7,8,9,10,11,12,13;262:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;450:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;110:7,8,9,10,11,12,13;1104:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1958:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1719:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;836:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;256:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;705:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2168:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;207:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1345:7,8,9,10,11,12,13;1233:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;18:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;936:7,8,9,10,11,12,13;1754:7,8,9,10,11,12,13;1677:7,8,9,10,11,12,13;169:7,8,9,10,11,12,13;1191:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;516:7,8,9,10,11,12,13;1170:7,8,9,10,11,12,13;1330:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1823:7,8,9,10,11,12,13;1633:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;574:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1760:7,8,9,10,11,12,13;2028:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1354:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1636:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1621:7,8,9,10,11,12,13;1902:2,3,4,5,6,7,8,9,10,11,12,13;675:7,8,9,10,11,12,13;293:7,8,9,10,11,12,13;795:2,3,4,5,6;557:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1694:7,8,9,10,11,12,13;1098:7,8,9,10,11,12,13;1455:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;233:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;814:7,8,9,10,11,12,13;1686:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;756:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1450:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;976:7,8,9,10,11,12,13;926:2,3,4,5,6;241:7,8,9,10,11,12,13;1282:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;979:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;83:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1141:7,8,9,10,11,12,13;264:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2089:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1519:7,8,9,10,11,12,13;580:7,8,9,10,11,12,13;862:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1682:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;696:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1580:7,8,9,10,11,12,13;722:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;106:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;826:7,8,9,10,11,12,13;1875:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;25:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;991:7,8,9,10,11,12,13;1734:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;309:7,8,9,10,11,12,13;1910:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;993:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1597:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1376:2,3,4,5,6,7,8,9,10,11,12,13;683:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1831:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2019:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1619:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2080:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;172:7,8,9,10,11,12,13;1423:7,8,9,10,11,12,13;1877:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;881:7,8,9,10,11,12,13;353:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;956:7,8,9,10,11,12,13;2032:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;751:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1444:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;821:7,8,9,10,11,12,13;904:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1855:2,3,4,5,6;1440:2,3,4,5,6,7,8,9,10,11,12,13;1407:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1464:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1228:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2156:7,8,9,10,11,12,13;390:7,8,9,10,11,12,13;1871:7,8,9,10,11,12,13;120:2,3,4,5,6,7,8,9,10,11,12,13;196:7,8,9,10,11,12,13;1761:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1523:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;791:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1250:7,8,9,10,11,12,13;471:2,3,4,5,6,7,8,9,10,11,12,13;1281:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;484:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1421:7,8,9,10,11,12,13;1079:7,8,9,10,11,12,13;248:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;370:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1375:7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;399:7,8,9,10,11,12,13;1317:7,8,9,10,11,12,13;45:7,8,9,10,11,12,13;1892:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1299:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1765:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;943:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1802:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;151:7,8,9,10,11,12,13;796:2,3,4,5,6,7,8,9,10,11,12,13;1909:7,8,9,10,11,12,13;649:7,8,9,10,11,12,13;133:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2150:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2131:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;472:7,8,9,10,11,12,13;2127:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1142:7,8,9,10,11,12,13;330:7,8,9,10,11,12,13;1611:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1883:7,8,9,10,11,12,13;1392:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;431:7,8,9,10,11,12,13;1737:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1077:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2094:2,3,4,5,6;1819:2,3,4,5,6;1644:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1824:7,8,9,10,11,12,13;1483:7,8,9,10,11,12,13;284:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2053:7,8,9,10,11,12,13;339:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;395:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;96:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;694:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2118:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1371:2,3,4,5,6,7,8,9,10,11,12,13;1848:7,8,9,10,11,12,13;491:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;568:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1442:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;3:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1436:7,8,9,10,11,12,13;1815:7,8,9,10,11,12,13;209:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;674:7,8,9,10,11,12,13;820:7,8,9,10,11,12,13;1293:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2059:7,8,9,10,11,12,13;216:7,8,9,10,11,12,13;729:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;539:7,8,9,10,11,12,13;237:7,8,9,10,11,12,13;40:7,8,9,10,11,12,13;1845:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;481:2,3,4,5,6;1437:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1016:7,8,9,10,11,12,13;1490:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1776:7,8,9,10,11,12,13;1604:7,8,9,10,11,12,13;231:2,3,4,5,6,7,8,9,10,11,12,13;198:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1804:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;833:7,8,9,10,11,12,13;1290:2,3,4,5,6,7,8,9,10,11,12,13;1109:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;701:2,3,4,5,6;1278:7,8,9,10,11,12,13;234:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1164:7,8,9,10,11,12,13;723:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1481:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1333:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1427:7,8,9,10,11,12,13;878:7,8,9,10,11,12,13;2009:7,8,9,10,11,12,13;983:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1537:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2067:7,8,9,10,11,12,13;946:7,8,9,10,11,12,13;870:7,8,9,10,11,12,13;113:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;939:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1948:7,8,9,10,11,12,13;1606:7,8,9,10,11,12,13;1125:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1113:2,3,4,5,6,7,8,9,10,11,12,13;155:7,8,9,10,11,12,13;1028:7,8,9,10,11,12,13;1155:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;718:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;802:2,3,4,5,6;635:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;592:7,8,9,10,11,12,13;1140:2,3,4,5,6,7,8,9,10,11,12,13;1826:7,8,9,10,11,12,13;404:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1565:7,8,9,10,11,12,13;423:7,8,9,10,11,12,13;899:7,8,9,10,11,12,13;1445:7,8,9,10,11,12,13;1027:7,8,9,10,11,12,13;1980:2,3,4,5,6,7,8,9,10,11,12,13;1957:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;594:2,3,4,5,6,7,8,9,10,11,12,13;1618:7,8,9,10,11,12,13;1720:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;419:7,8,9,10,11,12,13;1177:7,8,9,10,11,12,13;807:7,8,9,10,11,12,13;335:2,3,4,5,6,7,8,9,10,11,12,13;1858:7,8,9,10,11,12,13;811:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;653:7,8,9,10,11,12,13;1420:7,8,9,10,11,12,13;761:7,8,9,10,11,12,13;365:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1944:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2173:2,3,4,5,6;920:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;834:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1106:7,8,9,10,11,12,13;218:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;299:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;168:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2006:7,8,9,10,11,12,13;147:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1749:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;2050:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;929:7,8,9,10,11,12,13;183:7,8,9,10,11,12,13;396:14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31;1799:2,3,4,5,6,7,8,9,10,11,12,13"
}),
new Pair<SATResult, Double>(SATResult.UNSAT, 5.0));
}
/**
* Parse instance parameters from command line arguments.
*/
private static InstanceParameters getInstance(String[] aArguments) {
InstanceParameters instance = new InstanceParameters();
JCommanderHelper.parseCheckingForHelpAndVersion(aArguments, instance);
return instance;
}
/**
* Create SATFC Facade Executor command line arguments from data folder name and domains arguments.
*/
private static String[] createArguments(String aDataFoldername, Map<Integer, Set<Integer>> aDomains) {
List<String> arguments = new ArrayList<String>();
arguments.add("-DATA-FOLDERNAME");
arguments.add(aDataFoldername);
arguments.add("-DOMAINS");
StringBuilder domainsBuilder = new StringBuilder();
Iterator<Integer> stationsIterator = aDomains.keySet().iterator();
while (stationsIterator.hasNext()) {
Integer station = stationsIterator.next();
domainsBuilder.append(station);
domainsBuilder.append(":");
domainsBuilder.append(StringUtils.join(aDomains.get(station), ","));
if (stationsIterator.hasNext()) {
domainsBuilder.append(";");
}
}
arguments.add(domainsBuilder.toString());
return arguments.toArray(new String[arguments.size()]);
}
/**
* Runs the SATFC facade executor main method on all the test cases.
*/
@Test
public void testFacadeExecution() {
for (InstanceParameters testCase : TEST_CASES.keySet()) {
String dataFoldername = testCase.fDataFoldername;
SATFCFacadeExecutor.main(createArguments(dataFoldername, testCase.getDomains()));
}
}
private SATFCFacade buildFacade() {
return new SATFCFacadeBuilder().build();
}
/**
* Test the facade on all test cases.
*/
@Test
public void testFacade() throws Exception {
@Cleanup
SATFCFacade facade = buildFacade();
int i = 0;
log.info("Solving " + TEST_CASES.size() + " problems");
for (Entry<InstanceParameters, Pair<SATResult, Double>> entry : TEST_CASES.entrySet()) {
i++;
log.info("Starting problem " + i);
InstanceParameters testCase = entry.getKey();
Pair<SATResult, Double> expectedResult = entry.getValue();
SATFCResult result = facade.solve(testCase.getDomains(), testCase.getPreviousAssignment(), testCase.Cutoff, testCase.Seed, testCase.fDataFoldername);
assertEquals(expectedResult.getFirst(), result.getResult());
if (result.getRuntime() > expectedResult.getSecond()) {
log.warn("[WARNING] Test case " + testCase.toString() + " took more time (" + result.getRuntime() + ") than expected (" + expectedResult.getSecond() + ").");
}
}
System.out.println("DONE TEST");
}
@Test
public void testInterrupt() throws Exception {
@Cleanup
SATFCFacade facade = buildFacade();
int i = 0;
for (Entry<InstanceParameters, Pair<SATResult, Double>> entry : TEST_CASES.entrySet()) {
i++;
log.info("Starting problem " + i);
InstanceParameters testCase = entry.getKey();
final InterruptibleSATFCResult interruptibleSATFCResult = facade.solveInterruptibly(testCase.getDomains(), testCase.getPreviousAssignment(), testCase.Cutoff, testCase.Seed, testCase.fDataFoldername);
new Thread() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("interrupting problem");
interruptibleSATFCResult.interrupt();
}
}.start();
final SATFCResult result = interruptibleSATFCResult.computeResult();
assertEquals(SATResult.TIMEOUT, result.getResult());
}
}
}
| 60,905
| 333.648352
| 27,782
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/ASolverBundleTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/ASolverBundleTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Splitter;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.StationPackingTestUtils;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
import ca.ubc.cs.beta.stationpacking.facade.InternalSATFCConfigFile;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder.SATFCLibLocation;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeParameter;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.ManagerBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.ISolverBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.YAMLBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.ConfigFile;
import ca.ubc.cs.beta.stationpacking.polling.PollingService;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 22/05/15.
*/
@Slf4j
public abstract class ASolverBundleTest {
private final String INSTANCE_FILE = "data/ASolverBundleTestInstances.csv";
protected ManagerBundle managerBundle;
public ASolverBundleTest() {
try {
DomainStationManager stationManager = new DomainStationManager(Resources.getResource("data/021814SC3M/Domain.csv").getFile());
ChannelSpecificConstraintManager constraintManager = new ChannelSpecificConstraintManager(stationManager, Resources.getResource("data/021814SC3M/Interference_Paired.csv").getFile());
managerBundle = new ManagerBundle(stationManager, constraintManager, Resources.getResource("data/021814SC3M").getPath());
} catch (FileNotFoundException e) {
Assert.fail("Could not find constraint set files");
}
}
protected abstract String getBundleName();
@Test
public void testSimplestProblemPossible() throws Exception {
final SATFCFacadeParameter parameter = SATFCFacadeParameter.builder().configFile(new ConfigFile(getBundleName(), true)).claspLibrary(SATFCFacadeBuilder.findSATFCLibrary(SATFCLibLocation.CLASP)).satensteinLibrary(SATFCFacadeBuilder.findSATFCLibrary(SATFCLibLocation.SATENSTEIN)).build();
try (final ISolverBundle bundle = new YAMLBundle(managerBundle, parameter, new PollingService(), null)) {
final StationPackingInstance instance = StationPackingTestUtils.getSimpleInstance();
final SolverResult solve = bundle.getSolver(instance).solve(instance, new WalltimeTerminationCriterion(60), 1);
Assert.assertEquals(StationPackingTestUtils.getSimpleInstanceAnswer(), solve.getAssignment()); // There is only one answer to this problem
}
}
@Test
public void testAFewSrpks() throws Exception {
final SATFCFacadeParameter parameter = SATFCFacadeParameter.builder().configFile(new ConfigFile(getBundleName(), true)).claspLibrary(SATFCFacadeBuilder.findSATFCLibrary(SATFCLibLocation.CLASP)).satensteinLibrary(SATFCFacadeBuilder.findSATFCLibrary(SATFCLibLocation.SATENSTEIN)).build();
try (final ISolverBundle bundle = new YAMLBundle(managerBundle, parameter, new PollingService(), null)) {
final List<String> lines = Files.readLines(new File(Resources.getResource(INSTANCE_FILE).getFile()), Charset.defaultCharset());
final Map<String, SATResult> instanceFileToAnswers = new HashMap<>();
lines.stream().forEach(line -> {
final List<String> csvParts = Splitter.on(',').splitToList(line);
instanceFileToAnswers.put(csvParts.get(0), Enum.valueOf(SATResult.class, csvParts.get(1)));
});
for (Map.Entry<String, SATResult> entry : instanceFileToAnswers.entrySet()) {
final Converter.StationPackingProblemSpecs stationPackingProblemSpecs = Converter.StationPackingProblemSpecs.fromStationRepackingInstance(Resources.getResource("data/srpks/" + entry.getKey()).getPath());
final StationPackingInstance instance = StationPackingTestUtils.instanceFromSpecs(stationPackingProblemSpecs, managerBundle.getStationManager());
log.info("Solving instance " + entry.getKey());
final SolverResult solverResult = bundle.getSolver(instance).solve(instance, new WalltimeTerminationCriterion(60), 1);
Assert.assertEquals(entry.getValue(), solverResult.getResult());
}
}
}
public static class SATFCSolverBundleTest extends ASolverBundleTest {
@Override
protected String getBundleName() {
return InternalSATFCConfigFile.SATFC_SEQUENTIAL.getFilename();
}
}
public static class SATFCParallelSolverBundleTest extends ASolverBundleTest {
@Override
protected String getBundleName() {
return InternalSATFCConfigFile.SATFC_PARALLEL.getFilename();
}
}
}
| 6,346
| 48.585938
| 294
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelNoWaitSolverCompositeTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelNoWaitSolverCompositeTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.composites;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import ca.ubc.cs.beta.stationpacking.StationPackingTestUtils;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ParallelNoWaitSolverCompositeTest {
/**
* Run a lot of infinite loop solvers and one auto-return the answer solver
* The good solver should interrupt the infinite loopers
*/
@Test(timeout = 3000)
public void testInterruptOtherSolvers() {
final List<ISolverFactory> solvers = new ArrayList<>();
// We need to have enough threads so that the good solver is run concurrently with the bad solvers
final int nThreads = 11;
for (int i = 0; i < nThreads - 1; i++) {
// create many solvers that loop infinitely
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> {
final Watch watch = Watch.constructAutoStartWatch();
while (!aTerminationCriterion.hasToStop()) {} // infinite loop
return SolverResult.createTimeoutResult(watch.getElapsedTime());
});
}
// construct a solver that just returns the answer immediately
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> new SolverResult(SATResult.SAT, 32.0, StationPackingTestUtils.getSimpleInstanceAnswer(), SolvedBy.UNKNOWN));
final ParallelNoWaitSolverComposite parallelSolverComposite = new ParallelNoWaitSolverComposite(nThreads, solvers);
final SolverResult solve = parallelSolverComposite.solve(StationPackingTestUtils.getSimpleInstance(), new NeverEndingTerminationCriterion(), 1);
assertEquals(SATResult.SAT, solve.getResult());
}
@Test
public void everySolverIsQueriedIfNoOneHasAConclusiveAnswer() {
final List<ISolverFactory> solvers = new ArrayList<>();
final AtomicInteger numCalls = new AtomicInteger(0);
final int N_SOLVERS = 10;
for (int i = 0; i < N_SOLVERS; i++) {
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> {
numCalls.incrementAndGet();
return SolverResult.createTimeoutResult(60.0);
});
}
final ParallelNoWaitSolverComposite parallelSolverComposite = new ParallelNoWaitSolverComposite(1, solvers);
final SolverResult solve = parallelSolverComposite.solve(StationPackingTestUtils.getSimpleInstance(), new NeverEndingTerminationCriterion(), 1);
assertEquals(numCalls.get(), N_SOLVERS); // every solver should be asked
assertEquals(solve.getResult(), SATResult.TIMEOUT);
}
@Test(timeout = 2000)
public void notEverySolverIsWaitedForIfOneHasAConclusiveAnswer() {
final List<ISolverFactory> solvers = new ArrayList<>();
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> new SolverResult(SATResult.SAT, 1.0, ImmutableMap.of(), SolvedBy.UNKNOWN));
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> {
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
return SolverResult.createTimeoutResult(1.0);
});
final ParallelNoWaitSolverComposite parallelSolverComposite = new ParallelNoWaitSolverComposite(1, solvers);
final SolverResult solve = parallelSolverComposite.solve(StationPackingTestUtils.getSimpleInstance(), new NeverEndingTerminationCriterion(), 1);
assertEquals(SATResult.SAT, solve.getResult());
}
@Test(expected = RuntimeException.class)
public void exceptionsPropagateToMainThread() {
final List<ISolverFactory> solvers = new ArrayList<>();
solvers.add(s->(aInstance, aTerminationCriterion, aSeed) -> {
throw new IllegalArgumentException();
});
final ParallelNoWaitSolverComposite parallelSolverComposite = new ParallelNoWaitSolverComposite(1, solvers);
parallelSolverComposite.solve(StationPackingTestUtils.getSimpleInstance(), new NeverEndingTerminationCriterion(), 1);
}
}
| 5,401
| 47.232143
| 176
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/UnderconstrainedStationFinderTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/UnderconstrainedStationFinderTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.underconstrained;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.IntStream;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ConstraintKey;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraint;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
public class UnderconstrainedStationFinderTest {
final Station s1 = new Station(1);
final Station s2 = new Station(2);
final Station s3 = new Station(3);
final Set<Station> stations = Sets.newHashSet(s1, s2, s3);
@Test
public void testGetUnderconstrainedStations() throws Exception {
List<TestConstraint> testConstraints = new ArrayList<>();
stations.stream().forEach(station -> {
// Everyone co-interferes with everyone on the first two channels, no adj constraints
IntStream.rangeClosed(1, 2).forEach(channel -> {
testConstraints.add(new TestConstraint(ConstraintKey.CO, channel, station, Sets.difference(stations, Sets.newHashSet(station))));
});
});
IConstraintManager constraintManager = new TestConstraintManager(testConstraints);
IUnderconstrainedStationFinder finder = new HeuristicUnderconstrainedStationFinder(constraintManager, true);
final Map<Station, Set<Integer>> domains = ImmutableMap.<Station, Set<Integer>>builder()
.put(s1, ImmutableSet.of(1, 2, 3))
.put(s2, ImmutableSet.of(1, 2))
.put(s3, ImmutableSet.of(1, 2))
.build();
final Set<Station> underconstrainedStations = finder.getUnderconstrainedStations(domains, new NeverEndingTerminationCriterion());
// Regardless of how stations 2 and 3 rearrange themselves, station 1 always has a good channel
assertEquals(ImmutableSet.of(s1), underconstrainedStations);
}
}
| 3,228
| 42.053333
| 142
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ConnectedComponentGroupingDecoratorTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ConnectedComponentGroupingDecoratorTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.decorators;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
import ca.ubc.cs.beta.stationpacking.solvers.componentgrouper.IComponentGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
public class ConnectedComponentGroupingDecoratorTest {
@Test
@SuppressWarnings("unchecked")
public void testSplitIntoComponents() {
// should test that solve is called # components times on the decorator for a SAT problem
final long seed = 0;
final ISolver solver = mock(ISolver.class);
final IComponentGrouper grouper = mock(IComponentGrouper.class);
final IConstraintManager constraintManager = mock(IConstraintManager.class);
final ITerminationCriterion terminationCriterion = mock(ITerminationCriterion.class);
final ConnectedComponentGroupingDecorator connectedComponentGroupingDecorator = new ConnectedComponentGroupingDecorator(solver, grouper, constraintManager);
final StationPackingInstance instance = new StationPackingInstance(Maps.newHashMap());
final Set<Station> componentA = mock(Set.class);
final Set<Station> componentB = mock(Set.class);
final Set<Station> componentC = mock(Set.class);
final Set<Set<Station>> components = Sets.newHashSet(componentA, componentB, componentC);
when(grouper.group(instance, constraintManager)).thenReturn(components);
when(solver.solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed))).thenReturn(new SolverResult(SATResult.SAT, 0, new HashMap<>(), SolvedBy.UNKNOWN));
connectedComponentGroupingDecorator.solve(instance, terminationCriterion, seed);
verify(solver, times(components.size())).solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed));
}
@Test
@SuppressWarnings("unchecked")
public void testEarlyStopping() {
// should test that if a problem has 3 UNSAT components, then the code examines only 1 component
final long seed = 0;
final ISolver solver = mock(ISolver.class);
final IComponentGrouper grouper = mock(IComponentGrouper.class);
final IConstraintManager constraintManager = mock(IConstraintManager.class);
final ITerminationCriterion terminationCriterion = mock(ITerminationCriterion.class);
final ConnectedComponentGroupingDecorator connectedComponentGroupingDecorator = new ConnectedComponentGroupingDecorator(solver, grouper, constraintManager);
final StationPackingInstance instance = new StationPackingInstance(Maps.newHashMap());
final Set<Station> componentA = mock(Set.class);
final Set<Station> componentB = mock(Set.class);
final Set<Station> componentC = mock(Set.class);
final Set<Set<Station>> components = Sets.newHashSet(componentA, componentB, componentC);
when(grouper.group(instance, constraintManager)).thenReturn(components);
final SolverResult unsat = SolverResult.createNonSATResult(SATResult.UNSAT, 0, SolvedBy.UNKNOWN);
when(solver.solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed))).thenReturn(unsat);
connectedComponentGroupingDecorator.solve(instance, terminationCriterion, seed);
verify(solver, times(1)).solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed));
}
}
| 5,042
| 48.441176
| 180
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/DelayedSolverDecoratorTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/DelayedSolverDecoratorTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.decorators;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import ca.ubc.cs.beta.stationpacking.StationPackingTestUtils;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
public class DelayedSolverDecoratorTest {
@Test
public void testDelay() throws Exception {
final DelayedSolverDecorator delayedSolverDecorator = new DelayedSolverDecorator(new VoidSolver(), 0.1);
final Watch watch = Watch.constructAutoStartWatch();
delayedSolverDecorator.solve(StationPackingTestUtils.getSimpleInstance(), new WalltimeTerminationCriterion(10), 1);
assertTrue("Watch time was " + watch.getElapsedTime(), watch.getElapsedTime() >= 0.1);
}
@Test
public void testInterrupt() throws Exception {
final Watch watch = Watch.constructAutoStartWatch();
final DelayedSolverDecorator delayedSolverDecorator = new DelayedSolverDecorator(new VoidSolver(), 90);
new Thread() {
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
delayedSolverDecorator.interrupt();
}
}.start();
final SolverResult solve = delayedSolverDecorator.solve(StationPackingTestUtils.getSimpleInstance(), new WalltimeTerminationCriterion(90), 1);
final double time = watch.getElapsedTime();
assertTrue("Watch time was " + time + " expected less since interruption", time <= 1);
}
}
| 2,655
| 40.5
| 150
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PythonAssignmentVerifierDecoratorTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PythonAssignmentVerifierDecoratorTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.decorators;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Map;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.StationPackingTestUtils;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.factories.PythonInterpreterContainer;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import lombok.extern.slf4j.Slf4j;
/**
* Created by emily404 on 9/3/15.
*/
@Slf4j
public class PythonAssignmentVerifierDecoratorTest {
final static ISolver solver = mock(ISolver.class);
static PythonAssignmentVerifierDecorator pythonAssignmentVerifierDecorator;
static PythonAssignmentVerifierDecorator nonCompactPythonAssignmentVerifierDecorator;
final StationPackingInstance instance = new StationPackingInstance(Maps.newHashMap());
final ITerminationCriterion terminationCriterion = mock(ITerminationCriterion.class);
final long seed = 0;
@BeforeClass
public static void setUp() {
final String interferenceFolder = Resources.getResource("data/021814SC3M").getPath();
final boolean compact = true;
pythonAssignmentVerifierDecorator = new PythonAssignmentVerifierDecorator(solver, new PythonInterpreterContainer(interferenceFolder, compact));
nonCompactPythonAssignmentVerifierDecorator = new PythonAssignmentVerifierDecorator(solver, new PythonInterpreterContainer(interferenceFolder, !compact));
}
@Test(expected=IllegalStateException.class)
public void testDomainViolationCompactIntereference() {
Map<Integer,Set<Station>> domainViolationAnswer = ImmutableMap.of(-1, ImmutableSet.of(new Station(1)));
when(solver.solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed)))
.thenReturn(new SolverResult(SATResult.SAT, 0, domainViolationAnswer, SolverResult.SolvedBy.UNKNOWN));
pythonAssignmentVerifierDecorator.solve(instance, terminationCriterion, seed);
}
@Test
public void testNoViolationCompactInterference() {
when(solver.solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed)))
.thenReturn(new SolverResult(SATResult.SAT, 0, StationPackingTestUtils.getSimpleInstanceAnswer(), SolverResult.SolvedBy.UNKNOWN));
SolverResult result = pythonAssignmentVerifierDecorator.solve(instance, terminationCriterion, seed);
assertEquals(result.getAssignment(), StationPackingTestUtils.getSimpleInstanceAnswer());
}
@Test
public void testNoViolationNonCompactInterference() {
when(solver.solve(any(StationPackingInstance.class), eq(terminationCriterion), eq(seed)))
.thenReturn(new SolverResult(SATResult.SAT, 0, StationPackingTestUtils.getSimpleInstanceAnswer(), SolverResult.SolvedBy.UNKNOWN));
SolverResult result = nonCompactPythonAssignmentVerifierDecorator.solve(instance, terminationCriterion, seed);
assertEquals(result.getAssignment(), StationPackingTestUtils.getSimpleInstanceAnswer());
}
}
| 4,567
| 41.296296
| 162
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PreviousAssignmentContainsAnswerDecoratorTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PreviousAssignmentContainsAnswerDecoratorTest.java
|
package ca.ubc.cs.beta.stationpacking.solvers.decorators;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ConstraintKey;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraint;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.TestConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by newmanne on 2016-04-13.
*/
public class PreviousAssignmentContainsAnswerDecoratorTest {
final Station s1 = new Station(1);
final Station s2 = new Station(2);
@Test
public void testPreviousAssignmentSolves() throws Exception {
final IConstraintManager constraintManager = new TestConstraintManager(new ArrayList<>());
final PreviousAssignmentContainsAnswerDecorator decorator = new PreviousAssignmentContainsAnswerDecorator(new VoidSolver(), constraintManager);
final Map<Station, Set<Integer>> domains = new HashMap<>();
domains.put(s1, Sets.newHashSet(1));
final Map<Station, Integer> previousAssignment = ImmutableMap.of(s1, 1);
final StationPackingInstance instance = new StationPackingInstance(domains, previousAssignment);
final SolverResult solve = decorator.solve(instance, new NeverEndingTerminationCriterion(), 0);
Assert.assertEquals(SATResult.SAT, solve.getResult());
}
@Test
public void testPreviousAssignmentDoesNotSolveInvalid() throws Exception{
final IConstraintManager constraintManager = new TestConstraintManager(
Lists.newArrayList(
new TestConstraint(ConstraintKey.CO, 1, s1, Sets.newHashSet(s2))
)
);
final PreviousAssignmentContainsAnswerDecorator decorator = new PreviousAssignmentContainsAnswerDecorator(new VoidSolver(), constraintManager);
final Map<Station, Set<Integer>> domains = new HashMap<>();
domains.put(s1, Sets.newHashSet(1));
domains.put(s2, Sets.newHashSet(1, 2));
Map<Station, Integer> previousAssignment = ImmutableMap.of(s1, 1, s2, 1);
StationPackingInstance instance = new StationPackingInstance(domains, previousAssignment);
SolverResult solve = decorator.solve(instance, new NeverEndingTerminationCriterion(), 0);
Assert.assertEquals(SATResult.TIMEOUT, solve.getResult());
previousAssignment = ImmutableMap.of(s1, 1, s2, 2);
instance = new StationPackingInstance(domains, previousAssignment);
solve = decorator.solve(instance, new NeverEndingTerminationCriterion(), 0);
Assert.assertEquals(SATResult.SAT, solve.getResult());
// Test invalid domain doesn't count
domains.get(s2).remove(2);
instance = new StationPackingInstance(domains, previousAssignment);
solve = decorator.solve(instance, new NeverEndingTerminationCriterion(), 0);
Assert.assertEquals(SATResult.TIMEOUT, solve.getResult());
}
}
| 3,623
| 49.333333
| 151
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResultTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResultTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.base;
import static org.junit.Assert.assertEquals;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SolverResultTest {
@Before
public void setUp() {
Set<Station> s = Sets.newHashSet();
s.add(new Station(3));
result = new SolverResult(SATResult.SAT, 37.4, ImmutableMap.of(3, s), SolvedBy.UNKNOWN);
}
private SolverResult result;
@Test
public void testSerializationDeserializationAreInverses() throws Exception {
assertEquals(result, JSONUtils.toObject(JSONUtils.toString(result), SolverResult.class));
}
}
| 1,774
| 30.696429
| 97
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/ConstraintGraphNeighborhoodPresolverTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/ConstraintGraphNeighborhoodPresolverTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.GraphBackedConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.AddNeighbourLayerStrategy;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.IterativeDeepeningConfigurationStrategy;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.test.GraphLoader;
import ca.ubc.cs.beta.stationpacking.test.StationWholeSetSATCertifier;
/**
* @author pcernek
*/
public class ConstraintGraphNeighborhoodPresolverTest {
GraphLoader graphLoader;
private static final int ARBITRARY_CHANNEL = 42;
private static ITerminationCriterion mockTerminationCriterion;
private static long arbitrarySeed;
@Before
public void setUp() throws Exception {
// This mock termination criterion is never met.
mockTerminationCriterion = new NeverEndingTerminationCriterion();
// Completely random seed; value is not actually used since we never use any actual solvers here
arbitrarySeed = 17;
graphLoader = new GraphLoader();
graphLoader.loadAllGraphs();
}
@Test
public void testEmptyGraph() throws Exception {
// We expect the solver to return immediately since the previous assignment will be empty.
testGraph(graphLoader.getEmptyGraph(), Sets.newHashSet(new Station(3)), 0, SATResult.TIMEOUT);
}
@Test
public void testMaxNumberOfNeighborLayers() throws Exception {
testGraph(graphLoader.getBigConnectedGraph(), graphLoader.getEmptyGraph(), Collections.singleton(new Station(0)),
1, 1, SATResult.TIMEOUT);
testGraph(graphLoader.getBigConnectedGraph(), graphLoader.getEmptyGraph(), Collections.singleton(new Station(0)),
2, 2, SATResult.TIMEOUT);
testGraph(graphLoader.getBigConnectedGraph(), graphLoader.getEmptyGraph(), Collections.singleton(new Station(0)),
3, 3, SATResult.TIMEOUT);
testGraph(graphLoader.getBigConnectedGraph(), graphLoader.getEmptyGraph(), Collections.singleton(new Station(0)),
4, 4, SATResult.SAT);
}
@Test
public void testNoNeighbors() throws Exception {
// When the graph consists of multiple isolated nodes, we expect the neighbor search to run only one layer deep.
testGraph(graphLoader.getNoNeighbors(), new Station(0), 1);
// We expect similar behavior even when we start from two nodes simultaneously
HashSet<Station> startingStations = new HashSet<>(Arrays.asList(new Station(0), new Station(1)));
testGraph(graphLoader.getNoNeighbors(), startingStations, 1);
}
@Test
public void testBigConnectedGraph() throws Exception {
// This serves as a "normal" test case, with one central starting node.
testGraph(graphLoader.getBigConnectedGraph(), new Station(0), 4);
// We also test the case where we start from two nodes at once.
HashSet<Station> startingStations = new HashSet<>(Arrays.asList(new Station(0), new Station(14)));
testGraph(graphLoader.getBigConnectedGraph(), startingStations, 2);
}
@Test
public void testClique() throws Exception {
// Testing a fully connected graph ensures that the neighbor search excludes any nodes that have already been added.
testGraph(graphLoader.getClique(), new Station(0), 1);
// We verify that our method doesn't care about whether the graph specified is a CO or ADJ interference graph
testGraph(graphLoader.getEmptyGraph(), graphLoader.getClique(), Collections.singleton(new Station(0)),
Integer.MAX_VALUE, 1, SATResult.SAT);
}
@Test
public void testHubAndSpoke() throws Exception {
/*
* Similar to the oneRingOfNeighbors case, except each of the peripheral nodes is connected only to the central node.
* In this case we test the scenario in which each of the "peripheral" stations
* is a "new" station, and they all converge to the same neighbor. This should still run only a single iteration of
* the neighbor search.
*/
HashSet<Station> startingStations = new HashSet<>(Arrays.asList(new Station(1), new Station(2), new Station(3),
new Station(4), new Station(5)));
testGraph(graphLoader.getHubAndSpoke(), startingStations, 1);
// Starting from one of the peripheral edges should give two layers of search
testGraph(graphLoader.getHubAndSpoke(), new Station(1), 2);
}
@Test
public void testLongChainOfNeighbors() throws Exception {
// Visiting the neighbors of a long chain should be the same as visiting each member of that chain individually...
testGraph(graphLoader.getLongChainOfNeighbors(), new Station(0), 25);
// ...whether we start from the front or the back.
testGraph(graphLoader.getLongChainOfNeighbors(), new Station(25), 25);
}
@Test
public void testBipartiteGraph() throws Exception {
SimpleGraph<Station, DefaultEdge> bipartiteGraph = graphLoader.getBipartiteGraph();
// Regardless of the station from which we start, we should only ever travel 2 layers deep
testGraph(bipartiteGraph, new Station(0), 2);
testGraph(bipartiteGraph, new Station(1), 2);
testGraph(bipartiteGraph, new Station(2), 2);
testGraph(bipartiteGraph, new Station(3), 2);
// Starting from two nodes in the same cluster should yield the same result
HashSet<Station> startingStations = new HashSet<>(Arrays.asList(new Station(0), new Station(2)));
testGraph(bipartiteGraph, startingStations, 2);
// Starting from two nodes in opposite clusters should reduce it to a single iteration
startingStations = new HashSet<>(Arrays.asList(new Station(1), new Station(2)));
testGraph(bipartiteGraph, startingStations, 1);
}
@Test
public void testDisconnectedComponents() throws Exception {
SimpleGraph<Station, DefaultEdge> disconnectedComponents = graphLoader.getDisconnectedComponents();
// When starting from a single node in one of the components, the neighbor search should be unaffected by the
// other component
testGraph(disconnectedComponents, new Station(0), 2);
testGraph(disconnectedComponents, new Station(5), 3);
testGraph(disconnectedComponents, new Station(10), 1);
// When starting from multiple nodes in separate components, the neighbor search should go as deep as the
// component with the greatest number of neighbors
HashSet<Station> startingStations = new HashSet<>(Arrays.asList(new Station(0), new Station(5)));
testGraph(disconnectedComponents, startingStations, 3);
startingStations.add(new Station(10));
testGraph(disconnectedComponents, startingStations, 3);
}
private StationPackingInstance initializeInstance(SimpleGraph<Station, DefaultEdge> coGraph,
SimpleGraph<Station, DefaultEdge> adjGraph, Set<Station> newStations) {
Set<Station> allStations = new HashSet<>(coGraph.vertexSet());
allStations.addAll(adjGraph.vertexSet());
Map<Station, Set<Integer>> domains = new HashMap<>();
Map<Station, Integer> previousAssignment = new HashMap<>();
/*
* Domains and previous assignment are set to two arbitrary but consecutive channels for all stations;
* we don't particularly care about channels for this test, but the method ConstraintGrouper.getConstraintGraph
* does require both channels to be in a station's domain to function properly.
*/
for (Station station : allStations) {
domains.put(station, new HashSet<>(Arrays.asList(ARBITRARY_CHANNEL, ARBITRARY_CHANNEL + 1)));
if (!newStations.contains(station)) {
previousAssignment.put(station, ARBITRARY_CHANNEL);
previousAssignment.put(station, ARBITRARY_CHANNEL + 1);
}
}
return new StationPackingInstance(domains, previousAssignment);
}
private void testGraph(SimpleGraph<Station, DefaultEdge> graph, Set<Station> startingStations, int numberOfTimesToCall) {
testGraph(graph, startingStations, numberOfTimesToCall, SATResult.SAT);
}
private void testGraph(SimpleGraph<Station, DefaultEdge> graph, Station startingStation, int numberOfTimesToCall) {
testGraph(graph, Collections.singleton(startingStation), numberOfTimesToCall);
}
private void testGraph(SimpleGraph<Station, DefaultEdge> graph, Set<Station> startingStations,
int numberOfTimesToCall, SATResult expectedResult) {
testGraph(graph, graphLoader.getEmptyGraph(), startingStations,
Integer.MAX_VALUE, numberOfTimesToCall, expectedResult);
}
/**
* @param coGraph - the graph representing interference constraints between stations on the same channel.
* @param adjGraph - the graph representing interference constraints between stations on adjacent channels.
* @param startingStations - the set of stations that is being "added" relative to a previous assignment.
* @param expectedNumberOfLayers - the number of layers of neighbors we expect to explore; corresponds to the number
* of times the certifier is called.
* @param expectedResult - the SATResult we expect to receive from the solver.
*/
private void testGraph(SimpleGraph<Station, DefaultEdge> coGraph, SimpleGraph<Station, DefaultEdge> adjGraph,
Set<Station> startingStations, int maxLayersOfNeighbors, int expectedNumberOfLayers, SATResult expectedResult) {
IConstraintManager constraintManager = new GraphBackedConstraintManager(coGraph, adjGraph);
StationPackingInstance instance = initializeInstance(coGraph, adjGraph, startingStations);
StationWholeSetSATCertifier certifier = new StationWholeSetSATCertifier(Arrays.asList(coGraph, adjGraph), startingStations);
ConstraintGraphNeighborhoodPresolver presolver =
new ConstraintGraphNeighborhoodPresolver(new VoidSolver(), certifier, new IterativeDeepeningConfigurationStrategy(new AddNeighbourLayerStrategy(maxLayersOfNeighbors), Double.MAX_VALUE), constraintManager, false);
SolverResult result = presolver.solve(instance, mockTerminationCriterion, arbitrarySeed);
assertEquals(expectedNumberOfLayers, certifier.getNumberOfTimesCalled());
assertEquals(expectedResult, result.getResult());
}
}
| 12,488
| 49.562753
| 228
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddRandomNeighboursStrategyTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddRandomNeighboursStrategyTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.test.GraphLoader;
/**
* Created by newmanne on 2015-08-03.
*/
public class AddRandomNeighboursStrategyTest {
GraphLoader graphLoader;
@Before
public void setUp() throws Exception {
graphLoader = new GraphLoader();
graphLoader.loadAllGraphs();
}
@Test
public void testMaxExpansionPlowsThroughGraph() throws IOException, URISyntaxException {
AddRandomNeighboursStrategy addRandomNeighboursStrategy = new AddRandomNeighboursStrategy(Integer.MAX_VALUE);
Iterable<Set<Station>> stationsToPack = addRandomNeighboursStrategy.getStationsToPack(graphLoader.getLongChainOfNeighbors(), Sets.newHashSet(new Station(0)));
assertEquals(1, Iterables.size(stationsToPack));
}
@Test
public void testLimit() throws IOException, URISyntaxException {
AddRandomNeighboursStrategy addRandomNeighboursStrategy = new AddRandomNeighboursStrategy(5);
Iterable<Set<Station>> stationsToPack = addRandomNeighboursStrategy.getStationsToPack(graphLoader.getLongChainOfNeighbors(), Sets.newHashSet(new Station(0)));
assertEquals(5, Iterables.size(stationsToPack));
assertEquals(6, stationsToPack.iterator().next().size());
assertEquals(26, Iterables.getLast(stationsToPack).size());
}
@Test
public void testFinishLayerBeforeExpandingToNext() throws IOException, URISyntaxException {
AddRandomNeighboursStrategy addRandomNeighboursStrategy = new AddRandomNeighboursStrategy(3);
Iterable<Set<Station>> stationsToPack = addRandomNeighboursStrategy.getStationsToPack(graphLoader.getBigConnectedGraph(), Sets.newHashSet(new Station(0)));
assertEquals(Sets.newHashSet(0,1,2,3,4,10,12).stream().map(Station::new).collect(Collectors.toSet()), Iterables.get(stationsToPack, 1));
}
@Test
public void inBetweenLayers() throws IOException, URISyntaxException {
AddRandomNeighboursStrategy addRandomNeighboursStrategy = new AddRandomNeighboursStrategy(4);
Iterable<Set<Station>> stationsToPack = addRandomNeighboursStrategy.getStationsToPack(graphLoader.getBigConnectedGraph(), Sets.newHashSet(new Station(0)));
Set<Station> toPack = Iterables.get(stationsToPack, 1);
Set<Station> firstLayer = Sets.newHashSet(0,1,2,3,4,10,12).stream().map(Station::new).collect(Collectors.toSet());
Set<Station> secondLayer = Sets.newHashSet(5,6,8,9,11).stream().map(Station::new).collect(Collectors.toSet());
assertTrue(toPack.containsAll(firstLayer));
Set<Station> secondLayerAddedStations = Sets.difference(toPack, firstLayer);
assertEquals(2, secondLayerAddedStations.size());
assertTrue(secondLayer.containsAll(secondLayerAddedStations));
}
}
| 4,077
| 44.311111
| 166
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/UBCSATSolverTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/UBCSATSolverTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.sat.UBCSATLibSATSolverParameters;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.EncodingType;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.PollingService;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.Literal;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.ISATEncoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATCompressor;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATEncoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.ubcsat.UBCSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.cputime.CPUTimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
/**
* @author pcernek
*/
public class UBCSATSolverTest {
private static final String libraryPath = SATFCFacadeBuilder.findSATFCLibrary(SATFCFacadeBuilder.SATFCLibLocation.SATENSTEIN);
private static SATEncoder.CNFEncodedProblem unsatProblem;
private static SATEncoder.CNFEncodedProblem easyProblem;
private static SATEncoder.CNFEncodedProblem moderateProblem;
private static SATEncoder.CNFEncodedProblem otherProblem;
final IPollingService pollingService = new PollingService();
@BeforeClass
public static void init() throws IOException {
final IStationManager stationManager = new DomainStationManager(Resources.getResource("data/021814SC3M/Domain.csv").getFile());
final IConstraintManager manager = new ChannelSpecificConstraintManager(stationManager, Resources.getResource("data/021814SC3M/Interference_Paired.csv").getFile());
ISATEncoder aSATEncoder = new SATCompressor(manager, EncodingType.DIRECT);
unsatProblem = parseSRPK(Resources.getResource("data/srpks/2469-2483_1671735211211766343_33.srpk").getFile(), aSATEncoder, stationManager);
easyProblem = parseSRPK(Resources.getResource("data/srpks/2469-2483_1582973565573889317_33.srpk").getFile(), aSATEncoder, stationManager);
moderateProblem = parseSRPK(Resources.getResource("data/srpks/2469-2483_4310537143272356051_107.srpk").getFile(), aSATEncoder, stationManager);
otherProblem = parseSRPK(Resources.getResource("data/srpks/2469-2483_1853993831659981677_29.srpk").getFile(), aSATEncoder, stationManager);
}
@Test
public void testSolveEasy() throws Exception {
UBCSATSolver solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN, pollingService);
SATEncoder.CNFEncodedProblem currentProblem = easyProblem;
ITerminationCriterion terminationCriterion = new CPUTimeTerminationCriterion(1.0);
SATSolverResult result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
}
@Test
public void testTimeout() throws Exception {
UBCSATSolver solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN, pollingService);
Watch watch = Watch.constructAutoStartWatch();
ITerminationCriterion terminationCriterion = new WalltimeTerminationCriterion(0.5);
SATSolverResult result = solver.solve(unsatProblem.getCnf(), unsatProblem.getInitialAssignment(), terminationCriterion, 1);
double solvingTime = watch.getElapsedTime();
System.out.println("Solving time: " + solvingTime);
watch.stop();
assertEquals(SATResult.TIMEOUT, result.getResult());
assertTrue(solvingTime < 2);
}
@Test
public void testSolveMultipleInstances() throws Exception {
UBCSATSolver solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN, pollingService);
// Problem 1
SATEncoder.CNFEncodedProblem currentProblem = easyProblem;
ITerminationCriterion terminationCriterion = new CPUTimeTerminationCriterion(10.0);
SATSolverResult result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
// Problem 2
currentProblem = moderateProblem;
terminationCriterion = new CPUTimeTerminationCriterion(10.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
// Problem 3
currentProblem = otherProblem;
terminationCriterion = new CPUTimeTerminationCriterion(10.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
}
@Test
public void testSolveMultipleConfigsSameInstance() {
SATEncoder.CNFEncodedProblem currentProblem = easyProblem;
ITerminationCriterion terminationCriterion;
SATSolverResult result;
UBCSATSolver solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS, pollingService);
terminationCriterion = new CPUTimeTerminationCriterion(1.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.STEIN_R3SAT_PARAMILS, pollingService);
terminationCriterion = new CPUTimeTerminationCriterion(1.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.STEIN_FAC_PARAMILS, pollingService);
terminationCriterion = new CPUTimeTerminationCriterion(1.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
}
@Test
public void testSameProblemHundredTimes() {
// SATEncoder.CNFEncodedProblem currentProblem = otherProblem;
SATEncoder.CNFEncodedProblem currentProblem = easyProblem;
ITerminationCriterion terminationCriterion;
UBCSATSolver solver;
SATSolverResult result;
for (int i=0; i < 100; i++) {
solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.STEIN_FAC_PARAMILS, pollingService);
terminationCriterion = new CPUTimeTerminationCriterion(1.0);
result = solver.solve(currentProblem.getCnf(), currentProblem.getInitialAssignment(), terminationCriterion, 1);
assertEquals(SATResult.SAT, result.getResult());
checkSolutionMakesSense(result, currentProblem.getCnf().getVariables().size());
}
}
@Test
public void testInterrupt() throws Exception {
UBCSATSolver solver = new UBCSATSolver(libraryPath, UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN, pollingService);
Thread interrupter = new Thread(() -> {
try {
Thread.sleep(200);
solver.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Watch watch = new Watch();
watch.start();
ITerminationCriterion terminationCriterion = new CPUTimeTerminationCriterion(5);
interrupter.start();
SATSolverResult result = solver.solve(unsatProblem.getCnf(), unsatProblem.getInitialAssignment(), terminationCriterion, 1);
watch.stop();
interrupter.join();
assertEquals(SATResult.INTERRUPTED, result.getResult());
assertTrue(watch.getElapsedTime() < 0.5);
}
private static SATEncoder.CNFEncodedProblem parseSRPK(String srpkFilePath, ISATEncoder encoder, IStationManager stationManager) throws IOException {
Converter.StationPackingProblemSpecs problemSpecs = Converter.StationPackingProblemSpecs.fromStationRepackingInstance(srpkFilePath);
StationPackingInstance instance = new StationPackingInstance(problemSpecs.getDomains().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), Map.Entry::getValue)), problemSpecs.getPreviousAssignment().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), Map.Entry::getValue)));
return encoder.encodeWithAssignment(instance);
}
private static void checkSolutionMakesSense(SATSolverResult result, int numVars) {
assertEquals(numVars, result.getAssignment().size());
for (int i=1; i <= numVars; i++) {
boolean containsPositiveLit = result.getAssignment().contains(new Literal(i, true));
boolean containsNegativeLit = result.getAssignment().contains(new Literal(i, false));
assertTrue( containsPositiveLit != containsNegativeLit );
}
}
}
| 11,744
| 51.668161
| 368
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/UBCSATLibraryTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/UBCSATLibraryTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.Pair;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Resources;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.sat.UBCSATLibSATSolverParameters;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.EncodingType;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.ISATDecoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.ISATEncoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATCompressor;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.UBCSATTestHelperLibrary;
import ca.ubc.cs.beta.stationpacking.utils.NativeUtils;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
/**
* In adherence to the principle of RAII (Resource Acquisition Is Initialization), and to allow for flexibility in running
* different configurations in each test case, each test case instantiates and initializes its own UBCSATLibrary, and
* then destroys it.
*
* @author pcernek
*/
public class UBCSATLibraryTest {
private static UBCSATTestHelperLibrary library;
private Pointer state;
String dummyCNF = "p cnf 4 20\n-1 2 3 0\n1 -2 4 0\n1 3 4 0\n2 3 -4 0\n-1 -2 -4 0\n1 -2 3 0\n2 -3 4 0\n-2 3 4 0\n-1 3 -4 0\n2 3 4 0\n1 2 -3 0\n1 -3 -4 0\n1 3 -4 0\n-1 2 4 0\n-1 -2 -3 0\n1 2 0\n-2 4 0\n-3 4 0\n2 3 0\n1 2 3 4 0\n";
String miniUnsatCNF = "p cnf 4 8\n-1 2 4 0\n-2 3 4 0\n1 -3 4 0\n1 -2 -4 0\n2 -3 -4 0\n-1 3 -4 0\n1 2 3 0\n-1 -2 -3 0";
// This one should be solvable within a few seconds
String sampleSRPKPath = Resources.getResource("data/srpks/2469-2483_1582973565573889317_33.srpk").getFile();
private CNF loadSRPKasCNF(String srpkPath) throws IOException {
final IStationManager stationManager = new DomainStationManager(Resources.getResource("data/021814SC3M/Domain.csv").getFile());
final IConstraintManager manager = new ChannelSpecificConstraintManager(stationManager, Resources.getResource("data/021814SC3M/Interference_Paired.csv").getFile());
Converter.StationPackingProblemSpecs specs = Converter.StationPackingProblemSpecs.fromStationRepackingInstance(srpkPath);
final StationPackingInstance instance = new StationPackingInstance(specs.getDomains().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), Map.Entry::getValue)), specs.getPreviousAssignment().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), Map.Entry::getValue)));
ISATEncoder aSATEncoder = new SATCompressor(manager, EncodingType.DIRECT);
Pair<CNF, ISATDecoder> aEncoding = aSATEncoder.encode(instance);
return aEncoding.getKey();
}
@BeforeClass
static public void init() {
String libraryPath = SATFCFacadeBuilder.findSATFCLibrary(SATFCFacadeBuilder.SATFCLibLocation.SATENSTEIN);
library = (UBCSATTestHelperLibrary) Native.loadLibrary(libraryPath, UBCSATTestHelperLibrary.class, NativeUtils.NATIVE_OPTIONS);
}
@Test
public void testInitProblem() {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertEquals(4, library.getNumVars());
assertEquals(20, library.getNumClauses());
library.destroyProblem(state);
}
@Test
public void testInitAssignment() {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
long[] assignment = new long[]{1, 2, -3};
assertTrue(library.initAssignment(state, assignment, 3));
library.runInitData();
for(int i=0; i < assignment.length; i++) {
assertEquals(assignment[i] > 0, library.getVarAssignment(i + 1));
}
library.destroyProblem(state);
}
@Test
public void testSolveProblemDefaultConfig() throws IOException {
state = library.initConfig(UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testSolveProblemConfig1() throws IOException {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testSolveProblemConfig2() throws IOException {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_R3SAT_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testSolveProblemConfig3() throws IOException {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_FAC_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testSolveTwoDifferentProblems() throws IOException {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
CNF sampleSRPK = loadSRPKasCNF(sampleSRPKPath);
assertTrue( library.initProblem(state, sampleSRPK.toDIMACS(new String[]{})) );
assertTrue(library.solveProblem(state, 60));
assertEquals(1, library.getResultState(state));
library.destroyProblem(state);
state = library.initConfig(UBCSATLibSATSolverParameters.DEFAULT_SATENSTEIN);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 5));
assertEquals(1, library.getResultState(state));
library.destroyProblem(state);
}
@Test
public void testSameProblemDifferentConfigs() {
/* The following strings of parameters were found to perform well for the SATenstein paper on other (non-SATFC)
instance distributions */
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
library.destroyProblem(state);
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_R3SAT_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
library.destroyProblem(state);
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_FAC_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
library.destroyProblem(state);
}
@Test
public void testSameProblemHundredTimes() {
for (int i=0; i < 100; i++) {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
}
@Test
public void testDCCA() {
String dccaParams = "-alg dcca";
state = library.initConfig(dccaParams);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testsparrow() {
String sparrowParams = "-alg sparrow";
state = library.initConfig(sparrowParams);
assertTrue(library.initProblem(state, dummyCNF));
assertTrue(library.solveProblem(state, 0.5));
assertEquals(1, library.getResultState(state));
IntByReference pRef = library.getResultAssignment(state);
int size = pRef.getValue();
int[] assignment = pRef.getPointer().getIntArray(0, size + 1);
assertEquals(true, assignment[1] > 0);
assertEquals(false, assignment[2] > 0);
assertEquals(true, assignment[3] > 0);
assertEquals(true, assignment[4] > 0);
library.destroyProblem(state);
}
@Test
public void testInterrupt() throws IOException, InterruptedException {
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
library.initProblem(state, miniUnsatCNF);
Thread interrupter = new Thread(() -> {
try {
Thread.sleep(200);
library.interrupt(state);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
interrupter.start();
Watch watch = Watch.constructAutoStartWatch();
library.solveProblem(state, 60);
watch.stop();
interrupter.join();
assertTrue(watch.getElapsedTime() < 1);
assertEquals(3, library.getResultState(state));
library.destroyProblem(state);
}
@Test
public void testTimeout() throws IOException {
Watch watch = Watch.constructAutoStartWatch();
state = library.initConfig(UBCSATLibSATSolverParameters.STEIN_QCP_PARAMILS);
library.initProblem(state, miniUnsatCNF);
library.solveProblem(state, 0.5);
watch.stop();
assertTrue(watch.getElapsedTime() < 1);
assertEquals(2, library.getResultState(state));
library.destroyProblem(state);
}
}
| 13,993
| 40.525223
| 360
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/Clasp3SATSolverTest.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/Clasp3SATSolverTest.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import java.io.IOException;
import java.util.stream.Collectors;
import org.apache.commons.math3.util.Pair;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.sat.ClaspLibSATSolverParameters;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeBuilder;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.EncodingType;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.PollingService;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.ISATDecoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.ISATEncoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATCompressor;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.interrupt.InterruptibleTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Clasp3SATSolverTest {
private static CNF hardCNF;
final String libraryPath = SATFCFacadeBuilder.findSATFCLibrary(SATFCFacadeBuilder.SATFCLibLocation.CLASP);
final String parameters = ClaspLibSATSolverParameters.UHF_CONFIG_04_15_h1;
final IPollingService pollingService = new PollingService();
@BeforeClass
public static void init() throws IOException {
final IStationManager stationManager = new DomainStationManager(Resources.getResource("data/021814SC3M/Domain.csv").getFile());
final IConstraintManager manager = new ChannelSpecificConstraintManager(stationManager, Resources.getResource("data/021814SC3M/Interference_Paired.csv").getFile());
Converter.StationPackingProblemSpecs specs = Converter.StationPackingProblemSpecs.fromStationRepackingInstance(Resources.getResource("data/srpks/2469-2483_4310537143272356051_107.srpk").getFile());
final StationPackingInstance instance = new StationPackingInstance(specs.getDomains().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), e -> e.getValue())), specs.getPreviousAssignment().entrySet().stream().collect(Collectors.toMap(e -> stationManager.getStationfromID(e.getKey()), e-> e.getValue())));
ISATEncoder aSATEncoder = new SATCompressor(manager, EncodingType.DIRECT);
Pair<CNF, ISATDecoder> aEncoding = aSATEncoder.encode(instance);
hardCNF = aEncoding.getKey();
}
@Test(expected = IllegalArgumentException.class)
public void testFailOnInvalidParameters() {
final String libraryPath = SATFCFacadeBuilder.findSATFCLibrary(SATFCFacadeBuilder.SATFCLibLocation.CLASP);
final String parameters = "these are not valid parameters";
log.info(libraryPath);
new Clasp3SATSolver(libraryPath, parameters,pollingService);
}
// Verify that clasp respects the timeout we send it by sending it a hard CNF with a very low cutoff and making sure it doesn't stall
@Test(timeout = 3000)
public void testTimeout() {
final Clasp3SATSolver clasp3SATSolver = new Clasp3SATSolver(libraryPath, parameters, pollingService);
final ITerminationCriterion terminationCriterion = new WalltimeTerminationCriterion(1.0);
clasp3SATSolver.solve(hardCNF, terminationCriterion, 1);
}
@Test(timeout = 3000)
public void testInterrupt() {
final Clasp3SATSolver clasp3SATSolver = new Clasp3SATSolver(libraryPath, parameters, pollingService);
final ITerminationCriterion.IInterruptibleTerminationCriterion terminationCriterion = new InterruptibleTerminationCriterion(new NeverEndingTerminationCriterion());
new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.error("Sleep interrupted?", e);
}
terminationCriterion.interrupt();
clasp3SATSolver.interrupt();
}).start();
clasp3SATSolver.solve(hardCNF, terminationCriterion, 1);
}
}
| 5,672
| 53.028571
| 355
|
java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/UBCSATTestHelperLibrary.java
|
SATFC-release/satfc/src/test/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/UBCSATTestHelperLibrary.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries;
import com.sun.jna.Pointer;
/**
* Created by pcernek on 7/29/15.
*/
public interface UBCSATTestHelperLibrary extends UBCSATLibrary {
/**
* Gets the number of variables in the current SAT problem according to UBCSAT.
* Must be called after {@link #initProblem(Pointer, String)}.
* @return the number of variables in the current SAT problem
*/
int getNumVars();
/**
* Gets the number of clauses in the current SAT problem according to UBCSAT.
* Must be called after {@link #initProblem(Pointer, String)}.
* @return the number of clauses in the current SAT problem
*/
int getNumClauses();
/**
* Get the current assignment (True or False) of the given variable.
* @param varNumber the number of the variable for which to get the assignment.
* @return the given variable's assignment.
*/
boolean getVarAssignment(int varNumber);
/**
* Runs the triggers associated with the InitData event point in UBCSAT.
* Must be run after initProblem.
*/
void runInitData();
}
| 1,962
| 32.844828
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/stations/DomainStationManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/stations/DomainStationManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.stations;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.hash.Funnel;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.hash.PrimitiveSink;
import au.com.bytecode.opencsv.CSVReader;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* In charge of managing collections of stations read from a domain file.
* @author afrechet
*/
public class DomainStationManager implements IStationManager{
private final Map<Integer,Station> fStations = new HashMap<Integer,Station>();
private final Map<Station,Set<Integer>> fDomains = new HashMap<Station,Set<Integer>>();
private final String fHash;
/**
* @param aStationDomainsFilename - domain file from which stations should be read.
* @throws FileNotFoundException - if domain file is not found.
*/
public DomainStationManager(String aStationDomainsFilename) throws FileNotFoundException{
CSVReader aReader;
aReader = new CSVReader(new FileReader(aStationDomainsFilename),',');
String[] aLine;
Integer aID,aChannel;
String aString;
try
{
while((aLine = aReader.readNext())!=null){
final ImmutableSet.Builder<Integer> aChannelDomainBuilder = ImmutableSet.builder();
for(int i=2;i<aLine.length;i++){ //NA - Ideally would have a more robust check here
aString = aLine[i].replaceAll("\\s", "");
if(aString.length()>0){
aChannel = Integer.valueOf(aString);
aChannelDomainBuilder.add(aChannel);
}
}
aID = Integer.valueOf(aLine[1].replaceAll("\\s", ""));
final ImmutableSet<Integer> aChannelDomain = aChannelDomainBuilder.build();
if(aChannelDomain.isEmpty()){
try{
throw new IllegalStateException("Station "+aID+" has empty domain.");
} catch(Exception e) {
e.printStackTrace();
}
}
Station station = new Station(aID);
fStations.put(aID, station);
fDomains.put(station,aChannelDomain);
}
aReader.close();
}
catch(IOException e)
{
throw new IllegalStateException("There was an exception while reading the station domains file ("+e.getMessage()+").");
}
final HashFunction hf = Hashing.murmur3_32();
final HashCode hc = hf.newHasher()
.putObject(fDomains, new Funnel<Map<Station, Set<Integer>>>() {
@Override
public void funnel(Map<Station, Set<Integer>> from, PrimitiveSink into) {
from.keySet().stream().sorted().forEach(s -> {
into.putInt(s.getID());
from.get(s).stream().sorted().forEach(into::putInt);
});
}
})
.hash();
fHash = hc.toString();
}
@Override
public Set<Station> getStations() {
return new HashSet<Station>(fStations.values());
}
@Override
public Station getStationfromID(Integer aID){
if(!fStations.containsKey(aID))
{
throw new IllegalArgumentException("Station manager does not contain station for ID "+aID);
}
return fStations.get(aID);
}
@Override
public Set<Integer> getDomain(Station aStation) {
Set<Integer> domain = fDomains.get(aStation);
if(domain == null)
{
throw new IllegalArgumentException("No domain contained for station "+aStation);
}
return domain;
}
public String getDomainHash() {
return fHash;
}
}
| 4,511
| 31.228571
| 122
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/stations/IStationManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/stations/IStationManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.stations;
import java.util.HashSet;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
/**
* Interface for objects in charge of managing a collection of stations.
* @author afrechet
*/
public interface IStationManager {
/**
* @return - all the stations represented by the station manager.
*/
Set<Station> getStations();
/**
*
* @param aID - a station ID.
* @return the station for the particular ID.
* @throws IllegalArgumentException - if the provided ID cannot be found in the stations.
*/
Station getStationfromID(Integer aID) throws IllegalArgumentException;
/**
* @param aStation - a station.
* @return the channels on which this station can be packed.
*/
Set<Integer> getDomain(Station aStation);
default Set<Integer> getRestrictedDomain(Station station, int maxChannel, boolean UHFOnly) {
final Set<Integer> domain = new HashSet<>(getDomain(station));
domain.removeIf(chan -> chan > maxChannel || (UHFOnly && chan < StationPackingUtils.UHFmin));
return domain;
}
/**
* @return a hash of the domain
*/
String getDomainHash();
}
| 2,047
| 29.117647
| 95
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ChannelSpecificConstraintManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ChannelSpecificConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import au.com.bytecode.opencsv.CSVReader;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import lombok.extern.slf4j.Slf4j;
/**
* Channel specific interference constraint data manager.
*
* @author afrechet, narnosti, tqichen
*/
@Slf4j
public class ChannelSpecificConstraintManager extends AMapBasedConstraintManager {
/**
* Construct a Channel Specific Constraint Manager from a station manager and an interference constraints filename.
*
* @param aStationManager - station manager.
* @param aInterferenceConstraintsFilename - name of the file containing interference constraints.
* @throws FileNotFoundException - if indicated file cannot be found.
*/
public ChannelSpecificConstraintManager(IStationManager aStationManager, String aInterferenceConstraintsFilename) throws FileNotFoundException {
super(aStationManager, aInterferenceConstraintsFilename);
}
/**
* Add the constraint to the constraint manager represented by subject station, target station, subject channel and constraint key.
*
* @param aSubjectStation
* @param aTargetStation
* @param aSubjectChannel
* @param aConstraintKey
*/
@Override
protected void addConstraint(Station aSubjectStation,
Station aTargetStation,
Integer aSubjectChannel,
ConstraintKey aConstraintKey) {
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel, aConstraintKey);
switch (aConstraintKey) {
case CO:
break;
case ADJp1:
//Add implied CO constraints;
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel, ConstraintKey.CO);
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel + 1, ConstraintKey.CO);
break;
case ADJp2:
// Add implied CO constraints
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel, ConstraintKey.CO);
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel + 1, ConstraintKey.CO);
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel + 2, ConstraintKey.CO);
// Add impied +1 constraints
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel, ConstraintKey.ADJp1);
super.addConstraint(aSubjectStation, aTargetStation, aSubjectChannel + 1, ConstraintKey.ADJp1);
break;
default:
throw new IllegalStateException("Unrecognized constraint key " + aConstraintKey);
}
}
@Override
protected void loadConstraints(IStationManager aStationManager, String aInterferenceConstraintsFilename) throws FileNotFoundException {
try {
try (CSVReader reader = new CSVReader(new FileReader(aInterferenceConstraintsFilename))) {
String[] line;
while ((line = reader.readNext()) != null) {
final String key = line[0].trim();
final ConstraintKey constraintKey = ConstraintKey.fromString(key);
if (constraintKey.equals(ConstraintKey.ADJm1) || constraintKey.equals(ConstraintKey.ADJm2)) {
throw new IllegalArgumentException("ADJ-1 and ADJ-2 constraints are not part of the compact format, but were seen in line:" + Arrays.toString(line));
}
final int lowChannel = Integer.valueOf(line[1].trim());
final int highChannel = Integer.valueOf(line[2].trim());
if (lowChannel > highChannel) {
throw new IllegalStateException("Low channel greater than high channel on line " + Arrays.toString(line));
}
final int subjectStationID = Integer.valueOf(line[3].trim());
final Station subjectStation = aStationManager.getStationfromID(subjectStationID);
for (int subjectChannel = lowChannel; subjectChannel <= highChannel; subjectChannel++) {
for (int i = 4; i < line.length; i++) {
if (line[i].trim().isEmpty()) {
break;
}
final int targetStationID = Integer.valueOf(line[i].trim());
final Station targetStation = aStationManager.getStationfromID(targetStationID);
addConstraint(subjectStation, targetStation, subjectChannel, constraintKey);
}
}
}
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read interference constraints file: " + aInterferenceConstraintsFilename, e);
}
}
}
| 6,073
| 45.723077
| 173
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ConstraintKey.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/ConstraintKey.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
/**
* Type of possible constraints.
*
* @author afrechet
*/
public enum ConstraintKey {
CO,
ADJp1,
ADJm1,
ADJp2,
ADJm2;
public static ConstraintKey fromString(String string) {
switch (string) {
case "CO":
return CO;
case "ADJ+1":
return ADJp1;
case "ADJ-1":
return ADJm1;
case "ADJ+2":
return ADJp2;
case "ADJ-2":
return ADJm2;
default:
throw new IllegalArgumentException("Unrecognized constraint key " + string);
}
}
}
| 1,516
| 28.173077
| 92
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/AMapBasedConstraintManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/AMapBasedConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.hash.Funnel;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
public abstract class AMapBasedConstraintManager extends AConstraintManager {
/*
* Map taking subject station to map taking channel to interfering station that cannot be
* on channel concurrently with subject station.
*/
protected final Map<Station, Map<Integer, Set<Station>>> fCOConstraints;
/*
* Map taking subject station to map taking channel to interfering station that cannot be
* on channel+1 concurrently with subject station.
*/
protected final Map<Station, Map<Integer, Set<Station>>> fADJp1Constraints;
/*
* Map taking subject station to map taking channel to interfering station that cannot be
* on channel+2 concurrently with subject station.
*/
protected final Map<Station, Map<Integer, Set<Station>>> fADJp2Constraints;
protected String fHash;
public AMapBasedConstraintManager(IStationManager aStationManager, String aInterferenceConstraintsFilename) throws FileNotFoundException {
fCOConstraints = new HashMap<>();
fADJp1Constraints = new HashMap<>();
fADJp2Constraints = new HashMap<>();
loadConstraints(aStationManager, aInterferenceConstraintsFilename);
final HashCode hc = computeHash();
fHash = hc.toString();
}
private Set<Station> getInterferingStations(Station aStation, int aChannel, Map<Station, Map<Integer, Set<Station>>> constraintMap) {
final Map<Integer, Set<Station>> subjectStationConstraints = constraintMap.getOrDefault(aStation, Collections.emptyMap());
final Set<Station> interferingStations = subjectStationConstraints.getOrDefault(aChannel, Collections.emptySet());
return Collections.unmodifiableSet(interferingStations);
}
@Override
public Set<Station> getCOInterferingStations(Station aStation, int aChannel) {
return getInterferingStations(aStation, aChannel, fCOConstraints);
}
@Override
public Set<Station> getADJplusOneInterferingStations(Station aStation, int aChannel) {
return getInterferingStations(aStation, aChannel, fADJp1Constraints);
}
@Override
public Set<Station> getADJplusTwoInterferingStations(Station aStation, int aChannel) {
return getInterferingStations(aStation, aChannel, fADJp2Constraints);
}
/**
* Add the constraint to the constraint manager represented by subject station, target station, subject channel and constraint key.
*
* @param aSubjectStation
* @param aTargetStation
* @param aSubjectChannel
* @param aConstraintKey
*/
protected void addConstraint(Station aSubjectStation,
Station aTargetStation,
Integer aSubjectChannel,
ConstraintKey aConstraintKey) {
final Map<Integer, Set<Station>> subjectStationConstraints;
final Set<Station> interferingStations;
switch (aConstraintKey) {
case CO:
/*
* Switch subject station for target station depending on the ID of the stations
* to remove possible duplicate CO interference clauses.
*/
if (aSubjectStation.getID() > aTargetStation.getID()) {
Station tempStation = aSubjectStation;
aSubjectStation = aTargetStation;
aTargetStation = tempStation;
}
subjectStationConstraints = fCOConstraints.getOrDefault(aSubjectStation, new HashMap<>());
interferingStations = subjectStationConstraints.getOrDefault(aSubjectChannel, new HashSet<>());
interferingStations.add(aTargetStation);
subjectStationConstraints.put(aSubjectChannel, interferingStations);
fCOConstraints.put(aSubjectStation, subjectStationConstraints);
break;
case ADJp1:
//Add +1 constraint;
subjectStationConstraints = fADJp1Constraints.getOrDefault(aSubjectStation, new HashMap<>());
interferingStations = subjectStationConstraints.getOrDefault(aSubjectChannel, new HashSet<>());
interferingStations.add(aTargetStation);
subjectStationConstraints.put(aSubjectChannel, interferingStations);
fADJp1Constraints.put(aSubjectStation, subjectStationConstraints);
break;
case ADJm1:
//Add corresponding reverse ADJ+1 constraint.
addConstraint(aTargetStation, aSubjectStation, aSubjectChannel - 1, ConstraintKey.ADJp1);
break;
case ADJp2:
//Add +2 constraint;
subjectStationConstraints = fADJp2Constraints.getOrDefault(aSubjectStation, new HashMap<>());
interferingStations = subjectStationConstraints.getOrDefault(aSubjectChannel, new HashSet<>());
interferingStations.add(aTargetStation);
subjectStationConstraints.put(aSubjectChannel, interferingStations);
fADJp2Constraints.put(aSubjectStation, subjectStationConstraints);
break;
case ADJm2:
//Add corresponding reverse ADJ+2 constraint.
addConstraint(aTargetStation, aSubjectStation, aSubjectChannel - 2, ConstraintKey.ADJp2);
break;
default:
throw new IllegalStateException("Unrecognized constraint key " + aConstraintKey);
}
}
protected HashCode computeHash() {
final Funnel<Map<Station, Map<Integer, Set<Station>>>> funnel = (from, into) -> from.keySet().stream().sorted().forEach(s -> {
into.putInt(s.getID());
from.get(s).keySet().stream().sorted().forEach(c -> {
into.putInt(c);
from.get(s).get(c).stream().sorted().forEach(s2 -> {
into.putInt(s2.getID());
});
});
});
final HashFunction hf = Hashing.murmur3_32();
return hf.newHasher()
.putObject(fCOConstraints, funnel)
.putObject(fADJp1Constraints, funnel)
.putObject(fADJp2Constraints, funnel)
.hash();
}
protected abstract void loadConstraints(IStationManager stationManager, String fileName) throws FileNotFoundException;
@Override
public String getConstraintHash() {
return fHash;
}
}
| 7,831
| 41.107527
| 142
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/AConstraintManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/AConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 06/03/15.
*/
@Slf4j
public abstract class AConstraintManager implements IConstraintManager {
@Override
public boolean isSatisfyingAssignment(Map<Integer, Set<Station>> aAssignment) {
final Set<Station> allStations = new HashSet<Station>();
for (Map.Entry<Integer, Set<Station>> entry : aAssignment.entrySet()) {
final int channel = entry.getKey();
final Set<Station> channelStations = aAssignment.get(channel);
for (Station station1 : channelStations) {
//Check if we have already seen station1, and add it to the set of seen stations
if (!allStations.add(station1)) {
log.error("Station {} is assigned to multiple channels", station1);
return false;
}
//Make sure current station does not CO interfere with other stations.
final Set<Station> coInterferingStations = getCOInterferingStations(station1, channel);
for (Station station2 : channelStations) {
if (coInterferingStations.contains(station2)) {
log.trace("Station {} and {} share channel {} on which they CO interfere.", station1, station2, channel);
return false;
}
}
//Make sure current station does not ADJ+1 interfere with other stations.
final Set<Station> adjInterferingStations = getADJplusOneInterferingStations(station1, channel);
int channelp1 = channel + 1;
final Set<Station> channelp1Stations = aAssignment.getOrDefault(channelp1, Collections.emptySet());
for (Station station2 : channelp1Stations) {
if (adjInterferingStations.contains(station2)) {
log.trace("Station {} is on channel {}, and station {} is on channel {}, causing ADJ+1 interference.", station1, channel, station2, channelp1);
return false;
}
}
//Make sure current station does not ADJ+2 interfere with other stations.
final Collection<Station> adjPlusTwoInterferingStations = getADJplusTwoInterferingStations(station1, channel);
int channelp2 = channel + 2;
final Set<Station> channelp2Stations = aAssignment.getOrDefault(channelp2, Collections.emptySet());
for (Station station2 : channelp2Stations) {
if (adjPlusTwoInterferingStations.contains(station2)) {
log.trace("Station {} is on channel {}, and station {} is on channel {}, causing ADJ+2 interference.", station1, channel, station2, channelp2);
return false;
}
}
}
}
return true;
}
@Override
public Iterable<Constraint> getAllRelevantConstraints(Map<Station, Set<Integer>> domains) {
final Set<Station> stations = domains.keySet();
final Collection<Constraint> constraintCollection = new ArrayList<>();
for (Station sourceStation : stations) {
for (Integer sourceChannel : domains.get(sourceStation)) {
for (Station targetStation : getCOInterferingStations(sourceStation, sourceChannel)) {
if (stations.contains(targetStation) && domains.get(targetStation).contains(sourceChannel)) {
constraintCollection.add(new Constraint(sourceStation, targetStation, sourceChannel, sourceChannel));
}
}
for (Station targetStation : getADJplusOneInterferingStations(sourceStation, sourceChannel)) {
if (stations.contains(targetStation) && domains.get(targetStation).contains(sourceChannel + 1)) {
constraintCollection.add(new Constraint(sourceStation, targetStation, sourceChannel, sourceChannel + 1));
}
}
for (Station targetStation : getADJplusTwoInterferingStations(sourceStation, sourceChannel)) {
if (stations.contains(targetStation) && domains.get(targetStation).contains(sourceChannel + 2)) {
constraintCollection.add(new Constraint(sourceStation, targetStation, sourceChannel, sourceChannel + 2));
}
}
}
}
return constraintCollection;
}
}
| 5,653
| 49.035398
| 167
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/Constraint.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/Constraint.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.Value;
/**
* Representation of a binary constraint
*/
@Value
public class Constraint {
private final Station source;
private final Station target;
private final int sourceChannel;
private final int targetChannel;
}
| 1,178
| 31.75
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/UnabridgedFormatConstraintManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/UnabridgedFormatConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import au.com.bytecode.opencsv.CSVReader;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import lombok.extern.slf4j.Slf4j;
/**
* Unabridged format constraint manager for specific format that is released to the public by the FCC.
*
* @author afrechet
*/
@Slf4j
public class UnabridgedFormatConstraintManager extends AMapBasedConstraintManager {
/**
* Construct a Channel Specific Constraint Manager from a station manager and an interference constraints filename.
*
* @param aStationManager - station manager.
* @param aInterferenceConstraintsFilename - name of the file containing interference constraints.
* @throws FileNotFoundException - if indicated file cannot be found.
*/
public UnabridgedFormatConstraintManager(IStationManager aStationManager, String aInterferenceConstraintsFilename) throws FileNotFoundException {
super(aStationManager, aInterferenceConstraintsFilename);
}
@Override
protected void loadConstraints(IStationManager aStationManager, String aInterferenceConstraintsFilename) throws FileNotFoundException {
try {
try (CSVReader reader = new CSVReader(new FileReader(aInterferenceConstraintsFilename))) {
String[] line;
while ((line = reader.readNext()) != null) {
final String key = line[0].trim();
final ConstraintKey constraintKey = ConstraintKey.fromString(key);
final int subjectChannel = Integer.valueOf(line[1].trim());
final int targetChannel = Integer.valueOf(line[2].trim());
if (constraintKey.equals(ConstraintKey.CO) && subjectChannel != targetChannel) {
throw new IllegalArgumentException(Arrays.toString(line) + System.lineSeparator() + "Constraint key is " + constraintKey + " but subject channel (" + subjectChannel + ") is different than target channel (" + targetChannel + ").");
} else if (constraintKey.equals(ConstraintKey.ADJp1) && subjectChannel != targetChannel - 1) {
throw new IllegalArgumentException(Arrays.toString(line) + System.lineSeparator() + "Constraint key is " + constraintKey + " but subject channel (" + subjectChannel + ") is not one less than target channel (" + targetChannel + ").");
} else if (constraintKey.equals(ConstraintKey.ADJm1) && subjectChannel != targetChannel + 1) {
throw new IllegalArgumentException(Arrays.toString(line) + System.lineSeparator() + "Constraint key is " + constraintKey + " but subject channel (" + subjectChannel + ") is not one more than target channel (" + targetChannel + ").");
} else if (constraintKey.equals(ConstraintKey.ADJp2) && subjectChannel != targetChannel - 2) {
throw new IllegalArgumentException(Arrays.toString(line) + System.lineSeparator() + "Constraint key is " + constraintKey + " but subject channel (" + subjectChannel + ") is not two less than target channel (" + targetChannel + ").");
} else if (constraintKey.equals(ConstraintKey.ADJm2) && subjectChannel != targetChannel + 2) {
throw new IllegalArgumentException(Arrays.toString(line) + System.lineSeparator() + "Constraint key is " + constraintKey + " but subject channel (" + subjectChannel + ") is not two more than target channel (" + targetChannel + ").");
}
final int subjectStationID = Integer.valueOf(line[3].trim());
final Station subjectStation = aStationManager.getStationfromID(subjectStationID);
for (int i = 4; i < line.length; i++) {
if (line[i].trim().isEmpty()) {
break;
}
final int targetStationID = Integer.valueOf(line[i].trim());
final Station targetStation = aStationManager.getStationfromID(targetStationID);
addConstraint(subjectStation, targetStation, subjectChannel, constraintKey);
}
}
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read interference constraints filename", e);
}
}
}
| 5,439
| 55.666667
| 257
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/IConstraintManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/datamanagers/constraints/IConstraintManager.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.datamanagers.constraints;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Manages co- and adjacent- channel constraints.
*
* @author afrechet
*/
public interface IConstraintManager {
/**
* @param aStation - a (source) station of interest.
* @param aChannel - a channel on which we wish to know interfering stations.
* @return all the (target) stations that cannot be on the same given channel, <i> i.e. </i> if s is the
* source station and c the given channel, then the set of stations T returned is such that, for all t in T,
* <p>
* s and t cannot be both on c
* </p>
*/
Set<Station> getCOInterferingStations(Station aStation, int aChannel);
/**
* @param aStation - a (source) station of interest.
* @param aChannel - a channel on which we wish to know interfering stations.
* @return all the (target) stations that cannot be on a channel that is one above the given channel on which the source station is, <i> i.e. </i> if s is the
* source station and c the given channel, then the set of stations T returned is such that, for all t in T,
* <p>
* s cannot be on c at the same time as t is on c+1 for all c in C
* </p>
*/
Set<Station> getADJplusOneInterferingStations(Station aStation, int aChannel);
/**
* @param aStation - a (source) station of interest.
* @param aChannel - a channel on which we wish to know interfering stations.
* @return all the (target) stations that cannot be on a channel that is two above the given channel on which the source station is, <i> i.e. </i> if s is the
* source station and c the given channel, then the set of stations T returned is such that, for all t in T,
* <p>
* s cannot be on c at the same time as t is on c+2 for all c in C
* </p>
*/
Set<Station> getADJplusTwoInterferingStations(Station aStation, int aChannel);
/**
* @param aAssignment - an assignment of channels to (set of) stations.
* @return true if and only if the assignment satisfies all the constraints represented by the constraint manager.
*/
boolean isSatisfyingAssignment(Map<Integer, Set<Station>> aAssignment);
/**
* @return a hash of the constraints
*/
String getConstraintHash();
/**
* @param domains - The domain of a problem
* @return all the constraints that apply to that problem
*/
Iterable<Constraint> getAllRelevantConstraints(Map<Station, Set<Integer>> domains);
/**
* A shortcut function to {@link IConstraintManager#isSatisfyingAssignment(Map)} for the case of 2 stations
* Essentially tests whether or not a constraint exists
* @param s1 The first station
* @param c1 The channel the first station is on
* @param s2 The second station
* @param c2 The channel the second station is on
* @return true if and only if the assignment satisfies all the constraints represented by the constraint manager.
*/
default boolean isSatisfyingAssignment(Station s1, int c1, Station s2, int c2) {
final Map<Integer, Set<Station>> assignment = new HashMap<>();
assignment.put(c1, Sets.newHashSet(s1));
assignment.putIfAbsent(c2, new HashSet<>());
assignment.get(c2).add(s2);
return isSatisfyingAssignment(assignment);
}
}
| 4,350
| 39.287037
| 162
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ISATFCCacheEntry.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ISATFCCacheEntry.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import java.util.BitSet;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
/**
* Created by newmanne on 27/10/15.
*/
public interface ISATFCCacheEntry {
BitSet getBitSet();
SATResult getResult();
}
| 1,083
| 27.526316
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/SatisfiabilityCacheFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/SatisfiabilityCacheFactory.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.SatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import containmentcache.IContainmentCache;
import containmentcache.ILockableContainmentCache;
import containmentcache.bitset.opt.MultiPermutationBitSetCache;
import containmentcache.bitset.opt.sortedset.redblacktree.RedBlackTree;
import containmentcache.decorators.BufferedThreadSafeCacheDecorator;
import containmentcache.util.PermutationUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 22/04/15.
*/
@Slf4j
public class SatisfiabilityCacheFactory implements ISatisfiabilityCacheFactory {
private static final int SAT_BUFFER_SIZE = 100;
private static final int UNSAT_BUFFER_SIZE = 3;
private final int numPermutations;
private final long seed;
public SatisfiabilityCacheFactory(int numPermutations, long seed) {
Preconditions.checkArgument(numPermutations > 0, "Need at least one permutation!");
this.numPermutations = numPermutations;
this.seed = seed;
}
@Override
public ISatisfiabilityCache create(ImmutableBiMap<Station, Integer> permutation) {
// 1) Create other permutations, if any
final List<BiMap<Station, Integer>> permutations;
if (numPermutations > 1) {
permutations = PermutationUtils.makeNPermutations(permutation, seed, numPermutations - 1);
} else {
permutations = ImmutableList.of();
}
// 2) Create the actual caches
final IContainmentCache<Station, ContainmentCacheSATEntry> undecoratedSATCache = new MultiPermutationBitSetCache<>(permutation, permutations, RedBlackTree::new);
final ILockableContainmentCache<Station, ContainmentCacheSATEntry> SATCache = BufferedThreadSafeCacheDecorator.makeBufferedThreadSafe(undecoratedSATCache, SAT_BUFFER_SIZE);
final IContainmentCache<Station, ContainmentCacheUNSATEntry> undecoratedUNSATCache = new MultiPermutationBitSetCache<>(permutation, permutations, RedBlackTree::new);
final ILockableContainmentCache<Station, ContainmentCacheUNSATEntry> UNSATCache = BufferedThreadSafeCacheDecorator.makeBufferedThreadSafe(undecoratedUNSATCache, UNSAT_BUFFER_SIZE);
return new SatisfiabilityCache(permutation, SATCache, UNSATCache);
}
}
| 3,638
| 45.653846
| 188
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacheEntryFilter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacheEntryFilter.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
/**
* Created by newmanne on 01/02/16.
* Filter entries (determine whether or not they should be cached)
*/
public interface ICacheEntryFilter {
/**
* @Return True if should cache
*/
boolean shouldCache(CacheCoordinate coordinate, StationPackingInstance instance, SolverResult result);
}
| 1,303
| 32.435897
| 106
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/NewInfoEntryFilter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/NewInfoEntryFilter.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import lombok.RequiredArgsConstructor;
/**
* Created by newmanne on 2016-02-14.
*/
@RequiredArgsConstructor
public class NewInfoEntryFilter implements ICacheEntryFilter {
private final ICacheLocator cacheLocator;
@Override
public boolean shouldCache(CacheCoordinate coordinate, StationPackingInstance instance, SolverResult result) {
final ISatisfiabilityCache cache = cacheLocator.locate(coordinate);
final boolean containsNewInfo;
if (result.getResult().equals(SATResult.SAT)) {
containsNewInfo = !cache.proveSATBySuperset(instance).isValid();
} else if (result.getResult().equals(SATResult.UNSAT)) {
containsNewInfo = !cache.proveUNSATBySubset(instance).isValid();
} else {
throw new IllegalStateException("Tried adding a result that was neither SAT or UNSAT");
}
return containsNewInfo;
}
}
| 2,054
| 38.519231
| 114
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/StationPackingInstanceHasher.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/StationPackingInstanceHasher.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
/**
* Created by newmanne on 25/03/15.
*/
public class StationPackingInstanceHasher {
// hashing function
private static final HashFunction fHashFuction = Hashing.murmur3_128();
public static HashCode hash(StationPackingInstance aInstance) {
final HashCode hash = fHashFuction.newHasher()
.putString(aInstance.toString(), Charsets.UTF_8)
.hash();
return hash;
}
}
| 1,523
| 31.425532
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacher.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacher.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 1/25/15.
*/
public interface ICacher {
void cacheResult(StationPackingInstance instance, SolverResult result, ITerminationCriterion criterion);
}
| 1,256
| 32.972973
| 108
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/CacheCoordinate.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/CacheCoordinate.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.utils.CacheUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class determines which cache is accessed
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CacheCoordinate {
private String domainHash;
private String interferenceHash;
// transform a redis key into a cache coordinate
public static CacheCoordinate fromKey(String key) {
final CacheUtils.ParsedKey parsedKey = CacheUtils.parseKey(key);
return new CacheCoordinate(parsedKey.getDomainHash(), parsedKey.getInterferenceHash());
}
// create a redis key from a coordinate, a result, and an instance
public String toKey(SATResult result, long num) {
Preconditions.checkArgument(result.equals(SATResult.SAT) || result.equals(SATResult.UNSAT));
return Joiner.on(":").join(ImmutableList.of("SATFC", result, domainHash, interferenceHash, num));
}
}
| 2,026
| 33.948276
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/RedisCacher.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/RedisCacher.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import containmentcache.ICacheEntry;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATEntry;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.ManagerBundle;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.utils.CacheUtils;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;
/**
* Created by newmanne on 02/12/14.
* Interfaces with redis to store and retrieve CacheEntry's
*/
@Slf4j
public class RedisCacher {
private final static int SAT_PIPELINE_SIZE = 10000;
private final static int UNSAT_PIPELINE_SIZE = 2500;
public static final String HASH_NUM = "SATFC:HASHNUM";
private final DataManager dataManager;
private final StringRedisTemplate redisTemplate;
private final BinaryJedis binaryJedis;
private final StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
public RedisCacher(DataManager dataManager, StringRedisTemplate redisTemplate, BinaryJedis binaryJedis) {
this.dataManager = dataManager;
this.redisTemplate = redisTemplate;
this.binaryJedis = binaryJedis;
}
public ISATFCCacheEntry cacheEntryFromKey(String key) {
return cacheEntryFromKeyAndAnswer(key, binaryJedis.hgetAll(stringRedisSerializer.serialize(key)));
}
public ISATFCCacheEntry cacheEntryFromKeyAndAnswer(String key, final Map<byte[], byte[]> answer) {
final CacheUtils.ParsedKey parsedKey = CacheUtils.parseKey(key);
final CacheCoordinate coordinate = CacheCoordinate.fromKey(key);
final ImmutableBiMap<Station, Integer> permutation = dataManager.getData(coordinate).getPermutation();
final Map<String, byte[]> stringKeyAnswer = answer.entrySet().stream().collect(Collectors.toMap(entry -> stringRedisSerializer.deserialize(entry.getKey()), Map.Entry::getValue));
if (parsedKey.getResult().equals(SATResult.SAT)) {
return parseSATEntry(stringKeyAnswer, key, permutation);
} else {
return parseUNSATEntry(stringKeyAnswer, key, permutation);
}
}
public static final String ASSIGNMENT_KEY = "assignment";
public static final String BITSET_KEY = "bitset";
public static final String NAME_KEY = "name";
public static final String DOMAINS_KEY = "domains";
private static final Set<String> SAT_REQUIRED_KEYS = Sets.newHashSet(ASSIGNMENT_KEY, BITSET_KEY);
private static final Set<String> UNSAT_REQUIRED_KEYS = Sets.newHashSet(DOMAINS_KEY, BITSET_KEY);
private ContainmentCacheSATEntry parseSATEntry(Map<String, byte[]> entry, String key, ImmutableBiMap<Station, Integer> permutation) {
if (!entry.keySet().containsAll(SAT_REQUIRED_KEYS)) {
throw new IllegalArgumentException("Entry does not contain required keys " + SAT_REQUIRED_KEYS + ". Only have keys " + entry.keySet());
}
final BitSet bitSet = BitSet.valueOf(entry.get(BITSET_KEY));
final byte[] channels = entry.get(ASSIGNMENT_KEY);
final String name = stringRedisSerializer.deserialize(entry.get(NAME_KEY));
final String auction = StationPackingUtils.parseAuctionFromName(name);
return new ContainmentCacheSATEntry(bitSet, channels, key, permutation, auction);
}
private ContainmentCacheUNSATEntry parseUNSATEntry(Map<String, byte[]> entry, String key, ImmutableBiMap<Station, Integer> permutation) {
if (!entry.keySet().containsAll(UNSAT_REQUIRED_KEYS)) {
throw new IllegalArgumentException("Entry does not contain required keys " + UNSAT_REQUIRED_KEYS + ". Only have keys " + entry.keySet());
}
final BitSet bitSet = BitSet.valueOf(entry.get(BITSET_KEY));
final BitSet domains = BitSet.valueOf(entry.get(DOMAINS_KEY));
final String name = stringRedisSerializer.deserialize(entry.get(NAME_KEY));
final String auction = StationPackingUtils.parseAuctionFromName(name);
return new ContainmentCacheUNSATEntry(bitSet, domains, key, permutation, auction);
}
public <T extends ISATFCCacheEntry> String cacheResult(CacheCoordinate coordinate, T entry, String name) {
final long newID = redisTemplate.boundValueOps(HASH_NUM).increment(1);
final String key = coordinate.toKey(entry.getResult(), newID);
final byte[] keyBytes = stringRedisSerializer.serialize(key);
final Transaction multi = binaryJedis.multi();
multi.hset(keyBytes, stringRedisSerializer.serialize(BITSET_KEY), entry.getBitSet().toByteArray());
if (entry instanceof ContainmentCacheSATEntry) {
multi.hset(keyBytes, stringRedisSerializer.serialize(ASSIGNMENT_KEY), ((ContainmentCacheSATEntry) entry).getChannels());
} else if (entry instanceof ContainmentCacheUNSATEntry) {
multi.hset(keyBytes, stringRedisSerializer.serialize(DOMAINS_KEY), ((ContainmentCacheUNSATEntry) entry).getDomainsBitSet().toByteArray());
}
if (name != null) {
multi.hset(keyBytes, stringRedisSerializer.serialize(NAME_KEY), stringRedisSerializer.serialize(name));
}
multi.exec();
if (name != null) {
log.info("Adding result for {} to cache with key {}", name, key);
}
return key;
}
public <CONTAINMENT_CACHE_ENTRY extends ISATFCCacheEntry> ListMultimap<CacheCoordinate, CONTAINMENT_CACHE_ENTRY> processResults(Set<String> keys, SATResult entryTypeName, int partitionSize, boolean validateSAT) {
final ListMultimap<CacheCoordinate, CONTAINMENT_CACHE_ENTRY> results = ArrayListMultimap.create();
final AtomicInteger numProcessed = new AtomicInteger();
Lists.partition(new ArrayList<>(keys), partitionSize).stream().forEach(keyChunk -> {
log.info("Processed {} {} keys out of {}", numProcessed, entryTypeName, keys.size());
final List<String> orderedKeys = new ArrayList<>();
final List<Response<Map<byte[], byte[]>>> responses = new ArrayList<>();
final Pipeline p = binaryJedis.pipelined();
for (String key : keyChunk) {
numProcessed.incrementAndGet();
final CacheCoordinate coordinate = CacheCoordinate.fromKey(key);
final ImmutableBiMap<Station, Integer> permutation = dataManager.getData(coordinate).getPermutation();
if (permutation == null) {
log.warn("Skipping cache entry from key {}. Could not find a permutation known for coordinate {}. This probably means that the cache entry does not correspond to any known constraint folders ({})", key, coordinate, dataManager.getCoordinateToBundle().keySet());
continue;
}
orderedKeys.add(key);
responses.add(p.hgetAll(stringRedisSerializer.serialize(key)));
}
p.sync();
Preconditions.checkState(responses.size() == orderedKeys.size(), "Different number of queries and answers from redis!");
for (int i = 0; i < responses.size(); i++) {
final String key = orderedKeys.get(i);
final CacheCoordinate coordinate = CacheCoordinate.fromKey(key);
final Map<byte[], byte[]> answer = responses.get(i).get();
try {
final ISATFCCacheEntry cacheEntry = cacheEntryFromKeyAndAnswer(key, answer);
if (entryTypeName.equals(SATResult.SAT) && validateSAT) {
ContainmentCacheSATEntry satEntry = (ContainmentCacheSATEntry) cacheEntry;
final Map<Integer, Set<Station>> assignment = ((ContainmentCacheSATEntry) cacheEntry).getAssignmentChannelToStation();
final ManagerBundle managerBundle = dataManager.getData(coordinate);
boolean valid = StationPackingUtils.weakVerify(managerBundle.getStationManager(), managerBundle.getConstraintManager(), satEntry.getAssignmentStationToChannel());
if (!valid) {
throw new IllegalStateException("Cache entry for key " + key + " contains an invalid assignment!");
}
}
results.put(coordinate, (CONTAINMENT_CACHE_ENTRY) cacheEntry);
} catch (Exception e) {
log.error("Error making cache entry for key {}", key, e);
}
}
});
log.info("Finished processing {} {} entries", numProcessed, entryTypeName);
results.keySet().forEach(cacheCoordinate -> {
log.info("Found {} {} entries for cache {}", results.get(cacheCoordinate).size(), entryTypeName, cacheCoordinate);
});
return results;
}
public ContainmentCacheInitData getContainmentCacheInitData(long limit, boolean skipSAT, boolean skipUNSAT, boolean validateSAT) {
log.info("Pulling precache data from redis");
final Watch watch = Watch.constructAutoStartWatch();
final Set<String> SATKeys = new HashSet<>();
final Set<String> UNSATKeys = new HashSet<>();
final Cursor<byte[]> scan = redisTemplate.getConnectionFactory().getConnection().scan(ScanOptions.scanOptions().build());
while (SATKeys.size() + UNSATKeys.size() < limit && scan.hasNext()) {
final String key = new String(scan.next());
if (key.equals(HASH_NUM)) {
continue;
}
final CacheUtils.ParsedKey parsedKey = CacheUtils.parseKey(key);
if (parsedKey.getResult().equals(SATResult.SAT) && !skipSAT) {
SATKeys.add(key);
} else if (parsedKey.getResult().equals(SATResult.UNSAT) && !skipUNSAT) {
UNSATKeys.add(key);
}
}
// filter out coordinates we don't know about
SATKeys.removeIf(key -> !dataManager.getCoordinateToBundle().containsKey(CacheCoordinate.fromKey(key)));
UNSATKeys.removeIf(key -> !dataManager.getCoordinateToBundle().containsKey(CacheCoordinate.fromKey(key)));
log.info("Found " + SATKeys.size() + " SAT keys");
log.info("Found " + UNSATKeys.size() + " UNSAT keys");
final ListMultimap<CacheCoordinate, ContainmentCacheSATEntry> SATResults = processResults(SATKeys, SATResult.SAT, SAT_PIPELINE_SIZE, validateSAT);
final ListMultimap<CacheCoordinate, ContainmentCacheUNSATEntry> UNSATResults = processResults(UNSATKeys, SATResult.UNSAT, UNSAT_PIPELINE_SIZE, false);
log.info("It took {}s to pull precache data from redis", watch.getElapsedTime());
return new ContainmentCacheInitData(SATResults, UNSATResults);
}
@Data
public static class ContainmentCacheInitData {
private final ListMultimap<CacheCoordinate, ContainmentCacheSATEntry> SATResults;
private final ListMultimap<CacheCoordinate, ContainmentCacheUNSATEntry> UNSATResults;
public Set<CacheCoordinate> getCaches() {
return Sets.union(SATResults.keySet(), UNSATResults.keySet());
}
}
/**
* Removes the cache entries in Redis
* @param collection collection of SAT entries
*/
public void deleteSATCollection(List<ContainmentCacheSATEntry> collection) {
redisTemplate.delete(collection.stream().map(ContainmentCacheSATEntry::getKey).collect(Collectors.toList()));
}
/**
* Removes the cache entries in Redis
* @param collection collection of UNSAT entries
*/
public void deleteUNSATCollection(List<ContainmentCacheUNSATEntry> collection){
redisTemplate.delete(collection.stream().map(ContainmentCacheUNSATEntry::getKey).collect(Collectors.toList()));
}
public Iterable<ISATFCCacheEntry> iterateSAT() {
final Cursor<byte[]> scan = redisTemplate.getConnectionFactory().getConnection().scan(ScanOptions.scanOptions().build());
return () -> new AbstractIterator<ISATFCCacheEntry>() {
@Override
protected ISATFCCacheEntry computeNext() {
while (scan.hasNext()) {
final String key = new String(scan.next());
try {
return cacheEntryFromKey(key);
} catch (Exception e) {
if (!key.equals(HASH_NUM)) {
log.warn("Exception parsing key " + key, e);
}
continue;
}
}
return endOfData();
}
};
}
}
| 14,738
| 50.897887
| 281
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ISatisfiabilityCacheFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ISatisfiabilityCacheFactory.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import com.google.common.collect.ImmutableBiMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
/**
* Created by newmanne on 22/04/15.
*/
public interface ISatisfiabilityCacheFactory {
ISatisfiabilityCache create(ImmutableBiMap<Station, Integer> permutation);
}
| 1,227
| 34.085714
| 93
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacheLocator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/ICacheLocator.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import net.jcip.annotations.ThreadSafe;
/**
* Created by newmanne on 20/03/15.
*/
@ThreadSafe
public interface ICacheLocator {
ISatisfiabilityCache locate(CacheCoordinate coordinate);
Set<CacheCoordinate> getCoordinates();
}
| 1,216
| 30.205128
| 93
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATEntry.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATEntry.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import java.util.BitSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.StreamSupport;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimaps;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.ISATFCCacheEntry;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.utils.GuavaCollectors;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import containmentcache.ICacheEntry;
import lombok.Data;
import lombok.NonNull;
/**
* Created by newmanne on 25/03/15.
*/
@Data
public class ContainmentCacheUNSATEntry implements ICacheEntry<Station>, ISATFCCacheEntry {
public static final int BITS_PER_STATION = StationPackingUtils.UHFmax - StationPackingUtils.LVHFmin + 1;
private final BitSet bitSet;
private final BitSet domainsBitSet;
private final ImmutableBiMap<Station, Integer> permutation;
private String key;
private String auction;
public ContainmentCacheUNSATEntry(
@NonNull Map<Station, Set<Integer>> domains,
@NonNull BiMap<Station, Integer> permutation) {
domainsBitSet = new BitSet(domains.size() * BITS_PER_STATION);
// Sort stations according to the permutation
final ImmutableList<Station> stations = domains.keySet().stream()
.sorted((a, b) -> permutation.get(a).compareTo(permutation.get(b)))
.collect(GuavaCollectors.toImmutableList());
int offset = 0;
for (Station s: stations) {
// Set a bit for each channel that is in the domain
for (Integer chan : domains.get(s)) {
int index = offset + chan - StationPackingUtils.UHFmin;
domainsBitSet.set(index);
}
offset += BITS_PER_STATION;
}
this.permutation = ImmutableBiMap.copyOf(permutation);
this.bitSet = new BitSet(permutation.size());
domains.keySet().forEach(station -> bitSet.set(permutation.get(station)));
}
// construct from Redis cache entry
public ContainmentCacheUNSATEntry(
@NonNull BitSet bitSet,
@NonNull BitSet domains,
@NonNull String key,
@NonNull BiMap<Station, Integer> permutation,
String auction
) {
this.permutation = ImmutableBiMap.copyOf(permutation);
this.key = key;
this.bitSet = bitSet;
this.domainsBitSet = domains;
this.auction = auction;
}
@Override
public Set<Station> getElements() {
final Map<Integer, Station> inverse = permutation.inverse();
return bitSet.stream().mapToObj(inverse::get).collect(GuavaCollectors.toImmutableSet());
}
public Map<Station, Set<Integer>> getDomains() {
final HashMultimap<Station, Integer> domains = HashMultimap.create();
final Map<Integer, Station> inversePermutation = permutation.inverse();
int offset = 0;
// Loop over all stations
for (int bit = bitSet.nextSetBit(0); bit >= 0; bit = bitSet.nextSetBit(bit+1)) {
final Station station = inversePermutation.get(bit);
// Reconstruct a station's domain
for (int chanBit = domainsBitSet.nextSetBit(offset); chanBit < offset + BITS_PER_STATION && chanBit >= 0; chanBit = domainsBitSet.nextSetBit(chanBit+1)) {
int chan = (chanBit % BITS_PER_STATION) + StationPackingUtils.UHFmin;
domains.put(station, chan);
}
offset += BITS_PER_STATION;
}
return Multimaps.asMap(domains);
}
/*
* returns true if this UNSAT entry is less restrictive than the cacheEntry
* this UNSAT entry is less restrictive cacheEntry if this UNSAT has same or less stations than cacheEntry
* and each each stations has same or more candidate channels than the corresponding station in cacheEntry
* UNSAT entry with same key is not considered
*/
public boolean isLessRestrictive(ContainmentCacheUNSATEntry cacheEntry) {
// skip checking against itself
if (this != cacheEntry) {
Map<Station, Set<Integer>> moreRes = cacheEntry.getDomains();
Map<Station, Set<Integer>> lessRes = this.getDomains();
// lessRes has less stations to pack
if (moreRes.keySet().containsAll(lessRes.keySet())) {
// each station in lessRes has same or more candidate channels than the corresponding station in moreRes
return StreamSupport.stream(lessRes.keySet().spliterator(), false)
.allMatch(station -> lessRes.get(station).containsAll(moreRes.get(station)));
}
}
return false;
}
@Override
public SATResult getResult() {
return SATResult.UNSAT;
}
}
| 5,925
| 39.040541
| 166
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATResult.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import java.util.Map;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.Data;
/**
* Created by newmanne on 25/03/15.
*/
@Data
public class ContainmentCacheSATResult {
public ContainmentCacheSATResult() {
valid = false;
}
public ContainmentCacheSATResult(Map<Integer, Set<Station>> result, String key) {
this.key = key;
this.result = result;
this.valid = true;
}
private Map<Integer, Set<Station>> result;
// the redis key of the problem whose solution "solves" this problem
private String key;
private boolean valid;
// return an empty or failed result, that represents an error or that the problem was not solvable via the cache
public static ContainmentCacheSATResult failure() {
return new ContainmentCacheSATResult();
}
}
| 1,726
| 29.839286
| 116
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/SatisfiabilityCache.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/SatisfiabilityCache.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.cache.containment;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import containmentcache.ILockableContainmentCache;
import containmentcache.SimpleCacheSet;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 19/04/15.
*/
@Slf4j
public class SatisfiabilityCache implements ISatisfiabilityCache {
final ILockableContainmentCache<Station, ContainmentCacheSATEntry> SATCache;
final ILockableContainmentCache<Station, ContainmentCacheUNSATEntry> UNSATCache;
@Getter
final ImmutableBiMap<Station, Integer> permutation;
public SatisfiabilityCache(
BiMap<Station, Integer> permutation,
ILockableContainmentCache<Station, ContainmentCacheSATEntry> SATCache,
ILockableContainmentCache<Station, ContainmentCacheUNSATEntry> UNSATCache) {
this.permutation = ImmutableBiMap.copyOf(permutation);
this.SATCache = SATCache;
this.UNSATCache = UNSATCache;
}
@Override
public ContainmentCacheSATResult proveSATBySuperset(final StationPackingInstance aInstance, final Predicate<ContainmentCacheSATEntry> ignorePredicate) {
// try to narrow down the entries we have to search by only looking at supersets
try {
SATCache.getReadLock().lock();
final Iterable<ContainmentCacheSATEntry> iterable = SATCache.getSupersets(new SimpleCacheSet<Station>(aInstance.getStations(), permutation));
return StreamSupport.stream(iterable.spliterator(), false)
/**
* The entry must contain at least every station in the query in order to provide a solution (hence superset)
* The entry should also be a solution to the problem, which it will be as long as the solution can project onto the query's domains since they come from the set of interference constraints
*/
.filter(entry -> entry.isSolutionTo(aInstance))
.filter(ignorePredicate)
.map(entry -> new ContainmentCacheSATResult(entry.getAssignmentChannelToStation(), entry.getKey()))
.findAny()
.orElse(ContainmentCacheSATResult.failure());
} finally {
SATCache.getReadLock().unlock();
}
}
@Override
public ContainmentCacheUNSATResult proveUNSATBySubset(final StationPackingInstance aInstance) {
// try to narrow down the entries we have to search by only looking at subsets
try {
UNSATCache.getReadLock().lock();
final Iterable<ContainmentCacheUNSATEntry> iterable = UNSATCache.getSubsets(new SimpleCacheSet<Station>(aInstance.getStations(), permutation));
return StreamSupport.stream(iterable.spliterator(), false)
/*
* The entry's stations should be a subset of the query's stations (so as to be less constrained)
* and each station in the entry must have larger than or equal to the corresponding station domain in the target (so as to be less constrained)
*/
.filter(entry -> isSupersetOrEqualToByDomains(entry.getDomains(), aInstance.getDomains()))
.map(entry -> new ContainmentCacheUNSATResult(entry.getKey()))
.findAny()
.orElse(ContainmentCacheUNSATResult.failure());
} finally {
UNSATCache.getReadLock().unlock();
}
}
@Override
public void add(ContainmentCacheSATEntry SATEntry) {
SATCache.add(SATEntry);
}
@Override
public void add(ContainmentCacheUNSATEntry UNSATEntry) {
UNSATCache.add(UNSATEntry);
}
/**
* Domain a has less stations than domain b because of previous method call getSubsets();
* If each station domain in domain a has same or more channels than the matching station in domain b,
* then a is superset of b
*
* @param a superset domain
* @param b subset domain
* @return true if a's domain is a superset of b's domain
*/
private boolean isSupersetOrEqualToByDomains(Map<Station, Set<Integer>> a, Map<Station, Set<Integer>> b) {
return a.entrySet().stream().allMatch(entry -> {
final Set<Integer> integers = b.get(entry.getKey());
return integers != null && entry.getValue().containsAll(integers);
});
}
/**
* removes redundant SAT entries from this SATCache
*
* @return list of cache entries to be removed
*/
@Override
public List<ContainmentCacheSATEntry> filterSAT(IStationManager stationManager, boolean strong) {
List<ContainmentCacheSATEntry> prunableEntries = Collections.synchronizedList(new ArrayList<>());
Iterable<ContainmentCacheSATEntry> satEntries = SATCache.getSets();
final AtomicLong counter = new AtomicLong();
SATCache.getReadLock().lock();
try {
StreamSupport.stream(satEntries.spliterator(), true)
.forEach(cacheEntry -> {
if (counter.getAndIncrement() % 1000 == 0) {
log.info("Scanned {} / {} entries; Found {} prunables", counter.get(), SATCache.size(), prunableEntries.size());
}
if ((strong && shouldFilterStrong(cacheEntry, stationManager)) || (!strong && shouldFilterWeak(cacheEntry))) {
prunableEntries.add(cacheEntry);
}
});
} finally {
SATCache.getReadLock().unlock();
}
prunableEntries.forEach(SATCache::remove);
return prunableEntries;
}
private boolean shouldFilterWeak(ContainmentCacheSATEntry cacheEntry) {
Iterable<ContainmentCacheSATEntry> supersets = SATCache.getSupersets(cacheEntry);
return StreamSupport.stream(supersets.spliterator(), false)
.filter(entry -> entry.hasMoreSolvingPower(cacheEntry))
.findAny().isPresent();
}
private boolean shouldFilterStrong(ContainmentCacheSATEntry cacheEntry, IStationManager stationManager) {
final Map<Station, Set<Integer>> domains = new HashMap<>();
for (Map.Entry<Integer, Integer> e : cacheEntry.getAssignmentStationToChannel().entrySet()) {
final Station station = stationManager.getStationfromID(e.getKey());
domains.put(station, stationManager.getRestrictedDomain(station, e.getValue(), false));
}
final StationPackingInstance i = new StationPackingInstance(domains);
return proveSATBySuperset(i, entry -> entry != cacheEntry).isValid();
}
/**
* removes redundant UNSAT entries from this UNSATCache
*
* @return list of cache entries to be removed
*/
@Override
public List<ContainmentCacheUNSATEntry> filterUNSAT() {
List<ContainmentCacheUNSATEntry> prunableEntries = new ArrayList<>();
Iterable<ContainmentCacheUNSATEntry> unsatEntries = UNSATCache.getSets();
final AtomicLong counter = new AtomicLong();
UNSATCache.getReadLock().lock();
try {
unsatEntries.forEach(cacheEntry -> {
if (counter.getAndIncrement() % 1000 == 0) {
log.info("Scanned {} / {} entries; Found {} prunables", counter.get(), UNSATCache.size(), prunableEntries.size());
}
Iterable<ContainmentCacheUNSATEntry> subsets = UNSATCache.getSubsets(cacheEntry);
// For two UNSAT problems P and Q, if Q has less stations to pack,
// and each station has more candidate channels, then Q is less restrictive than P
Optional<ContainmentCacheUNSATEntry> lessRestrictiveUNSAT =
StreamSupport.stream(subsets.spliterator(), true)
.filter(entry -> entry.isLessRestrictive(cacheEntry))
.findAny();
if (lessRestrictiveUNSAT.isPresent()) {
prunableEntries.add(cacheEntry);
}
});
} finally {
UNSATCache.getReadLock().unlock();
}
prunableEntries.forEach(UNSATCache::remove);
return prunableEntries;
}
@Override
public List<ContainmentCacheSATEntry> findMaxIntersections(StationPackingInstance instance, int k) {
BitSet bitSet = new SimpleCacheSet<>(instance.getStations(), permutation).getBitSet();
ImmutableMap<Station, Set<Integer>> domains = instance.getDomains();
SATCache.getReadLock().lock();
try {
return StreamSupport.stream(SATCache.getSets().spliterator(), false)
.sorted((a, b) -> {
final BitSet aCopy = (BitSet) a.getBitSet().clone();
final BitSet bCopy = (BitSet) b.getBitSet().clone();
aCopy.and(bitSet);
bCopy.and(bitSet);
aCopy.stream().forEach(i -> {
Station station = permutation.inverse().get(i);
if (!domains.get(station).contains(a.getAssignmentStationToChannel().get(station.getID()))) {
aCopy.clear(i);
}
});
bCopy.stream().forEach(i -> {
Station station = permutation.inverse().get(i);
if (!domains.get(station).contains(b.getAssignmentStationToChannel().get(station.getID()))) {
bCopy.clear(i);
}
});
return Integer.compare(aCopy.cardinality(), bCopy.cardinality());
})
.limit(k)
.collect(Collectors.toList());
} finally {
SATCache.getReadLock().unlock();
}
}
}
| 11,624
| 44.588235
| 209
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.