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 |
|---|---|---|---|---|---|---|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheUNSATResult.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 lombok.Data;
/**
* Created by newmanne on 25/03/15.
*/
@Data
public class ContainmentCacheUNSATResult {
public ContainmentCacheUNSATResult() {
valid = false;
}
public ContainmentCacheUNSATResult(String key) {
this.key = key;
valid = true;
}
// 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 ContainmentCacheUNSATResult failure() {
return new ContainmentCacheUNSATResult();
}
}
| 1,523
| 29.48
| 116
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATEntry.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/ContainmentCacheSATEntry.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.HashMap;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
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.cache.ISATFCCacheEntry;
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 containmentcache.ICacheEntry;
import lombok.Data;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 25/03/15.
*/
@Slf4j
@Data
public class ContainmentCacheSATEntry implements ICacheEntry<Station>, ISATFCCacheEntry {
private final byte[] channels;
private final BitSet bitSet;
private final ImmutableBiMap<Station, Integer> permutation;
private String key;
private String auction;
// warning: watch out for type erasure on these constructors....
// Construct from a result
public ContainmentCacheSATEntry(
@NonNull Map<Integer, Set<Station>> answer,
@NonNull BiMap<Station, Integer> permutation
) {
this.permutation = ImmutableBiMap.copyOf(permutation);
this.bitSet = CacheUtils.toBitSet(answer, permutation);
final Map<Station, Integer> stationToChannel = StationPackingUtils.stationToChannelFromChannelToStation(answer);
final int numStations = this.bitSet.cardinality();
channels = new byte[numStations];
int j = 0;
final Map<Integer, Station> inversePermutation = permutation.inverse();
for (int bit = bitSet.nextSetBit(0); bit >= 0; bit = bitSet.nextSetBit(bit+1)) {
channels[j] = stationToChannel.get(inversePermutation.get(bit)).byteValue();
j++;
}
}
// construct from Redis cache entry
public ContainmentCacheSATEntry(
@NonNull BitSet bitSet,
@NonNull byte[] channels,
@NonNull String key,
@NonNull BiMap<Station, Integer> permutation,
String auction
) {
this.permutation = ImmutableBiMap.copyOf(permutation);
this.key = key;
this.bitSet = bitSet;
this.channels = channels;
Preconditions.checkArgument(bitSet.cardinality() == channels.length, "Number of stations in bitset %s and size of assignment %s do not align! (KEY=%s)", bitSet.cardinality(), channels.length, key);
this.auction = auction;
}
// aInstance is already known to be a subset of this entry
public boolean isSolutionTo(StationPackingInstance aInstance) {
final ImmutableMap<Station, Set<Integer>> domains = aInstance.getDomains();
final Map<Integer, Integer> stationToChannel = getAssignmentStationToChannel();
return domains.entrySet().stream().allMatch(entry -> entry.getValue().contains(stationToChannel.get(entry.getKey().getID())));
}
public Map<Integer, Set<Station>> getAssignmentChannelToStation() {
final Map<Integer, Integer> stationToChannel = getAssignmentStationToChannel();
return StationPackingUtils.channelToStationFromStationToChannel(stationToChannel);
}
public Map<Integer,Integer> getAssignmentStationToChannel() {
final Map<Integer, Integer> stationToChannel = new HashMap<>();
int j = 0;
final Map<Integer, Station> inversePermutation = permutation.inverse();
for (int bit = bitSet.nextSetBit(0); bit >= 0; bit = bitSet.nextSetBit(bit+1)) {
stationToChannel.put(inversePermutation.get(bit).getID(), Byte.toUnsignedInt(channels[j]));
j++;
}
return stationToChannel;
}
@Override
public Set<Station> getElements() {
final Map<Integer, Station> inversePermutation = permutation.inverse();
final ImmutableSet.Builder<Station> builder = ImmutableSet.builder();
for (int bit = bitSet.nextSetBit(0); bit >= 0; bit = bitSet.nextSetBit(bit+1)) {
final Station station = inversePermutation.get(bit);
if (station == null) {
throw new IllegalStateException("Bit " + bit + " is set in key " + key + ", but inverse permutation does not contain it!\n" + inversePermutation);
}
builder.add(station);
}
return builder.build();
}
/*
* returns true if this SAT entry is a superset of the cacheEntry, hence this SAT has more solving power than cacheEntry
* this SAT entry is superset of the cacheEntry if this SAT has same or more channels than cacheEntry
* and each each channel covers same or more stations than the corresponding channel in cacheEntry
* SAT entry with same key is not considered as a superset
*/
public boolean hasMoreSolvingPower(ContainmentCacheSATEntry cacheEntry) {
if (this != cacheEntry) {
final Map<Integer, Set<Station>> subset = cacheEntry.getAssignmentChannelToStation();
final Map<Integer, Set<Station>> superset = getAssignmentChannelToStation();
if (superset.keySet().containsAll(subset.keySet())) {
return subset.keySet().stream()
.allMatch(channel -> superset.get(channel).containsAll(subset.get(channel)));
}
}
return false;
}
@Override
public SATResult getResult() {
return SATResult.SAT;
}
}
| 6,528
| 41.122581
| 205
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/containmentcache/ISatisfiabilityCache.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/containmentcache/ISatisfiabilityCache.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.containmentcache;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import com.google.common.collect.ImmutableBiMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATResult;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATResult;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
/**
* Created by newmanne on 19/04/15.
*/
public interface ISatisfiabilityCache {
ContainmentCacheSATResult proveSATBySuperset(final StationPackingInstance aInstance, final Predicate<ContainmentCacheSATEntry> filterPredicate);
default ContainmentCacheSATResult proveSATBySuperset(final StationPackingInstance aInstance) {
return proveSATBySuperset(aInstance, unused -> true);
}
ContainmentCacheUNSATResult proveUNSATBySubset(final StationPackingInstance aInstance);
void add(ContainmentCacheSATEntry SATEntry);
default void addAllSAT(Collection<ContainmentCacheSATEntry> SATEntries) {
SATEntries.forEach(this::add);
}
void add(ContainmentCacheUNSATEntry UNSATEntry);
default void addAllUNSAT(Collection<ContainmentCacheUNSATEntry> UNSATEntries) {
UNSATEntries.forEach(this::add);
}
List<ContainmentCacheSATEntry> filterSAT(IStationManager stationManager, boolean strong);
List<ContainmentCacheUNSATEntry> filterUNSAT();
List<ContainmentCacheSATEntry> findMaxIntersections(final StationPackingInstance instance, int k);
ImmutableBiMap<Station, Integer> getPermutation();
}
| 2,714
| 40.136364
| 148
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/UHFRestrictionTransformer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/UHFRestrictionTransformer.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.transformer;
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.utils.StationPackingUtils;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Set;
/**
* Created by newmanne on 2016-03-28.
* Restrict the instance / result to be in UHF only (or return null if that doesn't make sense)
*/
public class UHFRestrictionTransformer implements ICacheEntryTransformer {
@Override
public InstanceAndResult transform(InstanceAndResult instanceAndResult) {
final SolverResult result = instanceAndResult.getResult();
final SATResult satResult = result.getResult();
final StationPackingInstance instance = instanceAndResult.getInstance();
final Map<Station, Set<Integer>> uhfRestrictedDomains = Maps.filterValues(instance.getDomains(), StationPackingUtils.UHF_CHANNELS::containsAll);
if (satResult.equals(SATResult.UNSAT)) {
// We require the ENTIRE problem to have been in UHF
if (uhfRestrictedDomains.equals(instance.getDomains())) {
return instanceAndResult;
} else {
return null;
}
} else if (satResult.equals(SATResult.SAT)) {
final StationPackingInstance uhfRestrictedInstance = new StationPackingInstance(uhfRestrictedDomains, instance.getPreviousAssignment(), instance.getMetadata());
final Map<Integer, Set<Station>> uhfRestrictedAssignment = Maps.filterKeys(instanceAndResult.getResult().getAssignment(), StationPackingUtils.UHF_CHANNELS::contains);
if (!uhfRestrictedAssignment.isEmpty()) {
final SolverResult uhfRestrictedResult = new SolverResult(result.getResult(), result.getRuntime(), uhfRestrictedAssignment, result.getSolvedBy(), result.getNickname());
return new InstanceAndResult(uhfRestrictedInstance, uhfRestrictedResult);
} else {
return null;
}
} else {
throw new IllegalArgumentException("Result neither SAT nor UNSAT");
}
}
}
| 3,147
| 45.985075
| 184
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/InstanceAndResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/InstanceAndResult.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.transformer;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import lombok.Data;
/**
* Created by newmanne on 2016-03-28.
*/
@Data
public class InstanceAndResult {
private final StationPackingInstance instance;
private final SolverResult result;
}
| 1,213
| 32.722222
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/ICacheEntryTransformer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/containment/transformer/ICacheEntryTransformer.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.transformer;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
/**
* Created by newmanne on 2016-03-28.
*/
public interface ICacheEntryTransformer {
/**
* Transform an instance / result pair prior to caching
*
* @return the transformed instance, or null if it decides not to cache it
*/
InstanceAndResult transform(InstanceAndResult instanceAndResult);
default InstanceAndResult transform(StationPackingInstance instance, SolverResult result) {
return transform(new InstanceAndResult(instance, result));
}
}
| 1,510
| 33.340909
| 95
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/scripts/ConstrainCache.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/cache/scripts/ConstrainCache.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.scripts;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.CacheCoordinate;
import ca.ubc.cs.beta.stationpacking.cache.ISATFCCacheEntry;
import ca.ubc.cs.beta.stationpacking.cache.RedisCacher;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATEntry;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATEntry;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
import ca.ubc.cs.beta.stationpacking.facade.*;
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.GuavaCollectors;
import ca.ubc.cs.beta.stationpacking.utils.RedisUtils;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Cleanup;
import lombok.Getter;
import redis.clients.jedis.Jedis;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by newmanne on 2016-02-11.
*/
public class ConstrainCache {
private static org.slf4j.Logger log;
@UsageTextField(title = "Cache constrain script", description = "Iterate over a cache to accumulate another cache (via the server)")
public static class FilterMandatoryStationsOptions extends AbstractOptions {
@Parameter(names = "-MAX-CHANNEL", description = "The clearing target used for any cache entries that trigger resolving")
@Getter
private int maxChannel = StationPackingUtils.UHFmax;
@ParametersDelegate
@Getter
private SATFCFacadeParameters facadeParameters = new SATFCFacadeParameters();
@Parameter(names = "-MANDATORY-STATIONS", description = "Stations that must be present in each entry")
private List<Integer> stations;
public Set<Station> getRequiredStations() {
return stations == null ? Collections.emptySet() : stations.stream().map(Station::new).collect(GuavaCollectors.toImmutableSet());
}
@Parameter(names = "-CONSTRAINT-SET", description = "All cache entries will be validated against this constraint set. Absolute path to folder")
@Getter
private String masterConstraintFolder;
@Parameter(names = "-ALL-CONSTRAINTS", description = "Folder with all constraint sets", required = true)
@Getter
private String allConstraints;
@Getter
@Parameter(names = "-ENFORCE-MAX-CHANNEL", description = "Force a resolve (and delete) any cache entry where a station is assigned above the max channel")
private boolean enforceMaxChannel = false;
@Getter
@Parameter(names = "-DISTRIBUTED", description = "Use the redis queuing system")
private boolean distributed = false;
@Getter
@Parameter(names = "-ASSUME-IMPAIRING", description = "Whether or not to assume a station above max channel is impairing")
private boolean assumeImpairing = false;
@Getter
@Parameter(names = "-NO-SOLVE", description = "Whether or not any solving is allowed")
private boolean noSolve = true;
@Getter
@Parameter(names = "-IGNORE-UNSAT", description = "Whether to ignore UNSAT entries")
private boolean ignoreUNSAT = true;
}
public static void main(String[] args) throws Exception {
// Parse args
final FilterMandatoryStationsOptions options = new FilterMandatoryStationsOptions();
JCommanderHelper.parseCheckingForHelpAndVersion(args, options);
SATFCFacadeBuilder.initializeLogging(options.facadeParameters.getLogLevel(), options.getFacadeParameters().logFileName);
log = org.slf4j.LoggerFactory.getLogger(ConstrainCache.class);
if (options.isDistributed()) {
Preconditions.checkArgument(options.facadeParameters.cachingParams.serverURL != null, "No server URL specified!");
} else if (options.facadeParameters.cachingParams.serverURL == null) {
log.warn("No server URL specified. This script likely won't have side effects...");
}
final Jedis jedis = options.getFacadeParameters().fRedisParameters.getJedis();
final Set<Station> requiredStations = options.getRequiredStations();
log.info("Retrying every cache entry that does not contain stations {}", requiredStations);
// Load constraint folders
final DataManager dataManager = new DataManager();
dataManager.loadMultipleConstraintSets(options.getAllConstraints());
final ManagerBundle managerBundle = dataManager.getData(options.getMasterConstraintFolder());
final CacheCoordinate masterCoordinate = managerBundle.getCacheCoordinate();
log.info("Migrating all cache entries to match constraints in {} ({})", options.getMasterConstraintFolder(), masterCoordinate);
// Load up a facade
@Cleanup
final SATFCFacade facade = SATFCFacadeBuilder.builderFromParameters(options.facadeParameters).build();
@Cleanup
final SATFCFacade unsatFacade = SATFCFacadeBuilder.builderFromParameters(options.facadeParameters).setConfigFile(InternalSATFCConfigFile.UNSAT_LABELLER).build();
final RedisCacher redisCacher = new RedisCacher(dataManager, options.getFacadeParameters().fRedisParameters.getStringRedisTemplate(), options.getFacadeParameters().fRedisParameters.getBinaryJedis());
if (!options.isDistributed()) {
for (ISATFCCacheEntry cacheEntry : redisCacher.iterateSAT()) {
processEntry(options, requiredStations, managerBundle, masterCoordinate, facade, unsatFacade, cacheEntry);
}
} else {
String key;
String queueName = options.getFacadeParameters().fRedisParameters.fRedisQueue;
while (true) {
key = jedis.rpoplpush(RedisUtils.makeKey(queueName), RedisUtils.makeKey(queueName, RedisUtils.PROCESSING_QUEUE));
if (key == null) {
break;
}
final CacheUtils.ParsedKey parsedKey;
try {
parsedKey = CacheUtils.parseKey(key);
} catch (Exception e) {
if (!key.equals(RedisCacher.HASH_NUM)) {
log.warn("Exception parsing key " + key, e);
}
continue;
}
processEntry(options, requiredStations, managerBundle, masterCoordinate, facade, unsatFacade, redisCacher.cacheEntryFromKey(key));
}
}
log.info("Finished. You should now restart the SATFCServer");
}
private static void processEntry(FilterMandatoryStationsOptions options, Set<Station> requiredStations, ManagerBundle managerBundle, CacheCoordinate masterCoordinate, SATFCFacade facade, SATFCFacade unsatFacade, ISATFCCacheEntry cacheEntry) {
if (cacheEntry instanceof ContainmentCacheSATEntry) {
processSATEntry((ContainmentCacheSATEntry) cacheEntry, requiredStations, options, facade, managerBundle);
} else if (cacheEntry instanceof ContainmentCacheUNSATEntry) {
if (!options.isIgnoreUNSAT()) {
processUNSATEntry((ContainmentCacheUNSATEntry) cacheEntry, masterCoordinate, options, unsatFacade, managerBundle);
}
} else {
throw new IllegalStateException("Cache entry neither sat or unsat?");
}
}
public static void processUNSATEntry(ContainmentCacheUNSATEntry entry, CacheCoordinate masterCoordinate, FilterMandatoryStationsOptions options, SATFCFacade unsatFacade, ManagerBundle managerBundle) {
final CacheCoordinate coordinate = CacheCoordinate.fromKey(entry.getKey());
boolean rightCoordinate = coordinate.equals(masterCoordinate);
if (!rightCoordinate) {
log.debug("Key {} is not in right coordinate and UNSAT, skipping", entry.getKey());
return; // We can't do anything with this
}
final Map<Integer, Set<Integer>> domains = entry.getDomains().entrySet().stream().collect(Collectors.toMap(k -> k.getKey().getID(), Map.Entry::getValue));
unsatFacade.solve(domains, new HashMap<>(), options.facadeParameters.fInstanceParameters.Cutoff, options.facadeParameters.fInstanceParameters.Seed, managerBundle.getInterferenceFolder());
}
public static void processSATEntry(ContainmentCacheSATEntry entry, Set<? extends Station> requiredStations, FilterMandatoryStationsOptions options, SATFCFacade facade, ManagerBundle managerBundle) {
log.info("Entry {} stats: Domain size is {}", entry.getKey(), entry.getElements().size());
final int maxChannel = options.getMaxChannel();
final IStationManager stationManager = managerBundle.getStationManager();
final IConstraintManager constraintManager = managerBundle.getConstraintManager();
// Some stations may have been deleted in between constraint sets, so let's get rid of them
final Set<Station> entryStations = Sets.intersection(entry.getElements(), stationManager.getStations());
final Set<Station> allRequiredStations = Sets.union(entryStations, requiredStations);
final Map<Integer, Integer> previousAssignment;
final Map<Integer, Set<Integer>> domains;
// A) I can transfer b/c once I've removed stations that no longer exist, I'm still valid (and I meet any channel requirements if they are being enforced)
final Map<Integer, Integer> entryAssignment = Maps.filterKeys(entry.getAssignmentStationToChannel(), s -> entryStations.contains(new Station(s)));
if (entryStations.size() == allRequiredStations.size() && (!options.isAssumeImpairing() || entryAssignment.values().stream().allMatch(c -> c <= options.getMaxChannel())) && constraintManager.isSatisfyingAssignment(StationPackingUtils.channelToStationFromStationToChannel(entryAssignment))) {
previousAssignment = entryAssignment;
domains = previousAssignment.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> Collections.singleton(e.getValue())));
} else {
if (options.isNoSolve()) {
return;
}
// B) I have to be resolved.
domains = new HashMap<>();
for (Station s : allRequiredStations) {
Integer prevChan = entryAssignment.get(s.getID());
if (options.isAssumeImpairing() && prevChan != null && prevChan > maxChannel && stationManager.getDomain(s).contains(prevChan)) {
log.debug("Station {} above max chan, assuming impairing", s);
domains.put(s.getID(), Collections.singleton(prevChan));
} else {
Set<Integer> restrictedDomain;
try {
restrictedDomain = stationManager.getRestrictedDomain(s, maxChannel, true);
if (!restrictedDomain.isEmpty()) {
domains.put(s.getID(), restrictedDomain);
} else {
log.debug("Skipping station {} due to no domain", s);
}
} catch (Exception e) {
log.debug("Skipping station {} due to no domain", s);
}
}
}
// Make the previous assignment compatible with these domains
previousAssignment = Maps.filterEntries(entry.getAssignmentStationToChannel(), e -> domains.get(e.getKey()) != null && domains.get(e.getKey()).contains(e.getValue()));
log.debug("Pre prev assign size is {}", previousAssignment.size());
// Make the previous assignment at least consistent in a stupid greedy way
List<Integer> stations = new ArrayList<>(previousAssignment.keySet());
for (Integer s1 : stations) {
if (previousAssignment.containsKey(s1)) {
for (Integer s2 : stations) {
if (previousAssignment.containsKey(s2) && !Objects.equals(s1, s2)) {
if (!constraintManager.isSatisfyingAssignment(new Station(s1), previousAssignment.get(s1), new Station(s2), previousAssignment.get(s2))) {
// Violation! Remove s1 arbitrarily and continue
previousAssignment.remove(s1);
break;
}
}
}
}
}
}
if (!domains.values().stream().anyMatch(Set::isEmpty)) {
// This will cause a re-cache of the newly done solution (unless something already exists in the cache)
log.trace("Domains are {}", domains);
log.info("Solving problem domain size is {}, prev assign size is {}", domains.size(), previousAssignment.size());
final SATFCResult solve = facade.solve(domains, previousAssignment, options.facadeParameters.fInstanceParameters.Cutoff, options.facadeParameters.fInstanceParameters.Seed, managerBundle.getInterferenceFolder());
if (solve.getResult().equals(SATResult.SAT)) {
log.info("Re-solve successful");
} else {
log.info("Re-solve failed, {}", solve.getResult());
}
} else {
log.info("Skipping re-solve due to empty domain");
}
}
}
| 15,031
| 52.304965
| 299
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/consistency/AC3Output.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/consistency/AC3Output.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 java.util.Map;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.Data;
/**
* Created by newmanne on 10/06/15.
*/
@Data
public class AC3Output {
private boolean noSolution = false;
private final Map<Station, Set<Integer>> reducedDomains;
private int numReducedChannels = 0;
}
| 1,200
| 29.794872
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/consistency/AC3Enforcer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/consistency/AC3Enforcer.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 java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
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.componentgrouper.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 10/06/15.
*/
@Slf4j
public class AC3Enforcer {
private final IConstraintManager constraintManager;
public AC3Enforcer(IConstraintManager constraintManager) {
this.constraintManager = constraintManager;
}
/**
* Enforces arc consistency using AC3 (see https://en.wikipedia.org/wiki/AC-3_algorithm)
* Will fail at the first indication of inconsistency.
*/
public AC3Output AC3(StationPackingInstance instance, ITerminationCriterion criterion) {
// Deep copy map
final Map<Station, Set<Integer>> reducedDomains = instance.getDomains().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new HashSet<>(entry.getValue())));
final AC3Output output = new AC3Output(reducedDomains);
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(ConstraintGrouper.getConstraintGraph(instance.getDomains(), constraintManager));
final LinkedBlockingQueue<Pair<Station, Station>> workList = getInterferingStationPairs(neighborIndex, instance);
while (!criterion.hasToStop() && !workList.isEmpty()) {
final Pair<Station, Station> pair = workList.poll();
if (removeInconsistentValues(pair, output)) {
final Station referenceStation = pair.getLeft();
if (reducedDomains.get(referenceStation).isEmpty()) {
log.debug("Reduced a domain to empty! Problem is solved UNSAT");
output.setNoSolution(true);
return output;
} else {
reenqueueAllAffectedPairs(workList, pair, neighborIndex);
}
}
}
return output;
}
public AC3Output AC3(StationPackingInstance instance) {
return AC3(instance, new NeverEndingTerminationCriterion());
}
private void reenqueueAllAffectedPairs(Queue<Pair<Station, Station>> interferingStationPairs,
Pair<Station, Station> modifiedPair, NeighborIndex<Station, DefaultEdge> neighborIndex) {
final Station x = modifiedPair.getLeft();
final Station y = modifiedPair.getRight();
neighborIndex.neighborsOf(x).stream().filter(neighbor -> !neighbor.equals(y)).forEach(neighbor -> {
interferingStationPairs.add(Pair.of(neighbor, x));
});
}
private LinkedBlockingQueue<Pair<Station, Station>> getInterferingStationPairs(NeighborIndex<Station, DefaultEdge> neighborIndex, StationPackingInstance instance) {
final LinkedBlockingQueue<Pair<Station, Station>> workList = new LinkedBlockingQueue<>();
for (Station referenceStation : instance.getStations()) {
for (Station neighborStation : neighborIndex.neighborsOf(referenceStation)) {
workList.add(Pair.of(referenceStation, neighborStation));
}
}
return workList;
}
/**
* @return true if x's domain changed
*/
private boolean removeInconsistentValues(Pair<Station, Station> pair, AC3Output output) {
final Map<Station, Set<Integer>> domains = output.getReducedDomains();
final Station x = pair.getLeft();
final Station y = pair.getRight();
final List<Integer> xValuesToPurge = new ArrayList<>();
for (int vx : domains.get(x)) {
if (channelViolatesArcConsistency(x, vx, y, domains.get(y))) {
log.trace("Purging channel {} from station {}'s domain", vx, x.getID());
output.setNumReducedChannels(output.getNumReducedChannels() + 1);
xValuesToPurge.add(vx);
}
}
return domains.get(x).removeAll(xValuesToPurge);
}
private boolean channelViolatesArcConsistency(Station x, int vx, Station y, Set<Integer> yDomain) {
return yDomain.stream().noneMatch(vy -> constraintManager.isSatisfyingAssignment(x, vx, y, vy));
}
}
| 5,685
| 42.738462
| 187
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/metrics/InstanceInfo.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/metrics/InstanceInfo.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.metrics;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonInclude;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import lombok.Data;
/**
* Created by newmanne on 21/01/15.
*/
@Data
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class InstanceInfo {
private int numStations;
private Set<Station> stations;
private String name;
private String interference;
private Double runtime;
private SATResult result;
private Set<Integer> underconstrainedStations = new HashSet<>();
private Map<String, InstanceInfo> components = new HashMap<>();
private SolverResult.SolvedBy solvedBy;
private Map<String, Double> timingInfo = new HashMap<>();
private String cacheResultUsed;
private Map<Station, Integer> stationToDegree = new HashMap<>();
private Map<Station, Integer> assignment;
private String nickname;
private String hash;
}
| 1,965
| 31.766667
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/metrics/SATFCMetrics.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/metrics/SATFCMetrics.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.metrics;
import java.lang.management.ManagementFactory;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.jvm.BufferPoolMetricSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.StationPackingInstanceHasher;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
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.componentgrouper.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 15/01/15.
* Collects metrics on solving SATFC problems
* If your problems don't have unique names, behaviour is undefined (because we use names to reference problems)
*/
@Slf4j
public class SATFCMetrics {
private static MetricHandler metricsHandler;
private static EventBus eventBus;
public static void init() {
metricsHandler = new MetricHandler();
eventBus = new EventBus((exception, context) -> {
log.error("Could not dispatch event: " + context.getSubscriber() + " to " + context.getSubscriberMethod(), exception);
});
eventBus.register(metricsHandler);
registerAll("gc", new GarbageCollectorMetricSet(), registry);
registerAll("buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()), registry);
registerAll("memory", new MemoryUsageGaugeSet(), registry);
registerAll("threads", new ThreadStatesGaugeSet(), registry);
}
public static void postEvent(Object event) {
if (eventBus != null) {
eventBus.post(event);
}
}
public static void doWithMetrics(MetricHandler.IMetricCallback callback) {
metricsHandler.doWithMetrics(callback);
}
public static void clear() {
if (eventBus != null) {
metricsHandler.clear();
}
}
@Data
public static class NewStationPackingInstanceEvent {
private final StationPackingInstance instance;
private final IConstraintManager constraintManager;
}
@Data
public static class InstanceSolvedEvent {
private final String name;
private final SolverResult solverResult;
}
@Data
public static class UnderconstrainedStationsRemovedEvent {
private final String name;
private final Set<Station> underconstrainedStations;
}
@Data
public static class SplitIntoConnectedComponentsEvent {
private final String name;
private final Collection<StationPackingInstance> components;
}
@Data
public static class TimingEvent {
public final static String FIND_SUPERSET = "find_superset";
public final static String FIND_SUBSET = "find_subset";
public final static String FIND_UNDERCONSTRAINED_STATIONS = "find_underconstrained_stations";
public final static String PUT_BACK_UNDERCONSTRAINED_STATIONS = "put_back_underconstrained_stations";
public final static String CONNECTED_COMPONENTS = "split_connected_components";
public final static String ARC_CONSISTENCY = "arc_consistency";
private final String name;
private final String timedEvent;
private final double time;
}
@Data
public static class JustifiedByCacheEvent {
private final String name;
private final String key;
}
public static class MetricHandler {
private InstanceInfo activeProblemMetrics;
private Lock metricsLock = new ReentrantLock();
public interface IMetricCallback {
void doWithLock(InstanceInfo info);
}
private void safeMetricEdit(String name, IMetricCallback callback) {
try {
metricsLock.lock();
// ensure that you only edit the "current problem" metrics.
if (activeProblemMetrics != null && name.startsWith(activeProblemMetrics.getName())) {
final InstanceInfo info = getInfo(name);
if (info != null) {
callback.doWithLock(info);
}
}
} finally {
metricsLock.unlock();
}
}
public void doWithMetrics(IMetricCallback callback) {
try {
metricsLock.lock();
callback.doWithLock(activeProblemMetrics);
} finally {
metricsLock.unlock();
}
}
private void clear() {
activeProblemMetrics = null;
}
private InstanceInfo getInfo(String name) {
if (activeProblemMetrics == null) {
throw new IllegalStateException("Trying to add metrics with no valid problem");
} else if (name.equals(activeProblemMetrics.getName())) {
return activeProblemMetrics;
} else if (name.contains("_component")) {
return activeProblemMetrics.getComponents().get(name);
}
return null; // This will catch presolver instances
}
@Subscribe
public void onNewStationPackingInstanceEvent(NewStationPackingInstanceEvent event) {
// don't thread this one
if (activeProblemMetrics != null) {
throw new IllegalStateException("Metrics already in progress!");
}
activeProblemMetrics = new InstanceInfo();
final StationPackingInstance instance = event.getInstance();
activeProblemMetrics.setName(instance.getName());
activeProblemMetrics.setStations(instance.getStations());
activeProblemMetrics.setNumStations(instance.getStations().size());
activeProblemMetrics.setHash(StationPackingInstanceHasher.hash(instance).toString());
// Calculate degrees. May be a bit expensive...
final SimpleGraph<Station, DefaultEdge> constraintGraph = ConstraintGrouper.getConstraintGraph(instance.getDomains(), event.getConstraintManager());
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(constraintGraph);
activeProblemMetrics.setStationToDegree(instance.getStations().stream().collect(Collectors.toMap(Function.identity(), s -> neighborIndex.neighborsOf(s).size())));
}
@Subscribe
public void onInstanceSolvedEvent(InstanceSolvedEvent event) {
safeMetricEdit(event.getName(), info -> {
info.setResult(event.getSolverResult().getResult());
if (event.getSolverResult().getResult().equals(SATResult.SAT)) {
info.setAssignment(StationPackingUtils.stationToChannelFromChannelToStation(event.getSolverResult().getAssignment()));
}
info.setRuntime(event.getSolverResult().getRuntime());
info.setSolvedBy(event.getSolverResult().getSolvedBy());
info.setNickname(event.getSolverResult().getNickname());
});
}
@Subscribe
public void onUnderconstrainedStationsRemovedEvent(UnderconstrainedStationsRemovedEvent event) {
safeMetricEdit(event.getName(), info -> {
info.getUnderconstrainedStations().addAll(event.getUnderconstrainedStations().stream().map(Station::getID).collect(Collectors.toSet()));
});
}
@Subscribe
public void onSplitIntoConnectedComponentsEvent(SplitIntoConnectedComponentsEvent event) {
safeMetricEdit(event.getName(), outerInfo -> {
event.getComponents().forEach(component -> {
final InstanceInfo instanceInfo = new InstanceInfo();
outerInfo.getComponents().put(component.getName(), instanceInfo);
instanceInfo.setName(component.getName());
instanceInfo.setNumStations(component.getStations().size());
instanceInfo.setStations(component.getStations());
});
});
}
@Subscribe
public void onTimingEvent(TimingEvent event) {
safeMetricEdit(event.getName(), info -> {
info.getTimingInfo().put(event.getTimedEvent(), event.getTime());
});
}
@Subscribe
public void onJustifiedByCacheEvent(JustifiedByCacheEvent event) {
safeMetricEdit(event.getName(), info -> {
info.setCacheResultUsed(event.getKey());
});
}
}
// codahale metrics for jvm stuff:
private final static MetricRegistry registry = new MetricRegistry();
// log jvm metrics
public static void report() {
log.info("Reporting jvm metrics");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(registry)
.outputTo(log)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.report();
}
private static void registerAll(String prefix, MetricSet metricSet, MetricRegistry registry) {
for (Map.Entry<String, Metric> entry : metricSet.getMetrics().entrySet()) {
if (entry.getValue() instanceof MetricSet) {
registerAll(prefix + "." + entry.getKey(), (MetricSet) entry.getValue(), registry);
} else {
registry.register(prefix + "." + entry.getKey(), entry.getValue());
}
}
}
}
| 11,334
| 39.053004
| 174
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/AuctionCSVParser.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/AuctionCSVParser.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 java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.beust.jcommander.Parameter;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
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 ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import ch.qos.logback.classic.Level;
import lombok.Cleanup;
import lombok.Data;
/**
* Created by newmanne on 2016-02-18.
*/
public class AuctionCSVParser {
private static org.slf4j.Logger log;
private final static AtomicInteger nProblems = new AtomicInteger();
@UsageTextField(title = "s", description = "j")
public static class AuctionCSVParserParams extends AbstractOptions {
@Parameter(names = "-SERVER-URL", description = "server url")
public String serverURL;
}
public static void main(String[] args) throws Exception {
SATFCFacadeBuilder.initializeLogging(Level.INFO, null);
log = org.slf4j.LoggerFactory.getLogger(AuctionCSVParser.class);
final AuctionCSVParserParams p = new AuctionCSVParserParams();
JCommanderHelper.parseCheckingForHelpAndVersion(args, p);
final String INTERFERENCE_ROOT = "/ubc/cs/research/arrow/satfc/instances/interference-data/";
@Cleanup
final SATFCFacade facade = new SATFCFacadeBuilder()
.setServerURL(p.serverURL)
.build();
final String CSV_FILE_ROOT = "/ubc/cs/research/arrow/satfc/instances/rawdata/csvs";
final File[] csvFolders = new File(CSV_FILE_ROOT).listFiles(File::isDirectory);
for (File auctionDir : Arrays.stream(csvFolders).filter(d -> Integer.parseInt(d.getName()) >= 3240).collect(Collectors.toList())) {
final String auction = auctionDir.getName();
log.info("Reading files from auction {}", auction);
final File[] csvFiles = auctionDir.listFiles();
for (File csvFile : csvFiles) {
final List<ProblemAndAnswer> problems = parseAuctionFile(auction, csvFile.getAbsolutePath());
for (ProblemAndAnswer problem : problems) {
if (problem.getInterference().equals("102015SC44U") && problem.getResult().equals("yes")) {
int maxChan = problem.getDomains().values().stream().flatMap(Collection::stream).mapToInt(Integer::valueOf).max().getAsInt();
if (StationPackingUtils.UHF_CHANNELS.contains(maxChan)) {
final SATFCResult satfcResult = facade.solve(problem.getDomains(), new HashMap<>(), 60.0, 1, INTERFERENCE_ROOT + File.separator + problem.getInterference(), problem.getInstanceName());
Preconditions.checkState(satfcResult.getResult().equals(SATResult.SAT), "Result was not SAT!");
int nSolved = nProblems.getAndIncrement();
if (nSolved % 100 == 0) {
log.info("Solved {} problems", nSolved);
}
}
}
}
}
}
}
public static List<ProblemAndAnswer> parseAuctionFile(String auction, String fileName) throws IOException {
final List<String> lines = Files.readAllLines(Paths.get(fileName));
String interferenceData = null;
Double cutoff = null;
Long sequenceId = null;
int i;
for (i = 0; i < lines.size(); i++) {
final String line = lines.get(i);
final List<String> split = Splitter.on(',').splitToList(line);
// Parse header
if (split.get(0).equals("constraints")) {
interferenceData = split.get(1);
} else if (split.get(0).equals("timeout")) {
cutoff = Double.parseDouble(split.get(1)) / 1000.0;
} else if (split.get(0).equals("sequence_id")) {
sequenceId = Long.parseLong(split.get(1));
} else if (split.get(0).equals("shared_info")) {
i++;
break;
} else {
throw new IllegalStateException("Unrecognized key " + line);
}
}
Preconditions.checkNotNull(interferenceData);
Preconditions.checkNotNull(cutoff);
Preconditions.checkNotNull(sequenceId);
final Map<Integer, Integer> prevAssign = new HashMap<>();
final Map<Integer, Set<Integer>> currentProblem = new HashMap<>();
// Parse assignment
for (; i < lines.size(); i++) {
final String line = lines.get(i);
final List<String> split = Splitter.on(',').splitToList(line);
if (split.get(0).equals("problems")) {
i++;
break;
} else {
int station = Integer.parseInt(split.get(0));
int prevChan = Integer.parseInt(split.get(1));
Set<Integer> domains = split.subList(2, split.size()).stream().map(Integer::parseInt).collect(Collectors.toSet());
prevAssign.put(station, prevChan);
currentProblem.put(station, domains);
}
}
// Parse problems
final List<ProblemAndAnswer> problems = new ArrayList<>();
int p = 0;
for (; i < lines.size(); i++) {
p += 1;
final String line = lines.get(i);
final List<String> split = Splitter.on(',').splitToList(line);
if (split.get(0).equals("answers")) {
i++;
break;
} else {
int station = Integer.parseInt(split.get(0));
Set<Integer> domains = split.subList(1, split.size()).stream().map(Integer::parseInt).collect(Collectors.toSet());
Map<Integer, Set<Integer>> problem = new HashMap<>(currentProblem);
problem.put(station, domains);
final String fName = new File(fileName).getName().replace(".csv", "");
final String name = auction + "_" + fName + "_" + sequenceId + "_" + p + ".srpk";
problems.add(new ProblemAndAnswer(problem, prevAssign, interferenceData, name));
}
}
// Parse answers
p = 0;
for (; i < lines.size(); i++) {
p += 1;
final String line = lines.get(i);
final List<String> split = Splitter.on(',').splitToList(line);
final String result = split.get(1);
final Set<String> results = Sets.newHashSet("yes", "no", "unknown", "error", "interrupted");
Preconditions.checkState(results.contains(result), "Unrecognized result %s", result);
problems.get(p - 1).setResult(result);
if (result.equals("yes")) {
Map<Integer, Integer> stationToChannel = new HashMap<>();
for (int j = 2; j < split.size(); j++) {
final List<String> sc = Splitter.on(':').splitToList(split.get(j));
int station = Integer.parseInt(sc.get(0));
int chan = Integer.parseInt(sc.get(1));
stationToChannel.put(station, chan);
}
problems.get(p - 1).setAnswer(stationToChannel);
}
}
return problems;
}
@Data
public static class ProblemAndAnswer {
private final Map<Integer, Set<Integer>> domains;
private final Map<Integer, Integer> previousAssignment;
private final String interference;
private final String instanceName;
private String result;
private Map<Integer, Integer> answer;
}
}
| 9,238
| 41.380734
| 212
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/SATFCFacadeExecutor.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/SATFCFacadeExecutor.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 java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.aeatk.misc.returnvalues.AEATKReturnValues;
import ca.ubc.cs.beta.aeatk.targetalgorithmevaluator.init.TargetAlgorithmEvaluatorLoader;
import ca.ubc.cs.beta.stationpacking.execution.metricwriters.IMetricWriter;
import ca.ubc.cs.beta.stationpacking.execution.metricwriters.MetricWriterFactory;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.CutoffChooserFactory;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.ICutoffChooser;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.IProblemReader;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.ProblemGeneratorFactory;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.SATFCFacadeProblem;
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.metrics.SATFCMetrics;
/**
* Executes a SATFC facade built from parameters on an instance given in parameters.
*
* @author afrechet
*/
public class SATFCFacadeExecutor {
/**
* @param args - parameters satisfying {@link SATFCFacadeParameters}.
*/
public static void main(String[] args) {
//Parse the command line arguments in a parameter object.
SATFCFacadeParameters parameters = new SATFCFacadeParameters();
Logger log = parseParameter(args, parameters);
logVersionInfo(log);
try {
log.info("Initializing facade.");
try(final SATFCFacade satfc = SATFCFacadeBuilder.builderFromParameters(parameters).build()) {
IProblemReader problemReader = ProblemGeneratorFactory.createFromParameters(parameters);
ICutoffChooser cutoffChooser = CutoffChooserFactory.createFromParameters(parameters);
IMetricWriter metricWriter = MetricWriterFactory.createFromParameters(parameters);
SATFCFacadeProblem problem;
while ((problem = problemReader.getNextProblem()) != null) {
final double cutoff = cutoffChooser.getCutoff(problem);
log.info("Beginning problem {} with cutoff {}", problem.getInstanceName(), cutoff);
log.info("Solving ...");
SATFCResult result = satfc.solve(
problem.getDomains(),
problem.getPreviousAssignment(),
cutoff,
parameters.fInstanceParameters.Seed,
problem.getStationConfigFolder(),
problem.getInstanceName()
);
log.info("..done!");
if (!log.isInfoEnabled()) {
System.out.println(result.getResult());
System.out.println(result.getRuntime());
System.out.println(result.getWitnessAssignment());
} else {
log.info("Result:" + System.lineSeparator() + result.getResult() + System.lineSeparator() + result.getRuntime() + System.lineSeparator() + result.getWitnessAssignment());
}
problemReader.onPostProblem(problem, result);
metricWriter.writeMetrics();
SATFCMetrics.clear();
}
log.info("Finished all of the problems!");
problemReader.onFinishedAllProblems();
metricWriter.onFinished();
}
} catch (ParameterException e) {
log.error("Invalid parameter argument detected.", e);
e.printStackTrace();
System.exit(AEATKReturnValues.PARAMETER_EXCEPTION);
} catch (RuntimeException e) {
log.error("Runtime exception encountered ", e);
e.printStackTrace();
System.exit(AEATKReturnValues.UNCAUGHT_EXCEPTION);
} catch (UnsatisfiedLinkError e) {
log.error("Couldn't initialize facade, see previous log messages and/or try logging with DEBUG.", e);
System.exit(AEATKReturnValues.UNCAUGHT_EXCEPTION);
} catch (Throwable t) {
log.error("Throwable encountered ", t);
t.printStackTrace();
System.exit(AEATKReturnValues.UNCAUGHT_EXCEPTION);
}
log.info("Normal termination. Goodbye");
}
private static Logger parseParameter(String[] args, SATFCFacadeParameters parameters) {
Logger log;
try {
//Check for help
JCommanderHelper.parseCheckingForHelpAndVersion(args, parameters, TargetAlgorithmEvaluatorLoader.getAvailableTargetAlgorithmEvaluators());
SATFCFacadeBuilder.initializeLogging(parameters.getLogLevel(), parameters.logFileName);
JCommanderHelper.logCallString(args, SATFCFacadeExecutor.class);
} finally {
log = LoggerFactory.getLogger(SATFCFacadeExecutor.class);
}
return log;
}
public static void logVersionInfo(Logger log) {
try {
final String versionProperties = Resources.toString(Resources.getResource("version.properties"), Charsets.UTF_8);
log.info("Version info: " + System.lineSeparator() + versionProperties);
} catch (IllegalArgumentException | IOException e) {
log.error("Could not log version info.");
}
}
}
| 6,700
| 46.864286
| 194
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/AProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/AProblemReader.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 ca.ubc.cs.beta.stationpacking.execution.problemgenerators.IProblemReader;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.SATFCFacadeProblem;
import ca.ubc.cs.beta.stationpacking.facade.SATFCResult;
/**
* Created by newmanne on 12/05/15.
*/
public abstract class AProblemReader implements IProblemReader {
protected int index = 1;
public abstract SATFCFacadeProblem getNextProblem();
@Override
public void onPostProblem(SATFCFacadeProblem problem, SATFCResult result) {
index++;
}
}
| 1,406
| 32.5
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/Converter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/Converter.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 java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.ParametersDelegate;
import ca.ubc.cs.beta.aeatk.logging.ConsoleOnlyLoggingOptions;
import ca.ubc.cs.beta.aeatk.logging.LoggingOptions;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
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.stations.IStationManager;
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.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 lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
/**
* In charge of converting different station repacking instance formats to other formats (either .sprk, or SAT/MIP encodings).
* Intended for internal use only
*
* @author afrechet
*/
public class Converter {
private static Logger log;
private static enum OutType {
INSTANCE,
CNF
}
@UsageTextField(title = "Converter Parameters", description = "Parameters needed to convert station packing instances.")
private static class ConverterParameters extends AbstractOptions {
/**
*
*/
private static final long serialVersionUID = 1L;
@Parameter(names = "--instance", description = "The instances to convert. Can be a single instance file (.qstn for a question file, .sql for a sql instance, .srpk for a station repacking instance), a folder containing a bunch of files, or a .txt/.csv file containing a list of files, or any composition of the previous.")
List<String> fInstanceNames = null;
@Parameter(names = "--interference-folder", description = "Interference folder associated with the given instances (required for instances that do not specify interference folders).")
String fInterferenceFolder = null;
@Parameter(names = "--interference-folder-prefix", description = "Prefix to add to any interference folder, usually a path to a directory containing all interference folders.")
String fInterferenceFolderPrefix = null;
@UsageTextField(defaultValues = "<current directory>")
@Parameter(names = "--out-directory", description = "Folder where to write converted instance")
String fOutDirectory = null;
@Parameter(names = "--out-type", description = "what to convert instances to.")
OutType fOutType = OutType.INSTANCE;
@ParametersDelegate
private LoggingOptions fLoggingOptions = new ConsoleOnlyLoggingOptions();
}
/**
* @param aInstanceNames - list of instance names, either instance file names (.qstn, .sql, .srpk), folder containing instances or instance lists (.txt, .csv).
* @return a list of proper instance files.
*/
private static List<String> getInstancesFilenames(List<String> aInstanceNames) {
final List<String> instancesFilenames = new ArrayList<String>();
final Queue<String> instanceNames = new LinkedList<String>(aInstanceNames);
while (!instanceNames.isEmpty()) {
log.debug("Still {} possible instances to add...", instanceNames.size());
final String instanceName = instanceNames.remove();
final File instanceFile = new File(instanceName);
if (!instanceFile.exists()) {
throw new ParameterException("Provided instance name " + instanceName + " is not a file/directory that exists.");
}
if (instanceFile.isDirectory()) {
log.debug("Adding all the instances from the directory {} ...", instanceFile.getAbsolutePath());
final File[] subFiles = instanceFile.listFiles();
for (final File subFile : subFiles) {
instanceNames.add(subFile.getPath());
}
log.debug("Added {} instances.", subFiles.length);
} else {
final String extension = FilenameUtils.getExtension(instanceName);
switch (extension) {
case "txt":
log.debug("Adding all the instances listed in the file {} ...", instanceFile.getAbsolutePath());
int count = 0;
try {
try (final BufferedReader br = new BufferedReader(new FileReader(instanceFile));) {
String line;
while ((line = br.readLine()) != null) {
instanceNames.add(line);
count++;
}
}
} catch (IOException e) {
e.printStackTrace();
throw new ParameterException("Could not read instances from instance list file " + instanceName + " (" + e.getMessage() + ").");
}
log.debug("Added {} instances.", count);
break;
case "sql":
case "srpk":
instancesFilenames.add(instanceName);
break;
default:
log.warn("Unrecognized instance extension {} for file in provided instance {}. Skipping instance.", extension, instanceName);
}
}
}
return instancesFilenames;
}
/**
* Station packing problem specs that contains the necessary information to instantiate a station packing problem.
*
* @author afrechet
*/
@Data
@AllArgsConstructor
public static class StationPackingProblemSpecs {
private String source;
@NonNull
private final Map<Integer, Set<Integer>> domains;
private Map<Integer, Integer> previousAssignment;
@NonNull
private final String dataFoldername;
private Double cutoff;
public StationPackingProblemSpecs(Map<Integer, Set<Integer>> domains, Map<Integer, Integer> previousAssignment, String dataFoldername) {
this.dataFoldername = dataFoldername;
this.domains = domains;
this.previousAssignment = previousAssignment;
}
/**
* @param aSQLInstanceFilename - a sql instance filename. Taken from MYSQLDBTAE additional run data from auction simulator runs.
* @return a station packing problem spec from the SQL instance.
* @throws IOException
*/
public static StationPackingProblemSpecs fromSQL(String aSQLInstanceFilename) throws IOException {
List<String> lines = FileUtils.readLines(new File(aSQLInstanceFilename));
if (lines.isEmpty()) {
throw new IllegalArgumentException("SQL instance file " + aSQLInstanceFilename + " is empty.");
} else if (lines.size() > 1) {
log.warn("SQL instance file {} has more than one lines ({}), but only the first line will be read.", aSQLInstanceFilename, lines.size());
}
String sqlInstanceString = lines.get(0);
final Map<Integer, Set<Integer>> stationID_domains = new HashMap<Integer, Set<Integer>>();
final Map<Integer, Integer> previous_assignmentID = new HashMap<Integer, Integer>();
final String config_foldername;
String[] encoded_instance_parts = sqlInstanceString.split("_");
if (encoded_instance_parts.length == 0) {
throw new IllegalArgumentException("Unparseable encoded instance string \"" + sqlInstanceString + "\".");
}
config_foldername = encoded_instance_parts[0];
//Get problem info.
for (int i = 1; i < encoded_instance_parts.length; i++) {
Integer station;
Integer previousChannel;
Set<Integer> domain;
String station_info_string = encoded_instance_parts[i];
String[] station_info_parts = station_info_string.split(";");
String station_string = station_info_parts[0];
try {
station = Integer.parseInt(station_string);
} catch (NumberFormatException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable station info \"" + station_info_string + "\" (station ID " + station_string + " is not an integer).");
}
String previous_channel_string = station_info_parts[1];
try {
previousChannel = Integer.parseInt(previous_channel_string);
if (previousChannel <= 0) {
previousChannel = null;
}
} catch (NumberFormatException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable station info \"" + station_info_string + "\" (previous channel " + previous_channel_string + " is not an integer).");
}
domain = new HashSet<Integer>();
String channels_string = station_info_parts[2];
String[] channels_parts = channels_string.split(",");
for (String channel_string : channels_parts) {
try {
domain.add(Integer.parseInt(channel_string));
} catch (NumberFormatException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable station info \"" + station_info_string + "\" (domain channel " + channel_string + " is not an integer).");
}
}
stationID_domains.put(station, domain);
if (previousChannel != null) {
previous_assignmentID.put(station, previousChannel);
}
}
return new StationPackingProblemSpecs(aSQLInstanceFilename, stationID_domains, previous_assignmentID, config_foldername, null);
}
/**
* @param aStationRepackingInstanceFilename - a srpk instance filename.
* @return a station repacking instance taken from the srpk file.
* @throws IOException
*/
public static StationPackingProblemSpecs fromStationRepackingInstance(String aStationRepackingInstanceFilename) throws IOException {
Map<Integer, Set<Integer>> domains = new HashMap<Integer, Set<Integer>>();
Map<Integer, Integer> previousAssignment = new HashMap<Integer, Integer>();
String configFoldername = null;
Double cutoff = null;
List<String> lines = FileUtils.readLines(new File(aStationRepackingInstanceFilename));
for (String line : lines) {
final String[] lineParts = line.split(",");
String key = lineParts[0];
switch (key) {
case "INTERFERENCE":
configFoldername = lineParts[1];
break;
case "CUTOFF":
cutoff = Double.valueOf(lineParts[1]);
break;
case "SOURCE":
break;
default:
try {
Integer stationID = Integer.valueOf(lineParts[0]);
Integer previousChannel = Integer.valueOf(lineParts[1]);
if (previousChannel > 0) {
previousAssignment.put(stationID, previousChannel);
}
Set<Integer> domain = new HashSet<Integer>();
for (int i = 2; i < lineParts.length; i++) {
Integer channel = Integer.valueOf(lineParts[i]);
domain.add(channel);
}
domains.put(stationID, domain);
} catch (NumberFormatException e) {
e.printStackTrace();
throw new IllegalArgumentException("Unparseable station info \"" + line + "\" (could not cast one of the components to integer).");
}
}
}
return new StationPackingProblemSpecs(aStationRepackingInstanceFilename, domains, previousAssignment, configFoldername, cutoff);
}
}
/**
* @param aInstanceFilename - a station repacking instance file.
* @return a station repacking problem spec from the given instance file.
*/
private static StationPackingProblemSpecs getStationPackingProblemSpecs(String aInstanceFilename) {
final String extension = FilenameUtils.getExtension(aInstanceFilename);
final StationPackingProblemSpecs specs;
switch (extension) {
case "sql":
try {
specs = StationPackingProblemSpecs.fromSQL(aInstanceFilename);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Could not read lines from SQL instance file " + aInstanceFilename + ".");
}
break;
case "srpk":
try {
specs = StationPackingProblemSpecs.fromStationRepackingInstance(aInstanceFilename);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("Could not convert station repacking instance " + aInstanceFilename + " (" + e.getMessage() + ").");
}
break;
default:
throw new IllegalArgumentException("Unsupported instance " + aInstanceFilename + " with extension " + extension + ".");
}
return specs;
}
public static void main(String[] args) {
ConverterParameters parameters = new ConverterParameters();
JCommanderHelper.parseCheckingForHelpAndVersion(args, parameters);
parameters.fLoggingOptions.initializeLogging();
log = LoggerFactory.getLogger(Converter.class);
/*
* Gather all instances.
*/
log.debug("Gathering all instance names...");
if (parameters.fInstanceNames == null) {
throw new ParameterException("Must specify at least one instance.");
}
List<String> problemFilenames = getInstancesFilenames(parameters.fInstanceNames);
/*
* Convert the instances.
*/
log.debug("Converting the instances ...");
final DataManager dataManager = new DataManager();
final Map<String, ISATEncoder> satEncoders = new HashMap<String, ISATEncoder>();
String outputDir = parameters.fOutDirectory != null ? parameters.fOutDirectory : "";
OutType outType = parameters.fOutType;
int i = 0;
for (String problemFilename : problemFilenames) {
if (i % 50 == 0) {
System.gc();
}
log.debug("Reading in instance {}/{}.", i++, problemFilenames.size());
StationPackingProblemSpecs spec = getStationPackingProblemSpecs(problemFilename);
final String source = spec.getSource();
String configFoldername;
if (spec.getDataFoldername() != null) {
configFoldername = spec.getDataFoldername();
} else if (parameters.fInterferenceFolder == null) {
throw new IllegalArgumentException("Instance " + source + " does not specify interference config folder, and the latter hasn't been specified as an option.");
} else {
configFoldername = parameters.fInterferenceFolder;
}
//Append prefix
if (parameters.fInterferenceFolderPrefix != null) {
configFoldername = new File(parameters.fInterferenceFolderPrefix, configFoldername).toString();
}
//Load in the interference data.
log.debug("Loading in interference data from {} ...", configFoldername);
ManagerBundle bundle;
try {
bundle = dataManager.getData(configFoldername);
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new IllegalArgumentException("Could not load in interference data (" + e.getMessage() + ").");
}
final IStationManager stationManager = bundle.getStationManager();
final IConstraintManager constraintManager = bundle.getConstraintManager();
final Map<Station, Set<Integer>> domains = new HashMap<Station, Set<Integer>>();
for (Entry<Integer, Set<Integer>> entryDomains : spec.getDomains().entrySet()) {
domains.put(stationManager.getStationfromID(entryDomains.getKey()), entryDomains.getValue());
}
Map<Station, Integer> previousAssignment = null;
if (spec.getPreviousAssignment() != null) {
previousAssignment = new HashMap<Station, Integer>();
for (Entry<Integer, Integer> entryPreviousAssignment : spec.getPreviousAssignment().entrySet()) {
previousAssignment.put(stationManager.getStationfromID(entryPreviousAssignment.getKey()), entryPreviousAssignment.getValue());
}
}
final StationPackingInstance instance;
if (previousAssignment == null) {
instance = new StationPackingInstance(domains);
} else {
instance = new StationPackingInstance(domains, previousAssignment);
}
switch (outType) {
case INSTANCE:
List<String> lines = new ArrayList<String>();
lines.add("SOURCE," + source);
lines.add("INTERFERENCE," + configFoldername);
if (spec.getCutoff() != null) {
lines.add("CUTOFF," + spec.getCutoff());
}
List<Station> stations = new ArrayList<Station>(instance.getStations());
Collections.sort(stations);
for (Station station : stations) {
List<Integer> domain = new ArrayList<Integer>(instance.getDomains().get(station));
Collections.sort(domain);
Integer previousChannel = instance.getPreviousAssignment().get(station);
if (previousChannel == null || previousChannel < 0) {
previousChannel = -1;
}
lines.add(station.getID() + "," + previousChannel + "," + StringUtils.join(domain, ","));
}
String instanceFilename = FilenameUtils.concat(outputDir, FilenameUtils.getBaseName(source) + ".srpk");
File instanceFile = new File(instanceFilename);
if (instanceFile.exists()) {
throw new IllegalStateException("Instance file already exists with name \"" + instanceFilename + "\".");
}
try {
FileUtils.writeLines(instanceFile, lines);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Could not write instance to file.");
}
break;
case CNF:
final ISATEncoder satEncoder;
if (satEncoders.containsKey(configFoldername)) {
satEncoder = satEncoders.get(configFoldername);
} else {
satEncoder = new SATCompressor(constraintManager, EncodingType.DIRECT);
satEncoders.put(configFoldername, satEncoder);
}
log.debug("Converting instance from {} to CNF ...", source);
Pair<CNF, ISATDecoder> satEncoding = satEncoder.encode(instance);
CNF cnf = satEncoding.getFirst();
List<Integer> sortedStationIDs = new ArrayList<Integer>();
for (Station station : instance.getStations()) {
sortedStationIDs.add(station.getID());
}
Collections.sort(sortedStationIDs);
List<Integer> sortedAllChannels = new ArrayList<Integer>(instance.getAllChannels());
Collections.sort(sortedAllChannels);
String[] aComments = new String[]{
"FCC Feasibility Checking Instance",
"Original Instance File: " + source,
"Interference folder: " + configFoldername,
"Channels: " + StringUtils.join(sortedAllChannels, ","),
"Stations: " + StringUtils.join(sortedStationIDs, ",")};
String aCNFFilename = FilenameUtils.concat(outputDir, FilenameUtils.getBaseName(source) + ".cnf");
File cnfFile = new File(aCNFFilename);
if (cnfFile.exists()) {
log.warn("CNF file already exists with name \"" + cnfFile + "\".");
}
try {
FileUtils.writeStringToFile(cnfFile, cnf.toDIMACS(aComments));
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Could not write CNF to file.");
}
break;
default:
throw new ParameterException("Unrecognized out type " + outType + ".");
}
}
}
}
| 24,197
| 44.399625
| 329
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/WeightedCollection.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/WeightedCollection.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.extendedcache;
import java.util.NavigableMap;
import java.util.Random;
import java.util.TreeMap;
/**
* Created by emily404 on 6/15/15.
*/
/**
* Collection with random and weighted selector
* @param <E> class of the collection
*/
public class WeightedCollection<E> {
private final NavigableMap<Double, E> map = new TreeMap<>();
private final Random random;
private double total = 0;
public WeightedCollection() {
this(new Random());
}
public WeightedCollection(Random random) {
this.random = random;
}
/**
* Accumulate total weight
* Map current total weight to current object
* @param weight weight of current object
* @param object object to be added to map
*/
public void add(double weight, E object) {
if (weight <= 0) return;
total += weight;
map.put(total, object);
}
/**
* Random: generate a random number range [0, total] inclusisve
* Weighted: object contributed higher weight in method, add(double weight, E object), has a higher chance of being selected
* @return weighted random selection object
*/
public E next() {
double value = random.nextDouble() * total;
return map.ceilingEntry(value).getValue();
}
}
| 2,148
| 28.847222
| 128
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IStationSampler.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IStationSampler.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.extendedcache;
import java.util.Set;
/**
* Created by emily404 on 6/4/15.
*/
public interface IStationSampler {
/**
* Determine a new station to add to the problem based on the sampling method
* {@link ca.ubc.cs.beta.stationpacking.execution.extendedcache.StationSamplerParameters.StationSamplingMethod}
* @param stationsInProblem a set representing stations that are present in a problem
* @return stationID of the station to be added
*/
Integer sample(Set<Integer> stationsAlreadyInProblem);
}
| 1,397
| 34.846154
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IStationDB.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IStationDB.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.extendedcache;
/**
* Created by newmanne on 15/10/15.
* A database object providing additional information on stations
*/
public interface IStationDB {
/**
* @param id station id
* @return station population
*/
int getPopulation(int id);
/**
* @param id station id
* @return station volume
*/
double getVolume(int id);
}
| 1,238
| 27.159091
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IProblemSampler.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/IProblemSampler.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.extendedcache;
import java.util.List;
/**
* Created by emily404 on 6/4/15.
*/
public interface IProblemSampler {
/**
* Determine a list of new problems to extend based on a sampling method
* {@link ca.ubc.cs.beta.stationpacking.execution.extendedcache.ProblemSamplerParameters.ProblemSamplingMethod}
* @param counter put counter number of new problems to keyQueue
* @return keys of cache entries to be added to keyQueue
*/
List<String> sample(int counter);
/**
* Determine a new problems to extend based on a sampling method
* {@link ca.ubc.cs.beta.stationpacking.execution.extendedcache.ProblemSamplerParameters.ProblemSamplingMethod}
* @return key of cache entry to be added to keyQueue
*/
String sample();
}
| 1,641
| 34.695652
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/PopulationVolumeSampler.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/PopulationVolumeSampler.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.extendedcache;
import java.io.IOException;
import java.util.Random;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/**
* Created by emily404 on 6/4/15.
*/
@Slf4j
public class PopulationVolumeSampler implements IStationSampler {
private WeightedCollection<Integer> weightedStationMap;
/**
* @param keep The set of stations we actually want to sample from
* @throws IOException
*/
public PopulationVolumeSampler(IStationDB stationDB, Set<Integer> keep, int seed) {
weightedStationMap = new WeightedCollection<>(new Random(seed));
for (Integer stationID : keep) {
double weight = ((double) stationDB.getPopulation(stationID)) / stationDB.getVolume(stationID);
weightedStationMap.add(weight, stationID);
}
}
@Override
public Integer sample(Set<Integer> stationsAlreadyInProblem) {
Integer station = weightedStationMap.next();
log.debug("Sampling station...");
while(stationsAlreadyInProblem.contains(station)){
station = weightedStationMap.next();
}
log.debug("Sampled stationID: {}", station);
return station;
}
}
| 2,045
| 31.47619
| 107
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/CSVStationDB.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/extendedcache/CSVStationDB.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.extendedcache;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Preconditions;
import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 15/10/15.
*/
@Slf4j
public class CSVStationDB implements IStationDB {
final Map<Integer, Integer> stationToPopulation;
final Map<Integer, Double> stationToVolume;
/**
* @param stationFile a path to a csv file with a header and columns "id, population, volume"
*/
public CSVStationDB(String stationFile) {
log.info("Parsing {} for station info", stationFile);
stationToPopulation = new HashMap<>();
stationToVolume = new HashMap<>();
try (CSVReader reader = new CSVReader(new FileReader(stationFile))) {
String[] line;
while ((line = reader.readNext()) != null) {
final int id = Integer.parseInt(line[0].trim());
final int population = Integer.parseInt(line[1].trim());
final double volume = Double.parseDouble(line[2].trim());
Preconditions.checkState(!stationToVolume.containsKey(id) && !stationToVolume.containsKey(id), "Previous value associated with station id %d", id);
stationToPopulation.put(id, population);
stationToVolume.put(id, volume);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not read station information file: " + stationFile, e);
}
}
@Override
public int getPopulation(int id) {
Preconditions.checkState(stationToPopulation.containsKey(id), "No known population for station with id %d", id);
return stationToPopulation.get(id);
}
@Override
public double getVolume(int id) {
Preconditions.checkState(stationToPopulation.containsKey(id), "No known population for station with id %d", id);
return stationToVolume.get(id);
}
}
| 2,885
| 36.480519
| 163
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SingleProblemFromCommandLineProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SingleProblemFromCommandLineProblemReader.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.problemgenerators;
import ca.ubc.cs.beta.stationpacking.execution.AProblemReader;
/**
* Created by newmanne on 12/05/15.
*/
public class SingleProblemFromCommandLineProblemReader extends AProblemReader {
private final SATFCFacadeProblem problem;
public SingleProblemFromCommandLineProblemReader(SATFCFacadeProblem problem) {
this.problem = problem;
}
@Override
public SATFCFacadeProblem getNextProblem() {
return index == 1 ? problem : null;
}
}
| 1,355
| 30.534884
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SATFCFacadeProblem.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SATFCFacadeProblem.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.problemgenerators;
import java.util.Map;
import java.util.Set;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by newmanne on 12/05/15.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SATFCFacadeProblem {
private Set<Integer> stationsToPack;
private Set<Integer> channelsToPackOn;
private Map<Integer, Set<Integer>> domains;
private Map<Integer, Integer> previousAssignment;
private String stationConfigFolder;
private String instanceName;
}
| 1,400
| 28.808511
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/RedisProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/RedisProblemReader.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.problemgenerators;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.io.FilenameUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import ca.ubc.cs.beta.stationpacking.execution.AProblemReader;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.IProblemParser;
import ca.ubc.cs.beta.stationpacking.facade.SATFCResult;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import ca.ubc.cs.beta.stationpacking.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
/**
* Created by newmanne on 12/05/15.
* Reads in problems from a redis queue, where each entry in the queue is a (full path) to an srpk file
*/
@Slf4j
public class RedisProblemReader extends AProblemReader {
private final Jedis jedis;
private final String queueName;
private final IProblemParser nameToProblem;
private final boolean testForCachedSolution;
private String activeProblemFullPath;
public RedisProblemReader(Jedis jedis, String queueName, IProblemParser nameToProblem, boolean testForCachedSolution) {
this.jedis = jedis;
this.queueName = queueName;
this.nameToProblem = nameToProblem;
this.testForCachedSolution = testForCachedSolution;
log.info("Reading instances from queue {}", RedisUtils.makeKey(queueName));
}
@Override
public SATFCFacadeProblem getNextProblem() {
SATFCFacadeProblem problem = null;
String fullPathToInstanceFile;
String instanceFileName;
while (true) {
fullPathToInstanceFile = jedis.rpoplpush(RedisUtils.makeKey(queueName), RedisUtils.makeKey(queueName, RedisUtils.PROCESSING_QUEUE));
if (fullPathToInstanceFile == null) { // all problems exhausted
return null;
}
instanceFileName = FilenameUtils.getBaseName(fullPathToInstanceFile);
try {
problem = nameToProblem.problemFromName(fullPathToInstanceFile);
break;
} catch (IOException e) {
log.warn("Error parsing file " + fullPathToInstanceFile + ", skipping it", e);
}
}
if (problem != null) {
// Do a dumb check to see if we have a solution cached in redis
if (this.testForCachedSolution) {
String answer = jedis.get(instanceFileName);
if (answer != null) {
// TODO: storing JSON blows up memory for no reason, use a more condensed format...
final TypeReference<Map<String, Integer>> typeRef = new TypeReference<Map<String, Integer>>() {};
try {
final Map<String, Integer> ans = JSONUtils.getMapper().readValue(answer, typeRef);
final Map<Integer, Integer> solution = ans.entrySet().stream().collect(Collectors.toMap(e -> Integer.parseInt(e.getKey()), Map.Entry::getValue));
problem.setPreviousAssignment(solution);
} catch (IOException e) {
throw new RuntimeException("Couldn't parse solution!!!", e);
}
}
}
}
final long remainingJobs = jedis.llen(RedisUtils.makeKey(queueName));
log.info("There are {} problems remaining in the queue", remainingJobs);
activeProblemFullPath = fullPathToInstanceFile;
return problem;
}
@Override
public void onPostProblem(SATFCFacadeProblem problem, SATFCResult result) {
super.onPostProblem(problem, result);
// update redis queue - if the job timed out, move it to the timeout channel. Either way, delete it from the processing queue
if (!result.getResult().isConclusive()) {
log.info("Adding problem " + problem.getInstanceName() + " to the timeout queue");
jedis.rpush(RedisUtils.makeKey(queueName, RedisUtils.TIMEOUTS_QUEUE), activeProblemFullPath);
}
final long numDeleted = jedis.lrem(RedisUtils.makeKey(queueName, RedisUtils.PROCESSING_QUEUE), 1, activeProblemFullPath);
if (numDeleted != 1) {
log.error("Couldn't delete problem " + activeProblemFullPath + " from the processing queue!");
}
}
}
| 5,196
| 43.042373
| 169
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/ProblemGeneratorFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/ProblemGeneratorFactory.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.problemgenerators;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.CsvToProblem;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.IProblemParser;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.SrpkToProblem;
/**
* Created by newmanne on 12/05/15.
*/
public class ProblemGeneratorFactory {
public static IProblemReader createFromParameters(SATFCFacadeParameters parameters) {
IProblemReader reader;
IProblemParser nameToProblem = parameters.fCsvRoot == null ? new SrpkToProblem(parameters.fInterferencesFolder) : new CsvToProblem(parameters.fInterferencesFolder, parameters.fCsvRoot, parameters.checkForSolution);
if (parameters.fInstanceParameters.fDataFoldername != null && parameters.fInstanceParameters.getDomains() != null) {
reader = new SingleProblemFromCommandLineProblemReader(new SATFCFacadeProblem(
parameters.fInstanceParameters.getPackingStationIDs(),
parameters.fInstanceParameters.getPackingChannels(),
parameters.fInstanceParameters.getDomains(),
parameters.fInstanceParameters.getPreviousAssignment(),
parameters.fInstanceParameters.fDataFoldername,
null
));
} else if (parameters.fsrpkFile != null) {
reader = new SingleSrpkProblemReader(parameters.fsrpkFile, nameToProblem);
} else if (parameters.fRedisParameters.areValid() && parameters.fInterferencesFolder != null) {
reader = new RedisProblemReader(parameters.fRedisParameters.getJedis(), parameters.fRedisParameters.fRedisQueue, nameToProblem, parameters.checkForSolution);
} else if (parameters.fFileOfInstanceFiles != null && parameters.fInterferencesFolder != null) {
reader = new FileProblemReader(parameters.fFileOfInstanceFiles, nameToProblem);
} else {
throw new IllegalArgumentException("Illegal parameters provided. Must provide -DATA-FOLDERNAME and -DOMAINS. Please consult the SATFC manual for examples");
}
return reader;
}
}
| 3,128
| 52.948276
| 222
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/IProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/IProblemReader.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.problemgenerators;
import ca.ubc.cs.beta.stationpacking.facade.SATFCResult;
/**
* Created by newmanne on 12/05/15.
* Abstraction around how SATFC gets the next problem to solve
*/
public interface IProblemReader {
/**
* @return The next problem to solve, or null if there are no more problems to solve
*/
SATFCFacadeProblem getNextProblem();
/**
* Call this method after solving a problem. It handles cleanup that may be required (e.g. deleting from redis processing queue)
* @param problem The problem that was just solved
* @param result The result of the problem
*/
void onPostProblem(SATFCFacadeProblem problem, SATFCResult result);
/**
* Call this when all problems have been exhausted
*/
default void onFinishedAllProblems() {}
}
| 1,672
| 32.46
| 132
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/ICutoffChooser.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/ICutoffChooser.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.problemgenerators;
/**
* Created by newmanne on 2016-02-16.
*/
public interface ICutoffChooser {
double getCutoff(SATFCFacadeProblem problem);
}
| 1,017
| 30.8125
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SingleSrpkProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/SingleSrpkProblemReader.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.problemgenerators;
import java.io.IOException;
import ca.ubc.cs.beta.stationpacking.execution.AProblemReader;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.IProblemParser;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 11/06/15.
*/
@Slf4j
public class SingleSrpkProblemReader extends AProblemReader {
private final String srpkFile;
private final IProblemParser nameToProblem;
public SingleSrpkProblemReader(String srpkFile, IProblemParser nameToProblem) {
this.srpkFile = srpkFile;
this.nameToProblem = nameToProblem;
}
@Override
public SATFCFacadeProblem getNextProblem() {
if (index != 1) {
return null;
}
final SATFCFacadeProblem problem;
try {
problem = nameToProblem.problemFromName(srpkFile);
} catch (IOException e) {
throw new RuntimeException("Error parsing file " + srpkFile, e);
}
return problem;
}
}
| 1,870
| 30.711864
| 95
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/FileCutoffChooser.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/FileCutoffChooser.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.problemgenerators;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 2016-02-16.
*/
@Slf4j
public class FileCutoffChooser implements ICutoffChooser {
private final Map<String, Double> nameToRuntime;
private final double defaultCutoff;
public FileCutoffChooser(String cutoffFile, double defaultCutoff) throws FileNotFoundException {
this.defaultCutoff = defaultCutoff;
nameToRuntime = new HashMap<>();
final CSVReader csvReader = new CSVReader(new FileReader(cutoffFile), ',');
String[] line = null;
try {
while ((line = csvReader.readNext()) != null) {
String instanceName = line[0];
double cutoff = Double.parseDouble(line[1]);
nameToRuntime.put(instanceName, cutoff);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not parse line " + Arrays.toString(line), e);
}
}
@Override
public double getCutoff(SATFCFacadeProblem problem) {
return nameToRuntime.getOrDefault(problem.getInstanceName(), defaultCutoff);
}
}
| 2,204
| 32.923077
| 100
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/FileProblemReader.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/FileProblemReader.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.problemgenerators;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import ca.ubc.cs.beta.stationpacking.execution.AProblemReader;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.problemparsers.IProblemParser;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 12/05/15.
*/
@Slf4j
public class FileProblemReader extends AProblemReader {
private final IProblemParser nameToProblem;
private final List<String> instanceFiles;
private int listIndex = 0;
public FileProblemReader(String fileOfSrpkFiles, IProblemParser nameToProblem) {
this.nameToProblem = nameToProblem;
log.info("Reading instances from file {}", fileOfSrpkFiles);
try {
instanceFiles = Files.readLines(new File(fileOfSrpkFiles), Charsets.UTF_8);
} catch (IOException e) {
throw new IllegalArgumentException("Could not read instance files from " + fileOfSrpkFiles, e);
}
}
@Override
public SATFCFacadeProblem getNextProblem() {
SATFCFacadeProblem problem = null;
while (listIndex < instanceFiles.size()) {
String instanceFile = instanceFiles.get(listIndex++);
try {
problem = nameToProblem.problemFromName(instanceFile);
break;
} catch (IOException e) {
log.warn("Error parsing file " + instanceFile, e);
}
}
if (problem != null) {
log.info("This is problem {} out of {}", index, instanceFiles.size());
return problem;
} else {
return null;
}
}
}
| 2,586
| 33.039474
| 107
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/CutoffChooserFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/CutoffChooserFactory.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.problemgenerators;
import java.io.FileNotFoundException;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
/**
* Created by newmanne on 2016-02-16.
*/
public class CutoffChooserFactory {
public static ICutoffChooser createFromParameters(SATFCFacadeParameters parameters) {
if (parameters.fCutoffFile == null) {
return problem -> parameters.fInstanceParameters.Cutoff;
} else {
try {
return new FileCutoffChooser(parameters.fCutoffFile, parameters.fInstanceParameters.Cutoff);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("File not found " + parameters.fCutoffFile, e);
}
}
}
}
| 1,616
| 34.152174
| 108
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/ANameToProblem.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/ANameToProblem.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.problemgenerators.problemparsers;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import org.apache.commons.io.FilenameUtils;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.SATFCFacadeProblem;
/**
* Created by newmanne on 2016-03-24.
*/
public abstract class ANameToProblem implements IProblemParser {
public ANameToProblem(String interferencesFolder) {
this.interferencesFolder = interferencesFolder;
}
final String interferencesFolder;
public abstract Converter.StationPackingProblemSpecs getSpecs(String name) throws IOException;
@Override
public SATFCFacadeProblem problemFromName(String name) throws IOException {
String n = FilenameUtils.getBaseName(name);
Converter.StationPackingProblemSpecs stationPackingProblemSpecs = getSpecs(name);
return new SATFCFacadeProblem(
stationPackingProblemSpecs.getDomains().keySet(),
stationPackingProblemSpecs.getDomains().values().stream().reduce(new HashSet<>(), Sets::union),
stationPackingProblemSpecs.getDomains(),
stationPackingProblemSpecs.getPreviousAssignment(),
interferencesFolder + File.separator + stationPackingProblemSpecs.getDataFoldername(),
n
);
}
}
| 2,292
| 35.396825
| 111
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/CsvToProblem.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/CsvToProblem.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.problemgenerators.problemparsers;
import java.io.File;
import java.io.IOException;
import java.util.List;
import com.google.common.base.Splitter;
import ca.ubc.cs.beta.stationpacking.execution.AuctionCSVParser;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
/**
* Created by newmanne on 2016-03-24.
*/
public class CsvToProblem extends ANameToProblem {
final String csvRoot;
final boolean useSolutionIfExists;
public CsvToProblem(String interferencesFolder, String csvRoot, boolean useSolutionIfExists) {
super(interferencesFolder);
this.csvRoot = csvRoot;
this.useSolutionIfExists = useSolutionIfExists;
}
@Override
public Converter.StationPackingProblemSpecs getSpecs(String name) throws IOException {
final List<String> splits = Splitter.on('_').splitToList(name);
final String auction = splits.get(0);
final String csvFile = csvRoot + File.separator + auction + File.separator + splits.get(1) + ".csv";
final int index = Integer.parseInt(splits.get(splits.size() - 1));
final List<AuctionCSVParser.ProblemAndAnswer> problemAndAnswers;
problemAndAnswers = AuctionCSVParser.parseAuctionFile(auction, csvFile);
final AuctionCSVParser.ProblemAndAnswer problemAndAnswer = problemAndAnswers.get(index - 1);
final Converter.StationPackingProblemSpecs stationPackingProblemSpecs = new Converter.StationPackingProblemSpecs(name, problemAndAnswer.getDomains(), problemAndAnswer.getPreviousAssignment(), problemAndAnswer.getInterference(), null);
if (useSolutionIfExists && problemAndAnswer.getResult().equals("yes")) {
stationPackingProblemSpecs.setPreviousAssignment(problemAndAnswer.getAnswer());
}
return stationPackingProblemSpecs;
}
}
| 2,670
| 40.734375
| 242
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/SrpkToProblem.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/SrpkToProblem.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.problemgenerators.problemparsers;
import java.io.IOException;
import ca.ubc.cs.beta.stationpacking.execution.Converter;
/**
* Created by newmanne on 2016-03-24.
*/
public class SrpkToProblem extends ANameToProblem {
public SrpkToProblem(String interferencesFolder) {
super(interferencesFolder);
}
@Override
public Converter.StationPackingProblemSpecs getSpecs(String name) throws IOException {
return Converter.StationPackingProblemSpecs.fromStationRepackingInstance(name);
}
}
| 1,385
| 31.232558
| 90
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/IProblemParser.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/problemgenerators/problemparsers/IProblemParser.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.problemgenerators.problemparsers;
import java.io.IOException;
import ca.ubc.cs.beta.stationpacking.execution.problemgenerators.SATFCFacadeProblem;
/**
* Created by newmanne on 2016-03-24.
*/
public interface IProblemParser {
SATFCFacadeProblem problemFromName(String name) throws IOException;
}
| 1,169
| 31.5
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/SATFCCachingParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/SATFCCachingParameters.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.parameters;
import com.beust.jcommander.Parameter;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
/**
* Created by newmanne on 04/12/14.
*/
@UsageTextField(title="SATFC Caching Parameters",description="Parameters for the SATFC problem cache.")
public class SATFCCachingParameters extends AbstractOptions {
@Parameter(names = {"--serverURL", "-SERVER-URL"}, description = "base URL for the SATFC server", required = false)
public String serverURL;
}
| 1,390
| 34.666667
| 119
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/RedisParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/RedisParameters.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.parameters;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import com.beust.jcommander.Parameter;
import ca.ubc.cs.beta.aeatk.misc.options.OptionLevel;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
/**
* Created by newmanne on 12/05/15.
*/
@UsageTextField(title="Redis Parameters",description="Parameters describing how to take jobs from redis", level = OptionLevel.DEVELOPER)
public class RedisParameters extends AbstractOptions {
@Parameter(names = "-REDIS-QUEUE", description = "The queue to take redis jobs from")
public String fRedisQueue;
@Parameter(names = "-REDIS-PORT", description = "Redis port (for problem queue)")
public Integer fRedisPort = 6379;
@Parameter(names = "-REDIS-HOST", description = "Redis host (for problem queue)")
public String fRedisHost = "localhost";
private static Jedis jedis;
synchronized public Jedis getJedis() {
Logger log = LoggerFactory.getLogger(RedisParameters.class);
if (jedis == null) {
log.info("Making a redis connection to {}:{}", fRedisHost, fRedisPort);
jedis = new Jedis(getShardInfo());
}
return jedis;
}
private JedisShardInfo getShardInfo() {
final int timeout = (int) TimeUnit.SECONDS.toMillis(60);
return new JedisShardInfo(fRedisHost, fRedisPort, timeout);
}
public BinaryJedis getBinaryJedis() {
return new BinaryJedis(getShardInfo());
}
public StringRedisTemplate getStringRedisTemplate() {
return new StringRedisTemplate(new JedisConnectionFactory(getShardInfo()));
}
public boolean areValid() {
return fRedisQueue != null && fRedisPort != null && fRedisHost != null;
}
}
| 2,943
| 36.265823
| 136
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/SATFCFacadeParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/SATFCFacadeParameters.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.parameters;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParametersDelegate;
import ca.ubc.cs.beta.aeatk.misc.options.OptionLevel;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.base.InstanceParameters;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeParameter.SolverChoice;
import ch.qos.logback.classic.Level;
/**
* SATFC facade parameters.
* @author afrechet
*/
@UsageTextField(title="SATFC Facade Parameters",description="Parameters needed to execute SATFC facade on a single instance.")
public class SATFCFacadeParameters extends AbstractOptions {
@Parameter(names={"--help-level"}, description="Show options at this level or lower")
public OptionLevel helpLevel = OptionLevel.BASIC;
/**
* Parameters for the instance to solve.
*/
@ParametersDelegate
public InstanceParameters fInstanceParameters = new InstanceParameters();
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-CNF-DIR", description = "folder for storing cnf results")
public String fCNFDir;
@ParametersDelegate
public SATFCCachingParameters cachingParams = new SATFCCachingParameters();
@ParametersDelegate
public RedisParameters fRedisParameters = new RedisParameters();
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-SRPK-FILE", description = "single srpk file to run")
public String fsrpkFile;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-INSTANCES-FILE", description = "file listing each instance file on a separate line")
public String fFileOfInstanceFiles;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-CSV-ROOT", description = "Root of CSV auction directory")
public String fCsvRoot;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-CHECK-FOR-SOLUTION", description = "Test for a solution in redis matching instancename, used to parse metrics files into cache")
public boolean checkForSolution = false;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = {"-METRICS-FILE", "-OUTPUT-FILE"}, description = "Causes the FileMetricWriter to be used, outputs a file with metrics (may cause performance loss)")
public String fMetricsFile;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-INTERFERENCES-FOLDER", description = "folder containing all the other interference folders")
public String fInterferencesFolder;
@UsageTextField(level = OptionLevel.DEVELOPER)
@Parameter(names = "-CUTOFF-FILE", description = "file listing each instance and the corresponding cutoff")
public String fCutoffFile;
/**
* Clasp library to use (optional - can be automatically detected).
*/
@Parameter(names = "-CLASP-LIBRARY",description = "clasp library file")
public String fClaspLibrary;
/**
* SATenstein library to use (optional - can be automatically detected).
*/
@Parameter(names = "-SATENSTEIN-LIBRARY",description = "SATenstein library file")
public String fSATensteinLibrary;
/**
* Logging options.
*/
@Parameter(names={"--log-level","--logLevel", "-LOG-LEVEL"},description="messages will only be logged if they are of this severity or higher.")
private String logLevel = "INFO";
@Parameter(names={"-LOG-FILE"},description="Log file name")
public String logFileName = "SATFC.log";
public Level getLogLevel() {
return Level.valueOf(logLevel);
}
@Parameter(names = "-CONFIG-FILE")
public String configFile;
@Parameter(names = "-SOLVER-CHOICE", hidden=true)
public SolverChoice solverChoice = SolverChoice.YAML;
}
| 4,665
| 40.292035
| 171
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/base/InstanceParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/base/InstanceParameters.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.parameters.solver.base;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.beust.jcommander.Parameter;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
import ca.ubc.cs.beta.stationpacking.execution.parameters.converters.PreviousAssignmentConverter;
import ca.ubc.cs.beta.stationpacking.execution.parameters.converters.StationDomainsConverter;
/**
* Defines a station packing problem instance from basic values.
* @author afrechet
*/
@UsageTextField(title="FCC Station Packing Packing Problem Instance Options",description="Parameters defining a single station packing problem.")
public class InstanceParameters extends AbstractOptions {
@Parameter(names = "-PACKING-CHANNELS", description = "List of channels to pack into.")
private List<String> fPackingChannels = null;
/**
* @return the instance's packing channels.
*/
public HashSet<Integer> getPackingChannels()
{
Logger log = LoggerFactory.getLogger(InstanceParameters.class);
log.debug("Getting packing channels...");
HashSet<Integer> aPackingChannels = new HashSet<Integer>();
if(fPackingChannels != null)
{
for(String aChannel : fPackingChannels)
{
aPackingChannels.add(Integer.valueOf(aChannel));
}
}
else
{
for(Integer stationID : fDomains.keySet())
{
aPackingChannels.addAll(fDomains.get(stationID));
}
}
return aPackingChannels;
}
@Parameter(names = "-PACKING-STATIONS", description = "List of stations to pack.")
private List<String> fPackingStations = null;
/**
* @return the IDs of the packing stations.
*/
public HashSet<Integer> getPackingStationIDs()
{
Logger log = LoggerFactory.getLogger(InstanceParameters.class);
log.debug("Getting packing stations...");
HashSet<Integer> aPackingStations = new HashSet<Integer>();
if(fPackingStations != null)
{
for(String aStationID : fPackingStations)
{
aPackingStations.add(Integer.valueOf(aStationID));
}
}
else
{
aPackingStations.addAll(fDomains.keySet());
}
return aPackingStations;
}
@Parameter(names = "-DOMAINS", description = "Map taking station IDs to reduced domain set (e.g. 1:14,15,16;2:14,15)", converter=StationDomainsConverter.class)
private HashMap<Integer,Set<Integer>> fDomains;
/**
* @return the channel domain on which to pack each station.
*/
public HashMap<Integer,Set<Integer>> getDomains()
{
return fDomains;
}
@Parameter(names = "-PREVIOUS-ASSIGNMENT", description = "Map taking (some) station IDs to valid previous channel assignment.", converter=PreviousAssignmentConverter.class)
private HashMap<Integer,Integer> fPreviousAssignment;
/**
* @return the valid previous assignment.
*/
public HashMap<Integer,Integer> getPreviousAssignment()
{
if(fPreviousAssignment== null)
{
return new HashMap<Integer,Integer>();
}
else
{
return fPreviousAssignment;
}
}
/**
* The instance's cutoff time (s). This is walltime.
*/
@Parameter(names = "-CUTOFF", description = "Time allowed to the feasibility checker (in seconds).")
public double Cutoff = 60.0;
/**
* The instance's seed.
*/
@Parameter(names = "-SEED", description = "(Random) seed given to the feasibility checker.")
public long Seed = 1;
/**
* The instance station config foldername.
*/
@Parameter(names = "-DATA-FOLDERNAME",description = "station config data folder name")
public String fDataFoldername;
@Override
public String toString()
{
return "("+fDomains+","+getPreviousAssignment().toString()+","+Cutoff+","+Seed+","+fDataFoldername+")";
}
}
| 4,598
| 28.480769
| 173
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/sat/UBCSATLibSATSolverParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/sat/UBCSATLibSATSolverParameters.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.parameters.solver.sat;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
/**
* @author pcernek
*/
public class UBCSATLibSATSolverParameters extends AbstractOptions {
/**
*
*/
public final static String DEFAULT_SATENSTEIN = "-alg satenstein -cutoff max";
public final static String DEFAULT_DCCA = "-alg dcca -cutoff max";
public final static String DEFAULT_DCCA_IN_STEIN = DEFAULT_SATENSTEIN + " -promisinglist 1 -decreasingvariable 13 -heuristic 20 -avgweightthreshold 300 -DCCAp 0.3 -DCCAq 0";
/**
* Optimal parameter configuration for the QCP instance distribution found by tuning SATenstein 1.0 using ParamILS in Fall 2014.
*/
public final static String STEIN_QCP_PARAMILS = "-alg satenstein -adaptive 0 -alpha 1.3 -clausepen 0 -heuristic 5 -maxinc 10 -novnoise 0.3 -performrandomwalk 1 -pflat 0.15 -promisinglist 0 -randomwalk 4 -rfp 0.07 -rho 0.8 -sapsthresh -0.1 -scoringmeasure 1 -selectclause 1 -singleclause 1 -tabusearch 0 -varinfalse 1";
/**
* Optimal parameter configuration for the R3SAT instance distribution found by tuning SATenstein 1.0 using ParamILS in Fall 2014.
*/
public final static String STEIN_R3SAT_PARAMILS = "-alg satenstein -adaptivenoisescheme 1 -adaptiveprom 0 -adaptpromwalkprob 0 -adaptwalkprob 0 -alpha 1.126 -decreasingvariable 3 -dp 0.05 -heuristic 2 -novnoise 0.5 -performalternatenovelty 1 -phi 5 -promdp 0.05 -promisinglist 0 -promnovnoise 0.5 -promphi 5 -promtheta 6 -promwp 0.01 -rho 0.17 -scoringmeasure 3 -selectclause 1 -theta 6 -tiebreaking 1 -updateschemepromlist 3 -wp 0.03 -wpwalk 0.3 -adaptive 1 -clausepen 1 -performrandomwalk 0 -singleclause 0 -smoothingscheme 1 -tabusearch 0 -varinfalse 1";
/**
* Optimal parameter configuration for the FAC instance distribution found by tuning SATenstein 1.0 using ParamILS in Fall 2014.
*/
public final static String STEIN_FAC_PARAMILS = "-alg satenstein -adaptivenoisescheme 2 -adaptiveprom 0 -adaptpromwalkprob 0 -adaptwalkprob 0 -alpha 1.126 -c 0.0001 -decreasingvariable 3 -dp 0.05 -heuristic 2 -novnoise 0.5 -performalternatenovelty 1 -phi 5 -promdp 0.05 -promisinglist 0 -promnovnoise 0.5 -promphi 5 -promtheta 6 -promwp 0.01 -ps 0.033 -rho 0.8 -s 0.001 -scoringmeasure 3 -selectclause 1 -theta 6 -tiebreaking 3 -updateschemepromlist 3 -wp 0.04 -wpwalk 0.3 -adaptive 0 -clausepen 1 -performrandomwalk 0 -singleclause 0 -smoothingscheme 1 -tabusearch 0 -varinfalse 1";
}
| 3,325
| 59.472727
| 588
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/sat/ClaspLibSATSolverParameters.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/solver/sat/ClaspLibSATSolverParameters.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.parameters.solver.sat;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
/**
* Clasp SAT solver library parameters.
* @author afrechet
*/
@UsageTextField(title="FCC Station Packing Packing Clasp Library Based SAT Solver Parameters",description="Parameters defining a Clasp library based SAT solver.")
public class ClaspLibSATSolverParameters extends AbstractOptions {
/**
* Clasp3 configurations
*/
/*
* Adapted from HVHF_CONFIG_09_13 for clasp3 (by removing parameters until it worked).
*/
public final static String HVHF_CONFIG_09_13_MODIFIED = "--backprop --eq=0 --trans-ext=all --sat-prepro=0 --sign-def=0 --del-max=100000 --strengthen=local,1 --loops=common --init-watches=0 --heuristic=Vsids,96 --del-cfl=F,500 --restarts=D,100,0.8,100 --update-act --del-glue=4,0 --update-lbd=0 --reverse-arcs=3 --otfs=2 --del-on-restart=0 --contraction=500 --local-restarts --lookahead=no --save-progress=50";
/*
* First UHF clasp configuration that is intended to be run on full instances.
*/
public final static String UHF_CONFIG_04_15_h1 = "--sat-prepro=0 --init-watches=0 --rand-freq=0.02 --sign-def=2 --del-init=5.0,10,2500 --strengthen=local,2 --lookahead=hybrid,1 --otfs=1 --reverse-arcs=3 --save-progress=180 --del-glue=2,0 --del-cfl=L,2000 --restarts=F,1600 --local-restarts --update-lbd=3 --heuristic=Vsids,92 --deletion=ipSort,75,2 --contraction=100 --del-grow=1.1,20.0 --del-on-restart=50 --del-max=32767";
/*
* Second UHF clasp configuration that is intended to be run on decomposed instances.
*/
public final static String UHF_CONFIG_04_15_h2 = "--sat-prepro=0 --init-watches=2 --rand-freq=0.0 --sign-def=2 --del-init=5.0,10,2500 --strengthen=local,2 --lookahead=hybrid,1 --otfs=2 --reverse-arcs=3 --save-progress=180 --del-glue=2,0 --del-cfl=L,2000 --restarts=F,1600 --local-restarts --update-lbd=1 --heuristic=Vsids,92 --deletion=ipSort,75,2 --contraction=166 --del-grow=0 --del-on-restart=50 --del-max=32767";
}
| 2,935
| 52.381818
| 433
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/converters/StationDomainsConverter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/converters/StationDomainsConverter.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.parameters.converters;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
/**
* Converter that transforms an integer to set of integers map string (e.g. "1:1,2,3;2:2,3,4") to its map representation.
* @author afrechet
*/
public class StationDomainsConverter implements IStringConverter<HashMap<Integer,Set<Integer>>>{
@Override
public final HashMap<Integer,Set<Integer>> convert(String value) {
HashMap<Integer,Set<Integer>> map = new HashMap<Integer,Set<Integer>>();
try
{
for(String entries : value.split(";"))
{
String[] entriesparts = entries.split(":");
String k = entriesparts[0];
Integer intk = Integer.valueOf(k);
String vs = entriesparts[1];
HashSet<Integer> intvs = new HashSet<Integer>();
for(String v : vs.split(","))
{
Integer intv = Integer.valueOf(v);
intvs.add(intv);
}
map.put(intk, intvs);
}
}
catch(ArrayIndexOutOfBoundsException | NumberFormatException e)
{
throw new ParameterException("Cannot convert "+value+" to an integer to set of integer map.");
}
return map;
}
}
| 2,093
| 27.297297
| 123
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/converters/PreviousAssignmentConverter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/parameters/converters/PreviousAssignmentConverter.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.parameters.converters;
import java.util.HashMap;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;
/**
* Converter that transforms an integer to integer map string (e.g. "1:2;2:4") to its map representation.
* @author afrechet
*/
public class PreviousAssignmentConverter implements IStringConverter<HashMap<Integer,Integer>>{
@Override
public final HashMap<Integer,Integer> convert(String value) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
try
{
for(String entries : value.split(";"))
{
String[] entriesparts = entries.split(":");
String k = entriesparts[0];
String v = entriesparts[1];
Integer intk = Integer.valueOf(k);
Integer intv = Integer.valueOf(v);
map.put(intk, intv);
}
}
catch(ArrayIndexOutOfBoundsException | NumberFormatException e)
{
throw new ParameterException("Cannot convert "+value+" to an integer to set of integer map ("+e.getMessage()+")");
}
return map;
}
}
| 1,899
| 28.230769
| 117
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/MetricWriterFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/MetricWriterFactory.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.metricwriters;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
/**
* Created by newmanne on 29/05/15.
* Determine what implementation of @link{IMetricWriter} to use
*/
public class MetricWriterFactory {
public static IMetricWriter createFromParameters(SATFCFacadeParameters parameters) {
if (parameters.fMetricsFile != null) {
SATFCMetrics.init();
return new FileMetricsWriter(parameters.fMetricsFile);
} else {
// a void implementation that does nothing
return new IMetricWriter() {
@Override
public void writeMetrics() {
}
@Override
public void onFinished() {
}
};
}
}
}
| 1,725
| 31.566038
| 88
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/FileMetricsWriter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/FileMetricsWriter.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.metricwriters;
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 29/05/15.
* Write metrics to a file on disk, appending each problem's metrics as a line of json
*/
@Slf4j
public class FileMetricsWriter implements IMetricWriter {
private final File metricsFile;
public FileMetricsWriter(String metricsFileName) {
this.metricsFile = new File(metricsFileName);
if (this.metricsFile.exists()) {
this.metricsFile.delete();
}
}
@Override
public void writeMetrics() {
SATFCMetrics.doWithMetrics(info -> {
try {
Files.append(JSONUtils.toString(info) + System.lineSeparator(), metricsFile, Charsets.UTF_8);
} catch (IOException e) {
log.error("Couldn't save metrics to file " + metricsFile.getAbsolutePath(), e);
}
});
}
@Override
public void onFinished() {
SATFCMetrics.report();
}
}
| 2,065
| 29.835821
| 109
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/IMetricWriter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/execution/metricwriters/IMetricWriter.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.metricwriters;
/**
* Created by newmanne on 29/05/15.
* This interface abstracts away where metrics are written to (to file, to redis, to stdout)
*/
public interface IMetricWriter {
/**
* Write metrics for a particular problem
*/
void writeMetrics();
void onFinished();
}
| 1,163
| 30.459459
| 92
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/UNSATLabeller.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/UNSATLabeller.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 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.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 2016-03-28.
* A solver that always labels problems as UNSAT
* Note that this DOES NOT PROVE THAT THEY ARE UNSAT and therefore can be VERY DANGEROUS unless used properly (i.e. when you already know the problem is UNSAT!)
*/
public class UNSATLabeller extends ASolverDecorator {
/**
* @param aSolver - decorated ISolver.
*/
public UNSATLabeller(ISolver aSolver) {
super(aSolver);
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
return SolverResult.createNonSATResult(SATResult.UNSAT, 0, SolverResult.SolvedBy.UNSAT_LABELLER);
}
}
| 1,906
| 37.14
| 160
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/ISolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/ISolver.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 ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ISATFCInterruptible;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* <p>
* Solves station packing problem instance.
* </p>
* <p>
* Strongly suggested to use notifyShutdown() once finished with the solver (so that all resources can be released).
* </p>
* @author afrechet
*/
public interface ISolver extends ISATFCInterruptible {
/**
* Solve a station packing instance under the provided CPU time cutoff and given seed.
* @param aInstance - the instance to solved.
* @param aTerminationCriterion - the termination criterion for solver execution (usually cutoff time based).
* @param aSeed - the execution seed.
* @return
*/
SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed);
/**
* Ask the solver to shutdown.
*/
default void notifyShutdown() {};
default void interrupt() {};
}
| 1,961
| 33.421053
| 117
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/SolverHelper.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/SolverHelper.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.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import ca.ubc.cs.beta.stationpacking.base.Station;
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 lombok.extern.slf4j.Slf4j;
@Slf4j
public class SolverHelper {
private SolverHelper()
{
//Cannot construct a solver helper object.
}
/**
* @param aComponentResults
* @return the combined the results of solving a single station packing instance in different ways.
*/
public static SolverResult combineResults(Collection<SolverResult> aComponentResults)
{
double runtime = 0.0;
HashSet<SATResult> SATresults = new HashSet<SATResult>();
for(SolverResult solverResult : aComponentResults)
{
runtime += solverResult.getRuntime();
SATresults.add(solverResult.getResult());
}
SATResult SATresult = SATResult.CRASHED;
//Combine SAT results.
if(SATresults.isEmpty())
{
SATresult = SATResult.TIMEOUT;
}
else if(SATresults.size()==1)
{
SATresult = SATresults.iterator().next();
}
else if(SATresults.contains(SATResult.SAT))
{
SATresult = SATResult.SAT;
}
else if(SATresults.contains(SATResult.UNSAT))
{
SATresult = SATResult.UNSAT;
}
else if(SATresults.contains(SATResult.INTERRUPTED))
{
SATresult = SATResult.INTERRUPTED;
}
else if(SATresults.contains(SATResult.CRASHED))
{
SATresult = SATResult.CRASHED;
}
else if(SATresults.contains(SATResult.TIMEOUT) || SATresults.contains(SATResult.KILLED))
{
SATresult = SATResult.TIMEOUT;
}
if(SATresult.equals(SATResult.KILLED))
{
SATresult = SATResult.TIMEOUT;
}
//Find assignment.
Map<Integer,Set<Station>> assignment = new HashMap<Integer,Set<Station>>();
if(SATresult.equals(SATResult.SAT))
{
for(SolverResult solverResult : aComponentResults)
{
if(solverResult.getResult().equals(SATResult.SAT))
{
assignment = solverResult.getAssignment();
break;
}
}
}
return new SolverResult(SATresult,runtime,assignment, SolvedBy.UNKNOWN);
}
/**
* @param aComponentResults
* @return the merged the results of solving multiple disconnected components of a same station packing problem.
*/
public static SolverResult mergeComponentResults(Collection<SolverResult> aComponentResults){
//Merge runtimes as sum of times.
HashSet<SATResult> aSATResults = new HashSet<SATResult>();
double runtime = 0.0;
for(SolverResult aSolverResult : aComponentResults)
{
aSATResults.add(aSolverResult.getResult());
runtime += aSolverResult.getRuntime();
}
//Merge SAT results
SATResult aSATResult = SATResult.CRASHED;
if(aSATResults.isEmpty())
{
aSATResult = SATResult.TIMEOUT;
}
else if(aSATResults.size()==1)
{
aSATResult = aSATResults.iterator().next();
}
else if(aSATResults.contains(SATResult.UNSAT))
{
aSATResult = SATResult.UNSAT;
}
else if(aSATResults.contains(SATResult.INTERRUPTED))
{
aSATResult = SATResult.INTERRUPTED;
}
else if(aSATResults.contains(SATResult.CRASHED))
{
aSATResult = SATResult.CRASHED;
}
else if(aSATResults.contains(SATResult.TIMEOUT) || aSATResults.contains(SATResult.KILLED))
{
aSATResult = SATResult.TIMEOUT;
}
//If all runs were killed, it is because we went over time.
if(aSATResult.equals(SATResult.KILLED))
{
aSATResult = SATResult.TIMEOUT;
}
//Merge assignments
Map<Integer,Set<Station>> aAssignment = new HashMap<Integer,Set<Station>>();
if(aSATResult.equals(SATResult.SAT))
{
for(SolverResult aComponentResult : aComponentResults)
{
Map<Integer,Set<Station>> aComponentAssignment = aComponentResult.getAssignment();
for(Integer aAssignedChannel : aComponentAssignment.keySet())
{
if(!aAssignment.containsKey(aAssignedChannel))
{
aAssignment.put(aAssignedChannel, new HashSet<Station>());
}
aAssignment.get(aAssignedChannel).addAll(aComponentAssignment.get(aAssignedChannel));
}
}
}
return new SolverResult(aSATResult,runtime,aAssignment, SolvedBy.UNKNOWN);
}
}
| 5,077
| 26.448649
| 113
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/VoidSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/VoidSolver.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 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 11/05/15.
* A solver that always returns timeouts. Can be used to end a decorator chain without waiting for time to run out, or for testing purposes
*/
public class VoidSolver implements ISolver {
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
return SolverResult.createTimeoutResult(0);
}
}
| 1,497
| 38.421053
| 138
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelNoWaitSolverComposite.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelNoWaitSolverComposite.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 java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import com.google.common.collect.Queues;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import ca.ubc.cs.beta.aeatk.concurrent.threadfactory.SequentiallyNamedThreadFactory;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.interrupt.InterruptibleTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 26/05/15.
*/
@Slf4j
/**
* This class executes the ISolver's created from the ISolverFactories that are passed into its constructor in parallel.
* A result is returned **immediately** after a conclusive result is found, even though other threads may still be computing the (now stale) result.
*/
public class ParallelNoWaitSolverComposite implements ISolver {
private final ListeningExecutorService executorService;
private final List<BlockingQueue<ISolver>> listOfSolverQueues;
private final AtomicReference<Throwable> error;
/**
* @param threadPoolSize The number of threads to use in the thread pool
* @param solvers A list of ISolverFactory, sorted by priority (first in the list means high priority). This is the order that we will try things in if there are not enough threads to go around
*/
public ParallelNoWaitSolverComposite(int threadPoolSize, List<ISolverFactory> solvers) {
log.debug("Creating a fixed pool with {} threads", threadPoolSize);
executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadPoolSize, new SequentiallyNamedThreadFactory("SATFC Parallel Worker Thread")));
listOfSolverQueues = new ArrayList<>(solvers.size());
for (ISolverFactory solverFactory : solvers) {
final LinkedBlockingQueue<ISolver> solverQueue = Queues.newLinkedBlockingQueue(threadPoolSize);
listOfSolverQueues.add(solverQueue);
for (int i = 0; i < threadPoolSize; i++) {
final ISolver solver = solverFactory.create();
solverQueue.offer(solver);
}
}
error = new AtomicReference<>();
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
if (aTerminationCriterion.hasToStop()) {
return SolverResult.createTimeoutResult(0);
}
log.debug("Solving via parallel solver");
final Watch watch = Watch.constructAutoStartWatch();
// Swap out the termination criterion to one that can be interrupted
final ITerminationCriterion.IInterruptibleTerminationCriterion interruptibleCriterion = new InterruptibleTerminationCriterion(aTerminationCriterion);
//Semaphore holding how many components are done working on the current instance.
final Semaphore workDone = new Semaphore(0);
//Number of completed solver processes we need before terminating with a timeout.
final int numWorkToDo = listOfSolverQueues.size();
final AtomicReference<SolverResult> resultReference = new AtomicReference<>();
// We maintain a list of all the solvers current solving the problem so we know who to interrupt via the interrupt method
final List<ISolver> solversSolvingCurrentProblem = Collections.synchronizedList(new ArrayList<>());
final List<Future<Void>> futures = new ArrayList<>();
try {
// Submit one job per each solver in the portfolio
listOfSolverQueues.forEach(solverQueue -> {
final ListenableFuture<Void> future = executorService.submit(() -> {
log.debug("Job starting...");
if (!interruptibleCriterion.hasToStop()) {
final ISolver solver = solverQueue.poll();
if (solver == null) {
throw new IllegalStateException("Couldn't take a solver from the queue!");
}
// During this block (while you are added to this list) it is safe for you to be interrupted via the interrupt method
solversSolvingCurrentProblem.add(solver);
log.debug("Begin solve {}", solver.getClass().getSimpleName());
final SolverResult solverResult = solver.solve(aInstance, interruptibleCriterion, aSeed);
log.debug("End solve {}", solver.getClass().getSimpleName());
solversSolvingCurrentProblem.remove(solver);
// Interrupt if the result is conclusive OR if the timeout has expired. Only the first one will go through this block
if ((solverResult.isConclusive() || interruptibleCriterion.hasToStop()) && interruptibleCriterion.interrupt()) {
log.debug("Found a conclusive result, interrupting other concurrent solvers");
synchronized (solversSolvingCurrentProblem) {
solversSolvingCurrentProblem.forEach(ISolver::interrupt);
}
// Signal the initial thread that it can move forwards
log.debug("Signalling the blocked thread to wake up!");
resultReference.set(solverResult);
workDone.release(numWorkToDo);
}
log.debug("Releasing a single permit as the work for this thread is done.");
workDone.release(1);
// Return your solver back to the queue
if (!solverQueue.offer(solver)) {
throw new IllegalStateException("Wasn't able to return solver to the queue!");
}
}
log.debug("Job ending...");
return null;
});
futures.add(future);
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
}
@Override
public void onFailure(Throwable t) {
if (t instanceof CancellationException) {
return;
}
log.error("Error occured while executing a task", t);
// Only set the first error
error.compareAndSet(null, t);
// Wake up the main thread (if it's still sleeping)
workDone.release(numWorkToDo);
}
});
});
// Wait for a thread to complete solving and signal you, or all threads to timeout
log.debug("Main thread going to sleep");
workDone.acquire(numWorkToDo);
log.debug("Main thread waking up, checking for errors then cancelling futures");
checkForErrors();
// Might as well cancel any jobs that haven't run yet. We don't interrupt them (via Thread interrupt) if they have already started, because we have our own interrupt system
futures.forEach(future -> future.cancel(false));
log.debug("Returning now");
return resultReference.get() == null ? SolverResult.createTimeoutResult(watch.getElapsedTime()) : SolverResult.relabelTime(resultReference.get(), watch.getElapsedTime());
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while running parallel job", e);
}
}
/**
* We want a fail-fast policy, but java executors aren't going to throw the exception on the main thread.
* We can't call Future.get() and check for errors, because that might block.
* So we set a variable when an error occurs, and check it here.
*/
private void checkForErrors() {
final Throwable e = error.getAndSet(null); // clear error for future uses
if (e != null) {
log.error("Found an error from a parallel task", e);
throw new RuntimeException("Error occurred while executing a task", e);
}
}
@Override
public void notifyShutdown() {
listOfSolverQueues.forEach(queue -> queue.forEach(ISolver::notifyShutdown));
executorService.shutdown();
}
@Override
public void interrupt() {
// Just wait for the individual solvers to terminate
}
}
| 10,299
| 51.284264
| 204
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ISolverFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ISolverFactory.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 ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
/**
* Created by newmanne on 26/05/15.
* A factory that creates an ISolver
*/
public interface ISolverFactory {
default ISolver create() {
return extend(new VoidSolver());
}
/**
* Decorate an existing solver
* @param aSolver
* @return
*/
ISolver extend(ISolver aSolver);
}
| 1,305
| 28.681818
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/SequentialSolversComposite.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/SequentialSolversComposite.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 java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.SolverHelper;
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;
/**
* Composes a list of solvers and executes each one ata time.
* @author afrechet
*/
public class SequentialSolversComposite implements ISolver{
private static Logger log = LoggerFactory.getLogger(SequentialSolversComposite.class);
private final List<ISolver> fSolvers;
public SequentialSolversComposite(List<ISolver> aSolvers)
{
fSolvers = aSolvers;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion,
long aSeed) {
Collection<SolverResult> results = new ArrayList<SolverResult>();
for(int i=0;i<fSolvers.size();i++)
{
if(aTerminationCriterion.hasToStop())
{
log.trace("All time spent.");
break;
}
log.debug("Trying solver {}.",i+1);
SolverResult result = fSolvers.get(i).solve(aInstance, aTerminationCriterion, aSeed);
results.add(result);
if(result.getResult().equals(SATResult.SAT) || result.getResult().equals(SATResult.UNSAT))
{
break;
}
}
return SolverHelper.combineResults(results);
}
@Override
public void notifyShutdown() {
for(ISolver solver : fSolvers)
{
solver.notifyShutdown();
}
}
@Override
public void interrupt() {
for(ISolver solver : fSolvers)
{
solver.interrupt();
}
}
}
| 2,702
| 26.03
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelSolverComposite.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/composites/ParallelSolverComposite.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 java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.interrupt.InterruptibleTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 13/05/15.
* A very simple parallel solver that forks and joins (i.e. blocks until every solver completes (though it does try to interrupt them))
*/
@Slf4j
public class ParallelSolverComposite implements ISolver {
Collection<ISolver> solvers;
private final ForkJoinPool forkJoinPool;
public ParallelSolverComposite(int threadPoolSize, List<ISolverFactory> solvers) {
this.solvers = solvers.stream().map(ISolverFactory::create).collect(Collectors.toList());
log.debug("Creating a fork join pool with {} threads", threadPoolSize);
forkJoinPool = new ForkJoinPool(threadPoolSize);
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
Watch watch = Watch.constructAutoStartWatch();
// Swap out the termination criterion to one that can be interrupted
final ITerminationCriterion.IInterruptibleTerminationCriterion interruptibleCriterion = new InterruptibleTerminationCriterion(aTerminationCriterion);
try {
final SolverResult endResult = forkJoinPool.submit(() -> {
return solvers.parallelStream()
.map(solver -> {
final SolverResult solve = solver.solve(aInstance, interruptibleCriterion, aSeed);
log.trace("Returned from solver");
// Interrupt only if the result is conclusive
if (solve.getResult().isConclusive() && interruptibleCriterion.interrupt()) {
log.debug("Found a conclusive result {}, interrupting other concurrent solvers", solve);
solvers.forEach(ISolver::interrupt);
}
return solve;
})
.filter(result -> result.getResult().isConclusive())
.findAny();
}).get().orElse(SolverResult.createTimeoutResult(watch.getElapsedTime()));
// Note that we don't modify time here, even though you might have to wait a while for the other threads to finish between the time the result is created and the time it can be returned. This solver is used for experimental purposes, to make sure that all threads have "caught up" before the next problem is started
return endResult;
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Error processing jobs in parallel!", e);
}
}
@Override
public void notifyShutdown() {
solvers.forEach(ISolver::notifyShutdown);
}
@Override
public void interrupt() {
// Just wait for the individual solvers to terminate
}
}
| 4,333
| 45.602151
| 327
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/componentgrouper/ConstraintGrouper.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/componentgrouper/ConstraintGrouper.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.componentgrouper;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
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.datamanagers.constraints.IConstraintManager;
import net.jcip.annotations.ThreadSafe;
/**
* Groups the stations in a station packing instance based on connected components in interference constraint graph.
* @author afrechet
*/
@ThreadSafe
public class ConstraintGrouper implements IComponentGrouper {
@Override
public Set<Set<Station>> group(StationPackingInstance aInstance, IConstraintManager aConstraintManager){
final SimpleGraph<Station,DefaultEdge> aConstraintGraph = getConstraintGraph(aInstance.getDomains(), aConstraintManager);
final ConnectivityInspector<Station, DefaultEdge> aConnectivityInspector = new ConnectivityInspector<>(aConstraintGraph);
return aConnectivityInspector.connectedSets().stream().collect(Collectors.toSet());
}
/**
* @param aConstraintManager - the constraint manager to use to form edges of the constraint graph.
* @return the constraint graph.
*/
public static SimpleGraph<Station,DefaultEdge> getConstraintGraph(Map<Station, Set<Integer>> aDomains, IConstraintManager aConstraintManager)
{
final Set<Station> aStations = aDomains.keySet();
final SimpleGraph<Station,DefaultEdge> aConstraintGraph = new SimpleGraph<Station,DefaultEdge>(DefaultEdge.class);
for(Station aStation : aStations){
aConstraintGraph.addVertex(aStation);
}
aConstraintManager.getAllRelevantConstraints(aDomains).forEach(constraint -> {
aConstraintGraph.addEdge(constraint.getSource(), constraint.getTarget());
});
return aConstraintGraph;
}
}
| 2,795
| 38.942857
| 142
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/componentgrouper/IComponentGrouper.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/componentgrouper/IComponentGrouper.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.componentgrouper;
import java.util.Set;
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;
/**
* Partition station sets so that each member can be solved separately.
* @author afrechet
*/
public interface IComponentGrouper {
/**
* @param aInstance instance to partition.
* @param aConstraintManager constraint manager for that instance.
* @return A partition of the input station sets (such that each station can be encoded separately).
*/
public Set<Set<Station>> group(StationPackingInstance aInstance, IConstraintManager aConstraintManager);
}
| 1,579
| 33.347826
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/HeuristicUnderconstrainedStationFinder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/HeuristicUnderconstrainedStationFinder.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 java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.componentgrouper.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 1/8/15.
*
* The goal is to find stations for which, no matter how their neighbours are arranged, there will always be a channel
* to put them onto. Then, you can remove them from the problem, and simply add them back afterwards by iterating
* through their domain until you find a satisfying assignment.
*
* One helpful framework for thinking about this problem is to think of the question as:
* If all of my neighbours were placed adversarially to block out the maximum number of channels from my domain,
* how many could they block out? If the answer is less than my domain's size, then I am underconstrained.
*
* For example,
* Neighbour A can block out {1, 2} or {2, 3}
* Neighbour B can block out {2} or {2, 3}
* Then the worst case is when neighbour A blocks out {1,2} and neighbour B blocks out {2,3}
*
* Slightly more formally:
* There are N groups of sets
* You have to choose exactly one set from each group
* Your goal is to maximize the size of the union of the groups that you choose
* (Note that we don't need the actual values of the choices, just the size)
*
* This problem seems to be a variant of the Maximum Coverage Problem
*
* We do not solve the problem exactly, but rely instead take the minimum of two heuristics that are upper bounds to this question
* 1) The size of the union of all the sets in every group
* 2) The sum of the sizes of the largest set in every group
*/
@Slf4j
public class HeuristicUnderconstrainedStationFinder implements IUnderconstrainedStationFinder {
private final IConstraintManager constraintManager;
private final boolean performExpensiveAnalysis;
public HeuristicUnderconstrainedStationFinder(IConstraintManager constraintManager, boolean performExpensiveAnalysis) {
this.constraintManager = constraintManager;
this.performExpensiveAnalysis = performExpensiveAnalysis;
}
@Override
public Set<Station> getUnderconstrainedStations(Map<Station, Set<Integer>> domains, ITerminationCriterion criterion, Set<Station> stationsToCheck) {
final Set<Station> underconstrainedStations = new HashSet<>();
log.debug("Finding underconstrained stations in the instance...");
/**
* Heuristic #1 for underconstrained:
* Take the union of all the channels that my neighbours can block and see if its smaller than my domain
*/
final HashMultimap<Station, Integer> badChannels = HashMultimap.create();
constraintManager.getAllRelevantConstraints(domains).forEach(constraint -> {
badChannels.put(constraint.getSource(), constraint.getSourceChannel());
badChannels.put(constraint.getTarget(), constraint.getTargetChannel());
});
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(ConstraintGrouper.getConstraintGraph(domains, constraintManager));
for (final Station station : stationsToCheck) {
if (criterion.hasToStop()) {
log.debug("Underconstrained stations timed out. Returned set will be only a partial set");
break;
}
final Set<Integer> domain = domains.get(station);
final Set<Integer> stationBadChannels = badChannels.get(station);
final Set<Integer> stationGoodChannels = Sets.difference(domain, stationBadChannels);
log.trace("Station {} domain channels: {}.", station, domain);
log.trace("Station {} bad channels: {}.", station, stationBadChannels);
if (!stationGoodChannels.isEmpty()) {
log.trace("Station {} is underconstrained as it has {} domain channels ({}) on which it interferes with no one.", station, stationGoodChannels.size(), stationGoodChannels);
underconstrainedStations.add(station);
continue;
}
if (performExpensiveAnalysis) {
/*
* Heuristic #2 for underconstrained:
* For each of my neighbours, count the maximum number of channels in my domain that each neighbour can potentially "block" out. Then assume each neighbour does block out this maximal number of channels. Would I still have a channel left over?
*/
final Set<Station> neighbours = neighborIndex.neighborsOf(station);
if (neighbours.size() >= domain.size()) {
log.trace("Station {} has {} neighbours but only {} channels, so the channel counting heuristic will not work", station, neighbours.size(), domain.size());
continue;
}
final long interferingStationsMaxChannelSpread = neighbours.stream() // for each neighbour
.mapToLong(neighbour -> domains.get(neighbour).stream() // for each channel in the neighbour's domain
.mapToLong(neighbourChannel -> domain.stream() // for each of my channel's
.filter(myChannel -> !constraintManager.isSatisfyingAssignment(station, myChannel, neighbour, neighbourChannel))
.count() // count the number of my channels that would be invalid if my neighbour were assigned to neighbourChannel
)
.max() // max over all neighbour's channels
.getAsLong()
)
.sum();
if (interferingStationsMaxChannelSpread < domain.size()) {
log.trace("Station {} is underconstrained as it has {} domain channels, but the neighbouring interfering stations can only spread to a max of {} of them", station, domain.size(), interferingStationsMaxChannelSpread);
underconstrainedStations.add(station);
}
}
}
return underconstrainedStations;
}
}
| 7,473
| 49.5
| 259
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/IUnderconstrainedStationFinder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/underconstrained/IUnderconstrainedStationFinder.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 java.util.Map;
import java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 1/8/15.
*/
public interface IUnderconstrainedStationFinder {
/** Returns the set of stations that are underconstrained (they will ALWAYS have a feasible channel) */
default Set<Station> getUnderconstrainedStations(Map<Station, Set<Integer>> domains, ITerminationCriterion criterion) {
return getUnderconstrainedStations(domains, criterion, domains.keySet());
}
Set<Station> getUnderconstrainedStations(Map<Station, Set<Integer>> domains, ITerminationCriterion criterion, Set<Station> stationsToCheck);
}
| 1,619
| 36.674419
| 144
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/ITerminationCriterionFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/ITerminationCriterionFactory.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.termination;
/**
* Factory for termination criteria. Useful when an object can be asked to solve an instance many time in its life, and thus needs to create a new
* termination criterion each time.
* @author afrechet
*/
public interface ITerminationCriterionFactory {
public ITerminationCriterion getTerminationCriterion();
}
| 1,196
| 34.205882
| 146
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/ITerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/ITerminationCriterion.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.termination;
/**
* <p>
* In charge of managing time resource and termination.
* </p>
* <p>
* Even though time is measured in seconds, there is no guarantee about what kind of time (<i>e.g.</i> walltime, CPU time, ...) we're dealing with.
* This depends on the implementation.
* <p>
*
* @author afrechet
*/
public interface ITerminationCriterion {
/**
* <p>
* Return how much time (s) is remaining before the termination criterion is met. Return 0 if the termination criterion is met.
* </p>
* <p>
* This is used to allocate time to blocking (synchronous) processes. <br>
* </p>
* @return how much time (s) is remaining before the termination criterion is met.
*/
public double getRemainingTime();
/**
* Signals if the termination criterion is met.
* @return true if and only if termination criterion is met.
*/
public boolean hasToStop();
/**
* Notify the termination criterion that an (external) event was completed.
* @param aTime - the time the event took to complete.
*/
public void notifyEvent(double aTime);
/**
* A termination criterion that can be interrupted.
*/
public interface IInterruptibleTerminationCriterion extends ITerminationCriterion {
/**
* @return true if you managed to interrupt, false if already interrupted
*/
boolean interrupt();
}
}
| 2,232
| 30.450704
| 147
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/walltime/WalltimeTerminationCriterionFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/walltime/WalltimeTerminationCriterionFactory.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.termination.walltime;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterionFactory;
public class WalltimeTerminationCriterionFactory implements ITerminationCriterionFactory{
private final double fWalltimeLimit;
public WalltimeTerminationCriterionFactory(double aWalltimeLimit)
{
fWalltimeLimit = aWalltimeLimit;
}
@Override
public WalltimeTerminationCriterion getTerminationCriterion() {
return new WalltimeTerminationCriterion(fWalltimeLimit);
}
}
| 1,356
| 30.55814
| 89
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/walltime/WalltimeTerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/walltime/WalltimeTerminationCriterion.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.termination.walltime;
import org.apache.commons.math.util.FastMath;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
public class WalltimeTerminationCriterion implements ITerminationCriterion {
private final long fEndTimeMilli;
/**
* Create a wallclock time termination criterion starting immediately and running for the provided duration (s).
* @param aWalltimeLimit - wallclock duration (s).
*/
public WalltimeTerminationCriterion(double aWalltimeLimit)
{
this(System.currentTimeMillis(),aWalltimeLimit);
}
/**
* Create a wallclock time termination criterion starting at the given time (ms) and running for the provided duration (s).
* @param aApplicationStartTimeMilli - starting time (ms).
* @param aWalltimeLimit - wallclock duration (s).
*/
private WalltimeTerminationCriterion(long aApplicationStartTimeMilli, double aWalltimeLimit)
{
fEndTimeMilli = aApplicationStartTimeMilli + (long)(aWalltimeLimit *1000);
}
@Override
public boolean hasToStop() {
return getRemainingTime()<=0;
}
@Override
public double getRemainingTime() {
final long currentTime = System.currentTimeMillis();
final double remainingTime = (fEndTimeMilli-currentTime)/1000.0;
return FastMath.max(remainingTime, 0);
}
@Override
public void notifyEvent(double aTime) {
//Do not need to account for any additional (parallel) time with walltime.
}
}
| 2,292
| 30.847222
| 124
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/cputime/CPUTimeTerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/cputime/CPUTimeTerminationCriterion.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.termination.cputime;
import org.apache.commons.math3.util.FastMath;
import com.google.common.util.concurrent.AtomicDouble;
import ca.ubc.cs.beta.aeatk.misc.cputime.CPUTime;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
public class CPUTimeTerminationCriterion implements ITerminationCriterion
{
private final double fStartingCPUTime;
private AtomicDouble fExternalEllapsedCPUTime;
private final double fCPUTimeLimit;
// Note that this will only measure time for JVM threads. Threads in native code DO NOT COUNT TOWARDS CPU TIME.
private final CPUTime fTimer;
/**
* Create a CPU time termination criterion starting immediately and running for the provided duration (s).
* @param aCPUTimeLimit - CPU time duration (s).
*/
public CPUTimeTerminationCriterion(double aCPUTimeLimit)
{
fTimer = new CPUTime();
fExternalEllapsedCPUTime = new AtomicDouble(0.0);
fCPUTimeLimit = aCPUTimeLimit;
fStartingCPUTime = getCPUTime();
}
private double getCPUTime()
{
return fTimer.getCPUTime()+fExternalEllapsedCPUTime.get();
}
private double getEllapsedCPUTime()
{
return getCPUTime() - fStartingCPUTime;
}
@Override
public boolean hasToStop()
{
return (getEllapsedCPUTime() >= fCPUTimeLimit);
}
@Override
public double getRemainingTime() {
return FastMath.max(fCPUTimeLimit-getEllapsedCPUTime(), 0.0);
}
@Override
public void notifyEvent(double aTime) {
fExternalEllapsedCPUTime.addAndGet(aTime);
}
}
| 2,351
| 28.4
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/cputime/CPUTimeTerminationCriterionFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/cputime/CPUTimeTerminationCriterionFactory.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.termination.cputime;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterionFactory;
public class CPUTimeTerminationCriterionFactory implements ITerminationCriterionFactory{
private final double fCPUTimeLimit;
public CPUTimeTerminationCriterionFactory(double aCPUTimeLimit)
{
fCPUTimeLimit = aCPUTimeLimit;
}
@Override
public CPUTimeTerminationCriterion getTerminationCriterion() {
return new CPUTimeTerminationCriterion(fCPUTimeLimit);
}
}
| 1,344
| 31.804878
| 88
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/composite/DisjunctiveCompositeTerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/composite/DisjunctiveCompositeTerminationCriterion.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.termination.composite;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.math3.util.FastMath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Composite termination criterion that acts as a disjunction of the provided criteria.
* @author afrechet
*
*/
public class DisjunctiveCompositeTerminationCriterion implements ITerminationCriterion{
private static Logger log = LoggerFactory.getLogger(DisjunctiveCompositeTerminationCriterion.class);
private final Collection<ITerminationCriterion> fTerminationCriteria;
public DisjunctiveCompositeTerminationCriterion(Collection<ITerminationCriterion> aTerminationCriteria)
{
fTerminationCriteria = aTerminationCriteria;
}
public DisjunctiveCompositeTerminationCriterion(ITerminationCriterion... criterion) {
this(Arrays.asList(criterion));
}
@Override
public double getRemainingTime() {
double minTime = Double.POSITIVE_INFINITY;
for(ITerminationCriterion criterion : fTerminationCriteria)
{
double criterionTime = criterion.getRemainingTime();
log.trace("Criterion {} says there is {} s left.",criterion,criterionTime);
minTime = FastMath.min(minTime, criterionTime);
}
return minTime;
}
@Override
public boolean hasToStop() {
for(ITerminationCriterion criterion : fTerminationCriteria)
{
if(criterion.hasToStop())
{
log.trace("Criterion {} says we should stop ({} s left).",criterion,criterion.getRemainingTime());
return true;
}
}
return false;
}
@Override
public void notifyEvent(double aTime) {
for(ITerminationCriterion criterion : fTerminationCriteria)
{
criterion.notifyEvent(aTime);
}
}
}
| 2,635
| 27.652174
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/interrupt/InterruptibleTerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/interrupt/InterruptibleTerminationCriterion.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.termination.interrupt;
import java.util.concurrent.atomic.AtomicBoolean;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.infinite.NeverEndingTerminationCriterion;
/**`
* Created by newmanne on 13/05/15.
*/
public class InterruptibleTerminationCriterion implements ITerminationCriterion.IInterruptibleTerminationCriterion {
private final ITerminationCriterion decoratedCriterion;
private final AtomicBoolean interrupt;
public InterruptibleTerminationCriterion(ITerminationCriterion decoratedCriterion) {
this.decoratedCriterion = decoratedCriterion;
this.interrupt = new AtomicBoolean(false);
}
public InterruptibleTerminationCriterion() {
this(new NeverEndingTerminationCriterion());
}
@Override
public double getRemainingTime() {
return interrupt.get() ? 0.0 : decoratedCriterion.getRemainingTime();
}
@Override
public boolean hasToStop() {
return interrupt.get() || decoratedCriterion.hasToStop();
}
@Override
public void notifyEvent(double aTime) {
decoratedCriterion.notifyEvent(aTime);
}
public boolean interrupt() {
return interrupt.compareAndSet(false, true);
}
}
| 2,156
| 31.681818
| 116
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/infinite/NeverEndingTerminationCriterion.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/termination/infinite/NeverEndingTerminationCriterion.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.termination.infinite;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 29/07/15.
* A termination criterion that always has time remaining and never says it's time to stop
*/
public class NeverEndingTerminationCriterion implements ITerminationCriterion {
@Override
public double getRemainingTime() {
return 99999; // arbitrary big number
}
@Override
public boolean hasToStop() {
return false;
}
@Override
public void notifyEvent(double aTime) {
}
}
| 1,430
| 29.446809
| 90
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ResultSaverSolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ResultSaverSolverDecorator.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 java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.io.FileUtils;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import net.jcip.annotations.NotThreadSafe;
/**
* Solver decorator that saves solve results post-execution.
*
* @author afrechet
*/
@NotThreadSafe
public class ResultSaverSolverDecorator extends ASolverDecorator {
private final File fResultFile;
public ResultSaverSolverDecorator(ISolver aSolver, String aResultFile) {
super(aSolver);
if (aResultFile == null) {
throw new IllegalArgumentException("Result file cannot be null.");
}
File resultFile = new File(aResultFile);
if (resultFile.exists()) {
throw new IllegalArgumentException("Result file " + aResultFile + " already exists.");
}
fResultFile = resultFile;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
SolverResult result = fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
String instanceName = aInstance.getHashString() + ".cnf";
String line = instanceName + "," + result.toParsableString();
try {
FileUtils.writeLines(
fResultFile,
Arrays.asList(line),
true);
} catch (IOException e) {
throw new IllegalStateException("Could not write result to file " + fResultFile + ".", e);
}
return result;
}
}
| 2,672
| 31.597561
| 122
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/UnderconstrainedStationRemoverSolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/UnderconstrainedStationRemoverSolverDecorator.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 java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
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.metrics.SATFCMetrics;
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.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.underconstrained.IUnderconstrainedStationFinder;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Solver decorator that removes underconstrained stations from the instance, solve the sub-instance and then add back
* the underconstrained stations using simply looping over all the station's domain channels.
* <p/>
* A station is underconstrained if no matter what channels the other stations are assigned to, the station will always have a feasible
* channel to be packed on.
*
* @author afrechet
*/
@Slf4j
public class UnderconstrainedStationRemoverSolverDecorator extends ASolverDecorator {
private final IUnderconstrainedStationFinder underconstrainedStationFinder;
private final IConstraintManager constraintManager;
private final boolean recurse;
public UnderconstrainedStationRemoverSolverDecorator(ISolver aSolver, IConstraintManager constraintManager, IUnderconstrainedStationFinder underconstrainedStationFinder, boolean recurse) {
super(aSolver);
this.underconstrainedStationFinder = underconstrainedStationFinder;
this.constraintManager = constraintManager;
this.recurse = recurse;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
return solve(aInstance, aTerminationCriterion, aSeed, aInstance.getStations(), Watch.constructAutoStartWatch());
}
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed, Set<Station> stationsToCheck, Watch overallWatch) {
Watch watch = Watch.constructAutoStartWatch();
final Map<Station, Set<Integer>> domains = aInstance.getDomains();
if (aTerminationCriterion.hasToStop()) {
log.debug("All time spent.");
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
final Set<Station> underconstrainedStations = underconstrainedStationFinder.getUnderconstrainedStations(domains, aTerminationCriterion, stationsToCheck);
SATFCMetrics.postEvent(new SATFCMetrics.UnderconstrainedStationsRemovedEvent(aInstance.getName(), underconstrainedStations));
if (aTerminationCriterion.hasToStop()) {
log.debug("All time spent.");
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
log.debug("Removing {} underconstrained stations...", underconstrainedStations.size());
//Remove the nodes from the instance.
final Map<Station, Set<Integer>> alteredDomains = new HashMap<>(domains);
alteredDomains.keySet().removeAll(underconstrainedStations);
final SolverResult subResult;
final double preTime;
if (!alteredDomains.isEmpty()) {
StationPackingInstance alteredInstance = new StationPackingInstance(alteredDomains, aInstance.getPreviousAssignment(), aInstance.getMetadata());
preTime = watch.getElapsedTime();
log.trace("{} s spent on underconstrained pre-solving setup.", preTime);
if (recurse && !underconstrainedStations.isEmpty()) {
log.debug("Going one layer deeper with underconstrained station removal");
// You only need to recheck a station that might be underconstrained because some of his neigbhours have disappeared
final SimpleGraph<Station, DefaultEdge> constraintGraph = ConstraintGrouper.getConstraintGraph(domains, constraintManager);
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(constraintGraph);
final Set<Station> stationsToRecheck = underconstrainedStations.stream().map(neighborIndex::neighborsOf).flatMap(Collection::stream).filter(s -> !underconstrainedStations.contains(s)).collect(Collectors.toSet());
subResult = solve(alteredInstance, aTerminationCriterion, aSeed, stationsToRecheck, overallWatch);
} else { // we bottomed out
//Solve the reduced instance.
log.debug("Spent {} overall on finding underconstrained stations", overallWatch.getElapsedTime());
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.FIND_UNDERCONSTRAINED_STATIONS, overallWatch.getElapsedTime()));
log.debug("Solving the sub-instance...");
subResult = fDecoratedSolver.solve(alteredInstance, aTerminationCriterion, aSeed);
}
} else {
log.debug("All stations were underconstrained!");
preTime = watch.getElapsedTime();
log.trace("{} s spent on underconstrained pre-solving setup.", preTime);
subResult = new SolverResult(SATResult.SAT, 0.0, new HashMap<>(), SolvedBy.UNDERCONSTRAINED);
}
if (subResult.getResult().equals(SATResult.SAT)) {
final SimpleGraph<Station, DefaultEdge> constraintGraph = ConstraintGrouper.getConstraintGraph(domains, constraintManager);
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(constraintGraph);
final Watch findChannelsForUnderconstrainedStationsTimer = Watch.constructAutoStartWatch();
log.debug("Sub-instance is packable, adding back the underconstrained stations...");
//If satisfiable, find a channel for the under constrained nodes that were removed by brute force through their domain.
final Map<Integer, Set<Station>> assignment = subResult.getAssignment();
final Map<Integer, Set<Station>> alteredAssignment = new HashMap<Integer, Set<Station>>(assignment);
final Map<Station, Integer> stationToChannel = StationPackingUtils.stationToChannelFromChannelToStation(alteredAssignment);
final Set<Station> assignedStations = new HashSet<>(subResult.getAssignment().values().stream().flatMap(Collection::stream).collect(Collectors.toSet()));
for (Station station : underconstrainedStations) {
boolean stationAdded = false;
Set<Integer> domain = domains.get(station);
//Try to add the underconstrained station at one of its channel domain.
log.trace("Trying to add back underconstrained station {} on its domain {} ...", station, domain);
final Set<Station> assignedStationsInNeighbourhood = Sets.intersection(neighborIndex.neighborsOf(station), assignedStations);
final Map<Integer, Set<Station>> neighbourHoodAssignment = new HashMap<>();
for (Station s : assignedStationsInNeighbourhood) {
int chan = stationToChannel.get(s);
neighbourHoodAssignment.computeIfAbsent(chan, k -> new HashSet<>()).add(s);
}
for (Integer channel : domain) {
log.trace("Checking domain channel {} ...", channel);
neighbourHoodAssignment.computeIfAbsent(channel, k -> new HashSet<>()).add(station);
final boolean addedSAT = constraintManager.isSatisfyingAssignment(neighbourHoodAssignment);
if (addedSAT) {
log.trace("Added on channel {}.", channel);
alteredAssignment.computeIfAbsent(channel, k -> new HashSet<>()).add(station);
stationToChannel.put(station, channel);
stationAdded = true;
break;
} else {
neighbourHoodAssignment.get(channel).remove(station);
if (neighbourHoodAssignment.get(channel).isEmpty()) {
neighbourHoodAssignment.remove(channel);
}
}
}
if (!stationAdded) {
throw new IllegalStateException("Could not add unconstrained station " + station + " on any of its domain channels.");
}
assignedStations.add(station);
}
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.PUT_BACK_UNDERCONSTRAINED_STATIONS, findChannelsForUnderconstrainedStationsTimer.getElapsedTime()));
log.trace("It took {} to find SAT channels for all of the underconstrained stations", findChannelsForUnderconstrainedStationsTimer.getElapsedTime());
return new SolverResult(SATResult.SAT, watch.getElapsedTime(), alteredAssignment, subResult.getSolvedBy());
} else {
log.debug("Sub-instance was not satisfiable, no need to consider adding back underconstrained stations.");
//Not satisfiable, so re-adding the underconstrained nodes cannot change anything.
return SolverResult.relabelTime(subResult, watch.getElapsedTime());
}
}
}
| 10,920
| 57.090426
| 228
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PreviousAssignmentContainsAnswerDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PreviousAssignmentContainsAnswerDecorator.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 java.util.Map;
import java.util.Set;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimaps;
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.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 19/01/16.
*/
@Slf4j
public class PreviousAssignmentContainsAnswerDecorator extends ASolverDecorator {
private final IConstraintManager constraintManager;
/**
* @param aSolver - decorated ISolver.
*/
public PreviousAssignmentContainsAnswerDecorator(ISolver aSolver, IConstraintManager constraintManager) {
super(aSolver);
this.constraintManager = constraintManager;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final HashMultimap<Integer, Station> assignment = HashMultimap.create();
aInstance.getPreviousAssignment().entrySet().stream().forEach(entry -> {
if (aInstance.getStations().contains(entry.getKey()) && aInstance.getDomains().get(entry.getKey()).contains(entry.getValue())) {
assignment.put(entry.getValue(), entry.getKey());
}
});
if (assignment.values().size() == aInstance.getStations().size() && assignment.values().containsAll(aInstance.getStations())) {
final Map<Integer, Set<Station>> integerSetMap = Multimaps.asMap(assignment);
if (constraintManager.isSatisfyingAssignment(integerSetMap)) {
log.debug("Previous solution directly solves this problem");
return new SolverResult(SATResult.SAT, watch.getElapsedTime(), integerSetMap, SolverResult.SolvedBy.PREVIOUS_ASSIGNMENT);
}
}
return super.solve(aInstance, aTerminationCriterion, aSeed);
}
}
| 3,207
| 41.773333
| 140
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ConnectedComponentGroupingDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ConnectedComponentGroupingDecorator.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 ca.ubc.cs.beta.stationpacking.utils.GuavaCollectors.toImmutableMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
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.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.SolverHelper;
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.componentgrouper.IComponentGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 28/11/14.
*/
@Slf4j
public class ConnectedComponentGroupingDecorator extends ASolverDecorator {
private final IComponentGrouper fComponentGrouper;
private final IConstraintManager fConstraintManager;
private final boolean fSolveEverything;
/**
* @param aSolveEverythingForCaching if true, solve every component, even when you know the problem is logically finished. (Used for caching results)
* @param aComponentGrouper
*/
public ConnectedComponentGroupingDecorator(ISolver aSolver, IComponentGrouper aComponentGrouper, IConstraintManager aConstraintManager, boolean aSolveEverythingForCaching) {
super(aSolver);
fComponentGrouper = aComponentGrouper;
fConstraintManager = aConstraintManager;
fSolveEverything = aSolveEverythingForCaching;
}
public ConnectedComponentGroupingDecorator(ISolver aSolver, IComponentGrouper aComponentGrouper, IConstraintManager aConstraintManger) {
this(aSolver, aComponentGrouper, aConstraintManger, false);
}
@Override
public SolverResult solve(StationPackingInstance aInstance, final ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
log.debug("Solving instance of {}...", aInstance.getInfo());
// Split into groups
final Set<Set<Station>> stationComponents = fComponentGrouper.group(aInstance, fConstraintManager);
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.CONNECTED_COMPONENTS, watch.getElapsedTime()));
log.debug("Problem separated in {} groups.", stationComponents.size());
// sort the components in ascending order of size. The idea is that this would decrease runtime if one of the small components was UNSAT
final List<Set<Station>> sortedStationComponents = stationComponents.stream().sorted((o1, o2) -> Integer.compare(o1.size(), o2.size())).collect(Collectors.toList());
// convert components into station packing problems
final List<StationPackingInstance> componentInstances = new ArrayList<>();
for (int i = 0; i < sortedStationComponents.size(); i++) {
final Set<Station> stationComponent = sortedStationComponents.get(i);
final ImmutableMap<Station, Set<Integer>> subDomains = aInstance.getDomains().entrySet()
.stream()
.filter(entry -> stationComponent.contains(entry.getKey()))
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
final String name = aInstance.getName() + "_component" + i;
// update name to include a component prefix
final Map<String, Object> metadata = new HashMap<>(aInstance.getMetadata());
metadata.put(StationPackingInstance.NAME_KEY, name);
componentInstances.add(new StationPackingInstance(subDomains, aInstance.getPreviousAssignment(), metadata));
}
SATFCMetrics.postEvent(new SATFCMetrics.SplitIntoConnectedComponentsEvent(aInstance.getName(), componentInstances));
final List<SolverResult> solverResults = new ArrayList<>();
for (int i = 0; i < componentInstances.size(); i++) {
final StationPackingInstance stationComponent = componentInstances.get(i);
log.debug("Solving component {}...", i);
log.debug("Component {} has {} stations.", i, stationComponent.getStations().size());
final SolverResult componentResult = fDecoratedSolver.solve(stationComponent, aTerminationCriterion, aSeed);
SATFCMetrics.postEvent(new SATFCMetrics.InstanceSolvedEvent(stationComponent.getName(), componentResult));
solverResults.add(componentResult);
// If any component matches this clause (is not SAT), the whole instance cannot be SAT, might as well stop then
if (!componentResult.getResult().equals(SATResult.SAT) && !fSolveEverything) {
break;
}
}
final SolverResult mergedResult = SolverHelper.mergeComponentResults(solverResults);
final SolverResult result = SolverResult.relabelTimeAndSolvedBy(mergedResult, watch.getElapsedTime(), SolverResult.SolvedBy.CONNECTED_COMPONENTS);
if (result.getResult().equals(SATResult.SAT)) {
Preconditions.checkState(solverResults.size() == stationComponents.size(), "Determined result was SAT without looking at every component!");
}
log.debug("Result:" + System.lineSeparator() + result.toParsableString());
return result;
}
}
| 6,610
| 50.648438
| 177
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/DelayedSolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/DelayedSolverDecorator.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 java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.math.util.FastMath;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 15/10/15.
* Wait for some time, then proceed
*/
@Slf4j
public class DelayedSolverDecorator extends ASolverDecorator {
private final long time;
private final long noise;
private volatile CountDownLatch latch;
/**
* @param time time to wait before proceeding, in seconds
* @param noise random noise 0 - noise is added
*/
public DelayedSolverDecorator(ISolver aSolver, double time, double noise) {
super(aSolver);
this.noise = (long) (noise * 1000);
this.time = (long) (time * 1000);
// meaningless initial assignment to prevent null
latch = new CountDownLatch(1);
}
public DelayedSolverDecorator(ISolver aSolver, double time) {
this(aSolver, time, 0);
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
latch = new CountDownLatch(1);
long remainingTime = (long) aTerminationCriterion.getRemainingTime() * 1000;
long timeToWait = FastMath.min(time + RandomUtils.nextLong(0, noise), remainingTime);
if (timeToWait > 0) {
try {
log.debug("Waiting {} ms", timeToWait);
latch.await(timeToWait, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new IllegalStateException("Interrupted while waiting for delayed solver", e);
}
}
return SolverResult.relabelTime(fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
@Override
public void interrupt() {
log.debug("Interrupting");
latch.countDown();
super.interrupt();
}
}
| 3,215
| 35.134831
| 129
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ASolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ASolverDecorator.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 ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Abstract {@link ISolver} decorator that passes the basic methods to the decorated solver.
*
* @author afrechet
*/
public abstract class ASolverDecorator implements ISolver {
protected final ISolver fDecoratedSolver;
/**
* @param aSolver - decorated ISolver.
*/
public ASolverDecorator(ISolver aSolver) {
fDecoratedSolver = aSolver;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
return aTerminationCriterion.hasToStop() ? SolverResult.createTimeoutResult(0.0) : fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
}
@Override
public void notifyShutdown() {
fDecoratedSolver.notifyShutdown();
}
@Override
public void interrupt() {
fDecoratedSolver.interrupt();
}
}
| 2,009
| 32.5
| 155
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ISATFCInterruptible.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/ISATFCInterruptible.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;
/**
* Created by newmanne on 15/10/15.
*/
public interface ISATFCInterruptible {
void interrupt();
}
| 983
| 29.75
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/CPUTimeDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/CPUTimeDecorator.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 ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.Clasp3Library;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 05/10/15.
* Used for configuration experiments, to return the CPU time of a single problem
*/
public class CPUTimeDecorator extends ASolverDecorator {
private final Clasp3Library library;
public CPUTimeDecorator(ISolver aSolver, Clasp3Library library) {
super(aSolver);
this.library = library;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
double startCpuTime = library.getCpuTime();
final SolverResult solve = super.solve(aInstance, aTerminationCriterion, aSeed);
double cpuTime = library.getCpuTime() - startCpuTime;
System.out.println("CPU TIME FOR HYDRA: " + cpuTime);
return solve;
}
}
| 2,015
| 37.769231
| 122
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/TimeBoundedSolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/TimeBoundedSolverDecorator.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 ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.composite.DisjunctiveCompositeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
/**
* Created by newmanne on 15/10/15.
* Run a solver for a fixed amount of time, then continue down the decorator tree if it fails
*/
public class TimeBoundedSolverDecorator extends ASolverDecorator {
private final ISolver timeBoundedSolver;
private final double timeBound;
public TimeBoundedSolverDecorator(ISolver solverToDecorate, ISolver timeBoundedSolver, double timeBound) {
super(solverToDecorate);
this.timeBoundedSolver = timeBoundedSolver;
this.timeBound = timeBound;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final ITerminationCriterion newCriterion = new DisjunctiveCompositeTerminationCriterion(aTerminationCriterion, new WalltimeTerminationCriterion(timeBound));
final SolverResult solve = timeBoundedSolver.solve(aInstance, newCriterion, aSeed);
if (aTerminationCriterion.hasToStop() || solve.isConclusive()) {
return solve;
} else {
return SolverResult.relabelTime(super.solve(aInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
}
@Override
public void interrupt() {
super.interrupt();
timeBoundedSolver.interrupt();
}
}
| 2,750
| 41.323077
| 164
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/AssignmentVerifierDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/AssignmentVerifierDecorator.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 java.util.Map;
import java.util.Set;
import com.google.common.base.Preconditions;
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.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
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 ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Verifies the assignments returned by decorated solver for satisfiability.
*
* @author afrechet
*/
@Slf4j
public class AssignmentVerifierDecorator extends ASolverDecorator {
private final IConstraintManager fConstraintManager;
private final IStationManager fStationManager;
public AssignmentVerifierDecorator(ISolver aSolver, IConstraintManager aConstraintManager, IStationManager aStationManager) {
super(aSolver);
fConstraintManager = aConstraintManager;
fStationManager = aStationManager;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final SolverResult result = fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
if (result.getResult().equals(SATResult.SAT)) {
log.debug("Independently verifying the veracity of returned assignment");
//Check that the assignment assigns every station to a channel
final int assignmentSize = result.getAssignment().keySet().stream().mapToInt(channel -> result.getAssignment().get(channel).size()).sum();
Preconditions.checkState(assignmentSize == aInstance.getStations().size(), "Merged station assignment doesn't assign exactly the stations in the instance. There are %s stations in the assignment but expected %s stations to be assigned", assignmentSize, aInstance.getStations().size());
// Check that the every station is on its domain
final Map<Station, Integer> stationToChannel = StationPackingUtils.stationToChannelFromChannelToStation(result.getAssignment());
final ImmutableMap<Station, Set<Integer>> domains = aInstance.getDomains();
for (Map.Entry<Station, Integer> entry : stationToChannel.entrySet()) {
final Station station = entry.getKey();
final int channel = entry.getValue();
Preconditions.checkState(domains.get(station).contains(channel), "Station %s is assigned to channel %s which is not in its domain %s", station, channel, domains.get(station));
Preconditions.checkState(fStationManager.getDomain(station).contains(channel), "Station %s is assigned to channel %s which is not in its domain %s", station, channel, fStationManager.getDomain(station));
}
Preconditions.checkState(fConstraintManager.isSatisfyingAssignment(result.getAssignment()), "Solver returned SAT, but assignment is not satisfiable.", result.getAssignment());
log.debug("Assignment was independently verified to be satisfiable.");
}
return result;
}
}
| 4,321
| 49.847059
| 297
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PythonAssignmentVerifierDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/PythonAssignmentVerifierDecorator.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 java.util.List;
import org.python.core.PyObject;
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 ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Created by emily404 on 8/31/15.
* Verifies that SAT results returned by solvers don't violate the constraints
* This verifier is actually written in python, by someone who has not seen any other constraint parsing code, just to be doubly sure of correctness.
*/
@Slf4j
public class PythonAssignmentVerifierDecorator extends ASolverDecorator {
private final PythonInterpreterContainer python;
/**
* @param aSolver - decorated ISolver, verifying assignemnt in python.
*/
public PythonAssignmentVerifierDecorator(ISolver aSolver, PythonInterpreterContainer pythonInterpreter) {
super(aSolver);
python = pythonInterpreter;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final SolverResult result = fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
if (result.getResult().equals(SATResult.SAT)) {
log.debug("Independently verifying the veracity of returned assignment using python verifier script");
final String evalString = "check_violations(\'"+JSONUtils.toString(result.getAssignment())+"\')";
final PyObject eval = python.eval(evalString);
final String checkResult = eval.toString();
if(!checkResult.equals("None")){
List<String> violationResult = (List<String>) eval.__tojava__(List.class);
throw new IllegalStateException("Station " + violationResult.get(0) + " is assigned to channel " + violationResult.get(1) + " which violated " + violationResult.get(2) + System.lineSeparator() + result.getAssignment());
};
log.debug("Assignment was independently verified to be satisfiable.");
}
return result;
}
}
| 3,270
| 43.202703
| 235
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/CNFSaverSolverDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/CNFSaverSolverDecorator.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 java.io.File;
import java.io.IOException;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import com.google.common.base.Joiner;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.EncodingType;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF;
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.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.RedisUtils;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import redis.clients.jedis.Jedis;
/**
* Solver decorator that saves CNFs on solve query.
*
* @author afrechet
*/
public class CNFSaverSolverDecorator extends ASolverDecorator {
private final IConstraintManager fConstraintManager;
private final ICNFSaver fCNFSaver;
private EncodingType encodingType;
private boolean saveAssignment;
public CNFSaverSolverDecorator(@NonNull ISolver aSolver,
@NonNull IConstraintManager aConstraintManager,
@NonNull ICNFSaver aCNFSaver,
@NonNull EncodingType encodingType,
boolean saveAssignment) {
super(aSolver);
this.fCNFSaver = aCNFSaver;
this.encodingType = encodingType;
this.saveAssignment = saveAssignment;
fConstraintManager = aConstraintManager;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
//Encode instance.
final SATCompressor aSATEncoder = new SATCompressor(fConstraintManager, encodingType);
final SATEncoder.CNFEncodedProblem aEncoding = aSATEncoder.encodeWithAssignment(aInstance);
final CNF CNF = aEncoding.getCnf();
//Create comments
final String[] comments = new String[]{
"FCC Feasibility Checking Instance",
"Instance Info: " + aInstance.getInfo(),
"Original instance: " + aInstance.getName()
};
final String cnfFileContentString = CNF.toDIMACS(comments);
//Save instance to redis
final String CNFName = aInstance.getName();
fCNFSaver.saveCNF(aInstance.getName(), CNFName, cnfFileContentString);
if (saveAssignment) {
// Create assignment
final String assignmentString = Joiner.on(System.lineSeparator()).join(aEncoding.getInitialAssignment().entrySet().stream()
.map(entry -> entry.getValue() ? entry.getKey() : -entry.getKey()).collect(Collectors.toList()));
fCNFSaver.saveAssignment(CNFName, assignmentString);
}
return fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
}
/**
* Abstraction around ssaving CNF files
*/
public interface ICNFSaver {
/**
* @param instanceName Name of the instance
* @param CNFName Name of the CNF
* @param CNFContents CNF contents as a string
*/
void saveCNF(String instanceName, String CNFName, String CNFContents);
/**
* @param CNFName Name of the CNF
* @param assignmentContents Assignment contents as string
*/
void saveAssignment(String CNFName, String assignmentContents);
}
/**
* This CNFSaver wraps anohter CNF saver and builds an index of saved CNFs in redis for easy parsing
*/
@RequiredArgsConstructor
public static class RedisIndexCNFSaver implements ICNFSaver {
// This just builds an index in redis: use a different saver to save the actual files
@NonNull
private final ICNFSaver saver;
@NonNull
private final Jedis jedis;
@NonNull
private final String queueName;
@Override
public void saveCNF(String instanceName, String CNFName, String CNFContents) {
final String indexKey = RedisUtils.makeKey(queueName, RedisUtils.CNF_INDEX_QUEUE);
jedis.rpush(indexKey, Joiner.on(',').join(CNFName, instanceName));
saver.saveCNF(instanceName, CNFName, CNFContents);
}
@Override
public void saveAssignment(String CNFName, String assignmentContents) {
saver.saveAssignment(CNFName, assignmentContents);
}
}
public static class FileCNFSaver implements ICNFSaver {
private final String fCNFDirectory;
public FileCNFSaver(@NonNull String aCNFDirectory) {
File cnfdir = new File(aCNFDirectory);
if (!cnfdir.exists()) {
throw new IllegalArgumentException("CNF directory " + aCNFDirectory + " does not exist.");
}
if (!cnfdir.isDirectory()) {
throw new IllegalArgumentException("CNF directory " + aCNFDirectory + " is not a directory.");
}
fCNFDirectory = aCNFDirectory;
}
@Override
public void saveCNF(String instanceName, String CNFName, String CNFContents) {
try {
FileUtils.writeStringToFile(new File(fCNFDirectory + File.separator + CNFName + ".cnf"), CNFContents);
} catch (IOException e) {
throw new IllegalStateException("Could not write CNF to file", e);
}
}
@Override
public void saveAssignment(String CNFName, String assignmentContents) {
try {
FileUtils.writeStringToFile(new File(fCNFDirectory + File.separator + CNFName + "_assignment.txt"), assignmentContents);
} catch (IOException e) {
throw new IllegalStateException("Could not write CNF to file", e);
}
}
}
}
| 7,051
| 37.118919
| 136
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/SupersetCacheSATDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/SupersetCacheSATDecorator.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.cache;
import java.util.Map;
import java.util.Set;
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.cache.containment.ContainmentCacheSATResult;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
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.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 28/01/15.
* Query the SATFCServer to see if it contains a SAT superset entry for the problem
*/
@Slf4j
public class SupersetCacheSATDecorator extends ASolverDecorator {
private final ContainmentCacheProxy proxy;
public SupersetCacheSATDecorator(ISolver aSolver, ContainmentCacheProxy proxy) {
super(aSolver);
this.proxy = proxy;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
// test sat cache - supersets of the problem that are SAT directly correspond to solutions to the current problem!
final SolverResult result;
log.debug("Sending query to cache");
final ContainmentCacheSATResult containmentCacheSATResult = proxy.proveSATBySuperset(aInstance, aTerminationCriterion);
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.FIND_SUPERSET, watch.getElapsedTime()));
if (containmentCacheSATResult.isValid()) {
final Map<Integer, Set<Station>> assignment = containmentCacheSATResult.getResult();
log.debug("Found a superset in the SAT cache - declaring result SAT because of " + containmentCacheSATResult.getKey());
final Map<Integer, Set<Station>> reducedAssignment = Maps.newHashMap();
for (Integer channel : assignment.keySet()) {
assignment.get(channel).stream().filter(station -> aInstance.getStations().contains(station)).forEach(station -> {
if (reducedAssignment.get(channel) == null) {
reducedAssignment.put(channel, Sets.newHashSet());
}
reducedAssignment.get(channel).add(station);
});
}
result = new SolverResult(SATResult.SAT, watch.getElapsedTime(), reducedAssignment, SolverResult.SolvedBy.SAT_CACHE);
SATFCMetrics.postEvent(new SATFCMetrics.JustifiedByCacheEvent(aInstance.getName(), containmentCacheSATResult.getKey()));
} else {
log.debug("Cache query unsuccessful");
result = SolverResult.relabelTime(fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
return result;
}
@Override
public void interrupt() {
proxy.interrupt();
super.interrupt();
}
}
| 4,180
| 43.956989
| 146
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/CacheResultDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/CacheResultDecorator.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.cache;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.ICacher;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 1/25/15.
* Cache result in the SATFCServer
*/
public class CacheResultDecorator extends ASolverDecorator {
private final ICacher cacher;
private final CachingStrategy cachingStrategy;
/**
* @param aSolver - decorated ISolver.
*/
public CacheResultDecorator(ISolver aSolver, ICacher aCacher, CachingStrategy cachingStrategy) {
super(aSolver);
cacher = aCacher;
this.cachingStrategy = cachingStrategy;
}
public CacheResultDecorator(ISolver aSolver, ICacher aCacher) {
this(aSolver, aCacher, new CacheConclusiveNewInfoStrategy());
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final SolverResult result = fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
if (cachingStrategy.shouldCache(result)) {
cacher.cacheResult(aInstance, result, aTerminationCriterion);
}
return result;
}
public interface CachingStrategy {
boolean shouldCache(SolverResult result);
}
/**
* Don't bother caching a result if we solved the problem using the cache, because it can't possibly have any added value
*/
public static class CacheConclusiveNewInfoStrategy implements CachingStrategy {
@Override
public boolean shouldCache(SolverResult result) {
return result.getResult().isConclusive() && !result.getSolvedBy().equals(SolverResult.SolvedBy.SAT_CACHE) && !result.getSolvedBy().equals(SolverResult.SolvedBy.UNSAT_CACHE);
}
}
}
| 2,917
| 35.024691
| 185
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/SubsetCacheUNSATDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/SubsetCacheUNSATDecorator.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.cache;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATResult;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
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.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 28/01/15.
* Query the SATFCServer to see if it contains an UNSAT subset entry for this problem
*/
@Slf4j
public class SubsetCacheUNSATDecorator extends ASolverDecorator {
private final ContainmentCacheProxy containmentCache;
public SubsetCacheUNSATDecorator(ISolver aSolver, ContainmentCacheProxy containmentCacheProxy) {
super(aSolver);
this.containmentCache = containmentCacheProxy;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final SolverResult result;
log.debug("Querying UNSAT cache");
ContainmentCacheUNSATResult proveUNSATBySubset = containmentCache.proveUNSATBySubset(aInstance, aTerminationCriterion);
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.FIND_SUBSET, watch.getElapsedTime()));
if (proveUNSATBySubset.isValid()) {
log.debug("Found a subset in the UNSAT cache - declaring problem UNSAT due to problem " + proveUNSATBySubset.getKey());
result = SolverResult.createNonSATResult(SATResult.UNSAT, watch.getElapsedTime(), SolverResult.SolvedBy.UNSAT_CACHE);
SATFCMetrics.postEvent(new SATFCMetrics.JustifiedByCacheEvent(aInstance.getName(), proveUNSATBySubset.getKey()));
} else {
log.debug("UNSAT cache unsuccessful");
result = SolverResult.relabelTime(fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
return result;
}
@Override
public void interrupt() {
containmentCache.interrupt();
super.interrupt();
}
}
| 3,299
| 44.205479
| 144
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/ContainmentCacheProxy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/cache/ContainmentCacheProxy.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.cache;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.math.util.FastMath;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.annotation.JsonInclude;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.CacheCoordinate;
import ca.ubc.cs.beta.stationpacking.cache.ICacher;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheSATResult;
import ca.ubc.cs.beta.stationpacking.cache.containment.ContainmentCacheUNSATResult;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.ProblemIncrementor;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ISATFCInterruptible;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 01/03/15.
* Abstracts away the Containment Cache data structure, which is really being accessed using web requests
* Not threadsafe!
*/
@Slf4j
public class ContainmentCacheProxy implements ICacher, ISATFCInterruptible {
// if the text is smaller than this length in bytes, then compression probably isn't worth the trouble
public static final int MIN_GZIP_LENGTH = 860;
public static Date lastSuccessfulCommunication;
private final CacheCoordinate coordinate;
private final CloseableHttpAsyncClient httpClient;
private final String SAT_URL;
private final String UNSAT_URL;
private final String CACHE_URL;
private final AtomicReference<Future<HttpResponse>> activeFuture;
private final int numAttempts;
private final boolean noErrorOnServerUnavailable;
private final ProblemIncrementor problemIncrementor;
public ContainmentCacheProxy(@NonNull String baseServerURL, @NonNull CacheCoordinate coordinate, int numAttempts, boolean noErrorOnServerUnavailable, IPollingService pollingService, @NonNull CloseableHttpAsyncClient httpClient) {
this.httpClient = httpClient;
SAT_URL = baseServerURL + "/v1/cache/query/SAT";
UNSAT_URL = baseServerURL + "/v1/cache/query/UNSAT";
CACHE_URL = baseServerURL + "/v1/cache";
this.coordinate = coordinate;
activeFuture = new AtomicReference<>();
this.numAttempts = numAttempts;
this.noErrorOnServerUnavailable = noErrorOnServerUnavailable;
problemIncrementor = new ProblemIncrementor(pollingService, this);
}
/**
* Object used to represent a cache lookup request
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public static class ContainmentCacheRequest {
public ContainmentCacheRequest(StationPackingInstance instance, CacheCoordinate coordinate) {
this.instance = instance;
this.coordinate = coordinate;
}
private StationPackingInstance instance;
private CacheCoordinate coordinate;
private SolverResult result;
}
public ContainmentCacheSATResult proveSATBySuperset(StationPackingInstance instance, ITerminationCriterion terminationCriterion) {
try {
problemIncrementor.scheduleTermination(terminationCriterion);
return makePost(SAT_URL, new ContainmentCacheRequest(instance, coordinate), ContainmentCacheSATResult.class, ContainmentCacheSATResult.failure(), terminationCriterion, numAttempts);
} finally {
problemIncrementor.jobDone();
}
}
public ContainmentCacheUNSATResult proveUNSATBySubset(StationPackingInstance instance, ITerminationCriterion terminationCriterion) {
try {
problemIncrementor.scheduleTermination(terminationCriterion);
return makePost(UNSAT_URL, new ContainmentCacheRequest(instance, coordinate), ContainmentCacheUNSATResult.class, ContainmentCacheUNSATResult.failure(), terminationCriterion, numAttempts);
} finally {
problemIncrementor.jobDone();
}
}
@Override
public void cacheResult(StationPackingInstance instance, SolverResult result, ITerminationCriterion terminationCriterion) {
makePost(CACHE_URL, new ContainmentCacheRequest(instance, coordinate, result), null, null, terminationCriterion, numAttempts);
}
private <T> T makePost(String URL, ContainmentCacheRequest request, Class<T> responseClass, T failure, ITerminationCriterion terminationCriterion, int remainingAttempts) {
try {
return makePost(URL, request, responseClass, failure, terminationCriterion);
} catch (Exception e) {
log.error("Error making a web request", e);
int newRemainingAttempts = remainingAttempts - 1;
if (newRemainingAttempts > 0) {
log.error("Retrying web request. Request will be retried {} more time(s)", newRemainingAttempts);
return makePost(URL, request, responseClass, failure, terminationCriterion, newRemainingAttempts);
} else {
log.error("The retry quota for this web request has been exceeded");
if (noErrorOnServerUnavailable) {
log.error("Continuing to solve the problem without the server...");
return failure;
} else {
throw new RuntimeException(e);
}
}
}
}
private <T> T makePost(String URL, ContainmentCacheRequest request, Class<T> responseClass, T failure, ITerminationCriterion terminationCriterion) {
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(URL);
final String uriString = builder.build().toUriString();
final HttpPost httpPost = new HttpPost(uriString);
log.debug("Making a request to the cache server for instance " + request.getInstance().getName() + " " + uriString);
final String jsonRequest = JSONUtils.toString(request);
// possibly do gzip compression
if (jsonRequest.length() > MIN_GZIP_LENGTH) {
final ByteArrayOutputStream arr = new ByteArrayOutputStream();
try {
final OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(jsonRequest.getBytes());
zipper.close();
} catch (IOException e) {
throw new RuntimeException("Error compressing json http post request to gzip", e);
}
final ByteArrayEntity postEntity = new ByteArrayEntity(arr.toByteArray());
postEntity.setContentEncoding("gzip");
postEntity.setContentType("application/json");
httpPost.setEntity(postEntity);
} else {
httpPost.setEntity(new StringEntity(jsonRequest, ContentType.APPLICATION_JSON));
}
httpPost.addHeader("Accept-Encoding", "gzip");
if (terminationCriterion.hasToStop()) {
return failure;
}
try {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<HttpResponse> httpResponse = new AtomicReference<>();
final AtomicReference<Exception> exception = new AtomicReference<>();
activeFuture.set(httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
log.trace("Back from making web request");
httpResponse.set(result);
lastSuccessfulCommunication = new Date();
latch.countDown();
}
@Override
public void failed(Exception ex) {
exception.set(ex);
latch.countDown();
}
@Override
public void cancelled() {
log.debug("Web request aborted");
latch.countDown();
}
}));
if (terminationCriterion.hasToStop()) {
return failure;
}
boolean timedOut;
try {
double waitTime = FastMath.max(0, terminationCriterion.getRemainingTime());
long waitTimeInMs = (long) (1000 * waitTime);
timedOut = !latch.await(waitTimeInMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted while waiting for countdown latch", e);
}
if (timedOut) {
log.debug("Timed out while waiting for server to respond");
interrupt();
}
final Exception ex = exception.get();
if (ex != null) {
throw new RuntimeException("Error making web request", ex);
}
if (terminationCriterion.hasToStop()) {
return failure;
}
if (responseClass != null) {
HttpEntity responseEntity = httpResponse.get().getEntity();
// Check to see if the response is compressed using gzip
final Header ceheader = responseEntity.getContentEncoding();
if (ceheader != null && Arrays.stream(ceheader.getElements()).anyMatch(codec -> codec.getName().equalsIgnoreCase("gzip"))) {
log.trace("gzip response detected");
responseEntity = new GzipDecompressingEntity(responseEntity);
}
final String response = EntityUtils.toString(responseEntity);
return JSONUtils.toObject(response, responseClass);
} else {
return null; // Not expecting a response
}
} catch (IOException e) {
throw new RuntimeException("Error reading input stream from httpResponse", e);
}
}
public void interrupt() {
final Future<HttpResponse> future = activeFuture.getAndSet(null);
if (future != null) {
log.debug("Cancelling web request future");
future.cancel(true);
}
}
}
| 12,050
| 44.475472
| 233
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/consistency/ArcConsistencyEnforcerDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/consistency/ArcConsistencyEnforcerDecorator.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.consistency;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.consistency.AC3Enforcer;
import ca.ubc.cs.beta.stationpacking.consistency.AC3Output;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
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.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by pcernek on 5/8/15.
* Enforce arc consistency on the problem domains with the hope of shrinking them
*/
@Slf4j
public class ArcConsistencyEnforcerDecorator extends ASolverDecorator {
private final AC3Enforcer ac3Enforcer;
/**
* @param aSolver - decorated ISolver.
* @param constraintManager
*/
public ArcConsistencyEnforcerDecorator(ISolver aSolver, IConstraintManager constraintManager) {
super(aSolver);
ac3Enforcer = new AC3Enforcer(constraintManager);
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final AC3Output ac3Output = ac3Enforcer.AC3(aInstance, aTerminationCriterion);
SATFCMetrics.postEvent(new SATFCMetrics.TimingEvent(aInstance.getName(), SATFCMetrics.TimingEvent.ARC_CONSISTENCY, watch.getElapsedTime()));
if (ac3Output.isNoSolution()) {
return SolverResult.createNonSATResult(SATResult.UNSAT, watch.getElapsedTime(), SolverResult.SolvedBy.ARC_CONSISTENCY);
} else {
log.debug("Removed {} channels", ac3Output.getNumReducedChannels());
final StationPackingInstance reducedInstance = new StationPackingInstance(ac3Output.getReducedDomains(), aInstance.getPreviousAssignment(), aInstance.getMetadata());
return SolverResult.relabelTime(fDecoratedSolver.solve(reducedInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
}
}
| 3,210
| 45.536232
| 177
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/consistency/ChannelKillerDecorator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/decorators/consistency/ChannelKillerDecorator.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.consistency;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
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.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.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.composite.DisjunctiveCompositeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 10/08/15.
* Consider a station and its neighbours only
* Fix that station to a single channel
* Assume that this reduced problem is UNSAT
* Then that channel can be soundly removed from that station's domain
*
* This class uses this idea to shrink domains by solving many of the above type of problems with short cutoffs
*/
@Slf4j
public class ChannelKillerDecorator extends ASolverDecorator {
// how long to spend on each problem
private final double subProblemCutoff;
// if true, any time a station's domain changes, we will recheck all of its neighbours
private final boolean recursive;
private final ISolver SATSolver;
private final IConstraintManager constraintManager;
public ChannelKillerDecorator(ISolver aSolver, ISolver SATSolver, IConstraintManager constraintManager, double subProblemCutoff, boolean recursive) {
super(aSolver);
this.SATSolver = SATSolver;
this.constraintManager = constraintManager;
this.subProblemCutoff = subProblemCutoff;
this.recursive = recursive;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
// Deep copy map
final Map<Station, Set<Integer>> domainsCopy = aInstance.getDomains().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new HashSet<>(entry.getValue())));
final SimpleGraph<Station, DefaultEdge> constraintGraph = ConstraintGrouper.getConstraintGraph(domainsCopy, constraintManager);
final NeighborIndex<Station, DefaultEdge> neighborIndex = new NeighborIndex<>(constraintGraph);
final LinkedHashSet<Station> stationQueue = new LinkedHashSet<>(aInstance.getStations());
int numChannelsRemoved = 0;
int numTimeouts = 0;
final Set<Station> changedStations = new HashSet<>();
while (!stationQueue.isEmpty() && !aTerminationCriterion.hasToStop()) {
final Station station = stationQueue.iterator().next();
final Set<Integer> domain = domainsCopy.get(station);
log.debug("Beginning station {} with domain {}", station, domain);
final Set<Station> neighbours = neighborIndex.neighborsOf(station);
final Map<Station, Set<Integer>> neighbourDomains = neighbours.stream().collect(Collectors.toMap(Function.identity(), domainsCopy::get));
final Set<Integer> SATChannels = new HashSet<>();
final Set<Integer> UNSATChannels = new HashSet<>();
boolean changed = false;
for (int channel : domain) {
if (SATChannels.contains(channel)) {
log.trace("Channel {} is already known to be SAT, skipping...", channel);
continue;
}
neighbourDomains.put(station, ImmutableSet.of(channel));
final StationPackingInstance reducedInstance = new StationPackingInstance(neighbourDomains);
final ITerminationCriterion subCriterion = new DisjunctiveCompositeTerminationCriterion(Arrays.asList(aTerminationCriterion, new WalltimeTerminationCriterion(subProblemCutoff)));
final SolverResult subResult = SATSolver.solve(reducedInstance, subCriterion, aSeed);
if (subResult.getResult().equals(SATResult.UNSAT)) {
log.debug("Station {} on channel {} is UNSAT with its neigbhours, removing channel!", station, channel);
UNSATChannels.add(channel);
numChannelsRemoved++;
changed = true;
changedStations.add(station);
} else if (subResult.getResult().equals(SATResult.SAT)) {
// What other channels would have also satisfied this assignment? We can skip those
SATChannels.add(channel);
final Set<Integer> unknownChannels = domain.stream().filter(c -> !SATChannels.contains(c) && !UNSATChannels.contains(c)).collect(Collectors.toSet());
final Map<Integer, Set<Station>> mutableAssignment = subResult.getAssignment().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> new HashSet<>(entry.getValue())));
mutableAssignment.get(channel).remove(station);
unknownChannels.stream().forEach(unknownChannel -> {
mutableAssignment.putIfAbsent(unknownChannel, new HashSet<>());
mutableAssignment.get(unknownChannel).add(station);
if (constraintManager.isSatisfyingAssignment(mutableAssignment)) {
log.trace("No need to check channel {} for station {} because it also a SAT to the previously checked problem", unknownChannel, station);
SATChannels.add(unknownChannel);
}
mutableAssignment.get(unknownChannel).remove(station);
if (mutableAssignment.get(unknownChannel).isEmpty()) {
mutableAssignment.remove(unknownChannel);
}
});
} else {
if (subResult.getResult().equals(SATResult.TIMEOUT)) {
numTimeouts++;
}
log.trace("Sub result was {}", subResult.getResult());
}
neighbourDomains.remove(station);
}
domain.removeAll(UNSATChannels);
log.debug("Done with station {}, now with domain {}", station, domain);
if (domain.isEmpty()) {
log.debug("Station {} has an empty domain, instance is UNSAT", station);
return SolverResult.createNonSATResult(SATResult.UNSAT, watch.getElapsedTime(), SolvedBy.CHANNEL_KILLER);
} else if (changed && recursive) {
// re-enqueue all neighbors
stationQueue.addAll(neighborIndex.neighborsOf(station));
}
stationQueue.remove(station);
}
log.debug("Removed {} channels from {} stations, had {} timeouts", numChannelsRemoved, changedStations.size(), numTimeouts);
final StationPackingInstance reducedInstance = new StationPackingInstance(domainsCopy, aInstance.getPreviousAssignment(), aInstance.getMetadata());
return SolverResult.relabelTime(fDecoratedSolver.solve(reducedInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
}
@Override
public void notifyShutdown() {
super.notifyShutdown();
SATSolver.notifyShutdown();
}
@Override
public void interrupt() {
super.interrupt();
SATSolver.interrupt();
}
}
| 9,085
| 52.763314
| 206
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResult.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 java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.python.google.common.base.Preconditions;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.collect.ImmutableMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.EqualsAndHashCode;
import lombok.Getter;
/**
* Container object for the result of a solver executed on a problem instance.
* @author afrechet
*
*/
@JsonDeserialize(using = SolverResultDeserializer.class)
@EqualsAndHashCode
public class SolverResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private SATResult fResult;
private double fRuntime;
private ImmutableMap<Integer,Set<Station>> fAssignment;
@JsonIgnore
@Getter
private final SolvedBy solvedBy;
@JsonIgnore
@Getter
private final String nickname;
public enum SolvedBy {
CLASP,
MIP,
SAT_PRESOLVER,
UNSAT_PRESOLVER,
CONNECTED_COMPONENTS,
SAT_CACHE,
UNSAT_CACHE,
ARC_CONSISTENCY,
CHANNEL_KILLER,
UNKNOWN,
UNSOLVED,
DCCA,
SATENSTEIN,
UNDERCONSTRAINED,
UNSAT_LABELLER, PREVIOUS_ASSIGNMENT
}
public SolverResult(SATResult aResult, double aRuntime, Map<Integer,Set<Station>> aAssignment, SolvedBy aSolvedBy) {
this(aResult, aRuntime, aAssignment, aSolvedBy, null);
}
/**
* @param aResult - solver result satisfiability.
* @param aRuntime - solver result runtime.
* @param aAssignment - solver result witness assignment.
*/
public SolverResult(SATResult aResult, double aRuntime, Map<Integer,Set<Station>> aAssignment, SolvedBy aSolvedBy, String nickname)
{
if(aRuntime<0 && Math.abs(aRuntime)!=0.0)
{
throw new IllegalArgumentException("Cannot create a solver result with negative runtime (runtime = "+aRuntime+").");
}
this.nickname = nickname;
fResult = aResult;
fRuntime = aRuntime;
fAssignment = ImmutableMap.copyOf(aAssignment);
solvedBy = aResult.isConclusive() ? aSolvedBy : SolvedBy.UNSOLVED;
}
/**
* @param aResult - solver result satisfiability.
* @param aRuntime - solver result runtime.
*/
public static SolverResult createNonSATResult(SATResult aResult, double aRuntime, SolvedBy aSolvedBy)
{
Preconditions.checkArgument(!aResult.equals(SATResult.SAT), "Must provide a station assignment when creating a SAT solver result.");
return new SolverResult(aResult, aRuntime, ImmutableMap.of(), aSolvedBy);
}
/**
* Create a TIMEOUT result with the given runtime.
* @param aRuntime - runtime
* @return a TIMEOUT SolverResult with the given runtime.
*/
public static SolverResult createTimeoutResult(double aRuntime)
{
return SolverResult.createNonSATResult(SATResult.TIMEOUT,aRuntime, SolvedBy.UNSOLVED);
}
public static SolverResult relabelTime(SolverResult aResult, double aTime) {
return new SolverResult(aResult.getResult(), aTime, aResult.getAssignment(), aResult.getSolvedBy());
}
public static SolverResult relabelTimeAndSolvedBy(SolverResult aResult, double aTime, SolvedBy aSolvedBy) {
return new SolverResult(aResult.getResult(), aTime, aResult.getAssignment(), aSolvedBy);
}
/**
* @return the satisfiabiltity result.
*/
public SATResult getResult(){
return fResult;
}
/**
* @return the runtime (s). This is walltime.
*/
public double getRuntime()
{
return fRuntime;
}
/**
* @return the witness assignment.
*/
public ImmutableMap<Integer,Set<Station>> getAssignment()
{
return fAssignment;
}
@Override
public String toString()
{
return fResult+","+fRuntime+","+fAssignment;//toStringAssignment(fAssignment);
}
/**
* @return a parseable string version of the result.
*/
public String toParsableString()
{
final StringBuilder aOutput = new StringBuilder();
aOutput.append(fResult.toString()).append(",").append(fRuntime).append(",");
Iterator<Integer> aChannelIterator = fAssignment.keySet().iterator();
while(aChannelIterator.hasNext())
{
Integer aChannel = aChannelIterator.next();
aOutput.append(aChannel).append("-");
Iterator<Station> aAssignedStationIterator = fAssignment.get(aChannel).iterator();
while(aAssignedStationIterator.hasNext())
{
Station aAssignedStation = aAssignedStationIterator.next();
aOutput.append(aAssignedStation.getID());
if(aAssignedStationIterator.hasNext())
{
aOutput.append("_");
}
}
if(aChannelIterator.hasNext())
{
aOutput.append(";");
}
}
return aOutput.toString();
}
@JsonIgnore
public boolean isConclusive() {
return fResult.isConclusive();
}
}
| 5,737
| 26.586538
| 134
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResultDeserializer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SolverResultDeserializer.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 ca.ubc.cs.beta.stationpacking.utils.GuavaCollectors.toImmutableMap;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
import lombok.Data;
/**
* Created by newmanne on 01/12/14.
*/
public class SolverResultDeserializer extends JsonDeserializer<SolverResult> {
@Override
public SolverResult deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final SolverResultJson solverResultJson = jsonParser.readValueAs(SolverResultJson.class);
// transform back into stations
Map<Integer,Set<Station>> assignment = solverResultJson.getAssignment().entrySet()
.stream()
.collect(toImmutableMap(
Map.Entry::getKey,
entry -> entry.getValue().stream().map(Station::new).collect(Collectors.toSet())
));
return new SolverResult(solverResultJson.getResult(), solverResultJson.getRuntime(), assignment, SolvedBy.UNKNOWN);
}
@Data
public static class SolverResultJson {
private Map<Integer, List<Integer>> assignment;
private double runtime;
private SATResult result;
}
}
| 2,520
| 37.19697
| 151
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SATResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/base/SATResult.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 java.io.Serializable;
import ca.ubc.cs.beta.aeatk.algorithmrunresult.RunStatus;
/**
* Enum for the result type of a SAT solver on a SAT instance.
* @author afrechet
*/
public enum SATResult implements Serializable{
/**
* The problem is satisfiable.
*/
SAT,
/**
* The problem is unsatisfiable.
*/
UNSAT,
/**
* A solution to the problem could not be found in the allocated time.
*/
TIMEOUT,
/**
* Run crashed while solving problem.
*/
CRASHED,
/**
* Run was killed while solving problem.
*/
KILLED,
/**
* Run was interrupted while solving problem.
*/
INTERRUPTED;
public boolean isConclusive() {
return this == SAT || this == UNSAT;
}
/**
* @param aRunResult - a runresult.
* @return the given RunStatus converted to a SATResult.
*/
public static SATResult fromRunResult(RunStatus aRunResult)
{
return SATResult.valueOf(aRunResult.toString());
}
}
| 1,872
| 24.310811
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/StationSubsetUNSATCertifier.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/StationSubsetUNSATCertifier.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 java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
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.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.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* UNSAT certifier. Checks if a given neighborhood of instances cannot be packed together.
*
* @author afrechet
*/
@Slf4j
public class StationSubsetUNSATCertifier implements IStationSubsetCertifier {
private final ISolver fSolver;
public StationSubsetUNSATCertifier(ISolver aSolver) {
fSolver = aSolver;
}
@Override
public SolverResult certify(StationPackingInstance aInstance, Set<Station> aToPackStations, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final ImmutableMap<Station, Set<Integer>> domains = aInstance.getDomains();
log.debug("Evaluating if stations not in previous assignment ({}) with their neighborhood are unpackable.", aToPackStations.size());
final Map<Station, Set<Integer>> toPackDomains = aToPackStations.stream().collect(Collectors.toMap(Function.identity(), domains::get));
final StationPackingInstance UNSATboundInstance = new StationPackingInstance(toPackDomains, aInstance.getPreviousAssignment(), aInstance.getMetadata());
final SolverResult UNSATboundResult = fSolver.solve(UNSATboundInstance, aTerminationCriterion, aSeed);
if (UNSATboundResult.getResult().equals(SATResult.UNSAT)) {
log.debug("Stations not in previous assignment cannot be packed with their neighborhood.");
return SolverResult.createNonSATResult(SATResult.UNSAT, watch.getElapsedTime(), SolvedBy.UNSAT_PRESOLVER);
} else {
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
}
@Override
public void notifyShutdown() {
fSolver.interrupt();
}
@Override
public void interrupt() throws UnsupportedOperationException {
fSolver.interrupt();
}
}
| 3,403
| 39.52381
| 160
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/IStationSubsetCertifier.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/IStationSubsetCertifier.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 java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
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;
/**
* Certifies if a station subset is packable or unpackable. Usually can only answer SAT or UNSAT cases exclusively.
* @author afrechet
*/
public interface IStationSubsetCertifier {
/**
* Certifies if a station subset is packable or unpackable.
* @param aInstance
* @param aToPackStations
* @param aTerminationCriterion
* @param aSeed
* @return
*/
public SolverResult certify(
StationPackingInstance aInstance,
Set<Station> aToPackStations,
ITerminationCriterion aTerminationCriterion,
long aSeed);
/**
* Ask the solver to shutdown.
*/
default void notifyShutdown() {};
default void interrupt() {};
}
| 1,852
| 30.40678
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/ConstraintGraphNeighborhoodPresolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/ConstraintGraphNeighborhoodPresolver.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 java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
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.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.IStationPackingConfigurationStrategy;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.StationPackingConfiguration;
import ca.ubc.cs.beta.stationpacking.solvers.componentgrouper.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ASolverDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.composite.DisjunctiveCompositeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* Pre-solve by applying a sequence of station subsets certifiers based on
* the neighborhood of stations missing from a problem instance's previous assignment.
* <p/>
* If an UNSAT result is found for the immediate local neighborhood of the missing stations, the search
* is expanded to include the neighbors' neighbors. This is iterated until any of the following conditions is met:
* <ol>
* <li>A SAT result is found</li>
* <li>The expanded neighborhood contains all the stations connected (directly or indirectly) to the original
* missing stations</li>
* <li>The search times out</li>
* </ol>
*
* @author afrechet
* @author pcernek
*/
@Slf4j
public class ConstraintGraphNeighborhoodPresolver extends ASolverDecorator {
private final IStationSubsetCertifier fCertifier;
private final IStationPackingConfigurationStrategy fStationAddingStrategy;
private final IConstraintManager constraintManager;
private final boolean dontSolveFullInstances;
/**
* @param aCertifier -the certifier to use to evaluate the satisfiability of station subsets.
* @param aStationAddingStrategy - determines which stations to fix / unfix, and how long to attempt at each expansion
*/
public ConstraintGraphNeighborhoodPresolver(ISolver decoratedSolver, IStationSubsetCertifier aCertifier, IStationPackingConfigurationStrategy aStationAddingStrategy, IConstraintManager constraintManager) {
this(decoratedSolver, aCertifier, aStationAddingStrategy, constraintManager, true);
}
ConstraintGraphNeighborhoodPresolver(ISolver decoratedSolver, IStationSubsetCertifier aCertifier, IStationPackingConfigurationStrategy aStationAddingStrategy, IConstraintManager constraintManager, boolean dontSolveFullInstances) {
super(decoratedSolver);
this.fCertifier = aCertifier;
this.fStationAddingStrategy = aStationAddingStrategy;
this.constraintManager = constraintManager;
this.dontSolveFullInstances = dontSolveFullInstances;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final Set<Station> stationsWithNoPreviousAssignment = getStationsNotInPreviousAssignment(aInstance);
if (aInstance.getPreviousAssignment().isEmpty() || stationsWithNoPreviousAssignment.isEmpty()) {
// This can happen, for example, if the new station to be packed is underconstrained and that is run first
log.debug("Could not identify a set of stations not present in the previous assignment, or else no previous assignment given. Nothing to do here...");
return fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed);
}
log.debug("There are {} stations that are not part of previous assignment.", stationsWithNoPreviousAssignment.size());
SolverResult result = null;
final SimpleGraph<Station, DefaultEdge> constraintGraph = ConstraintGrouper.getConstraintGraph(aInstance.getDomains(), constraintManager);
for (final StationPackingConfiguration configuration : fStationAddingStrategy.getConfigurations(constraintGraph, stationsWithNoPreviousAssignment)) {
if (aTerminationCriterion.hasToStop()) {
log.debug("All time spent.");
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
log.debug("Configuration is {} stations to pack, and {} seconds cutoff", configuration.getPackingStations().size(), configuration.getCutoff());
if (dontSolveFullInstances && configuration.getPackingStations().size() == aInstance.getDomains().size()) {
log.debug("The configuration is the entire problem. This should not be dealt with by a presolver. Skipping...");
continue;
}
final ITerminationCriterion criterion = new DisjunctiveCompositeTerminationCriterion(Arrays.asList(aTerminationCriterion, new WalltimeTerminationCriterion(configuration.getCutoff())));
result = fCertifier.certify(aInstance, configuration.getPackingStations(), criterion, aSeed);
if (result.getResult().isConclusive()) {
log.debug("Conclusive result from certifier");
break;
}
}
if (result == null || !result.isConclusive()) {
log.debug("Ran out of of configurations to try and no conclusive results. Passing onto next decorator...");
result = SolverResult.relabelTime(fDecoratedSolver.solve(aInstance, aTerminationCriterion, aSeed), watch.getElapsedTime());
} else {
result = SolverResult.relabelTime(result, watch.getElapsedTime());
}
log.debug("Result:" + System.lineSeparator() + result.toParsableString());
return result;
}
private Set<Station> getStationsNotInPreviousAssignment(StationPackingInstance aInstance) {
return aInstance.getStations().stream().filter(station -> !aInstance.getPreviousAssignment().containsKey(station)).collect(Collectors.toSet());
}
@Override
public void notifyShutdown() {
super.notifyShutdown();
fCertifier.notifyShutdown();
}
@Override
public void interrupt() {
super.interrupt();
fCertifier.interrupt();
}
}
| 7,551
| 48.684211
| 234
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/StationSubsetSATCertifier.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/StationSubsetSATCertifier.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 java.util.HashMap;
import java.util.Map;
import java.util.Set;
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.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 ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* SAT certifier. Pre-solver that checks whether the missing stations plus their neighborhood are packable when all other stations are fixed
* to their previous assignment values.
*
* @author afrechet
*/
@Slf4j
public class StationSubsetSATCertifier implements IStationSubsetCertifier {
private final ISolver fSolver;
public StationSubsetSATCertifier(ISolver aSolver) {
fSolver = aSolver;
}
@Override
public SolverResult certify(StationPackingInstance aInstance, Set<Station> aToPackStations, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final Map<Station, Integer> previousAssignment = aInstance.getPreviousAssignment();
/*
* Try the SAT bound, namely to see if the missing stations plus their neighborhood are packable when all other stations are fixed
* to their previous assignment values.
*/
//Change station packing instance so that the 'not to pack' stations have reduced domain.
final Map<Station, Set<Integer>> domains = aInstance.getDomains();
final Map<Station, Set<Integer>> reducedDomains = new HashMap<>();
for (final Station station : aInstance.getStations()) {
final Set<Integer> domain = domains.get(station);
if (!aToPackStations.contains(station)) {
final Integer previousChannel = previousAssignment.get(station);
if (!domain.contains(previousChannel)) {
log.warn("Station {} in previous assignment is assigned to channel {} not in current domain {} - SAT certifier is indecisive.", station, previousChannel, domain);
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
reducedDomains.put(station, Sets.newHashSet(previousChannel));
} else {
reducedDomains.put(station, domain);
}
}
log.debug("Evaluating if stations not in previous assignment with their neighborhood are packable when all other stations are fixed to previous assignment.");
final StationPackingInstance SATboundInstance = new StationPackingInstance(reducedDomains, previousAssignment);
log.debug("Going off to SAT solver...");
final SolverResult SATboundResult = fSolver.solve(SATboundInstance, aTerminationCriterion, aSeed);
log.debug("Back from SAT solver... SAT bound result was {}", SATboundResult.getResult());
final SolverResult result;
if (SATboundResult.getResult().equals(SATResult.SAT)) {
log.debug("Stations not in previous assignment can be packed with their neighborhood when all other stations are fixed to their previous assignment..");
result = SolverResult.relabelTimeAndSolvedBy(SATboundResult, watch.getElapsedTime(), SolverResult.SolvedBy.SAT_PRESOLVER);
} else {
result = SolverResult.createTimeoutResult(watch.getElapsedTime());
}
return result;
}
@Override
public void notifyShutdown() {
fSolver.notifyShutdown();
}
@Override
public void interrupt() {
fSolver.interrupt();
}
}
| 4,681
| 41.18018
| 182
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IterativeDeepeningConfigurationStrategy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IterativeDeepeningConfigurationStrategy.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 java.util.Iterator;
import java.util.Set;
import org.apache.commons.math.util.FastMath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import com.google.common.collect.AbstractIterator;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Created by newmanne on 27/07/15.
* Iterate through an IStationAddingStrategy, starting with quick cutoffs and then looping back with larger ones
*/
public class IterativeDeepeningConfigurationStrategy implements IStationPackingConfigurationStrategy {
// Strategy for adding the next set of stations to pack
private final IStationAddingStrategy stationAddingStrategy;
// Whether or not to cycle over the IStationAddingStrategy (or stop once it ends)
private final boolean loop;
private final double baseCutoff;
private final double scalingFactor;
// Create a non-iterative version
public IterativeDeepeningConfigurationStrategy(IStationAddingStrategy stationAddingStrategy, double baseCutoff) {
this(stationAddingStrategy, baseCutoff, 0);
}
public IterativeDeepeningConfigurationStrategy(IStationAddingStrategy stationAddingStrategy, double baseCutoff, double scalingFactor) {
this.stationAddingStrategy = stationAddingStrategy;
this.baseCutoff = baseCutoff;
this.scalingFactor = scalingFactor;
this.loop = scalingFactor != 0;
}
@Override
public Iterable<StationPackingConfiguration> getConfigurations(SimpleGraph<Station, DefaultEdge> graph, Set<Station> missingStations) {
final Iterable<Set<Station>> stationsToPackIterable = stationAddingStrategy.getStationsToPack(graph, missingStations);
return () -> new AbstractIterator<StationPackingConfiguration>() {
Iterator<Set<Station>> stationsToPackIterator = stationsToPackIterable.iterator();
int iteration = 0;
@Override
protected StationPackingConfiguration computeNext() {
if (!stationsToPackIterator.hasNext()) {
if (!loop) {
return endOfData();
} else {
stationsToPackIterator = stationsToPackIterable.iterator();
iteration++;
if (!stationsToPackIterator.hasNext()) { // 0 element iterator
return endOfData();
}
}
}
final Set<Station> toPack = stationsToPackIterator.next();
final double cutoff = baseCutoff + FastMath.pow(scalingFactor, iteration);
return new StationPackingConfiguration(cutoff, toPack);
}
};
}
}
| 3,627
| 40.227273
| 139
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IStationPackingConfigurationStrategy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IStationPackingConfigurationStrategy.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 java.util.Set;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Created by newmanne on 27/07/15.
*/
public interface IStationPackingConfigurationStrategy {
Iterable<StationPackingConfiguration> getConfigurations(SimpleGraph<Station, DefaultEdge> graph, Set<Station> missingStations);
}
| 1,286
| 32
| 131
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddRandomNeighboursStrategy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddRandomNeighboursStrategy.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 java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 27/07/15.
*/
@Slf4j
public class AddRandomNeighboursStrategy implements IStationAddingStrategy {
private final int numNeigbhoursToAdd;
private final Random random;
public AddRandomNeighboursStrategy(int numNeigbhoursToAdd, long seed) {
this.numNeigbhoursToAdd = numNeigbhoursToAdd;
this.random = new Random(seed);
}
public AddRandomNeighboursStrategy(int numNeigbhoursToAdd) {
this(numNeigbhoursToAdd, new Random().nextInt());
}
@Override
public Iterable<Set<Station>> getStationsToPack(SimpleGraph<Station, DefaultEdge> graph, Set<Station> missingStations) {
Preconditions.checkArgument(missingStations.size() > 0, "Cannot provide empty missing stations");
log.debug("Building constraint graph.");
final NeighborIndex<Station, DefaultEdge> neighbourIndex = new NeighborIndex<>(graph);
return () -> new RandomNeighbourIterator(missingStations, neighbourIndex);
}
private class RandomNeighbourIterator extends AbstractIterator<Set<Station>> {
private final NeighborIndex<Station, DefaultEdge> neighbourIndex;
final Set<Station> prev;
final Set<Station> remainingToAddFromPreviousLayer;
public RandomNeighbourIterator(Set<Station> missingStations, NeighborIndex<Station, DefaultEdge> neighbourIndex) {
this.remainingToAddFromPreviousLayer = new HashSet<>();
this.prev = new HashSet<>(missingStations);
this.neighbourIndex = neighbourIndex;
}
@Override
protected Set<Station> computeNext() {
// Start by seeing if there are "leftovers" that you can use
final Set<Station> toAdd = uniformlyRandomPick(remainingToAddFromPreviousLayer, numNeigbhoursToAdd);
remainingToAddFromPreviousLayer.removeAll(toAdd);
prev.addAll(toAdd);
if (toAdd.size() == numNeigbhoursToAdd) { // we found enough in the leftovers
return prev;
} else if (toAdd.size() == 0 && getNoneAddedNeighbours(prev).isEmpty()) { // we're done
return endOfData();
} else {
int remainingToAdd = numNeigbhoursToAdd - toAdd.size();
while (remainingToAdd > 0) {
// Expand a new layer, if necessary
if (remainingToAddFromPreviousLayer.isEmpty()) {
remainingToAddFromPreviousLayer.addAll(getNoneAddedNeighbours(prev));
if (remainingToAddFromPreviousLayer.isEmpty()) { // can't expand anymore
break;
}
}
final Set<Station> newToAdd = uniformlyRandomPick(remainingToAddFromPreviousLayer, remainingToAdd);
remainingToAddFromPreviousLayer.removeAll(newToAdd);
remainingToAdd -= newToAdd.size();
prev.addAll(newToAdd);
}
return prev;
}
}
private Set<Station> uniformlyRandomPick(Set<Station> choices, int num) {
final List<Station> choiceList = new ArrayList<>(choices);
Collections.shuffle(choiceList, random);
return new HashSet<>(choiceList.subList(0, Math.min(num, choiceList.size())));
}
private Set<Station> getNoneAddedNeighbours(Set<Station> stations) {
return Sets.difference(stations.stream().map(neighbourIndex::neighborsOf).flatMap(Collection::stream).collect(Collectors.toSet()), stations);
}
}
}
| 5,066
| 39.536
| 153
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddNeighbourLayerStrategy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/AddNeighbourLayerStrategy.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 java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapht.alg.NeighborIndex;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import com.google.common.base.Preconditions;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Sets;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 27/07/15.
*/
@Slf4j
public class AddNeighbourLayerStrategy implements IStationAddingStrategy {
private final int maxLayers;
public AddNeighbourLayerStrategy(int maxLayers) {
Preconditions.checkArgument(maxLayers > 0, "max layers must be > 0");
this.maxLayers = maxLayers;
}
public AddNeighbourLayerStrategy() {
this(Integer.MAX_VALUE);
}
@Override
public Iterable<Set<Station>> getStationsToPack(SimpleGraph<Station, DefaultEdge> graph, Set<Station> missingStations) {
Preconditions.checkArgument(missingStations.size() > 0, "Cannot provide empty missing stations");
final NeighborIndex<Station, DefaultEdge> neighbourIndex = new NeighborIndex<>(graph);
return () -> new NeighbourLayerIterator(missingStations, neighbourIndex);
}
private class NeighbourLayerIterator extends AbstractIterator<Set<Station>> {
int currentLayer = 1;
Set<Station> prev;
final NeighborIndex<Station, DefaultEdge> neighbourIndex;
NeighbourLayerIterator(Set<Station> missingStations, NeighborIndex<Station, DefaultEdge> neighbourIndex) {
this.prev = new HashSet<>(missingStations);
this.currentLayer = 1;
this.neighbourIndex = neighbourIndex;
}
@Override
protected Set<Station> computeNext() {
if (currentLayer > maxLayers) {
return endOfData();
}
Set<Station> newToPack = Sets.union(prev, getNeighbours(prev));
// If nothing new was added, we are done. Make sure we iterate at least once though, because the newly added station could be an island
if (prev.equals(newToPack) && currentLayer > 1) {
return endOfData();
}
currentLayer++;
prev = newToPack;
return newToPack;
}
private Set<Station> getNeighbours(Set<Station> stations) {
return stations.stream().map(neighbourIndex::neighborsOf).flatMap(Collection::stream).collect(Collectors.toSet());
}
}
}
| 3,477
| 34.85567
| 147
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/StationPackingConfiguration.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/StationPackingConfiguration.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 java.util.Set;
import ca.ubc.cs.beta.stationpacking.base.Station;
import lombok.Value;
/**
* Created by newmanne on 27/07/15.
*/
@Value
public class StationPackingConfiguration {
private final double cutoff;
private final Set<Station> packingStations;
}
| 1,171
| 30.675676
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IStationAddingStrategy.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/certifiers/cgneighborhood/strategies/IStationAddingStrategy.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 java.util.Set;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleGraph;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Created by newmanne on 27/07/15.
*/
public interface IStationAddingStrategy {
Iterable<Set<Station>> getStationsToPack(SimpleGraph<Station,DefaultEdge> graph, Set<Station> missingStations);
}
| 1,256
| 31.230769
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/CompressedSATBasedSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/CompressedSATBasedSolver.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;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATCompressor;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.AbstractCompressedSATSolver;
/**
* SAT based feasibility checking solver for SAT solvers that required compressed CNFs.
* @author afrechet
*/
public class CompressedSATBasedSolver extends GenericSATBasedSolver {
public CompressedSATBasedSolver(AbstractCompressedSATSolver aSATSolver, SATCompressor aSATCompressor)
{
super(aSATSolver,aSATCompressor);
}
}
| 1,364
| 34
| 102
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/GenericSATBasedSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/GenericSATBasedSolver.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;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.math3.util.Pair;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
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.sat.base.CNF;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.Literal;
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.SATEncoder;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.ISATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* SAT based ISolver that uses a SAT solver to solve station packing problems.
*/
@Slf4j
public class GenericSATBasedSolver implements ISolver {
private final ISATEncoder fSATEncoder;
private final ISATSolver fSATSolver;
protected GenericSATBasedSolver(ISATSolver aSATSolver, ISATEncoder aSATEncoder) {
fSATEncoder = aSATEncoder;
fSATSolver = aSATSolver;
}
@Override
public SolverResult solve(StationPackingInstance aInstance, ITerminationCriterion aTerminationCriterion, long aSeed) {
Watch watch = Watch.constructAutoStartWatch();
log.debug("Solving instance of {}...", aInstance.getInfo());
log.debug("Encoding subproblem in CNF...");
SATEncoder.CNFEncodedProblem aEncoding = fSATEncoder.encodeWithAssignment(aInstance);
CNF aCNF = aEncoding.getCnf();
ISATDecoder aDecoder = aEncoding.getDecoder();
log.debug("CNF has {} clauses.", aCNF.size());
if (aTerminationCriterion.hasToStop()) {
log.debug("All time spent.");
return SolverResult.createTimeoutResult(watch.getElapsedTime());
}
else
{
log.debug("Solving the subproblem CNF with " + aTerminationCriterion.getRemainingTime() + " s remaining.");
SATSolverResult satSolverResult = fSATSolver.solve(aCNF, aEncoding.getInitialAssignment(), aTerminationCriterion, aSeed);
// Even if the SAT solver was interrupted, this would be due to the fact that SATFC timed out. So to avoid confusion in output results, we make this change
if (satSolverResult.getResult().equals(SATResult.INTERRUPTED)) {
satSolverResult = new SATSolverResult(SATResult.TIMEOUT, satSolverResult.getRuntime(), satSolverResult.getAssignment(), satSolverResult.getSolvedBy(), satSolverResult.getNickname());
}
log.debug("Parsing result.");
Map<Integer, Set<Station>> aStationAssignment = new HashMap<Integer, Set<Station>>();
final Set<Station> assignedStations = new HashSet<>();
if (satSolverResult.getResult().equals(SATResult.SAT)) {
HashMap<Long, Boolean> aLitteralChecker = new HashMap<Long, Boolean>();
for (Literal aLiteral : satSolverResult.getAssignment()) {
boolean aSign = aLiteral.getSign();
long aVariable = aLiteral.getVariable();
//Do some quick verifications of the assignment.
if (aLitteralChecker.containsKey(aVariable)) {
log.warn("A variable was present twice in a SAT assignment.");
if (!aLitteralChecker.get(aVariable).equals(aSign)) {
throw new IllegalStateException("SAT assignment from TAE wrapper assigns a variable to true AND false.");
}
} else {
aLitteralChecker.put(aVariable, aSign);
}
//If the litteral is positive, then we keep it as it is an assigned station to a channel.
if (aSign) {
Pair<Station, Integer> aStationChannelPair = aDecoder.decode(aVariable);
Station aStation = aStationChannelPair.getKey();
if (assignedStations.contains(aStation)) {
continue;
}
Integer aChannel = aStationChannelPair.getValue();
if (!aInstance.getStations().contains(aStation) || !aInstance.getDomains().get(aStation).contains(aChannel)) {
throw new IllegalStateException("A decoded station and channel from a component SAT assignment is not in that component's problem instance. (" + aStation + ", channel:" + aChannel + ")");
}
if (!aStationAssignment.containsKey(aChannel)) {
aStationAssignment.put(aChannel, new HashSet<Station>());
}
aStationAssignment.get(aChannel).add(aStation);
assignedStations.add(aStation);
}
}
}
log.debug("...done.");
log.debug("Cleaning up...");
final SolverResult solverResult = new SolverResult(satSolverResult.getResult(), watch.getElapsedTime(), aStationAssignment, satSolverResult.getSolvedBy(), satSolverResult.getNickname());
log.debug("Result:");
log.debug(solverResult.toParsableString());
return solverResult;
}
}
@Override
public void interrupt() {
fSATSolver.interrupt();
}
@Override
public void notifyShutdown() {
fSATSolver.notifyShutdown();
}
}
| 6,848
| 44.66
| 215
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.