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/solvers/sat/cnfencoder/SATCompressor.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/SATCompressor.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.cnfencoder;
import org.apache.commons.math3.util.Pair;
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.sat.base.CNF;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.base.CompressionBijection;
/**
* Encodes a problem instance as a propositional satisfiability problem.
* Insures that the SAT variables are contiguous from 1 to n.
* A variable of the SAT encoding is a station channel pair, each constraint is trivially
* encoded as a clause (this station cannot be on this channel when this other station is on this other channel is a two clause with the previous
* SAT variables), and base clauses are added (each station much be on exactly one channel).
*
* @author afrechet
*/
public class SATCompressor implements ISATEncoder {
private final IConstraintManager fConstraintManager;
private EncodingType encodingType;
public SATCompressor(IConstraintManager aConstraintManager, EncodingType encodingType) {
fConstraintManager = aConstraintManager;
this.encodingType = encodingType;
}
@Override
public Pair<CNF, ISATDecoder> encode(StationPackingInstance aInstance) {
SATEncoder aSATEncoder = new SATEncoder(fConstraintManager, new CompressionBijection<>(), encodingType);
return aSATEncoder.encode(aInstance);
}
@Override
public SATEncoder.CNFEncodedProblem encodeWithAssignment(StationPackingInstance aInstance) {
SATEncoder aSATEncoder = new SATEncoder(fConstraintManager, new CompressionBijection<>(), encodingType);
return aSATEncoder.encodeWithAssignment(aInstance);
}
}
| 2,693
| 41.09375
| 145
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/ISATEncoder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/ISATEncoder.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.cnfencoder;
import org.apache.commons.math3.util.Pair;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF;
/**
* Encodes a problem instance as a propositional satisfiability problem.
* @author afrechet
*/
public interface ISATEncoder {
/**
* Encodes a station packing problem instances to a SAT CNF formula.
*
* @param aInstance - an instance to encode as a SAT problem.
* @return a SAT CNF representation of the problem instance.
*/
public Pair<CNF,ISATDecoder> encode(StationPackingInstance aInstance);
/**
*
* @param aInstance
* @return
*/
public SATEncoder.CNFEncodedProblem encodeWithAssignment(StationPackingInstance aInstance);
}
| 1,613
| 29.45283
| 92
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/ISATDecoder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/ISATDecoder.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.cnfencoder;
import org.apache.commons.math3.util.Pair;
import ca.ubc.cs.beta.stationpacking.base.Station;
/**
* Decodes variables to their station/channel equivalents.
* @author afrechet
*
*/
public interface ISATDecoder {
/**
* @param aVariable - a SAT variable.
* @return - the station and channel encoded by the given SAT variable.
*/
public Pair<Station,Integer> decode(long aVariable);
}
| 1,277
| 29.428571
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/SATEncoderUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/SATEncoderUtils.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.cnfencoder;
import org.apache.commons.math3.util.Pair;
public class SATEncoderUtils {
/*
* Szudzik's elegant pairing function (http://szudzik.com/ElegantPairing.pdf)
* that acts as a bijection between our station channel pairs and the SAT variables.
*/
/**
* Szudzik's <a href="http://szudzik.com/ElegantPairing.pdf">elegant pairing function</a>.
* @param x - an integer.
* @param y - an integer.
* @return a bijective mapping of (x,y) to a (long) integer z.
*/
public static long SzudzikElegantPairing(Integer x, Integer y)
{
long X = (long) x;
long Y = (long) y;
long Z;
if(X<Y)
{
Z= Y*Y+X;
}
else
{
Z = X*X+X+Y;
}
return Z;
}
/**
* Inverse of Szudzik's elegant pairing function.
* @param z - an integer.
* @return the bijective (inverse) mapping of z to a pair of integers (x,y).
*/
public static Pair<Integer,Integer> SzudzikElegantInversePairing(long z)
{
long a = (long) (z-Math.pow(Math.floor(Math.sqrt(z)),2));
long b =(long) Math.floor(Math.sqrt(z));
if(a<b)
{
if(a>Integer.MAX_VALUE || a<Integer.MIN_VALUE || b > Integer.MAX_VALUE || b<Integer.MIN_VALUE)
{
throw new IllegalArgumentException("Cannot unpair "+z+" to integer pairing components.");
}
return new Pair<Integer,Integer>((int)a,(int)b);
}
else
{
if(b>Integer.MAX_VALUE || b<Integer.MIN_VALUE || (a-b) > Integer.MAX_VALUE || (a-b)<Integer.MIN_VALUE)
{
throw new IllegalArgumentException("Cannot unpair "+z+" to integer pairing components.");
}
return new Pair<Integer,Integer>((int)b,(int)(a-b));
}
}
}
| 2,471
| 27.413793
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/SATEncoder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/SATEncoder.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.cnfencoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.datamanagers.constraints.IConstraintManager;
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.base.Clause;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.Literal;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.base.IBijection;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* Encodes a problem instance as a propositional satisfiability problem.
* A variable of the SAT encoding is a station channel pair, each constraint is trivially
* encoded as a clause (this station cannot be on this channel when this other station is on this other channel is a two clause with the previous
* SAT variables), and base clauses are added (each station much be on exactly one channel).
*
* @author afrechet
*/
@Slf4j
public class SATEncoder implements ISATEncoder {
private final IConstraintManager constraintManager;
private final IBijection<Long, Long> bijection;
private final EncodingType encodingType;
public SATEncoder(IConstraintManager constraintManager, IBijection<Long, Long> bijection, EncodingType encodingType) {
this.constraintManager = constraintManager;
this.bijection = bijection;
this.encodingType = encodingType;
}
@Override
public CNFEncodedProblem encodeWithAssignment(StationPackingInstance aInstance) {
Pair<CNF, ISATDecoder> enconding = encode(aInstance);
/**
* Generate the starting values of the variables based on the prevoius assignment information: if a station was
* assigned to a channel, then the corresponding variable is set to true. Otherwise, false. This might not result
* in a file with a value for every variable. Presumably whoever uses this can do something sensible with the rest,
* typically random assignment.
*/
final Map<Long, Boolean> initialAssignment = new LinkedHashMap<>();
aInstance.getDomains().entrySet().forEach(entry -> {
final Station station = entry.getKey();
if (aInstance.getPreviousAssignment().containsKey(station)) {
final Set<Integer> domain = entry.getValue();
domain.forEach(channel -> {
long varId = bijection.map(SATEncoderUtils.SzudzikElegantPairing(station.getID(), channel));
boolean startingValue = aInstance.getPreviousAssignment().get(station).equals(channel);
initialAssignment.put(varId, startingValue);
});
}
});
return new CNFEncodedProblem(enconding.getFirst(), enconding.getSecond(), initialAssignment);
}
@Data
public static class CNFEncodedProblem {
private final CNF cnf;
private final ISATDecoder decoder;
private final Map<Long, Boolean> initialAssignment;
}
@Override
public Pair<CNF, ISATDecoder> encode(StationPackingInstance aInstance) {
CNF aCNF = new CNF();
//Encode base clauses,
aCNF.addAll(encodeBaseClauses(aInstance));
//Encode co-channel and adj-channel constraints
aCNF.addAll(encodeInterferenceConstraints(aInstance));
//Save station map.
final Map<Integer, Station> stationMap = new HashMap<>();
for (Station station : aInstance.getStations()) {
stationMap.put(station.getID(), station);
}
//Create the decoder
ISATDecoder aDecoder = new ISATDecoder() {
@Override
public Pair<Station, Integer> decode(long aVariable) {
//Decode the long variable to station channel pair.
Pair<Integer, Integer> aStationChannelPair = SATEncoderUtils.SzudzikElegantInversePairing(bijection.inversemap(aVariable));
//Get station.
Integer stationID = aStationChannelPair.getKey();
Station aStation = stationMap.get(stationID);
//Get channel
Integer aChannel = aStationChannelPair.getValue();
return new Pair<>(aStation, aChannel);
}
};
return new Pair<CNF, ISATDecoder>(aCNF, aDecoder);
}
/**
* Get the base SAT clauses of a station packing instances. The base clauses encode the following two constraints:
* <ol>
* <li> Every station must be on at least one channel in the intersection of its domain and the problem instance's channels. </li>
* <li> Every station must be on at most one channel in the intersection of its domain and the problem instance's channels. </li>
* <ol>
*
* @param aInstance - a station packing problem instance.
* @return A CNF of base clauses.
*/
public CNF encodeBaseClauses(StationPackingInstance aInstance) {
CNF aCNF = new CNF();
Set<Station> aInstanceStations = aInstance.getStations();
Map<Station, Set<Integer>> aInstanceDomains = aInstance.getDomains();
//Each station has its own base clauses.
for (Station aStation : aInstanceStations) {
ArrayList<Integer> aStationInstanceDomain = new ArrayList<Integer>(aInstanceDomains.get(aStation));
//A station must be on at least one channel,
Clause aStationValidAssignmentBaseClause = new Clause();
for (Integer aChannel : aStationInstanceDomain) {
aStationValidAssignmentBaseClause.add(new Literal(bijection.map(SATEncoderUtils.SzudzikElegantPairing(aStation.getID(), aChannel)), true));
}
aCNF.add(aStationValidAssignmentBaseClause);
if (encodingType.equals(EncodingType.DIRECT)) {
//A station can be on at most one channel,
for (int i = 0; i < aStationInstanceDomain.size(); i++) {
for (int j = i + 1; j < aStationInstanceDomain.size(); j++) {
Clause aStationSingleAssignmentBaseClause = new Clause();
Integer aDomainChannel1 = aStationInstanceDomain.get(i);
aStationSingleAssignmentBaseClause.add(new Literal(bijection.map(SATEncoderUtils.SzudzikElegantPairing(aStation.getID(), aDomainChannel1)), false));
Integer aDomainChannel2 = aStationInstanceDomain.get(j);
aStationSingleAssignmentBaseClause.add(new Literal(bijection.map(SATEncoderUtils.SzudzikElegantPairing(aStation.getID(), aDomainChannel2)), false));
aCNF.add(aStationSingleAssignmentBaseClause);
}
}
}
}
return aCNF;
}
private CNF encodeInterferenceConstraints(StationPackingInstance aInstance) {
final CNF cnf = new CNF();
constraintManager.getAllRelevantConstraints(aInstance.getDomains()).forEach(constraint -> {
final Clause clause = new Clause();
clause.add(new Literal(bijection.map(SATEncoderUtils.SzudzikElegantPairing(constraint.getSource().getID(), constraint.getSourceChannel())), false));
clause.add(new Literal(bijection.map(SATEncoderUtils.SzudzikElegantPairing(constraint.getTarget().getID(), constraint.getTargetChannel())), false));
cnf.add(clause);
});
return cnf;
}
}
| 8,590
| 42.170854
| 172
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/IBijection.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/IBijection.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.cnfencoder.base;
/**
* Interface for a bijective function.
* @author afrechet
*/
public interface IBijection<X,Y> {
public Y map(X aDomainElement);
public X inversemap(Y aImageElement);
}
| 1,066
| 28.638889
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/IdentityBijection.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/IdentityBijection.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.cnfencoder.base;
/**
* The identity function.
* @author afrechet
* @param <X> - function arguments type.
*/
public class IdentityBijection<X> implements IBijection<X, X>{
@Override
public X map(X aDomainElement) {
return aDomainElement;
}
@Override
public X inversemap(X aImageElement) {
return aImageElement;
}
}
| 1,197
| 28.219512
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/CompressionBijection.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/cnfencoder/base/CompressionBijection.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.cnfencoder.base;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* Compression bijection that maps any number to [n] where n is the number of values seen so far.
* @author afrechet
* @param <X> - domain of bijection.
*/
public class CompressionBijection<X extends Number> implements IBijection<X, Long> {
private final HashBiMap<X,Long> fCompressionMap;
private long fCompressionMapMax = 1;
public CompressionBijection()
{
fCompressionMap = HashBiMap.create();
}
@Override
public Long map(X aDomainElement) {
if(!fCompressionMap.containsKey(aDomainElement))
{
fCompressionMap.put(aDomainElement, fCompressionMapMax);
return fCompressionMapMax++;
}
else
{
return fCompressionMap.get(aDomainElement);
}
}
@Override
public X inversemap(Long aImageElement) {
BiMap<Long,X> aInverseCompressionMap = fCompressionMap.inverse();
if(aInverseCompressionMap.containsKey(aImageElement))
{
return aInverseCompressionMap.get(aImageElement);
}
else
{
throw new IllegalArgumentException("Compression map does not contain an domain element for "+aImageElement);
}
}
}
| 2,034
| 26.5
| 111
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/AbstractCompressedSATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/AbstractCompressedSATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers;
/**
* Marker class to show that the SAT solver required a compressed CNF.
*/
public abstract class AbstractCompressedSATSolver implements ISATSolver {
}
| 1,031
| 33.4
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/AbstractSATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/AbstractSATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers;
/**
* Marker class for a SAT solver that does not require any type of particular CNFs.
*/
public abstract class AbstractSATSolver implements ISATSolver{
}
| 1,033
| 33.466667
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/ISATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/ISATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers;
import java.util.Map;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ISATFCInterruptible;
import ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Interface for a SAT solver.
* @author afrechet
*/
public interface ISATSolver extends ISATFCInterruptible {
/**
* @param aCNF - a CNF to solve.
* @param aTerminationCriterion - the criterion dictating when to stop execution of solver.
* @param aSeed - the seed for the execution.
*/
SATSolverResult solve(CNF aCNF, ITerminationCriterion aTerminationCriterion, long aSeed);
default SATSolverResult solve(CNF aCNF, Map<Long, Boolean> aPreviousAssignment, ITerminationCriterion aTerminationCriterion, long aSeed) {
return solve(aCNF, aTerminationCriterion, aSeed);
}
void notifyShutdown();
default void interrupt() {};
}
| 1,843
| 33.792453
| 139
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/TAESATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/TAESATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import ca.ubc.cs.beta.aeatk.algorithmexecutionconfiguration.AlgorithmExecutionConfiguration;
import ca.ubc.cs.beta.aeatk.algorithmrunconfiguration.AlgorithmRunConfiguration;
import ca.ubc.cs.beta.aeatk.algorithmrunresult.AlgorithmRunResult;
import ca.ubc.cs.beta.aeatk.parameterconfigurationspace.ParameterConfiguration;
import ca.ubc.cs.beta.aeatk.probleminstance.ProblemInstance;
import ca.ubc.cs.beta.aeatk.probleminstance.ProblemInstanceSeedPair;
import ca.ubc.cs.beta.aeatk.targetalgorithmevaluator.TargetAlgorithmEvaluator;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
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.solvers.AbstractCompressedSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Lean TAE based SAT solver.
* @author afrechet
*/
public class TAESATSolver extends AbstractCompressedSATSolver{
private final TargetAlgorithmEvaluator fTAE;
private final AlgorithmExecutionConfiguration fExecConfig;
private final ParameterConfiguration fParamConfiguration;
private final String fCNFDir;
/**
* Builds a TAE based SAT solver.
* @param aTargetAlgorithmEvaluator - target algorithm evaluator to use.
* @param aExecutionConfig - the execution config for the SAT solver we want to execute.
* @param aParamConfig - the parameter configuration for the SAT solver we want to execute.
* @param aCNFDir - a CNF directory in which to execute.
*/
public TAESATSolver(TargetAlgorithmEvaluator aTargetAlgorithmEvaluator,
ParameterConfiguration aParamConfig,
AlgorithmExecutionConfiguration aExecConfig,
String aCNFDir)
{
fTAE = aTargetAlgorithmEvaluator;
fExecConfig = aExecConfig;
fParamConfiguration = aParamConfig;
fCNFDir = aCNFDir;
}
@Override
public SATSolverResult solve(CNF aCNF, ITerminationCriterion aTerminationCriterion, long aSeed) {
//Setup the CNF file and filename.
String aCNFFilename = fCNFDir + File.separator + RandomStringUtils.randomAlphabetic(15)+".cnf";
File aCNFFile = new File(aCNFFilename);
while(aCNFFile.exists())
{
aCNFFilename = fCNFDir + File.separator + RandomStringUtils.randomAlphabetic(15)+".cnf";
aCNFFile = new File(aCNFFilename);
}
String aCNFString = aCNF.toDIMACS(new String[]{"FCC Station packing instance."});
//Write the CNF to disk.
try
{
FileUtils.writeStringToFile(aCNFFile, aCNFString);
}
catch (IOException e)
{
throw new IllegalStateException("Could not write CNF to file ("+e.getMessage()+").");
}
//Create the run config.
ProblemInstance aProblemInstance = new ProblemInstance(aCNFFilename);
ProblemInstanceSeedPair aProblemInstanceSeedPair = new ProblemInstanceSeedPair(aProblemInstance,aSeed);
AlgorithmRunConfiguration aRunConfig = new AlgorithmRunConfiguration(aProblemInstanceSeedPair, aTerminationCriterion.getRemainingTime(), fParamConfiguration,fExecConfig);
//Execute it.
List<AlgorithmRunResult> aRuns = fTAE.evaluateRun(aRunConfig);
if(aRuns.size()!=1)
{
throw new IllegalStateException("Got multiple runs back from the TAE when solving a single CNF.");
}
AlgorithmRunResult aRun = aRuns.iterator().next();
double aRuntime = aRun.getRuntime();
SATResult aResult;
HashSet<Literal> aAssignment = new HashSet<Literal>();
//Post process the result from the TAE.
switch (aRun.getRunStatus()){
case KILLED:
aResult = SATResult.KILLED;
break;
case SAT:
aResult = SATResult.SAT;
//Grab assignment
String aAdditionalRunData = aRun.getAdditionalRunData();
//The TAE wrapper is assumed to return a ';'-separated string of literals, one literal for each variable of the SAT problem.
for(String aLiteral : aAdditionalRunData.split(";"))
{
boolean aSign = !aLiteral.contains("-");
long aVariable = Long.valueOf(aLiteral.replace("-", ""));
aAssignment.add(new Literal(aVariable,aSign));
}
break;
case UNSAT:
aResult = SATResult.UNSAT;
break;
case TIMEOUT:
aResult = SATResult.TIMEOUT;
break;
default:
aResult = SATResult.CRASHED;
throw new IllegalStateException("Run "+aRun+" crashed!");
}
//Clean up
aCNFFile.delete();
return new SATSolverResult(aResult,aRuntime,aAssignment, SolvedBy.UNKNOWN);
}
@Override
public void notifyShutdown() {
fTAE.notifyShutdown();
}
}
| 5,723
| 33.902439
| 172
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/Clasp3SATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/Clasp3SATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import java.util.HashSet;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.base.Preconditions;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.ProblemIncrementor;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
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.solvers.AbstractCompressedSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.Clasp3Library;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.NativeUtils;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Clasp3SATSolver extends AbstractCompressedSATSolver {
private Clasp3Library fClaspLibrary;
private String fParameters;
private final Lock lock = new ReentrantLock();
private Pointer currentProblemPointer;
// boolean represents whether or not a solve is in progress, so that it is safe to do an interrupt
private final AtomicBoolean isCurrentlySolving = new AtomicBoolean(false);
private final int fSeedOffset;
private final ProblemIncrementor problemIncrementor;
private String nickname;
public Clasp3SATSolver(String libraryPath, String parameters, IPollingService service) {
this((Clasp3Library) Native.loadLibrary(libraryPath, Clasp3Library.class, NativeUtils.NATIVE_OPTIONS), parameters, service);
}
public Clasp3SATSolver(Clasp3Library library, String parameters, IPollingService service) {
this(library, parameters, 0, service, null);
}
public Clasp3SATSolver(Clasp3Library library, String parameters, int seedOffset, IPollingService pollingService, String nickname) {
this.nickname = nickname;
log.debug("Initializing clasp with params {}", parameters);
fSeedOffset = seedOffset;
fClaspLibrary = library;
fParameters = parameters;
// set the info about parameters, throw an exception if seed is contained.
if (parameters.contains("--seed")) {
throw new IllegalArgumentException("The parameter string cannot contain a seed as it is given upon a call to solve!");
}
// make sure the configuration is valid
String params = fParameters + " --seed=1";
Pointer jnaProblem = fClaspLibrary.initConfig(params);
try {
int status = fClaspLibrary.getConfigState(jnaProblem);
if (status == 2) {
throw new IllegalArgumentException(fClaspLibrary.getConfigErrorMessage(jnaProblem));
}
} finally {
fClaspLibrary.destroyProblem(jnaProblem);
}
problemIncrementor = new ProblemIncrementor(pollingService, this);
}
/*
* (non-Javadoc)
* NOT THREAD SAFE!
* @see ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.ISATSolver#solve(ca.ubc.cs.beta.stationpacking.solvers.sat.base.CNF, double, long)
*/
@Override
public SATSolverResult solve(CNF aCNF, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final int seed = Math.abs(new Random(aSeed + fSeedOffset).nextInt());
final String params = fParameters + " --seed=" + seed;
try {
// create the problem - config params have already been validated in the constructor, so this should work
Preconditions.checkState(currentProblemPointer == null, "Went to solve a new problem, but there is a problem in progress!");
if (aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
problemIncrementor.scheduleTermination(aTerminationCriterion);
currentProblemPointer = fClaspLibrary.initConfig(params);
fClaspLibrary.initProblem(currentProblemPointer, aCNF.toDIMACS(null));
if (aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
// We lock this variable so that the interrupt code will only execute if there is a valid problem to interrupt
lock.lock();
isCurrentlySolving.set(true);
lock.unlock();
final double cutoff = aTerminationCriterion.getRemainingTime();
if (cutoff <= 0 || aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
// Start solving
log.debug("Send problem to clasp cutting off after {}s", cutoff);
final Watch runtime = Watch.constructAutoStartWatch();
fClaspLibrary.solveProblem(currentProblemPointer, cutoff);
double runtimeDouble = runtime.getElapsedTime();
log.debug("Came back from clasp after {}s. (initial cutoff was {}s)", runtimeDouble, cutoff);
if (!(runtimeDouble < cutoff + 5)) {
log.warn("Runtime {} greatly exceeded cutoff {}!", runtimeDouble, cutoff);
}
lock.lock();
isCurrentlySolving.set(false);
lock.unlock();
if (aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
final Watch postTime = Watch.constructAutoStartWatch();
final ClaspResult claspResult = getSolverResult(fClaspLibrary, currentProblemPointer, runtime.getElapsedTime());
log.trace("Time to parse clasp result: {} s.", postTime.getElapsedTime());
final HashSet<Literal> assignment = parseAssignment(claspResult.getAssignment());
log.trace("Total post time (parsing result + assignment): {} s.", postTime.getElapsedTime());
if (postTime.getElapsedTime() > 60) {
log.error("Clasp SAT solver post solving time was greater than 1 minute, something wrong must have happened.");
}
final SATSolverResult output = new SATSolverResult(claspResult.getSATResult(), watch.getElapsedTime(), assignment, SolvedBy.CLASP, nickname);
log.debug("Returning result: {}, {}s.", output.getResult(), output.getRuntime());
log.trace("Full result: {}", output);
return output;
} finally {
problemIncrementor.jobDone();
// Cleanup in the finally block so it always executes: if we instantiated a problem, we make sure that we free it
if (currentProblemPointer != null) {
log.trace("Destroying problem");
lock.lock();
isCurrentlySolving.set(false);
lock.unlock();
fClaspLibrary.destroyProblem(currentProblemPointer);
currentProblemPointer = null;
}
}
}
@Override
public void notifyShutdown() {
}
@Override
public void interrupt() {
lock.lock();
if (isCurrentlySolving.get()) {
log.debug("Interrupting clasp");
fClaspLibrary.interrupt(currentProblemPointer);
log.debug("Back from interrupting clasp");
}
lock.unlock();
}
private HashSet<Literal> parseAssignment(int[] assignment) {
HashSet<Literal> set = new HashSet<>();
for (int i = 1; i < assignment[0]; i++) {
int intLit = assignment[i];
int var = Math.abs(intLit);
boolean sign = intLit > 0;
Literal aLit = new Literal(var, sign);
set.add(aLit);
}
return set;
}
/**
* Extract solver result from JNA Clasp library.
*/
public static ClaspResult getSolverResult(Clasp3Library library,
Pointer problem,
double runtime) {
final SATResult satResult;
int[] assignment = {0};
int state = library.getResultState(problem);
if (state == 0) {
satResult = SATResult.UNSAT;
} else if (state == 1) {
satResult = SATResult.SAT;
IntByReference pRef = library.getResultAssignment(problem);
int size = pRef.getValue();
assignment = pRef.getPointer().getIntArray(0, size);
} else if (state == 2) {
satResult = SATResult.TIMEOUT;
} else if (state == 3) {
satResult = SATResult.INTERRUPTED;
} else {
satResult = SATResult.CRASHED;
log.error("Clasp crashed!");
}
return new ClaspResult(satResult, assignment, runtime);
}
}
| 10,072
| 42.795652
| 153
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/ClaspResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/ClaspResult.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental;
import com.google.common.base.Preconditions;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
/**
* Clasp library result.
* @author gsauln
*/
public class ClaspResult {
private final SATResult fSATResult;
private final int[] fAssignment;
private final double fRuntime;
public ClaspResult(SATResult satResult, int[] assignment, double runtime)
{
Preconditions.checkState(runtime >= 0, "Runtime must be >= 0 (was " + runtime + " )");
fSATResult = satResult;
fAssignment = assignment;
fRuntime = runtime;
}
public SATResult getSATResult() {
return fSATResult;
}
public int[] getAssignment() {
return fAssignment;
}
public double getRuntime() {
return fRuntime;
}
}
| 1,612
| 26.338983
| 94
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/ubcsat/UBCSATSolver.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/nonincremental/ubcsat/UBCSATSolver.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.ubcsat;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import com.google.common.base.Preconditions;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.ProblemIncrementor;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult.SolvedBy;
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.solvers.AbstractCompressedSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base.SATSolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.UBCSATLibrary;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.NativeUtils;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.extern.slf4j.Slf4j;
/**
* The solver that runs different configurations of UBCSAT, including SATenstein.
*
* Created by pcernek on 7/28/15.
*/
@Slf4j
public class UBCSATSolver extends AbstractCompressedSATSolver {
private UBCSATLibrary fLibrary;
private final int seedOffset;
private final String fParameters;
private Pointer fState;
private final Lock lock = new ReentrantLock();
// boolean represents whether or not a solve is in progress, so that it is safe to do an interrupt
private final AtomicBoolean isCurrentlySolving = new AtomicBoolean(false);
private final ProblemIncrementor problemIncrementor;
private final String nickname;
public UBCSATSolver(String libraryPath, String parameters, IPollingService pollingService) {
this((UBCSATLibrary) Native.loadLibrary(libraryPath, UBCSATLibrary.class, NativeUtils.NATIVE_OPTIONS), parameters, 0, pollingService, null);
}
/**
* @param library - the UBCSATLibrary object that will be used to make the calls over JNA.
* @param parameters - a well-formed string of UBCSAT parameters. This constructor checks a couple basic things:
* 1) that the parameter string contains the -alg flag.
* 2) that the parameter string does not contain the -seed flag. (This is passed explicitly in {@link UBCSATSolver#solve(CNF, ITerminationCriterion, long)}.
* 3) if the -cutoff flag is not present, this constructor appends "-cutoff max" to the parameter string, which
* means that the algorithm will run for as long as possible until the time limit specified in {@link UBCSATSolver#solve(CNF, ITerminationCriterion, long)} is reached.
*
* Other than this, all parameter checking happens in UBCSAT native code, so if an illegal parameter string
* is passed, it will crash the JVM.
*
* Please consult the documentation for UBCSAT and for SATenstein for information regarding legal parameter
* strings. Alternatively, a simple way to test the legality of a parameter string is to run UBCSAT from
* the command line with that parameter string and specifying a sample .cnf file via the "-inst" flag.
*/
public UBCSATSolver(UBCSATLibrary library, String parameters, int seedOffset, IPollingService pollingService, String nickname) {
this.nickname = nickname;
fLibrary = library;
this.seedOffset = seedOffset;
log.debug("Using config {} for UBCSAT", parameters);
String mutableParameters = parameters;
if (mutableParameters.contains("-seed ")) {
throw new IllegalArgumentException("The parameter string cannot contain a seed as it is given upon a call to solve!" + System.lineSeparator() + mutableParameters);
}
if (!mutableParameters.contains("-alg ")) {
throw new IllegalArgumentException("Missing required UBCSAT parameter: -alg." + System.lineSeparator() + mutableParameters);
}
if (!mutableParameters.contains("-cutoff ")) {
mutableParameters = mutableParameters + " -cutoff max";
}
String testParameters = mutableParameters + " -seed 1";
Pointer jnaProblem = fLibrary.initConfig(testParameters);
fLibrary.destroyProblem(jnaProblem);
fParameters = mutableParameters;
problemIncrementor = new ProblemIncrementor(pollingService, this);
}
@Override
public SATSolverResult solve(CNF aCNF, ITerminationCriterion aTerminationCriterion, long aSeed) {
return solve(aCNF, null, aTerminationCriterion, aSeed);
}
@Override
public SATSolverResult solve(CNF aCNF, Map<Long, Boolean> aPreviousAssignment, ITerminationCriterion aTerminationCriterion, long aSeed) {
final Watch watch = Watch.constructAutoStartWatch();
final int seed = Math.abs(new Random(aSeed + seedOffset).nextInt());
final String seededParameters = fParameters + " -seed " + seed;
final double preTime;
final double runTime;
try {
Preconditions.checkState(fState == null, "Went to solve a new problem, but there is a problem in progress!");
boolean status;
if (aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
problemIncrementor.scheduleTermination(aTerminationCriterion);
fState = fLibrary.initConfig(seededParameters);
if (aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
status = fLibrary.initProblem(fState, aCNF.toDIMACS(null));
// We lock this variable so that the interrupt code will only execute if there is a valid problem to interrupt
lock.lock();
isCurrentlySolving.set(true);
lock.unlock();
checkStatus(status, fLibrary, fState);
if (aPreviousAssignment != null) {
setPreviousAssignment(aPreviousAssignment);
}
preTime = watch.getElapsedTime();
log.debug("PreTime: {}", preTime);
final double cutoff = aTerminationCriterion.getRemainingTime();
if (cutoff <= 0 || aTerminationCriterion.hasToStop()) {
return SATSolverResult.timeout(watch.getElapsedTime());
}
// Start solving
log.debug("Sending problem to UBCSAT with cutoff time of {} s", cutoff);
status = fLibrary.solveProblem(fState, cutoff);
log.trace("Back from solving problem. Acquiring lock");
lock.lock();
isCurrentlySolving.set(false);
lock.unlock();
log.trace("Checking status");
checkStatus(status, fLibrary, fState);
runTime = watch.getElapsedTime() - preTime;
log.debug("Came back from UBCSAT after {}s (initial cutoff was {} s).", runTime, cutoff);
if (!(runTime < cutoff + 5)) {
log.warn("Runtime {} greatly exceeded cutoff {}!", runTime, cutoff);
}
return getSolverResult(fLibrary, fState, runTime);
} finally {
problemIncrementor.jobDone();
// Cleanup in the finally block so it always executes: if we instantiated a problem, we make sure that we free it
if (fState != null) {
log.debug("Destroying problem");
lock.lock();
isCurrentlySolving.set(false);
lock.unlock();
fLibrary.destroyProblem(fState);
fState = null;
}
log.debug("Total solver time: {}", watch.getElapsedTime());
}
}
private void checkStatus(boolean status, UBCSATLibrary library, Pointer state) {
Preconditions.checkState(status, library.getErrorMessage(state));
}
private SATSolverResult getSolverResult(UBCSATLibrary fLibrary, Pointer fState, double runtime) {
final SATResult satResult;
int resultState = fLibrary.getResultState(fState);
HashSet<Literal> assignment = null;
if (resultState == 1) {
satResult = SATResult.SAT;
assignment = getAssignment(fLibrary, fState);
}
else if (resultState == 2) {
satResult = SATResult.TIMEOUT;
}
else if (resultState == 3) {
satResult = SATResult.INTERRUPTED;
}
else {
satResult = SATResult.CRASHED;
log.error("UBCSAT crashed!");
}
if(assignment == null) {
assignment = new HashSet<>();
}
return new SATSolverResult(satResult, runtime, assignment, SolvedBy.SATENSTEIN, nickname);
}
private HashSet<Literal> getAssignment(UBCSATLibrary fLibrary, Pointer fState) {
HashSet<Literal> assignment = new HashSet<>();
IntByReference pRef = fLibrary.getResultAssignment(fState);
int numVars = pRef.getValue();
int[] tempAssignment = pRef.getPointer().getIntArray(0, numVars + 1);
for (int i = 1; i <= numVars; i++) {
int intLit = tempAssignment[i];
int var = Math.abs(intLit);
boolean sign = intLit > 0;
Literal aLit = new Literal(var, sign);
assignment.add(aLit);
}
return assignment;
}
private void setPreviousAssignment(Map<Long, Boolean> aPreviousAssignment) {
long[] assignment = new long[aPreviousAssignment.size()];
int i = 0;
for (Long varID : aPreviousAssignment.keySet()) {
if (aPreviousAssignment.get(varID)) {
assignment[i] = varID;
} else {
assignment[i] = -varID;
}
i++;
}
fLibrary.initAssignment(fState, assignment, assignment.length);
}
@Override
public void notifyShutdown() {
}
@Override
public void interrupt() {
log.trace("Acquiring lock to interrupt UBCSAT");
lock.lock();
log.trace("Lock acquired");
if (isCurrentlySolving.get()) {
log.debug("Interrupting UBCSAT");
fLibrary.interrupt(fState);
log.debug("Interrupt sent to UBCSAT");
}
lock.unlock();
}
}
| 11,556
| 41.962825
| 192
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/base/SATSolverResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/base/SATSolverResult.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.base;
import java.io.Serializable;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
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.sat.base.Literal;
import lombok.Getter;
public class SATSolverResult implements Serializable {
private final SATResult fResult;
private final double fRuntime;
private final ImmutableSet<Literal> fAssignment;
@Getter
private final SolverResult.SolvedBy solvedBy;
@Getter
private final String nickname;
public SATSolverResult(SATResult aResult, double aRuntime, Set<Literal> aAssignment, SolverResult.SolvedBy solvedBy) {
this(aResult, aRuntime, aAssignment, solvedBy, null);
}
public SATSolverResult(SATResult aResult, double aRuntime, Set<Literal> aAssignment, SolverResult.SolvedBy solvedBy, String nickname)
{
Preconditions.checkArgument(aRuntime >= 0, "Cannot create a " + getClass().getSimpleName() + " with negative runtime: " + aRuntime);
this.nickname = nickname;
fResult = aResult;
fRuntime = aRuntime;
fAssignment = ImmutableSet.copyOf(aAssignment);
this.solvedBy = aResult.isConclusive() ? solvedBy : SolvedBy.UNSOLVED;
}
public SATResult getResult(){
return fResult;
}
public double getRuntime()
{
return fRuntime;
}
public ImmutableSet<Literal> getAssignment() {
return fAssignment;
}
@Override
public String toString()
{
return fResult+","+fRuntime+","+fAssignment;
}
public static SATSolverResult timeout(double time) {
return new SATSolverResult(SATResult.TIMEOUT, time, ImmutableSet.of(), SolverResult.SolvedBy.UNSOLVED);
}
}
| 2,706
| 31.22619
| 140
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/Clasp3Library.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/Clasp3Library.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries;
import com.sun.jna.Library;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
/**
* Created by newmanne on 15/04/15.
*/
public interface Clasp3Library extends Library {
/**
* Begin solving a problem by calling this method. The reference returned here is used in all subsequent methods.
* This should be called for every problem you want to solve - don't re-use the pointer returned across problems!
* @param params The arguments to clasp
* @return A pointer to a JNAProblem
*/
Pointer initConfig(final String params);
/**
* Pass a problem to the solver. Does not start solving the problem
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @param problemString CNF of the problem to solve
*/
void initProblem(Pointer jnaProblemPointer, final String problemString);
/**
* Actually solve the problem. Must have previously called {@link #initProblem(com.sun.jna.Pointer, String)} or this has undefined behavior
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @param timeoutTime How long to try solving the problem for before returning a timeout
*/
void solveProblem(Pointer jnaProblemPointer, double timeoutTime);
/**
* Destroy the problem and all associated information. Should always be called to clean up.
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
*/
void destroyProblem(Pointer jnaProblemPointer);
/**
* Interrupt the problem currently being solved. Should be called when another thread is blocking on {@link #solveProblem(com.sun.jna.Pointer, double)}
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return false is the interrupt was successful
*/
boolean interrupt(Pointer jnaProblemPointer);
/**
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return 0 if UNSAT, 1 if SAT, 2 if TIMEOUT, 3 if INTERRUPTED, 4 otherwise
*/
int getResultState(Pointer jnaProblemPointer);
/**
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return 0 if unconfigured, 1 if configured, 2 if error
*/
int getConfigState(Pointer jnaProblemPointer);
/**
* Only call this if the problem is SAT
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return The assignment returned for the problem. The first element is the size.
*/
IntByReference getResultAssignment(Pointer jnaProblemPointer);
/**
* Only call this method if configState == 2, in which case there was an error in configuration.
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return The configuration error message
*/
String getConfigErrorMessage(Pointer jnaProblemPointer);
double getCpuTime();
}
| 4,048
| 41.621053
| 155
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/UBCSATLibrary.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/solvers/jnalibraries/UBCSATLibrary.java
|
/**
* Copyright 2016, Auctionomics, Alexandre Fréchette, Neil Newman, Kevin Leyton-Brown.
*
* This file is part of SATFC.
*
* SATFC is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SATFC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SATFC. If not, see <http://www.gnu.org/licenses/>.
*
* For questions, contact us at:
* afrechet@cs.ubc.ca
*/
package ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries;
import com.sun.jna.Library;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
/**
* This is the Java half of the JNA bridge used to run any legal configuration of UBCSAT/SATenstein from SATFC.
*
* ***WARNING***: Due to conventions involving the use of global variables in UBCSAT, it is NOT
* safe to instantiate multiple configurations in succession that use different algorithms of UBCSAT
* (i.e. they pass different values to the "-alg" command-line parameter).
*
* If one wants to run multiple different algorithms, these should be instantiated separately
* via multiple calls to {@link com.sun.jna.Native#loadLibrary}, passing the
* {@link ca.ubc.cs.beta.stationpacking.utils.NativeUtils#NATIVE_OPTIONS} argument each time.
*
* Example: <code>Native.loadLibrary(pathToUBCSATLibrary, UBCSATLibrary.class, NativeUtils.NATIVE_OPTIONS);</code>
*
* @author pcernek on 7/27/15.
*/
public interface UBCSATLibrary extends Library {
/**
* First step in solving a problem. The reference returned here is used in all subsequent methods.
* This should be called for every problem you want to solve - don't re-use the pointer returned across problems!
* @param params The arguments to UBCSAT
* @return A pointer to a JNAProblem
*/
Pointer initConfig(final String params);
/**
Pass a problem to the solver. Does not start solving the problem.
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @param problemString CNF of the problem to solve
* @return True if returned error free
*/
boolean initProblem(Pointer jnaProblemPointer, final String problemString);
/**
* Set the values of the variables for a given problem.
* Must be called after {@link #initProblem(Pointer, String)}
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @param initialAssignment reference to an array of longs, where the magnitude of each number corresponds
* to a variable id, and the sign corresponds to the assignment for that variable.
* Positive vars get initialized to True, negative vars to False.
* Note that this can be a partial initial assignment, so any variable not mentioned
* in this initial assignment gets randomly initiated by default. (Random initial
* assignment happens in {@link #initProblem(Pointer, String)}
* @return True if returned error free
*/
boolean initAssignment(Pointer jnaProblemPointer, long[] initialAssignment, int numberOfVars);
/**
* Actually solve the problem. Must have previously called {@link #initProblem(com.sun.jna.Pointer, String)} or this has undefined behavior
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @param timeoutTime How long to try solving the problem for before returning a timeout (in seconds)
* @return True if returned error free
*/
boolean solveProblem(Pointer jnaProblemPointer, double timeoutTime);
/**
* Destroy the problem and all associated information. Should always be called to clean up.
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
*/
void destroyProblem(Pointer jnaProblemPointer);
/**
* Interrupt the problem currently being solved. Should be called when another thread is blocking on {@link #solveProblem(com.sun.jna.Pointer, double)}
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return false is the interrupt was successful
*/
void interrupt(Pointer jnaProblemPointer);
/**
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return 1 if SAT, 2 if TIMEOUT, 3 if INTERRUPTED, 4 otherwise
*/
int getResultState(Pointer jnaProblemPointer);
/**
* Only call this if the problem is SAT
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return The assignment returned for the problem. The first element is the size.
*/
IntByReference getResultAssignment(Pointer jnaProblemPointer);
/**
* Only call this method if configState == 2, in which case there was an error in configuration.
* @param jnaProblemPointer A pointer from having previously called {@link #initConfig(String)} method
* @return The configuration error message
*/
String getErrorMessage(Pointer jnaProblemPointer);
}
| 5,663
| 47.410256
| 155
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/Clause.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/Clause.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.base;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import org.apache.commons.lang3.StringUtils;
/**
* A disjunctive clause (OR's of litterals). Implementation-wise just a litteral collection wrapper.
* @author afrechet
*
*/
public class Clause implements Collection<Literal>{
private final Collection<Literal> fLitterals;
public Clause()
{
fLitterals = new HashSet<Literal>();
}
@Override
public String toString()
{
TreeSet<String> aLitteralStrings = new TreeSet<String>();
for(Literal aLitteral : fLitterals)
{
aLitteralStrings.add(aLitteral.toString());
}
return StringUtils.join(aLitteralStrings," v ");
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((fLitterals == null) ? 0 : fLitterals.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Clause other = (Clause) obj;
if (fLitterals == null) {
if (other.fLitterals != null)
return false;
} else if (!fLitterals.equals(other.fLitterals))
return false;
return true;
}
@Override
public int size() {
return fLitterals.size();
}
@Override
public boolean isEmpty() {
return fLitterals.isEmpty();
}
@Override
public boolean contains(Object o) {
return fLitterals.contains(o);
}
@Override
public Iterator<Literal> iterator() {
return fLitterals.iterator();
}
@Override
public Object[] toArray() {
return fLitterals.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return fLitterals.toArray(a);
}
@Override
public boolean add(Literal e) {
if(e==null)
{
throw new IllegalArgumentException("Cannot add a null literal to a clause.");
}
return fLitterals.add(e);
}
@Override
public boolean remove(Object o) {
return fLitterals.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return fLitterals.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Literal> c) {
if(c.contains(null))
{
throw new IllegalArgumentException("Cannot add a null literal to a clause.");
}
return fLitterals.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return fLitterals.removeAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return fLitterals.removeAll(c);
}
@Override
public void clear() {
fLitterals.clear();
}
}
| 3,421
| 20.658228
| 100
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/Literal.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/Literal.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.base;
import java.io.Serializable;
/**
* The construction blocks of SAT clauses, consists of an integral variable (long) and its sign/negation/polarity (true=not negated, false=negated).
* @author afrechet
*/
public class Literal implements Serializable{
private final long fVariable;
private final boolean fSign;
/**
* @param aVariable - the litteral's (positive) variable.
* @param aSign - the litteral's sign/negation (true=not negated, false=negated).
*/
public Literal(long aVariable, boolean aSign)
{
//TODO Litterals should not be allowed to be < 0 , but to support the current incremental code, we let it be.
fVariable = aVariable;
fSign = aSign;
}
/**
* @return the literal variable.
*/
public long getVariable() {
return fVariable;
}
/**
* @return the literal sign.
*/
public boolean getSign() {
return fSign;
}
@Override
public String toString()
{
return (fSign ? "" : "-") + (fVariable<0 ? "("+Long.toString(fVariable)+")" : Long.toString(fVariable) );
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (fSign ? 1231 : 1237);
result = prime * result + (int) (fVariable ^ (fVariable >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Literal other = (Literal) obj;
if (fSign != other.fSign)
return false;
if (fVariable != other.fVariable)
return false;
return true;
}
}
| 2,435
| 24.914894
| 149
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/CNF.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/CNF.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.base;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
/**
* A SAT formula in Conjunctive Normal Form (a conjunction of clauses - AND's of OR's of literals). Implementation wise just a clause collection wrapper.
* @author afrechet
*/
public class CNF implements Collection<Clause>{
private final Collection<Clause> fClauses;
public CNF()
{
fClauses = new ArrayDeque<Clause>();
//fClauses = new HashSet<Clause>();
}
/**
* Builds and returns the <a href="http://fairmut3x.wordpress.com/2011/07/29/cnf-conjunctive-normal-form-dimacs-format-explained/">DIMACS</a> string representation of the CNF.
* @param aComments - the comments to add at the beginning of the CNF, if any.
* @return the DIMACS string representation of the CNF.
*/
public String toDIMACS(String[] aComments)
{
StringBuilder aStringBuilder = new StringBuilder();
int aNumClauses = fClauses.size();
long aMaxVariable = 0;
for(Clause aClause : fClauses)
{
ArrayList<String> aLitteralStrings = new ArrayList<String>();
for(Literal aLitteral : aClause)
{
if(aLitteral.getVariable()<=0)
{
throw new IllegalArgumentException("Cannot transform to DIMACS a CNF that has a litteral with variable value <= 0 (clause: "+aClause.toString()+").");
}
else if(aLitteral.getVariable()>aMaxVariable)
{
aMaxVariable = aLitteral.getVariable();
}
aLitteralStrings.add((aLitteral.getSign() ? "" : "-") + Long.toString(aLitteral.getVariable()));
}
aStringBuilder.append(StringUtils.join(aLitteralStrings," ")+" 0\n");
}
aStringBuilder.insert(0, "p cnf "+aMaxVariable+" "+aNumClauses+"\n");
if (aComments != null)
{
for(int i=aComments.length-1;i>=0;i--)
{
aStringBuilder.insert(0, "c "+aComments[i].trim()+"\n");
}
}
return aStringBuilder.toString();
}
/**
* @return all the variables present in the CNF.
*/
public Collection<Long> getVariables()
{
Collection<Long> aVariables = new HashSet<Long>();
for(Clause aClause : fClauses)
{
for(Literal aLitteral : aClause)
{
aVariables.add(aLitteral.getVariable());
}
}
return aVariables;
}
@Override
public String toString()
{
ArrayDeque<String> aClauseStrings = new ArrayDeque<String>();
for(Clause aClause : fClauses)
{
aClauseStrings.add("("+aClause.toString()+")");
}
return StringUtils.join(aClauseStrings," ^ ");
}
public String getHashString() {
String aString = this.toString();
MessageDigest aDigest = DigestUtils.getSha1Digest();
try {
byte[] aResult = aDigest.digest(aString.getBytes("UTF-8"));
String aResultString = new String(Hex.encodeHex(aResult));
return aResultString;
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Could not encode cnf with sha1 hash.", e);
}
}
@Override
public int size() {
return fClauses.size();
}
@Override
public boolean isEmpty() {
return fClauses.isEmpty();
}
@Override
public boolean contains(Object o) {
return fClauses.contains(o);
}
@Override
public Iterator<Clause> iterator() {
return fClauses.iterator();
}
@Override
public Object[] toArray() {
return fClauses.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return fClauses.toArray(a);
}
@Override
public boolean add(Clause e) {
if(e==null)
{
throw new IllegalArgumentException("Cannot add a null clause to a CNF.");
}
return fClauses.add(e);
}
@Override
public boolean remove(Object o) {
return fClauses.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return fClauses.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Clause> c) {
if(c.contains(null))
{
throw new IllegalArgumentException("Cannot add a null clause to a CNF.");
}
return fClauses.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return fClauses.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return fClauses.remove(c);
}
@Override
public void clear() {
fClauses.clear();
}
}
| 6,009
| 26.953488
| 179
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/LiteralComparator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/solvers/sat/base/LiteralComparator.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.base;
import java.util.Comparator;
/**
* Compares literal based on their variable value.
* @author afrechet
*/
public class LiteralComparator implements Comparator<Literal>
{
@Override
public int compare(Literal o1, Literal o2) {
return Long.compare(o1.getVariable(),o2.getVariable());
}
};
| 1,165
| 31.388889
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationPackingInstance.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationPackingInstance.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.base;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import ca.ubc.cs.beta.stationpacking.utils.GuavaCollectors;
import lombok.Getter;
import lombok.NonNull;
/**
* Immutable container class representing a station packing instance.
* @author afrechet
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonDeserialize(using = StationPackingInstanceDeserializer.class)
public class StationPackingInstance {
public static final String NAME_KEY = "NAME";
public static final String CACHE_DATE_KEY = "CACHE_DATE";
public static final String UNTITLED = "UNTITLED";
private final ImmutableMap<Station, Set<Integer>> domains;
private final ImmutableMap<Station, Integer> previousAssignment;
@Getter
private final ConcurrentMap<String, Object> metadata;
/**
* Create a station packing instance.
* @param aDomains - a map taking each station to its domain of packable channels.
*/
public StationPackingInstance(Map<Station,Set<Integer>> aDomains){
this(aDomains, ImmutableMap.of());
}
public StationPackingInstance(Map<Station,Set<Integer>> aDomains, Map<Station,Integer> aPreviousAssignment) {
this(aDomains, aPreviousAssignment, ImmutableMap.of());
}
/**
* Create a station packing instance.
* @param aDomains - a map taking each station to its domain of packable channels.
* @param aPreviousAssignment - a map taking stations to the channels they were assigned to previously.
*/
public StationPackingInstance(Map<Station,Set<Integer>> aDomains, Map<Station,Integer> aPreviousAssignment, @NonNull Map<String, Object> metadata){
this.metadata = new ConcurrentHashMap<>(metadata);
// Remove any previous assignment info for stations that aren't present
previousAssignment = aPreviousAssignment.entrySet().stream().filter(entry -> aDomains.keySet().contains(entry.getKey())).collect(GuavaCollectors.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
//Validate assignment domain.
for(Station station : aDomains.keySet())
{
if(aDomains.get(station).isEmpty())
{
throw new IllegalArgumentException("Domain for station "+station+" is empty.");
}
}
// sort everything
final Map<Station, Set<Integer>> tempDomains = new LinkedHashMap<>();
aDomains.keySet().stream().sorted().forEach(station -> tempDomains.put(station, ImmutableSet.copyOf(aDomains.get(station).stream().sorted().iterator())));
this.domains = ImmutableMap.copyOf(tempDomains);
}
/**
* @return - all the channels present in the domains.
*/
public Set<Integer> getAllChannels()
{
Set<Integer> allChannels = new HashSet<>();
for(Set<Integer> channels : domains.values())
{
allChannels.addAll(channels);
}
return allChannels;
}
// warning: changing this method will completely mess up hashing!
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
int s=1;
for(Station station : getStations())
{
sb.append(station).append(":").append(StringUtils.join(domains.get(station), ","));
if(s+1<=getStations().size())
{
sb.append(";");
}
s++;
}
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((domains == null) ? 0 : domains.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StationPackingInstance other = (StationPackingInstance) obj;
if (domains == null) {
if (other.domains != null)
return false;
} else if (!domains.equals(other.domains))
return false;
return true;
}
/**
* An instance's stations is an unmodifiable set backed up by a hash set.
* @return - get the problem instance's stations.
*/
public ImmutableSet<Station> getStations(){
return domains.keySet();
}
/**
* An instance's channels is an unmodifiable set backed up by a hash set.
* @return - get the problem instance's channels.
*/
public ImmutableMap<Station,Set<Integer>> getDomains(){
return domains;
}
/**
* @return a map taking stations to the (valid) channels they were assigned to previously (if any).
*/
public ImmutableMap<Station,Integer> getPreviousAssignment()
{
return previousAssignment;
}
/**
* @return an information string about the instance.
*/
public String getInfo()
{
return domains.keySet().size()+" stations, "+getAllChannels().size()+" all channels";
}
/**
* @return a hashed version of the instance's string representation.
*/
public String getHashString()
{
String aString = this.toString();
MessageDigest aDigest = DigestUtils.getSha1Digest();
try {
byte[] aResult = aDigest.digest(aString.getBytes("UTF-8"));
return new String(Hex.encodeHex(aResult));
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Could not encode filename", e);
}
}
public String getName() {
return (String) metadata.getOrDefault(NAME_KEY, UNTITLED);
}
public boolean hasName() {
return !getName().equals(UNTITLED);
}
public String getAuction() {
final String name = (String) metadata.get(NAME_KEY);
return StationPackingUtils.parseAuctionFromName(name);
}
}
| 6,967
| 30.672727
| 203
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationPackingInstanceDeserializer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationPackingInstanceDeserializer.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.base;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.google.common.collect.ImmutableMap;
import lombok.Data;
public class StationPackingInstanceDeserializer extends
JsonDeserializer<StationPackingInstance> {
@Override
public StationPackingInstance deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
Dummy readValueAs = p.readValueAs(Dummy.class);
if (readValueAs.getMetadata() != null) {
return new StationPackingInstance(readValueAs.getDomains(), readValueAs.getPreviousAssignment(), readValueAs.getMetadata());
} else {
return new StationPackingInstance(readValueAs.getDomains(), readValueAs.getPreviousAssignment());
}
}
@Data
public static class Dummy {
private ImmutableMap<Station, Set<Integer>> domains;
private ImmutableMap<Station, Integer> previousAssignment;
private Map<String, Object> metadata;
}
}
| 1,962
| 34.053571
| 136
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/Station.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/Station.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.base;
import java.io.Serializable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
/**
* Immutable container class for the station object.
* Uniquely identified by its integer ID.
* @author afrechet
*/
@JsonSerialize(using = ToStringSerializer.class, as=String.class)
@JsonDeserialize(using = StationDeserializer.class)
public class Station implements Comparable<Station>, Serializable{
private final int fID;
/**
* Construct a station.
* @param aID - the station ID.
*/
public Station(Integer aID){
fID = aID;
}
/**
* @return - the station ID.
*/
public int getID(){
return fID;
}
@Override
public String toString(){
return Integer.toString(fID);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fID;
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Station other = (Station) obj;
if (fID != other.fID)
return false;
return true;
}
@Override
public int compareTo(Station o) {
return Integer.compare(fID,o.fID);
}
}
| 2,317
| 23.145833
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationDeserializer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/base/StationDeserializer.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.base;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.KeyDeserializer;
/**
* Created by newmanne on 06/03/15.
*/
public class StationDeserializer extends JsonDeserializer<Station> {
@Override
public Station deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return new Station(p.readValueAs(Integer.class));
}
public static class StationClassKeyDeserializer extends KeyDeserializer {
@Override
public Object deserializeKey(final String key, final DeserializationContext ctxt) throws IOException {
return new Station(Integer.parseInt(key));
}
}
}
| 1,677
| 33.958333
| 110
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/GuavaCollectors.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/GuavaCollectors.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.utils;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
public class GuavaCollectors {
public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() {
Supplier<ImmutableList.Builder<T>> supplier = ImmutableList.Builder::new;
BiConsumer<ImmutableList.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableList.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableList.Builder<T>, ImmutableList<T>> finisher = ImmutableList.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T> Collector<T, ?, ImmutableSet<T>> toImmutableSet() {
Supplier<ImmutableSet.Builder<T>> supplier = ImmutableSet.Builder::new;
BiConsumer<ImmutableSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher = ImmutableSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T extends Comparable<?>> Collector<T, ?, ImmutableSortedSet<T>> toNaturalImmutableSortedSet() {
Supplier<ImmutableSortedSet.Builder<T>> supplier = ImmutableSortedSet::naturalOrder;
BiConsumer<ImmutableSortedSet.Builder<T>, T> accumulator = (b, v) -> b.add(v);
BinaryOperator<ImmutableSortedSet.Builder<T>> combiner = (l, r) -> l.addAll(r.build());
Function<ImmutableSortedSet.Builder<T>, ImmutableSortedSet<T>> finisher = ImmutableSortedSet.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
public static <T, K, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableMap(
Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper) {
Supplier<ImmutableMap.Builder<K, V>> supplier = ImmutableMap.Builder::new;
BiConsumer<ImmutableMap.Builder<K, V>, T> accumulator = (b, t) -> b.put(keyMapper.apply(t),
valueMapper.apply(t));
BinaryOperator<ImmutableMap.Builder<K, V>> combiner = (l, r) -> l.putAll(r.build());
Function<ImmutableMap.Builder<K, V>, ImmutableMap<K, V>> finisher = ImmutableMap.Builder::build;
return Collector.of(supplier, accumulator, combiner, finisher);
}
}
| 4,371
| 46.521739
| 116
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/Watch.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/Watch.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.utils;
/**
* A pauseable walltime watch.
*
* @author afrechet
*/
public class Watch {
private long fStartTime;
private double fDuration;
private boolean fStopped;
/**
* Create a watch, initially stopped.
*/
public Watch() {
fStartTime = -1;
fDuration = 0.0;
fStopped = true;
}
/**
* @return a watch that has been started.
*/
public static Watch constructAutoStartWatch() {
Watch watch = new Watch();
watch.start();
return watch;
}
/**
* Stopped the watch.
*
* @return True if and only if the watch was running and then was stopped. False if the watch was already stopped.
*/
public boolean stop() {
if (!fStopped) {
fDuration += (System.currentTimeMillis() - fStartTime) / 1000.0;
fStartTime = -1;
fStopped = true;
return true;
} else {
return false;
}
}
/**
* Start the watch.
*
* @return True if and only if the watch was stopped and then was started. False if the watch was already started.
*/
public boolean start() {
if (fStopped) {
fStartTime = System.currentTimeMillis();
fStopped = false;
return true;
} else {
return false;
}
}
/**
* Reset the watch.
*/
public void reset() {
fStartTime = -1;
fDuration = 0.0;
fStopped = true;
}
/**
* @return the ellapsed time (s) between since the initial start (or reset) of the watch, the last end time being now if the watch
* is still running.
*/
public double getElapsedTime() {
if (fStopped) {
return fDuration;
} else {
return fDuration + (System.currentTimeMillis() - fStartTime) / 1000.0;
}
}
}
| 2,761
| 24.574074
| 134
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/StationPackingUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/StationPackingUtils.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.utils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Splitter;
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.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class StationPackingUtils {
private StationPackingUtils()
{
//Cannot construct a utils class.
}
public static final Integer LVHFmin = 2, LVHFmax = 6, UVHFmin=7, UVHFmax = 13, UHFmin = 14, UHFmax = 51;
public static final HashSet<Integer> LVHF_CHANNELS = new HashSet<Integer>(Arrays.asList(2,3,4,5,6));
public static final HashSet<Integer> HVHF_CHANNELS = new HashSet<Integer>(Arrays.asList(7,8,9,10,11,12,13));
public static final HashSet<Integer> UHF_CHANNELS = new HashSet<Integer>(Arrays.asList(14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,38,39,40,41,42,43,44,45,46,47,48,49,50,51));
public static Map<Station, Integer> stationToChannelFromChannelToStation(Map<Integer, Set<Station>> channelToStation) {
final Map<Station, Integer> stationToChannel = new HashMap<>();
channelToStation.entrySet().forEach(entry -> {
entry.getValue().forEach(station -> {
stationToChannel.put(station, entry.getKey());
});
});
return stationToChannel;
}
public static String parseAuctionFromName(String name) {
if (name != null) {
try {
return Splitter.on('_').splitToList(name).get(0);
} catch (Exception ignored) {
}
}
return null;
}
public static Map<Integer, Set<Station>> channelToStationFromStationToChannel(Map<Integer, Integer> stationToChannel) {
final HashMultimap<Integer, Station> channelAssignment = HashMultimap.create();
stationToChannel.entrySet().forEach(entry -> {
channelAssignment.get(entry.getValue()).add(new Station(entry.getKey()));
});
return Multimaps.asMap(channelAssignment);
}
public static boolean weakVerify(IStationManager stationManager, IConstraintManager constraintManager, Map<Integer, Integer> solution) {
return solution.keySet().stream().allMatch(s -> stationManager.getStations().contains(new Station(s))) && solution.entrySet().stream().allMatch(e -> stationManager.getDomain(stationManager.getStationfromID(e.getKey())).contains(e.getValue())) && constraintManager.isSatisfyingAssignment(channelToStationFromStationToChannel(solution));
}
}
| 3,617
| 41.564706
| 343
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/RedisUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/RedisUtils.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.utils;
import com.google.common.base.Joiner;
/**
* Created by newmanne on 11/05/15.
*/
public class RedisUtils {
public static final String TIMEOUTS_QUEUE = "TIMEOUTS";
public static final String PROCESSING_QUEUE = "PROCESSING";
public static final String JOB_QUEUE = "_JOB";
public static final String JSON_HASH = "_JSON";
public static final String CNF_INDEX_QUEUE = "CNFIndex";
public static String makeKey(String... args) {
return Joiner.on(':').join(args);
}
}
| 1,362
| 31.452381
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/RunnableUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/RunnableUtils.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.utils;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
public class RunnableUtils{
/**
* Submit a runnable to an executor service so that any uncaught exception will be processed by the uncaught exception handler.
* @param aExecutorService - an executor service to run a runnable.
* @param aUncaughtExceptionHandler - an uncaught exception handler to manager uncaught exceptions in the runnable's executions.
* @param r - a runnable to run.
*/
public static void submitRunnable(final ExecutorService aExecutorService, final UncaughtExceptionHandler aUncaughtExceptionHandler, final Runnable r)
{
aExecutorService.submit(
new Runnable() {
@Override
public void run() {
try {
r.run();
} catch(Throwable t)
{
aUncaughtExceptionHandler.uncaughtException(Thread.currentThread(), t);
}
}
});
}
}
| 1,989
| 37.269231
| 154
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/YAMLUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/YAMLUtils.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.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import lombok.Getter;
/**
* Created by newmanne on 05/10/15.
* Used to read and write YAML
*/
public class YAMLUtils {
@Getter
private static final ObjectMapper mapper;
static {
mapper = new ObjectMapper(new YAMLFactory());
mapper.registerModule(new GuavaModule());
mapper.registerModule(new SATFCJacksonModule());
}
}
| 1,395
| 29.347826
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/SATFCJacksonModule.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/SATFCJacksonModule.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.utils;
import com.fasterxml.jackson.databind.module.SimpleModule;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationDeserializer;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.YAMLBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.ISolverConfig;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.IStationAddingStrategyConfig;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.IStationPackingConfigurationStrategyConfig;
/**
* Created by newmanne on 05/10/15.
* A jackson module for all SATFC specific classes with custom serializer and deserializers
*/
public class SATFCJacksonModule extends SimpleModule {
public SATFCJacksonModule() {
addKeyDeserializer(Station.class, new StationDeserializer.StationClassKeyDeserializer());
addDeserializer(ISolverConfig.class, new YAMLBundle.SolverConfigDeserializer());
addDeserializer(IStationAddingStrategyConfig.class, new YAMLBundle.StationAddingStrategyConfigurationDeserializer());
addDeserializer(IStationPackingConfigurationStrategyConfig.class, new YAMLBundle.PresolverConfigurationDeserializer());
}
}
| 2,108
| 45.866667
| 127
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/NativeUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/NativeUtils.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.utils;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import com.sun.jna.Library;
import com.sun.jna.Platform;
/**
* Created by newmanne on 20/05/15.
*/
public class NativeUtils {
private final static int RTLD_LOCAL;
private final static int RTLD_LAZY;
public static final Map NATIVE_OPTIONS;
static {
if (Platform.isMac()) {
RTLD_LOCAL = 0x00000004;
RTLD_LAZY = 0x00000001;
} else {
if (!Platform.isLinux()) {
System.err.println("OS was not detected as mac or linux. Assuming values for <dlfcn.h> RTLD_LOCAL and RTLD_LAZY are same as linux. Unexpected errors can occur if this is not the case");
}
RTLD_LOCAL = 0x00000000;
RTLD_LAZY = 0x00000001;
}
NATIVE_OPTIONS = ImmutableMap.of(Library.OPTION_OPEN_FLAGS, RTLD_LAZY | RTLD_LOCAL);
}
}
| 1,762
| 31.648148
| 201
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/JSONUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/JSONUtils.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.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import lombok.Getter;
/**
* Created by newmanne on 02/12/14.
*/
public class JSONUtils {
@Getter
private static final ObjectMapper mapper;
static {
mapper = new ObjectMapper();
mapper.registerModule(new GuavaModule());
mapper.registerModule(new SATFCJacksonModule());
}
public static <T> T toObject(String jsonString, Class<T> klazz) {
try {
return toObjectWithException(jsonString, klazz);
} catch (IOException e) {
throw new RuntimeException("Couldn't deserialize string " + jsonString + " into type " + klazz, e);
}
}
public static <T> T toObjectWithException(String jsonString, Class<T> klazz) throws IOException {
return mapper.readValue(jsonString, klazz);
}
public static String toString(Object object) {
return toString(object, false);
}
public static String toString(Object object, boolean pretty) {
try {
final String json;
if (pretty) {
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
} else {
json = mapper.writeValueAsString(object);
}
return json;
} catch (JsonProcessingException e) {
throw new RuntimeException("Couldn't serialize object " + object, e);
}
}
}
| 2,408
| 30.697368
| 111
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/CacheUtils.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/CacheUtils.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.utils;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Created by newmanne on 19/03/15.
*/
public class CacheUtils {
public static BitSet toBitSet(Map<Integer, Set<Station>> answer, Map<Station, Integer> permutation) {
final BitSet bitSet = new BitSet();
answer.values().stream().forEach(stations -> stations.forEach(station -> bitSet.set(permutation.get(station))));
return bitSet;
}
public static CloseableHttpAsyncClient createHttpClient() {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
return client;
}
public static ParsedKey parseKey(String key) {
final List<String> strings = Splitter.on(":").splitToList(key);
Preconditions.checkState(strings.size() == 5, "Key %s not of expected cache key format SATFC:SAT:*:*:* or SATFC:UNSAT:*:*:*", key);
return new ParsedKey(Long.parseLong(strings.get(4)), SATResult.valueOf(strings.get(1)), strings.get(2), strings.get(3));
}
@Data
@AllArgsConstructor
public static class ParsedKey {
private final long num;
private final SATResult result;
private final String domainHash;
private final String interferenceHash;
}
}
| 2,545
| 33.405405
| 139
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/TimeLimitedCodeBlock.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/utils/TimeLimitedCodeBlock.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.utils;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import ca.ubc.cs.beta.aeatk.concurrent.threadfactory.SequentiallyNamedThreadFactory;
/**
* See http://stackoverflow.com/questions/5715235/java-set-timeout-on-a-certain-block-of-code
* Run a block of code until it either completes, or a certain amount of time has passed. Afterwards, continue. Note that the code might still continue running the background
*/
public class TimeLimitedCodeBlock {
public static void runWithTimeout(final Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception {
runWithTimeout(() -> {
runnable.run();
return null;
}, timeout, timeUnit);
}
public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception {
final ExecutorService executor = Executors.newSingleThreadExecutor(new SequentiallyNamedThreadFactory("SATFC Main Worker Thread"));
final Future<T> future = executor.submit(callable);
executor.shutdown(); // This does not cancel the already-scheduled task.
try {
return future.get(timeout, timeUnit);
}
catch (TimeoutException e) {
//remove this if you do not want to cancel the job in progress
//or set the argument to 'false' if you do not want to interrupt the thread
future.cancel(true);
throw e;
}
catch (ExecutionException e) {
//unwrap the root cause
Throwable t = e.getCause();
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof Exception) {
throw e;
} else {
throw new IllegalStateException(t);
}
}
}
}
| 2,886
| 38.547945
| 174
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacade.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacade.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.facade;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.IStationDB;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.sat.ClaspLibSATSolverParameters;
import ca.ubc.cs.beta.stationpacking.execution.parameters.solver.sat.UBCSATLibSATSolverParameters;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.SolverManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.ISolverBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.YAMLBundle;
import ca.ubc.cs.beta.stationpacking.metrics.SATFCMetrics;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.polling.PollingService;
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.cache.ContainmentCacheProxy;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.Clasp3SATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.ubcsat.UBCSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.composite.DisjunctiveCompositeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.interrupt.InterruptibleTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.solvers.termination.walltime.WalltimeTerminationCriterion;
import ca.ubc.cs.beta.stationpacking.utils.CacheUtils;
import ca.ubc.cs.beta.stationpacking.utils.TimeLimitedCodeBlock;
import ca.ubc.cs.beta.stationpacking.utils.Watch;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* A facade for solving station packing problems with SATFC.
* Each instance of the facade corresponds to an independent copy
* of SATFC (with different state).
* A SATFCFacade should only be involved in one solve operation at a time: do not have multiple threads calling solve concurrently
*
* @author afrechet
*/
@Slf4j
public class SATFCFacade implements AutoCloseable {
private final SolverManager fSolverManager;
private SATFCCacheAugmenter augmenter;
private final SATFCFacadeParameter parameter;
// measures idle time since the last time this facade solved a problem
private final Watch idleTime;
private volatile ScheduledFuture<?> future;
private final IPollingService pollingService;
private final CloseableHttpAsyncClient httpClient;
@Getter
private String versionInfo;
/**
* Construct a SATFC solver facade
* Package protected to enforce use of the builder
*
* @param aSATFCParameters parameters needed by the facade.
*/
SATFCFacade(final SATFCFacadeParameter aSATFCParameters) {
this.parameter = aSATFCParameters;
pollingService = new PollingService();
if (parameter.getServerURL() != null) {
log.info("Starting http client");
httpClient = CacheUtils.createHttpClient();
} else {
httpClient = null;
}
//Check provided library.
validateLibraries(aSATFCParameters.getClaspLibrary(), aSATFCParameters.getSatensteinLibrary(), pollingService);
log.info("Using clasp library {}", aSATFCParameters.getClaspLibrary());
log.info("Using SATenstein library {}", aSATFCParameters.getSatensteinLibrary());
log.info("Using bundle {}", aSATFCParameters.getSolverChoice());
fSolverManager = new SolverManager(
dataBundle -> {
switch (aSATFCParameters.getSolverChoice()) {
case YAML:
return new YAMLBundle(dataBundle, aSATFCParameters, pollingService, httpClient);
default:
throw new IllegalArgumentException("Unrecognized solver choice " + aSATFCParameters.getSolverChoice());
}
},
aSATFCParameters.getDataManager() == null ? new DataManager() : aSATFCParameters.getDataManager()
);
if (aSATFCParameters.getServerURL() != null && aSATFCParameters.getAutoAugmentOptions().isAugment()) {
log.info("Augment parameters {}", aSATFCParameters.getAutoAugmentOptions());
augmenter = new SATFCCacheAugmenter(this);
// schedule it
scheduleAugment(aSATFCParameters);
}
idleTime = Watch.constructAutoStartWatch();
try {
final String versionProperties = Resources.toString(Resources.getResource("version.properties"), Charsets.UTF_8);
final Iterator<String> split = Splitter.on(System.lineSeparator()).split(versionProperties).iterator();
Preconditions.checkState(split.hasNext(), "No version string in version properties file");
final String versionString = Splitter.on('=').splitToList(split.next()).get(1);
Preconditions.checkState(split.hasNext(), "No build time in version properties file");
final String buildTimeString = Splitter.on('=').splitToList(split.next()).get(1);
versionInfo = String.format("Using SATFC version %s, built on %s", versionString, buildTimeString);
log.info(versionInfo);
} catch (IllegalArgumentException | IOException e) {
log.error("Problem retrieving version info");
versionInfo = "Unknown version";
}
}
/**
* Solve a station packing problem.
*
* @param aDomains - a map taking integer station IDs to set of integer channels domains.
* @param aPreviousAssignment - a valid (proved to not create any interference) partial (can concern only some of the provided station) station to channel assignment.
* @param aCutoff - a cutoff in seconds for SATFC's execution.
* @param aSeed - a long seed for randomization in SATFC.
* @param aStationConfigFolder - a folder in which to find station config data (<i>i.e.</i> interferences and domains files).
* @return a result about the packability of the provided problem, with the time it took to solve, and corresponding valid witness assignment of station IDs to channels.
*/
public SATFCResult solve(
Map<Integer, Set<Integer>> aDomains,
Map<Integer, Integer> aPreviousAssignment,
double aCutoff,
long aSeed,
String aStationConfigFolder) {
return solve(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, null);
}
public SATFCResult solve(
@NonNull Map<Integer, Set<Integer>> aDomains,
@NonNull Map<Integer, Integer> aPreviousAssignment,
double aCutoff,
long aSeed,
@NonNull String aStationConfigFolder,
String instanceName) {
return createInterruptibleSATFCResult(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, instanceName, false).computeResult();
}
/**
* Solve a station packing problem. The channel domain of a station will be the intersection of the station's original domain (given in data files) with the packing channels,
* and additionally intersected with its reduced domain if available and if non-empty.
*
* @param aStations - a collection of integer station IDs.
* @param aChannels - a collection of integer channels.
* @param aReducedDomains - a map taking integer station IDs to set of integer channels domains.
* @param aPreviousAssignment - a valid (proved to not create any interference) partial (can concern only some of the provided station) station to channel assignment.
* @param aCutoff - a cutoff in seconds for SATFC's execution.
* @param aSeed - a long seed for randomization in SATFC.
* @param aStationConfigFolder - a folder in which to find station config data (<i>i.e.</i> interferences and domains files).
* @return a result about the packability of the provided problem, with the time it took to solve, and corresponding valid witness assignment of station IDs to channels.
*/
public SATFCResult solve(Set<Integer> aStations,
Set<Integer> aChannels,
Map<Integer, Set<Integer>> aReducedDomains,
Map<Integer, Integer> aPreviousAssignment,
double aCutoff,
long aSeed,
String aStationConfigFolder
) {
return solve(aStations, aChannels, aReducedDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, null);
}
public SATFCResult solve(@NonNull Set<Integer> aStations,
@NonNull Set<Integer> aChannels,
@NonNull Map<Integer, Set<Integer>> aReducedDomains,
@NonNull Map<Integer, Integer> aPreviousAssignment,
double aCutoff,
long aSeed,
String aStationConfigFolder,
String instanceName
) {
log.debug("Transforming instance to a domains only instance.");
//Construct the domains map.
final Map<Integer, Set<Integer>> aDomains = new HashMap<>();
for (Integer station : aStations) {
Set<Integer> domain = new HashSet<>(aChannels);
Set<Integer> reducedDomain = aReducedDomains.get(station);
if (reducedDomain != null && !reducedDomain.isEmpty()) {
domain = Sets.intersection(domain, reducedDomain);
}
aDomains.put(station, domain);
}
return solve(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, instanceName);
}
/**
* @return An interruptibleSATFCResult. Call {@link InterruptibleSATFCResult#computeResult} to start solving the problem.
* The problem will not begin solving automatically. The expected use case is that a reference to the {@link InterruptibleSATFCResult} will be made accessible to another thread, that may decide to interrupt the operation based on some external signal.
* You can call {@link InterruptibleSATFCResult#interrupt()} from another thread to interrupt the problem while it is being solved.
*/
public InterruptibleSATFCResult solveInterruptibly(Map<Integer, Set<Integer>> aDomains, Map<Integer, Integer> aPreviousAssignment, double aCutoff, long aSeed, String aStationConfigFolder) {
return solveInterruptibly(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, null);
}
public InterruptibleSATFCResult solveInterruptibly(Map<Integer, Set<Integer>> aDomains, Map<Integer, Integer> aPreviousAssignment, double aCutoff, long aSeed, String aStationConfigFolder, String instanceName) {
return createInterruptibleSATFCResult(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, instanceName, false);
}
InterruptibleSATFCResult createInterruptibleSATFCResult(
@NonNull Map<Integer, Set<Integer>> aDomains,
@NonNull Map<Integer, Integer> aPreviousAssignment,
double aCutoff,
long aSeed,
@NonNull String aStationConfigFolder,
String instanceName,
boolean internal) {
log.debug("Setting termination criterion...");
//Set termination criterion.
final InterruptibleTerminationCriterion termination = new InterruptibleTerminationCriterion();
final SATFCProblemSolveCallable satfcProblemSolveCallable = new SATFCProblemSolveCallable(aDomains, aPreviousAssignment, aCutoff, aSeed, aStationConfigFolder, termination, instanceName, internal);
return new InterruptibleSATFCResult(termination, satfcProblemSolveCallable);
}
/**
* Augment the cache by generating and solving new problems indefinitely. This call never terminates.
*
* @param domains Domains used for augmentation. A station used to augment the assignment will be drawn from this map, with this domain. A map taking integer station IDs to set of integer channels domains
* @param assignment The starting point for the augmentation. All augmentation will proceed from this starting point. A valid (proved to not create any interference) partial (can concern only some of the provided station) station to channel assignment.
* @param aStationConfigFolder a folder in which to find station config data (<i>i.e.</i> interferences and domains files).
* @param stationDB
* @param cutoff how long to spend on each generated problem before giving up
*/
public void augment(@NonNull Map<Integer, Set<Integer>> domains, @NonNull Map<Integer, Integer> assignment, @NonNull IStationDB stationDB, @NonNull String aStationConfigFolder, double cutoff) {
final SATFCCacheAugmenter satfcCacheAugmenter = new SATFCCacheAugmenter(this);
satfcCacheAugmenter.augment(domains, assignment, stationDB, aStationConfigFolder, cutoff);
}
@AllArgsConstructor
public class SATFCProblemSolveCallable implements Callable<SATFCResult> {
private final Map<Integer, Set<Integer>> aDomains;
private final Map<Integer, Integer> aPreviousAssignment;
private final double aCutoff;
private final long aSeed;
private final String aStationConfigFolder;
private final ITerminationCriterion criterion;
private final String instanceName;
// true if the call was generated from a cache augmenter
private final boolean internal;
@Override
public SATFCResult call() throws Exception {
if (parameter.getAutoAugmentOptions().isAugment() && !internal) {
log.debug("Cancelling any ongoing augmentation operation (if one exists)");
// Cancel any ongoing augmentation
augmenter.stop();
} else {
idleTime.reset();
}
if (aDomains.isEmpty()) {
log.warn("Provided an empty domains map.");
return new SATFCResult(SATResult.SAT, 0.0, ImmutableMap.of());
}
Preconditions.checkArgument(aCutoff > 0, "Cutoff must be strictly positive");
final ISolverBundle bundle = getSolverBundle(aStationConfigFolder);
final IStationManager stationManager = bundle.getStationManager();
log.debug("Translating arguments to SATFC objects...");
//Translate arguments.
final Map<Station, Set<Integer>> domains = new HashMap<>();
for (Entry<Integer, Set<Integer>> entry : aDomains.entrySet()) {
final Station station = stationManager.getStationfromID(entry.getKey());
final Set<Integer> domain = entry.getValue();
final Set<Integer> completeStationDomain = stationManager.getDomain(station);
final Set<Integer> trueDomain = Sets.intersection(domain, completeStationDomain);
if (trueDomain.isEmpty()) {
log.warn("Station {} has an empty domain, cannot pack.", station);
return new SATFCResult(SATResult.UNSAT, 0.0, ImmutableMap.of());
}
domains.put(station, trueDomain);
}
final Map<Station, Integer> previousAssignment = new HashMap<>();
for (Station station : domains.keySet()) {
final Integer previousChannel = aPreviousAssignment.get(station.getID());
if (previousChannel != null && previousChannel > 0) {
Preconditions.checkState(domains.get(station).contains(previousChannel), "Provided previous assignment assigned channel " + previousChannel + " to station " + station + " which is not in its problem domain " + domains.get(station) + ".");
previousAssignment.put(station, previousChannel);
}
}
log.debug("Constructing station packing instance...");
//Construct the instance.
final Map<String, Object> metadata = new HashMap<>();
if (instanceName != null) {
metadata.put(StationPackingInstance.NAME_KEY, instanceName);
}
StationPackingInstance instance = new StationPackingInstance(domains, previousAssignment, metadata);
SATFCMetrics.postEvent(new SATFCMetrics.NewStationPackingInstanceEvent(instance, bundle.getConstraintManager()));
log.debug("Getting solver...");
//Get solver
final ISolver solver = bundle.getSolver(instance);
/*
* Logging problem info
*/
log.trace("Solving instance {} ...", instance);
log.trace("Instance stats:");
log.trace("{} stations.", instance.getStations().size());
log.trace("stations: {}.", instance.getStations());
log.trace("{} all channels.", instance.getAllChannels().size());
log.trace("all channels: {}.", instance.getAllChannels());
log.trace("Previous assignment: {}", instance.getPreviousAssignment());
// Make sure that SATFC doesn't get hung. We give a VERY generous timeout window before throwing an exception
final int SUICIDE_GRACE_IN_SECONDS = 5 * 60;
final long totalSuicideGraceTimeInMillis = (long) (aCutoff + SUICIDE_GRACE_IN_SECONDS) * 1000;
final DisjunctiveCompositeTerminationCriterion disjunctiveCompositeTerminationCriterion = new DisjunctiveCompositeTerminationCriterion(new WalltimeTerminationCriterion(aCutoff), criterion);
//Solve instance.
final SolverResult result;
try {
result = TimeLimitedCodeBlock.runWithTimeout(() -> solver.solve(instance, disjunctiveCompositeTerminationCriterion, aSeed), totalSuicideGraceTimeInMillis, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new RuntimeException("SATFC waited " + totalSuicideGraceTimeInMillis + " ms for a result, but no result came back! The given timeout was " + aCutoff + " s, so SATFC appears to be hung. This is probably NOT a recoverable error");
} catch (Exception e) {
throw new RuntimeException(e);
}
SATFCMetrics.postEvent(new SATFCMetrics.InstanceSolvedEvent(instanceName, result));
log.debug("Transforming result into SATFC output...");
// Transform back solver result to output result
final Map<Integer, Integer> witness = new HashMap<>();
for (Entry<Integer, Set<Station>> entry : result.getAssignment().entrySet()) {
Integer channel = entry.getKey();
for (Station station : entry.getValue()) {
witness.put(station.getID(), channel);
}
}
final String extraInfo = getExtraInfo(bundle);
final SATFCResult outputResult = new SATFCResult(result.getResult(), result.getRuntime(), witness, extraInfo);
log.debug("Result: {}.", outputResult);
if (!internal && parameter.getAutoAugmentOptions().isAugment()) {
log.debug("Starting up timer again from 0 for augmentation");
// Start measuring time again and reschedule jobs
idleTime.start();
scheduleAugment(parameter);
}
return outputResult;
}
private String getExtraInfo(ISolverBundle bundle) {
final StringBuilder extraInfo = new StringBuilder();
extraInfo.append(getVersionInfo()).append(System.lineSeparator());
if (parameter.getServerURL() != null) {
extraInfo.append("SATFCServer registered at URL ").append(parameter.getServerURL());
if (ContainmentCacheProxy.lastSuccessfulCommunication != null) {
extraInfo.append(" last contacted succesfully at ").append(ContainmentCacheProxy.lastSuccessfulCommunication.toString());
} else {
extraInfo.append(" has not yet been contacted");
}
extraInfo.append(System.lineSeparator());
} else {
extraInfo.append("SATFCServer is not being used").append(System.lineSeparator());
}
extraInfo.append("Enabled checkers: ").append(System.lineSeparator()).append(bundle.getCheckers());
return extraInfo.toString();
}
}
private ISolverBundle getSolverBundle(String aStationConfigFolder) {
log.debug("Getting data managers...");
//Get the data managers and solvers corresponding to the provided station config data.
final ISolverBundle bundle;
try {
bundle = fSolverManager.getData(aStationConfigFolder);
} catch (FileNotFoundException e) {
log.error("Did not find the necessary data files in provided station config data folder {}.", aStationConfigFolder);
throw new IllegalArgumentException("Station config files not found.", e);
}
return bundle;
}
private void scheduleAugment(final SATFCFacadeParameter aSATFCParameters) {
final ScheduledExecutorService service = pollingService.getService();
final long pollingInterval = (long) (1000 * aSATFCParameters.getAutoAugmentOptions().getPollingInterval());
future = service.schedule(new Runnable() {
@Override
public void run() {
try {
final double elapsedTime = idleTime.getElapsedTime();
log.debug("Checking to see if cache augmentation should happen. SATFC Facade has been idle for {}s and we require it to be idle for {}s", elapsedTime, aSATFCParameters.getAutoAugmentOptions().getIdleTimeBeforeAugmentation());
if (elapsedTime >= aSATFCParameters.getAutoAugmentOptions().getIdleTimeBeforeAugmentation()) {
log.info("SATFC Facade has been idle for {}, time to start performing cache augmentations", elapsedTime);
augmenter.augment(aSATFCParameters.getAutoAugmentOptions().getAugmentStationConfigurationFolder(), aSATFCParameters.getServerURL(), httpClient, aSATFCParameters.getAutoAugmentOptions().getAugmentCutoff());
} else {
// not time to augment, check again later
log.debug("SATFC Facade has been occupied recently, not time to augment");
service.schedule(this, pollingInterval, TimeUnit.MILLISECONDS);
}
} catch (Throwable t) {
log.error("Caught exception in ScheduledExecutorService for scheduling augment", t);
}
}
}, pollingInterval, TimeUnit.MILLISECONDS);
}
private void validateLibraries(final String claspLib, final String satensteinLib, final IPollingService pollingService) {
validateLibraryFile(claspLib);
validateLibraryFile(satensteinLib);
try {
new Clasp3SATSolver(claspLib, ClaspLibSATSolverParameters.UHF_CONFIG_04_15_h1, pollingService);
} catch (UnsatisfiedLinkError e) {
unsatisfiedLinkWarn(claspLib, e);
}
try {
new UBCSATSolver(satensteinLib, UBCSATLibSATSolverParameters.DEFAULT_DCCA, pollingService);
} catch (UnsatisfiedLinkError e) {
unsatisfiedLinkWarn(satensteinLib, e);
}
}
private void unsatisfiedLinkWarn(final String libPath, UnsatisfiedLinkError e) {
log.error("\n--------------------------------------------------------\n" +
"Could not load native library : {}. \n" +
"Possible Solutions:\n" +
"1) Try rebuilding the library, on Linux this can be done by going to the clasp folder and running \"bash compile.sh\"\n" +
"2) Check that all library dependancies are met, e.g., run \"ldd {}\".\n" +
"3) Manually set the library to use with the \"-CLASP-LIBRARY\" or \"-SATENSTEIN-LIBRARY\" options.\n" +
"--------------------------------------------------------", libPath, libPath);
throw new IllegalArgumentException("Could not load JNA library", e);
}
private void validateLibraryFile(final String libraryFilePath) {
Preconditions.checkNotNull(libraryFilePath, "Cannot provide null library");
final File libraryFile = new File(libraryFilePath);
Preconditions.checkArgument(libraryFile.exists(), "Provided library " + libraryFile.getAbsolutePath() + " does not exist.");
Preconditions.checkArgument(!libraryFile.isDirectory(), "Provided library is a directory.");
}
@Override
public void close() throws Exception {
log.info("Shutting down...");
if (augmenter != null) {
log.trace("Closing augmenter");
augmenter.stop();
}
fSolverManager.close();
if (httpClient != null) {
log.trace("Closing http client");
httpClient.close();
}
if (future != null) {
future.cancel(false);
}
log.trace("Closing polling service");
pollingService.notifyShutdown();
log.info("Goodbye!");
}
}
| 27,637
| 52.355212
| 266
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacadeParameter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacadeParameter.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.facade;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.ConfigFile;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.CNFSaverSolverDecorator;
import ch.qos.logback.classic.Level;
import lombok.Value;
import lombok.experimental.Builder;
@Value
@Builder
public class SATFCFacadeParameter {
// public options
private final String claspLibrary;
private final String satensteinLibrary;
private final ConfigFile configFile;
private final String serverURL;
private final String resultFile;
private Level logLevel;
private int numServerAttempts;
private boolean noErrorOnServerUnavailable;
private AutoAugmentOptions autoAugmentOptions;
// developer options
private final CNFSaverSolverDecorator.ICNFSaver CNFSaver;
// It's possible to specify a datamanager here so that facade's can be quickly rebuilt without reloading constraints
private final DataManager dataManager;
private final SolverChoice solverChoice;
public enum SolverChoice
{
YAML;
}
}
| 1,974
| 30.854839
| 120
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/InterruptibleSATFCResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/InterruptibleSATFCResult.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.facade;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
/**
* Created by newmanne on 13/10/15.
* A SATFCResult object that is returned immediately from the facade. The {@link #computeResult()} method must be called to begin computation. The {@link #interrupt()} method can
* be called at any time (e.g. by another thread) to interrupt the problem.
*/
public class InterruptibleSATFCResult {
private final ITerminationCriterion.IInterruptibleTerminationCriterion criterion;
private final Callable<SATFCResult> solveTask;
private final CountDownLatch latch;
public InterruptibleSATFCResult(ITerminationCriterion.IInterruptibleTerminationCriterion criterion, Callable<SATFCResult> solveTask) {
this.criterion = criterion;
this.solveTask = solveTask;
latch = new CountDownLatch(1);
}
/**
* Interrupt the solve operation associated with this event.
* This method returns immediately, even though the interruption signal might not have been read by SATFC yet
* It is safe to call this method multiple times (but it will have no effect past the first time).
* It is safe to call this method if the problem has not started, or if the problem has finished
* Note that an interrupted result will look identical to a TIMEOUT (except that it may not actually match the cutoff)
*/
public void interrupt() {
criterion.interrupt();
}
/**
* Call this method to begin computing the problem. The problem will not start computation until this is called.
* Blocks until the problem is completed
* @return The SATFCResult
*/
public SATFCResult computeResult() {
try {
final SATFCResult call = solveTask.call();
latch.countDown();
return call;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Blocks until the problem is terminated (and the SATFCFacade is safe to use to start another problem.
* Note that {@link #computeResult()} should be used to solve the problem, this is for another thread that might want to wait
*/
public void blockUntilTerminated() throws InterruptedException {
latch.await();
}
}
| 3,210
| 39.1375
| 178
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacadeBuilder.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCFacadeBuilder.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.facade;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.io.Resources;
import ca.ubc.cs.beta.stationpacking.execution.parameters.SATFCFacadeParameters;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeParameter.SolverChoice;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.ConfigFile;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.CNFSaverSolverDecorator;
import ch.qos.logback.classic.Level;
import lombok.Data;
import lombok.NonNull;
import lombok.experimental.Builder;
/**
* Builder in charge of creating a SATFC facade, feeding it the necessary options.
* DO NOT USE LOGGER IN THIS CLASS. LOGGING HAS NOT BEEN INITIALIZED
*
* @author afrechet
*/
public class SATFCFacadeBuilder {
private volatile static boolean logInitialized = false;
// public params
private boolean initializeLogging;
private String fClaspLibrary;
private String fSATensteinLibrary;
private String fResultFile;
private String serverURL;
private Level logLevel;
private String logFileName;
private int numServerAttempts;
private boolean noErrorOnServerUnavailable;
private ConfigFile configFile;
private DeveloperOptions developerOptions;
private AutoAugmentOptions autoAugmentOptions;
/**
* Set the YAML file used to build up the SATFC solver bundle
* @param configFile path to a config file
*/
public SATFCFacadeBuilder setConfigFile(String configFile) {
this.configFile = new ConfigFile(configFile, false);
return this;
}
/**
* Set the YAML file used to build up the SATFC solver bundle
* @param configFile
*/
public SATFCFacadeBuilder setConfigFile(InternalSATFCConfigFile configFile) {
this.configFile = new ConfigFile(configFile.getFilename(), true);
return this;
}
// developer params
@Builder
@Data
public static class DeveloperOptions {
private CNFSaverSolverDecorator.ICNFSaver CNFSaver;
private DataManager dataManager;
private SolverChoice solverChoice;
}
/**
* Keeps track of the locations of the different shared libraries used by SATFC.
* Adding pathing for a new library is as simple as one line of code.
* @author pcernek
*/
public enum SATFCLibLocation {
CLASP ("SATFC_CLASP_LIBRARY", "clasp" + File.separator + "jna" + File.separator + "libjnaclasp.so"),
SATENSTEIN ("SATFC_SATENSTEIN_LIBRARY", "satenstein" + File.separator + "jna" + File.separator + "libjnasatenstein.so");
/**
* The name of the environment variable that the user may set to specify the library location.
*/
public final String SATFC_ENV_VAR;
/**
* The relative path to the .so file. This location is determined by the library's compile.sh script.
*/
public final String relativePath;
SATFCLibLocation(String aENV_VAR, String aRelativePath) {
this.SATFC_ENV_VAR = aENV_VAR;
this.relativePath = aRelativePath;
}
}
/**
* Create a SATFCFacadeBuilder with the default parameters - no logging initialized, autodetected clasp library, no saving of CNFs and results.
*/
public SATFCFacadeBuilder() {
// public params
fClaspLibrary = findSATFCLibrary(SATFCLibLocation.CLASP);
fSATensteinLibrary = findSATFCLibrary(SATFCLibLocation.SATENSTEIN);
fResultFile = null;
serverURL = null;
logLevel = Level.INFO;
logFileName = "SATFC.log";
configFile = autoDetectBundle();
numServerAttempts = 3;
noErrorOnServerUnavailable = false;
autoAugmentOptions = AutoAugmentOptions.builder().build();
developerOptions = DeveloperOptions.builder().solverChoice(SolverChoice.YAML).build();
}
public static ConfigFile autoDetectBundle() {
return new ConfigFile(Runtime.getRuntime().availableProcessors() >= 4 ? InternalSATFCConfigFile.SATFC_PARALLEL.getFilename() : InternalSATFCConfigFile.SATFC_SEQUENTIAL.getFilename(), true);
}
/**
* Some autodetection magic to find libraries used by SATFC.
*
* @return the path detected for the given library, null if none found.
* @param lib
*/
public static String findSATFCLibrary(SATFCLibLocation lib) {
final String envPath = System.getenv(lib.SATFC_ENV_VAR);
if (envPath != null) {
System.out.println("Using path set from env variable " + lib.SATFC_ENV_VAR + ", " + envPath);
return envPath;
}
//Relative path pointing to the clasp .so
final String relativeLibPath = lib.relativePath;
//Find the root of the clasp relative path.
final URL url = SATFCFacadeBuilder.class.getProtectionDomain().getCodeSource().getLocation();
File f;
try {
f = new File(url.toURI());
} catch (URISyntaxException e) {
f = new File(url.getPath());
}
final String currentLocation;
if (f.isDirectory()) {
if (f.getName().equals("bin")) {
// eclipse
currentLocation = new File(f.getParentFile(), "src" + File.separator + "dist").getAbsolutePath();
} else {
// intellij
currentLocation = new File(f.getParentFile().getParentFile().getParentFile(), "src" + File.separator + "dist").getAbsolutePath();
}
} else {
//Deployed, probably under the gradle install build structure.
currentLocation = f.getParentFile().getParentFile().getAbsolutePath();
}
final File file = new File(currentLocation + File.separator + relativeLibPath);
if (file.exists()) {
System.out.println("Found default library " + file.getAbsolutePath() + ".");
return file.getAbsolutePath();
} else {
System.err.println("Did not find SATFC library at " + file.getAbsolutePath());
}
return null;
}
/**
* Build a SATFC facade with the builder's options. These are either the default options (if available), or the ones provided with the
* builder's setters.
*
* @return a SATFC facade configured according to the builder's options.
*/
public SATFCFacade build() {
if (fClaspLibrary == null || fSATensteinLibrary == null) {
throw new IllegalArgumentException("Facade builder did not auto-detect default library, and no other library was provided.");
}
if (developerOptions.getSolverChoice().equals(SolverChoice.YAML)) {
Preconditions.checkNotNull(configFile, "No YAML config file was given to initialize the solver bundle with!");
}
if (initializeLogging) {
initializeLogging(logLevel, logFileName);
}
return new SATFCFacade(
SATFCFacadeParameter.builder()
.claspLibrary(fClaspLibrary)
.satensteinLibrary(fSATensteinLibrary)
.resultFile(fResultFile)
.serverURL(serverURL)
.configFile(configFile)
.numServerAttempts(numServerAttempts)
.noErrorOnServerUnavailable(noErrorOnServerUnavailable)
.autoAugmentOptions(autoAugmentOptions)
// developer
.dataManager(developerOptions.getDataManager())
.CNFSaver(developerOptions.getCNFSaver())
.solverChoice(developerOptions.getSolverChoice())
.build()
);
}
/**
* Set the clasp library SATFC should use.
*
* @param aLibrary
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder setClaspLibrary(String aLibrary) {
if (aLibrary == null) {
throw new IllegalArgumentException("Cannot provide a null clasp library.");
}
fClaspLibrary = aLibrary;
return this;
}
/**
* Set the SATenstein library SATFC should use.
*
* @param aLibrary
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder setSATensteinLibrary(String aLibrary) {
if (aLibrary == null) {
throw new IllegalArgumentException("Cannot provide a null SATenstein library.");
}
fSATensteinLibrary = aLibrary;
return this;
}
/**
* Set the file in which SATFC writes encountered problem/results pairs.
*
* @param aResultFile
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder setResultFile(@NonNull String aResultFile) {
fResultFile = aResultFile;
return this;
}
/**
* Set the URL of the SATFCServer. This is only required if you are using the SATFCServer module.
*
* @param serverURL
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder setServerURL(@NonNull String serverURL) {
this.serverURL = serverURL;
return this;
}
/**
* Set the number of attempts to retry a connection to the SATFCServer per query before giving up and continuing without the server's help (or throwing an error)
* @param numServerAttempts number of times to attempt the server for a given query
* @param noErrorOnServerUnavailable if true, just continue solving the problem without the server's help. if false, throw an error after numServerAttempts is exceeded
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder setServerAttempts(int numServerAttempts, boolean noErrorOnServerUnavailable) {
Preconditions.checkState(numServerAttempts > 0, "number of server attempts must be positive");
this.numServerAttempts = numServerAttempts;
this.noErrorOnServerUnavailable = noErrorOnServerUnavailable;
return this;
}
/**
* Call this method to have SATFC configure logging (this would only have any effect if the calling application hasn't initialized logging)
*
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder initializeLogging(String logFileName, @NonNull Level logLevel) {
this.initializeLogging = true;
this.logLevel = logLevel;
this.logFileName = logFileName;
return this;
}
/**
* Call this method to have SATFC configure logging (this would only have any effect if the calling application hasn't initialized logging)
*
* @return this {@code Builder} object
*/
public SATFCFacadeBuilder initializeLogging(@NonNull Level logLevel) {
return initializeLogging(null, logLevel);
}
/**
*/
public SATFCFacadeBuilder setAutoAugmentOptions(@NonNull AutoAugmentOptions autoAugmentOptions) {
this.autoAugmentOptions = autoAugmentOptions;
return this;
}
// Developer methods
public SATFCFacadeBuilder setDeveloperOptions(@NonNull DeveloperOptions developerOptions) {
this.developerOptions = developerOptions;
return this;
}
public static SATFCFacadeBuilder builderFromParameters(@NonNull SATFCFacadeParameters parameters) {
final SATFCFacadeBuilder builder = new SATFCFacadeBuilder();
// regular parameters
if (parameters.fClaspLibrary != null) {
builder.setClaspLibrary(parameters.fClaspLibrary);
}
if (parameters.fSATensteinLibrary != null) {
builder.setSATensteinLibrary(parameters.fSATensteinLibrary);
}
if (parameters.configFile != null) {
builder.setConfigFile(parameters.configFile);
}
builder.initializeLogging(parameters.logFileName, parameters.getLogLevel());
if (parameters.cachingParams.serverURL != null) {
builder.setServerURL(parameters.cachingParams.serverURL);
}
CNFSaverSolverDecorator.ICNFSaver CNFSaver = null;
if (parameters.fCNFDir != null) {
System.out.println("Saving CNFs to disk in " + parameters.fCNFDir);
CNFSaver = new CNFSaverSolverDecorator.FileCNFSaver(parameters.fCNFDir);
if (parameters.fRedisParameters.areValid()) {
System.out.println("Saving CNF index to redis");
CNFSaver = new CNFSaverSolverDecorator.RedisIndexCNFSaver(CNFSaver, parameters.fRedisParameters.getJedis(), parameters.fRedisParameters.fRedisQueue);
}
}
// developer parameters
builder.setDeveloperOptions(
DeveloperOptions
.builder()
.CNFSaver(CNFSaver)
.solverChoice(parameters.solverChoice)
.build()
);
return builder;
}
private static final String LOGBACK_CONFIGURATION_FILE_PROPERTY = "logback.configurationFile";
public static void initializeLogging(Level logLevel, String logFileName) {
if (logInitialized) {
return;
}
if (System.getProperty(LOGBACK_CONFIGURATION_FILE_PROPERTY) != null) {
Logger log = LoggerFactory.getLogger(SATFCFacade.class);
log.debug("System property for logback.configurationFile has been found already set as {} , logging will follow this file.", System.getProperty(LOGBACK_CONFIGURATION_FILE_PROPERTY));
} else {
String logback = Resources.getResource("logback_satfc.groovy").toString();
System.setProperty("SATFC.root.log.level", logLevel.toString());
if (logFileName != null) {
System.setProperty("SATFC.log.filename", logFileName);
}
System.setProperty(LOGBACK_CONFIGURATION_FILE_PROPERTY, logback);
Logger log = LoggerFactory.getLogger(SATFCFacade.class);
log.debug("Logging initialized to use file: {}", logback);
}
logInitialized = true;
}
}
| 15,092
| 38.202597
| 197
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/InternalSATFCConfigFile.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/InternalSATFCConfigFile.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.facade;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
* Created by newmanne on 14/10/15.
* Portfolios that come bundled with SATFC (inside the jar)
*/
@RequiredArgsConstructor
public enum InternalSATFCConfigFile {
SATFC_SEQUENTIAL("satfc_sequential"),
SATFC_PARALLEL("satfc_parallel"),
UNSAT_LABELLER("unsat_labeller")
;
@Getter
private final String filename;
}
| 1,262
| 29.804878
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCResult.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCResult.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.facade;
import java.io.Serializable;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* Container for the result returned by a SATFC facade.
*
* @author afrechet
*/
@Data
@Accessors(prefix = "f")
public class SATFCResult implements Serializable {
private final ImmutableMap<Integer, Integer> fWitnessAssignment;
private final SATResult fResult;
private final double fRuntime;
private final String fExtraInfo;
/**
* @param aResult - the satisfiability result.
* @param aRuntime - the time (s) it took to get to such result.
* @param aWitnessAssignment - the witness assignment
*/
public SATFCResult(SATResult aResult, double aRuntime, Map<Integer, Integer> aWitnessAssignment) {
this(aResult, aRuntime, aWitnessAssignment, "");
}
public SATFCResult(SATResult aResult, double aRuntime, Map<Integer, Integer> aWitnessAssignment, String extraInfo) {
fResult = aResult;
fRuntime = aRuntime;
fWitnessAssignment = ImmutableMap.copyOf(aWitnessAssignment);
fExtraInfo = extraInfo;
}
@Override
public String toString() {
return fRuntime + "," + fResult + "," + fWitnessAssignment.toString();
}
}
| 2,231
| 31.823529
| 120
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/AutoAugmentOptions.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/AutoAugmentOptions.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.facade;
import java.util.concurrent.TimeUnit;
import lombok.Data;
import lombok.experimental.Builder;
/**
* Created by newmanne on 16/10/15.
* Options regarding the auto-augmentation feature, which can be used to expand a SATFCServer cache during downtime
*/
@Data
@Builder
public class AutoAugmentOptions {
// How long should the SATFCFacade remain idle before beginning augmentation
private double idleTimeBeforeAugmentation = TimeUnit.MINUTES.convert(5, TimeUnit.SECONDS);
// Turn auto augmnent on / off
private boolean augment = false;
// The station configuration folder with the required files to auto augment from
private String augmentStationConfigurationFolder = null;
// How long to spend on each generated problem before giving up
private double augmentCutoff = TimeUnit.HOURS.convert(3, TimeUnit.SECONDS);
// How often SATFC should poll to see if the facade has been idle
private double pollingInterval = TimeUnit.MINUTES.convert(5, TimeUnit.SECONDS);
}
| 1,865
| 37.081633
| 115
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCCacheAugmenter.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/SATFCCacheAugmenter.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.facade;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.util.UriComponentsBuilder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.CSVStationDB;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.IStationDB;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.IStationSampler;
import ca.ubc.cs.beta.stationpacking.execution.extendedcache.PopulationVolumeSampler;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 15/10/15.
* The goal of this class is to use downtime to augment the cache for the SATFCServer by generating problems that might occur from a given starting point
*/
@Slf4j
public class SATFCCacheAugmenter {
private final SATFCFacade facade;
private volatile InterruptibleSATFCResult currentResult;
private final AtomicBoolean isAugmenting;
public SATFCCacheAugmenter(SATFCFacade facade) {
this.facade = facade;
isAugmenting = new AtomicBoolean(false);
}
/**
* @param stationConfigFolder a station configuration folder also containing a station info and augment domain file
* @param cutoff cutoff to use for augmenting
*/
void augment(String stationConfigFolder, String serverURL, CloseableHttpAsyncClient httpClient, double cutoff) {
final String stationInfoFile = stationConfigFolder + File.separator + "Station_Info.csv";
Preconditions.checkState(new File(stationInfoFile).exists(), "Station info file %s does not exist", stationInfoFile);
final CSVStationDB csvStationDB = new CSVStationDB(stationInfoFile);
// load up domains...
final String cacheDomainFile = stationConfigFolder + File.separator + "Augment_Domains.csv";
Preconditions.checkState(new File(cacheDomainFile).exists(), "Augment domain file %s does not exist", cacheDomainFile);
log.info("Parsing domains from {}", cacheDomainFile);
final IStationManager manager;
try {
manager = new DomainStationManager(cacheDomainFile);
} catch (FileNotFoundException e) {
throw new RuntimeException("Couldn't load domains for augmentation", e);
}
// get a previous assignment from the cache
log.info("Asking cache for last seen SAT assignment");
final Map<Integer, Integer> previousAssignment = getPreviousAssignmentFromCache(serverURL, httpClient);
// now some of the channels from this previous assignment might actually be off domain. If they are, let's assume impairment and fix them
final Map<Integer, Set<Integer>> domains = new HashMap<>();
manager.getStations().forEach(station -> {
domains.put(station.getID(), manager.getDomain(station));
Integer prevChannel = previousAssignment.get(station.getID());
if (prevChannel != null && !manager.getDomain(station).contains(prevChannel)) {
log.debug("Station {} is off of its domain, considered impairing and fixing it to {}", station, prevChannel);
domains.put(station.getID(), Collections.singleton(prevChannel));
}
});
log.info("Going into main augment method");
augment(domains, previousAssignment, csvStationDB, stationConfigFolder, cutoff);
}
private Map<Integer, Integer> getPreviousAssignmentFromCache(String serverURL, CloseableHttpAsyncClient httpClient) {
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(serverURL + "/v1/cache/previousAssignment");
final String uriString = builder.build().toUriString();
final HttpGet httpPost = new HttpGet(uriString);
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<HttpResponse> serverResponse = new AtomicReference<>();
final AtomicReference<Exception> exception = new AtomicReference<>();
httpClient.execute(httpPost, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
log.info("Got back answer from server");
serverResponse.set(result);
latch.countDown();
}
@Override
public void failed(Exception ex) {
exception.set(ex);
latch.countDown();
}
@Override
public void cancelled() {
latch.countDown();
}
});
log.info("Going to sleep");
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
final Exception ex = exception.get();
if (ex != null) {
throw new RuntimeException("Error making web request", ex);
}
final String response;
final Map<Integer, Set<Station>> assignment;
try {
response = EntityUtils.toString(serverResponse.get().getEntity());
assignment = JSONUtils.getMapper().readValue(response, new TypeReference<Map<Integer, Set<Station>>>() {});
} catch (IOException e) {
throw new RuntimeException("Can't parse server result", e);
}
log.info("Back from server");
return StationPackingUtils.stationToChannelFromChannelToStation(assignment).entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey().getID(), Map.Entry::getValue));
}
/**
* @param domains a map taking integer station IDs to set of integer channels domains.
* @param previousAssignment a valid (proved to not create any interference) partial (can concern only some of the provided station) station to channel assignment.
* @param stationConfigFolder a folder in which to find station config data (<i>i.e.</i> interferences and domains files).
* @param cutoff
*/
public void augment(@NonNull Map<Integer, Set<Integer>> domains,
@NonNull Map<Integer, Integer> previousAssignment,
@NonNull IStationDB stationDB,
@NonNull String stationConfigFolder,
double cutoff
) {
// Note that with auto augment, if the stop method is called in the period of time between the scheduler deciding to augment, and setting this isAugmenting variable, this can get stuck in a loop
isAugmenting.set(true);
log.info("Augmenting the following stations {}", previousAssignment.keySet());
// These stations will be in every single problem
final Set<Integer> exitedStations = previousAssignment.keySet();
// Init the station sampler
final IStationSampler sampler = new PopulationVolumeSampler(stationDB, domains.keySet(), RandomUtils.nextInt(0, Integer.MAX_VALUE));
while (isAugmenting.get()) {
log.debug("Starting to augment from the initial state");
// The set of stations that we are going to pack in every problem
final Set<Integer> packingStations = new HashSet<>(exitedStations);
Map<Integer, Integer> currentAssignment = new HashMap<>(previousAssignment);
// Augment
while (isAugmenting.get()) {
// Sample a new station
final Integer sampledStationId = sampler.sample(packingStations);
log.info("Trying to augment station {}", sampledStationId);
packingStations.add(sampledStationId);
final Map<Integer, Set<Integer>> reducedDomains = Maps.filterEntries(domains, new Predicate<Map.Entry<Integer, Set<Integer>>>() {
@Override
public boolean apply(Map.Entry<Integer, Set<Integer>> input) {
return packingStations.contains(input.getKey());
}
});
// Solve!
currentResult = facade.createInterruptibleSATFCResult(reducedDomains, currentAssignment, cutoff, RandomUtils.nextInt(1, Integer.MAX_VALUE), stationConfigFolder, "Augment", true);
final SATFCResult result = currentResult.computeResult();
log.debug("Result is {}", result);
if (result.getResult().equals(SATResult.SAT)) {
// Result was SAT. Let's continue down this trajectory
log.info("Result was SAT. Adding station {} to trajectory", sampledStationId);
currentAssignment = result.getWitnessAssignment();
} else {
log.info("Non-SAT result reached. Restarting from initial state");
// Either UNSAT or TIMEOUT. Time to restart
break;
}
}
}
}
/**
* Stop cache augmentation
*/
public void stop() {
isAugmenting.set(false);
final InterruptibleSATFCResult result = currentResult;
if (result != null) {
result.interrupt();
try {
result.blockUntilTerminated();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
| 11,251
| 45.688797
| 202
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/SolverManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/SolverManager.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.facade.datamanager.solver;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
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.ISolverBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.ISolverBundleFactory;
import lombok.extern.slf4j.Slf4j;
/**
* Manages the solvers & data corresponding to different directories to make sure it is only read once.
*/
@Slf4j
public class SolverManager implements AutoCloseable {
private HashMap<String, ISolverBundle> fSolverData;
private ISolverBundleFactory fSolverBundleFactory;
private DataManager fDataManager;
/**
* Creates a solver manager that will use the given factory to create the solvers when needed.
* @param aSolverBundleFactory a solver bundle factory to create solver bundles.
*/
public SolverManager(ISolverBundleFactory aSolverBundleFactory, DataManager aDataManager) {
fDataManager = aDataManager;
fSolverBundleFactory = aSolverBundleFactory;
fSolverData = new HashMap<>();
}
/**
* Adds the data (domain, interferences) contained in the path and a corresponding new solver to the manager.
* @param path path to add the data from.
* @return true if the data was added and solver created, false if it was already contained.
* @throws FileNotFoundException thrown if a file needed to add the data is not found.
*/
public boolean addData(String path) throws FileNotFoundException
{
log.debug("Adding data from {} to solver manager.",path);
ISolverBundle bundle = fSolverData.get(path);
if (bundle != null)
{
return false;
}
else
{
ManagerBundle dataBundle = fDataManager.getData(path);
ISolverBundle solverbundle = fSolverBundleFactory.getBundle(dataBundle);
fSolverData.put(path, solverbundle);
return true;
}
}
/**
* Returns a solver bundle corresponding to the given directory path. If the bundle does not exist,
* it is added (read) into the manager and then returned.
* @param path path to the directory for which to get the bundle.
* @return a solver bundle corresponding to the given directory path.
* @throws FileNotFoundException thrown if a file needed to add the data is not found.
*/
public ISolverBundle getData(String path) throws FileNotFoundException
{
ISolverBundle bundle = fSolverData.get(path);
if (bundle == null)
{
log.warn("Requested data from {} not available, will try to add it.",path);
addData(path);
bundle = fSolverData.get(path);
}
return bundle;
}
@Override
public void close() throws Exception
{
Set<String> keys = new HashSet<String>(fSolverData.keySet());
for (String path : keys)
{
ISolverBundle bundle = fSolverData.get(path);
bundle.close();
fSolverData.remove(path);
}
}
}
| 3,850
| 33.383929
| 111
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/ISATSolverFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/ISATSolverFactory.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.facade.datamanager.solver.factories;
import ca.ubc.cs.beta.stationpacking.solvers.sat.CompressedSATBasedSolver;
/**
* Created by newmanne on 10/10/15.
*/
public interface ISATSolverFactory {
/**
* @param seedOffset SATFC as a whole takes a given seed. This says how much to offset this particular instance against that seed.
* This allows us to run the same SAT solver with different seeds even though SATFC only takes one seed
*/
CompressedSATBasedSolver create(String params, int seedOffset);
default CompressedSATBasedSolver create(String params) {
return create(params, 0);
};
}
| 1,500
| 34.738095
| 134
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/NativeLibraryGenerator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/NativeLibraryGenerator.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.facade.datamanager.solver.factories;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.common.io.Files;
import com.sun.jna.Library;
import com.sun.jna.Native;
import ca.ubc.cs.beta.stationpacking.utils.NativeUtils;
import lombok.AccessLevel;
import lombok.Getter;
/**
* This class returns a fresh, independent clasp library to each thread
* We need to use this class because clasp is not re-entrant
* Because of the way JNA works, we need a new physical copy of the library each time we launch
* Also note the LD_OPEN options specified to Native.loadLibrary to make sure we use a different in-memory copy each time
*/
public abstract class NativeLibraryGenerator<T extends Library> {
@Getter(AccessLevel.PUBLIC)
private final String libraryPath;
private final Class<T> klazz;
private int numLibs;
private List<File> libFiles;
public NativeLibraryGenerator(String libraryPath, Class<T> klazz) {
this.libraryPath = libraryPath;
this.klazz = klazz;
numLibs = 0;
libFiles = new ArrayList<>();
}
@SuppressWarnings("unchecked")
public T createLibrary() {
File origFile = new File(libraryPath);
try {
File copy = File.createTempFile(Files.getNameWithoutExtension(libraryPath) + "_" + ++numLibs, "." + Files.getFileExtension(libraryPath));
Files.copy(origFile, copy);
copy.deleteOnExit();
libFiles.add(copy);
return (T) Native.loadLibrary(copy.getPath(), klazz, NativeUtils.NATIVE_OPTIONS);
} catch (IOException e) {
throw new RuntimeException("Couldn't create a copy of native library from path " + libraryPath);
}
}
public void notifyShutdown() {
libFiles.forEach(File::delete);
}
}
| 2,701
| 34.090909
| 149
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/Clasp3LibraryGenerator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/Clasp3LibraryGenerator.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.facade.datamanager.solver.factories;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.Clasp3Library;
/**
* Created by newmanne on 03/09/15.
*/
public class Clasp3LibraryGenerator extends NativeLibraryGenerator<Clasp3Library> {
public Clasp3LibraryGenerator(String libraryPath) {
super(libraryPath, Clasp3Library.class);
}
}
| 1,218
| 32.861111
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/PythonInterpreterContainer.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/PythonInterpreterContainer.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.facade.datamanager.solver.factories;
import java.io.File;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import lombok.extern.slf4j.Slf4j;
/**
* Created by emily404 on 9/23/15.
*/
@Slf4j
public class PythonInterpreterContainer {
private final ReadWriteLock fLock = new ReentrantReadWriteLock();
private PythonInterpreter python;
public PythonInterpreterContainer(String interferenceFolder, boolean compact) {
python = new PythonInterpreter();
python.execfile(getClass().getClassLoader().getResourceAsStream("verifier.py"));
String interference = interferenceFolder + File.separator + DataManager.INTERFERENCES_FILE;
String domain = interferenceFolder + "/" + DataManager.DOMAIN_FILE;
String interferenceResult;
if (compact) {
final String compactEvalString = "load_compact_interference(\"" + interference + "\")";
log.debug("Evaluation string feed to Python interpreter: " + compactEvalString);
final PyObject compactReturnObject = python.eval(compactEvalString);
interferenceResult = compactReturnObject.toString();
} else {
final String nonCompactEvalString = "load_interference(\"" + interference + "\")";
log.debug("Evaluation string feed to Python interpreter: " + nonCompactEvalString);
final PyObject nonCompactReturnObject = python.eval(nonCompactEvalString);
interferenceResult = nonCompactReturnObject.toString();
}
final String domainEvalString = "load_domain_csv(\"" + domain + "\")";
final PyObject loadDomainReturnObject = python.eval(domainEvalString);
final String domainResult = loadDomainReturnObject.toString();
if (interferenceResult.equals("0") && domainResult.equals("0")){
log.debug("Interference loaded");
} else {
throw new IllegalStateException("Interference not loaded properly");
}
}
public PyObject eval(String evalString) {
try{
fLock.readLock().lock();
return python.eval(evalString);
} finally {
fLock.readLock().unlock();
}
}
}
| 3,255
| 36.860465
| 99
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/UBCSATLibraryGenerator.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/factories/UBCSATLibraryGenerator.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.facade.datamanager.solver.factories;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.jnalibraries.UBCSATLibrary;
/**
* Created by newmanne on 03/09/15.
*/
public class UBCSATLibraryGenerator extends NativeLibraryGenerator<UBCSATLibrary> {
public UBCSATLibraryGenerator(String libraryPath) {
super(libraryPath, UBCSATLibrary.class);
}
}
| 1,217
| 33.8
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ISolverBundleFactory.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ISolverBundleFactory.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.facade.datamanager.solver.bundles;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.ManagerBundle;
/**
* Factory object for {@link ISolverBundle}.
* @author afrechet
*/
public interface ISolverBundleFactory {
/**
* @param dataBundle manager bundle that contains station manager and constraint manager.
* @return a solver bundle for the provided constraint managers.
*/
public ISolverBundle getBundle(ManagerBundle dataBundle);
}
| 1,311
| 32.641026
| 90
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/YAMLBundle.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/YAMLBundle.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.facade.datamanager.solver.bundles;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeParameter;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.ManagerBundle;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.yaml.*;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.factories.Clasp3LibraryGenerator;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.factories.PythonInterpreterContainer;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.factories.UBCSATLibraryGenerator;
import ca.ubc.cs.beta.stationpacking.polling.IPollingService;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.UNSATLabeller;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.ConstraintGraphNeighborhoodPresolver;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.StationSubsetSATCertifier;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.*;
import ca.ubc.cs.beta.stationpacking.solvers.componentgrouper.ConstraintGrouper;
import ca.ubc.cs.beta.stationpacking.solvers.composites.ISolverFactory;
import ca.ubc.cs.beta.stationpacking.solvers.composites.ParallelNoWaitSolverComposite;
import ca.ubc.cs.beta.stationpacking.solvers.composites.ParallelSolverComposite;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.*;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.cache.CacheResultDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.cache.SubsetCacheUNSATDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.cache.SupersetCacheSATDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.consistency.ArcConsistencyEnforcerDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.consistency.ChannelKillerDecorator;
import ca.ubc.cs.beta.stationpacking.solvers.sat.CompressedSATBasedSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.cnfencoder.SATCompressor;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.AbstractCompressedSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.Clasp3SATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.sat.solvers.nonincremental.ubcsat.UBCSATSolver;
import ca.ubc.cs.beta.stationpacking.solvers.underconstrained.HeuristicUnderconstrainedStationFinder;
import ca.ubc.cs.beta.stationpacking.utils.YAMLUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
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 com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
import com.google.common.base.Joiner;
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 lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.experimental.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import java.io.IOException;
import java.util.*;
/**
* Created by newmanne on 01/10/15.
* Builds a solver bundle based on a YAML file
*/
@Slf4j
public class YAMLBundle extends AVHFUHFSolverBundle {
@Getter
private final ISolver UHFSolver;
@Getter
private final ISolver VHFSolver;
private static boolean skipJython = false;
private final String checkers;
public YAMLBundle(
@NonNull ManagerBundle managerBundle,
@NonNull SATFCFacadeParameter parameter,
@NonNull IPollingService pollingService,
CloseableHttpAsyncClient httpClient
) {
super(managerBundle);
log.info("Using the following variables to build the bundle: configFile={}, serverURL={}, clasp={}, SATenstein={}, resultFile={}", parameter.getConfigFile(), parameter.getServerURL(), parameter.getClaspLibrary(), parameter.getSatensteinLibrary(), parameter.getResultFile());
final SATFCContext context = SATFCContext
.builder()
.managerBundle(managerBundle)
.clasp3LibraryGenerator(new Clasp3LibraryGenerator(parameter.getClaspLibrary()))
.ubcsatLibraryGenerator(new UBCSATLibraryGenerator(parameter.getSatensteinLibrary()))
.parameter(parameter)
.pollingService(pollingService)
.httpClient(httpClient)
.build();
log.info("Reading configuration file {}", parameter.getConfigFile());
final String configYAMLString = parameter.getConfigFile().getFileAsString();
log.trace("Running configuration file through YAML parser to handle anchors...");
// Need to run the text through the YAML class to process YAML anchors properly
final Yaml yaml = new Yaml();
final Map<?, ?> normalized = (Map<?, ?>) yaml.load(configYAMLString);
final String anchoredYAML;
try {
anchoredYAML = YAMLUtils.getMapper().writeValueAsString(normalized);
} catch (JsonProcessingException e) {
throw new RuntimeException("Couldn't parse YAML from file " + parameter.getConfigFile(), e);
}
log.info("Parsing configuration file {}", parameter.getConfigFile());
final YAMLBundleConfig config;
try {
config = YAMLUtils.getMapper().readValue(anchoredYAML, YAMLBundleConfig.class);
} catch (IOException e) {
throw new RuntimeException("Couldn't parse YAML from file " + parameter.getConfigFile(), e);
}
log.info("Configuration parsed! Building solvers...");
final List<ISolverConfig> uhf = config.getUHF();
final List<ISolverConfig> vhf = config.getVHF();
Preconditions.checkState(uhf != null && !uhf.isEmpty(), "No solver provided for UHF in config file %s", parameter.getConfigFile());
Preconditions.checkState(vhf != null && !vhf.isEmpty(), "No solver provided for VHF in config file %s", parameter.getConfigFile());
UHFSolver = concat(uhf, context);
VHFSolver = concat(vhf, context);
checkers = Joiner.on(',').join(context.getSolverTypes());
}
@Override
public String getCheckers() {
return checkers;
}
private static ISolver concat(List<ISolverConfig> configs, SATFCContext context) {
log.debug("Starting with a void solver...");
ISolver solver = new VoidSolver();
for (ISolverConfig config : configs) {
if (!config.shouldSkip(context)) {
log.debug("Decorating with {} using config of type {}", solver.getClass().getSimpleName(), config.getClass().getSimpleName());
solver = config.createSolver(context, solver);
context.getSolverTypes().add(SolverConfigDeserializer.typeToConfigClass.inverse().get(config.getClass()));
} else {
log.debug("Skipping decorator {}", config.getClass().getSimpleName());
}
}
return solver;
}
@Builder
@Data
public static class SATFCContext {
private final Clasp3LibraryGenerator clasp3LibraryGenerator;
private final UBCSATLibraryGenerator ubcsatLibraryGenerator;
private final ManagerBundle managerBundle;
private final SATFCFacadeParameter parameter;
private final IPollingService pollingService;
private final CloseableHttpAsyncClient httpClient;
private PythonInterpreterContainer python;
private final Set<SolverType> solverTypes = new HashSet<>();
}
/**
* Parse out separate configurations for VHF and UHF
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class YAMLBundleConfig {
@JsonProperty("UHF")
private List<ISolverConfig> UHF;
@JsonProperty("VHF")
private List<ISolverConfig> VHF;
}
@Data
public static class ClaspConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
final IConstraintManager constraintManager = context.getManagerBundle().getConstraintManager();
final Clasp3LibraryGenerator clasp3LibraryGenerator = context.getClasp3LibraryGenerator();
final AbstractCompressedSATSolver claspSATsolver = new Clasp3SATSolver(clasp3LibraryGenerator.createLibrary(), config, seedOffset, context.getPollingService(), nickname);
return new CompressedSATBasedSolver(claspSATsolver, new SATCompressor(constraintManager, encodingType));
}
private String config;
private EncodingType encodingType = EncodingType.DIRECT;
private int seedOffset = 0;
private String nickname;
}
@Data
public static class UBCSATConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
final IConstraintManager constraintManager = context.getManagerBundle().getConstraintManager();
final UBCSATLibraryGenerator ubcsatLibraryGenerator = context.getUbcsatLibraryGenerator();
final AbstractCompressedSATSolver ubcsatSolver = new UBCSATSolver(ubcsatLibraryGenerator.createLibrary(), config, seedOffset, context.getPollingService(), nickname);
return new CompressedSATBasedSolver(ubcsatSolver, new SATCompressor(constraintManager, encodingType));
}
private String config;
private EncodingType encodingType = EncodingType.DIRECT;
private int seedOffset = 0;
private String nickname;
}
@Data
public static class AssignmentVerifierConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new AssignmentVerifierDecorator(solverToDecorate, context.getManagerBundle().getConstraintManager(), context.getManagerBundle().getStationManager());
}
}
@Data
public static class PythonVerifierConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new PythonAssignmentVerifierDecorator(solverToDecorate, context.getPython());
}
@Override
public boolean shouldSkip(SATFCContext context) {
if (skipJython) {
return true;
} else {
if (context.getPython() != null) {
return false;
} else {
try {
final PythonInterpreterContainer pythonInterpreterContainer = new PythonInterpreterContainer(context.getManagerBundle().getInterferenceFolder(), context.getManagerBundle().isCompactInterference());
context.setPython(pythonInterpreterContainer);
return false;
} catch (Exception e) {
log.warn("Could not initialize jython. Secondary assignment verifier will be skipped", e);
skipJython = true;
return true;
}
}
}
}
}
@Data
public static class ConnectedComponentsConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ConnectedComponentGroupingDecorator(solverToDecorate, new ConstraintGrouper(), context.getManagerBundle().getConstraintManager(), solveEverything);
}
private boolean solveEverything = false;
}
@Data
public static class ArcConsistencyConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ArcConsistencyEnforcerDecorator(solverToDecorate, context.getManagerBundle().getConstraintManager());
}
}
@EqualsAndHashCode(callSuper = true)
@Data
public static class CacheConfig extends CacheSolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new CacheResultDecorator(solverToDecorate, createContainmentCacheProxy(context), new CacheResultDecorator.CachingStrategy() {
private final CacheResultDecorator.CacheConclusiveNewInfoStrategy strategy = new CacheResultDecorator.CacheConclusiveNewInfoStrategy();
@Override
public boolean shouldCache(SolverResult result) {
if (result.getResult().equals(SATResult.UNSAT) && doNotCacheUNSAT) {
return false;
} else if (result.getResult().equals(SATResult.SAT) && doNotCacheSAT) {
return false;
} else if (result.getRuntime() < minTimeToCache) {
return false;
} else {
return strategy.shouldCache(result);
}
}
});
}
private double minTimeToCache = 0;
private boolean doNotCacheUNSAT = false;
private boolean doNotCacheSAT = false;
}
@EqualsAndHashCode(callSuper = true)
@Data
public static class SATCacheConfig extends CacheSolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new SupersetCacheSATDecorator(solverToDecorate, createContainmentCacheProxy(context));
}
}
@EqualsAndHashCode(callSuper = true)
@Data
public static class UNSATCacheConfig extends CacheSolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new SubsetCacheUNSATDecorator(solverToDecorate, createContainmentCacheProxy(context));
}
}
@Data
public static class UnderconstrainedConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new UnderconstrainedStationRemoverSolverDecorator(solverToDecorate, context.getManagerBundle().getConstraintManager(), new HeuristicUnderconstrainedStationFinder(context.getManagerBundle().getConstraintManager(), expensive), recursive);
}
private boolean expensive = true;
private boolean recursive = true;
}
@Data
public static class ResultSaverConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ResultSaverSolverDecorator(solverToDecorate, context.getParameter().getResultFile());
}
@Override
public boolean shouldSkip(SATFCContext context) {
return context.getParameter().getResultFile() == null;
}
}
@Data
public static class SATPresolver implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ConstraintGraphNeighborhoodPresolver(solverToDecorate,
new StationSubsetSATCertifier(solverConfig.createSolver(context)),
strategy.createStrategy(),
context.getManagerBundle().getConstraintManager());
};
private ISolverConfig solverConfig;
private IStationPackingConfigurationStrategyConfig strategy;
}
@Data
public static class UNSATPresolver implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ConstraintGraphNeighborhoodPresolver(solverToDecorate,
new StationSubsetSATCertifier(solverConfig.createSolver(context)),
strategy.createStrategy(),
context.getManagerBundle().getConstraintManager());
};
private ISolverConfig solverConfig;
private IStationPackingConfigurationStrategyConfig strategy;
}
@Data
public static class ParallelConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
log.debug("Adding a parallel split");
List<ISolverFactory> solverFactories = new ArrayList<>();
for (final List<ISolverConfig> configPath : configs) {
solverFactories.add(aSolver -> concat(configPath, context));
}
if (wait) {
return new ParallelSolverComposite(solverFactories.size(), solverFactories);
} else {
return new ParallelNoWaitSolverComposite(solverFactories.size(), solverFactories);
}
}
private boolean wait = false;
private List<List<ISolverConfig>> configs;
}
@Data
public static class NeighbourLayerConfig implements IStationAddingStrategyConfig {
@Override
public IStationAddingStrategy createStrategy() {
return new AddNeighbourLayerStrategy(numLayers);
}
private int numLayers = Integer.MAX_VALUE;
}
@Data
public static class AddRandomNeighbourConfig implements IStationAddingStrategyConfig {
@Override
public IStationAddingStrategy createStrategy() {
return new AddRandomNeighboursStrategy(numNeighbours);
}
private int numNeighbours;
}
@Data
public static class IterativeDeepeningStrategyConfig implements IStationPackingConfigurationStrategyConfig {
@Override
public IStationPackingConfigurationStrategy createStrategy() {
return new IterativeDeepeningConfigurationStrategy(config.createStrategy(), baseCutoff, scalingFactor);
}
private double scalingFactor;
private double baseCutoff;
private IStationAddingStrategyConfig config;
}
@Data
public static class CNFSaverConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new CNFSaverSolverDecorator(solverToDecorate, context.getManagerBundle().getConstraintManager(), context.getParameter().getCNFSaver(), encodingType, true);
}
@Override
public boolean shouldSkip(SATFCContext context) {
return context.getParameter().getCNFSaver() == null;
}
EncodingType encodingType = EncodingType.DIRECT;
}
@Data
public static class ChannelKillerConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new ChannelKillerDecorator(solverToDecorate, solverConfig.createSolver(context), context.getManagerBundle().getConstraintManager(), time, recurisve);
}
private double time;
private boolean recurisve;
private ISolverConfig solverConfig;
}
@Data
public static class DelayedSolverConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new DelayedSolverDecorator(solverToDecorate, time);
}
private double time;
private double noise;
}
@Data
public static class TimeBoundedSolverConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new TimeBoundedSolverDecorator(solverToDecorate, solverConfig.createSolver(context), time);
}
private ISolverConfig solverConfig;
private double time;
}
@Data
public static class UNSATLabellerConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new UNSATLabeller(solverToDecorate);
}
}
@Data
public static class PreviousAssignmentConfig implements ISolverConfig {
@Override
public ISolver createSolver(SATFCContext context, ISolver solverToDecorate) {
return new PreviousAssignmentContainsAnswerDecorator(solverToDecorate, context.getManagerBundle().getConstraintManager());
}
}
public enum PresolverExpansion {
NEIGHBOURHOOD, UNIFORM_RANDOM
}
public enum TimingChoice {
ITERATIVE_DEEPEN
}
public static abstract class ANameArgsDeserializer<KEYTYPE extends Enum<KEYTYPE>, CLASSTYPE> extends JsonDeserializer<CLASSTYPE> {
@Override
public CLASSTYPE deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode root = p.readValueAsTree();
Preconditions.checkState(root.has("name"), "name is a required field!");
final String name = root.get("name").asText();
final KEYTYPE enumValue = stringToEnum(name);
final Class<? extends CLASSTYPE> targetClass = getMap().get(enumValue);
Preconditions.checkNotNull(targetClass, "No known conversion class for type %s", enumValue);
if (root.has("args")) {
return YAMLUtils.getMapper().treeToValue(root.get("args"), targetClass);
} else {
try {
return targetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Failed to instantiate an instance of " + targetClass.getSimpleName(), e);
}
}
}
protected abstract KEYTYPE stringToEnum(String string);
protected abstract Map<KEYTYPE, Class<? extends CLASSTYPE>> getMap();
}
public static class SolverConfigDeserializer extends ANameArgsDeserializer<SolverType, ISolverConfig> {
public static final BiMap<SolverType, Class<? extends ISolverConfig>> typeToConfigClass =
ImmutableBiMap.<SolverType, Class<? extends ISolverConfig>>builder()
.put(SolverType.CLASP, ClaspConfig.class)
.put(SolverType.SATENSTEIN, UBCSATConfig.class)
.put(SolverType.SAT_PRESOLVER, SATPresolver.class)
.put(SolverType.UNSAT_PRESOLVER, UNSATPresolver.class)
.put(SolverType.UNDERCONSTRAINED, UnderconstrainedConfig.class)
.put(SolverType.CONNECTED_COMPONENTS, ConnectedComponentsConfig.class)
.put(SolverType.ARC_CONSISTENCY, ArcConsistencyConfig.class)
.put(SolverType.VERIFIER, AssignmentVerifierConfig.class)
.put(SolverType.CACHE, CacheConfig.class)
.put(SolverType.SAT_CACHE, SATCacheConfig.class)
.put(SolverType.UNSAT_CACHE, UNSATCacheConfig.class)
.put(SolverType.PARALLEL, ParallelConfig.class)
.put(SolverType.RESULT_SAVER, ResultSaverConfig.class)
.put(SolverType.CNF, CNFSaverConfig.class)
.put(SolverType.PYTHON_VERIFIER, PythonVerifierConfig.class)
.put(SolverType.CHANNEL_KILLER, ChannelKillerConfig.class)
.put(SolverType.DELAY, DelayedSolverConfig.class)
.put(SolverType.TIME_BOUNDED, TimeBoundedSolverConfig.class)
.put(SolverType.PREVIOUS_ASSIGNMENT, PreviousAssignmentConfig.class)
.put(SolverType.UNSAT_LABELLER, UNSATLabellerConfig.class)
.build();
@Override
protected SolverType stringToEnum(String string) {
return SolverType.valueOf(string);
}
@Override
protected Map<SolverType, Class<? extends ISolverConfig>> getMap() {
return typeToConfigClass;
}
}
public static class PresolverConfigurationDeserializer extends ANameArgsDeserializer<TimingChoice, IStationPackingConfigurationStrategyConfig> {
private final Map<TimingChoice, Class<? extends IStationPackingConfigurationStrategyConfig>> typeToConfigClass = ImmutableMap.<TimingChoice, Class<? extends IStationPackingConfigurationStrategyConfig>>builder()
.put(TimingChoice.ITERATIVE_DEEPEN, YAMLBundle.IterativeDeepeningStrategyConfig.class)
.build();
@Override
protected TimingChoice stringToEnum(String string) {
return TimingChoice.valueOf(string);
}
@Override
protected Map<TimingChoice, Class<? extends IStationPackingConfigurationStrategyConfig>> getMap() {
return typeToConfigClass;
}
}
public static class StationAddingStrategyConfigurationDeserializer extends ANameArgsDeserializer<PresolverExpansion, IStationAddingStrategyConfig> {
private final Map<PresolverExpansion, Class<? extends IStationAddingStrategyConfig>> typeToConfigClass = ImmutableMap.<PresolverExpansion, Class<? extends IStationAddingStrategyConfig>>builder()
.put(PresolverExpansion.NEIGHBOURHOOD, NeighbourLayerConfig.class)
.put(PresolverExpansion.UNIFORM_RANDOM, AddRandomNeighbourConfig.class)
.build();
@Override
protected PresolverExpansion stringToEnum(String string) {
return PresolverExpansion.valueOf(string);
}
@Override
protected Map<PresolverExpansion, Class<? extends IStationAddingStrategyConfig>> getMap() {
return typeToConfigClass;
}
}
}
| 27,278
| 40.520548
| 282
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ISolverBundle.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ISolverBundle.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.facade.datamanager.solver.bundles;
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;
/**
* A solver bundle that holds solvers for a specific problem domain.
* Also performs solver selection when queried with a problem instance.
*
* @author afrechet
*/
public interface ISolverBundle extends AutoCloseable {
/**
* @param aInstance - the instance for which a solver is needed.
* @return the solver contained in the bundle for the given instance.
*/
ISolver getSolver(StationPackingInstance aInstance);
/**
* @return the station manager contained in the bundle.
*/
IStationManager getStationManager();
/**
* @return the constraint manager contained in the bundle.
*/
IConstraintManager getConstraintManager();
/**
* Get enabled checkers
*/
default String getCheckers() {
return "";
}
}
| 1,965
| 31.229508
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/AVHFUHFSolverBundle.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/AVHFUHFSolverBundle.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.facade.datamanager.solver.bundles;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.ManagerBundle;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 01/10/15.
*/
@Slf4j
public abstract class AVHFUHFSolverBundle extends ASolverBundle {
public AVHFUHFSolverBundle(ManagerBundle managerBundle) {
super(managerBundle);
}
protected abstract ISolver getUHFSolver();
protected abstract ISolver getVHFSolver();
@Override
public ISolver getSolver(StationPackingInstance aInstance) {
// Return the right solver based on what band the newly added station is in. This doesn't quite work for multi-band problems, but if a VHF problem incorrectly goes to the UHF solver, it will still get solved, so no harm done
if (StationPackingUtils.HVHF_CHANNELS.containsAll(aInstance.getAllChannels()) || StationPackingUtils.LVHF_CHANNELS.containsAll(aInstance.getAllChannels())) {
log.debug("Returning solver configured for VHF");
return getVHFSolver();
} else {
log.debug("Returning solver configured for UHF");
return getUHFSolver();
}
}
@Override
public void close() throws Exception {
getUHFSolver().notifyShutdown();
getVHFSolver().notifyShutdown();
}
}
| 2,347
| 37.491803
| 232
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ASolverBundle.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/ASolverBundle.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.facade.datamanager.solver.bundles;
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.ManagerBundle;
import lombok.extern.slf4j.Slf4j;
/**
* Abstract solver bundles that handles data management.
* @author afrechet
*/
@Slf4j
public abstract class ASolverBundle implements ISolverBundle {
private final ManagerBundle managerBundle;
public ASolverBundle(ManagerBundle managerBundle)
{
this.managerBundle = managerBundle;
}
@Override
public IStationManager getStationManager()
{
return managerBundle.getStationManager();
}
@Override
public IConstraintManager getConstraintManager()
{
return managerBundle.getConstraintManager();
}
}
| 1,679
| 29
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/ISolverConfig.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/ISolverConfig.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.facade.datamanager.solver.bundles.yaml;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.YAMLBundle;
import ca.ubc.cs.beta.stationpacking.solvers.ISolver;
import ca.ubc.cs.beta.stationpacking.solvers.VoidSolver;
/**
* Created by newmanne on 27/10/15.
*/
public interface ISolverConfig {
/**
* Decorate an existing solver with a new solver created from the config object and the context
*/
ISolver createSolver(YAMLBundle.SATFCContext context, ISolver solverToDecorate);
default ISolver createSolver(YAMLBundle.SATFCContext context) {
return createSolver(context, new VoidSolver());
}
/**
* True if the configuration mentioned in the config file should be skipped
*/
default boolean shouldSkip(YAMLBundle.SATFCContext context) { return false; }
}
| 1,676
| 36.266667
| 99
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/ConfigFile.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/ConfigFile.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.facade.datamanager.solver.bundles.yaml;
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import lombok.Data;
/**
* A YAML config file.
* Can either be internal (bundled inside the jar) or external (from the file system)
*/
@Data
public class ConfigFile {
final String fileName;
final boolean internal;
public String getFileAsString() {
try {
if (internal) {
return Resources.toString(Resources.getResource("bundles" + File.separator + fileName + ".yaml"), Charsets.UTF_8);
} else {
return Files.toString(new File(fileName), Charsets.UTF_8);
}
} catch (IOException e) {
throw new IllegalArgumentException("Could not load in config file", e);
}
}
}
| 1,744
| 30.160714
| 130
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/IStationPackingConfigurationStrategyConfig.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/IStationPackingConfigurationStrategyConfig.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.facade.datamanager.solver.bundles.yaml;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.IStationPackingConfigurationStrategy;
/**
* Created by newmanne on 27/10/15.
*/
public interface IStationPackingConfigurationStrategyConfig {
IStationPackingConfigurationStrategy createStrategy();
}
| 1,180
| 35.90625
| 119
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/SolverType.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/SolverType.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.facade.datamanager.solver.bundles.yaml;
/**
* Created by newmanne on 27/10/15.
*/
public enum SolverType {
CLASP,
SATENSTEIN,
SAT_PRESOLVER,
UNSAT_PRESOLVER,
UNDERCONSTRAINED,
CONNECTED_COMPONENTS,
ARC_CONSISTENCY,
PYTHON_VERIFIER,
VERIFIER,
CACHE,
SAT_CACHE,
UNSAT_CACHE,
PARALLEL,
RESULT_SAVER,
CNF,
CHANNEL_KILLER,
DELAY,
TIME_BOUNDED,
PREVIOUS_ASSIGNMENT,
UNSAT_LABELLER, NONE
}
| 1,317
| 25.897959
| 86
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/IStationAddingStrategyConfig.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/IStationAddingStrategyConfig.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.facade.datamanager.solver.bundles.yaml;
import ca.ubc.cs.beta.stationpacking.solvers.certifiers.cgneighborhood.strategies.IStationAddingStrategy;
/**
* Created by newmanne on 27/10/15.
*/
public interface IStationAddingStrategyConfig {
IStationAddingStrategy createStrategy();
}
| 1,138
| 34.59375
| 105
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/CacheSolverConfig.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/CacheSolverConfig.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.facade.datamanager.solver.bundles.yaml;
import ca.ubc.cs.beta.stationpacking.facade.SATFCFacadeParameter;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.solver.bundles.YAMLBundle;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.cache.ContainmentCacheProxy;
/**
* Created by newmanne on 27/10/15.
*/
public abstract class CacheSolverConfig implements ISolverConfig {
@Override
public boolean shouldSkip(YAMLBundle.SATFCContext context) {
return context.getParameter().getServerURL() == null;
}
protected ContainmentCacheProxy createContainmentCacheProxy(YAMLBundle.SATFCContext context) {
final SATFCFacadeParameter parameter = context.getParameter();
return new ContainmentCacheProxy(parameter.getServerURL(), context.getManagerBundle().getCacheCoordinate(), parameter.getNumServerAttempts(), parameter.isNoErrorOnServerUnavailable(), context.getPollingService(), context.getHttpClient());
}
}
| 1,813
| 40.227273
| 246
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/EncodingType.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/solver/bundles/yaml/EncodingType.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.facade.datamanager.solver.bundles.yaml;
/**
* Terminology from Local Search on SAT-Encoded Colouring Problems, Steven Prestwich, http://www.cs.sfu.ca/CourseCentral/827/havens/papers/topic%236(SAT)/steve1.pdf
*/
public enum EncodingType {
DIRECT, MULTIVALUED
}
| 1,120
| 36.366667
| 164
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/data/ManagerBundle.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/data/ManagerBundle.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.facade.datamanager.data;
import com.google.common.collect.ImmutableBiMap;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.cache.CacheCoordinate;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import containmentcache.util.PermutationUtils;
import lombok.Getter;
/**
* Bundle object containing a station and a constraint manager.
*/
public class ManagerBundle {
@Getter
private IStationManager stationManager;
@Getter
private IConstraintManager constraintManager;
@Getter
private final String interferenceFolder;
@Getter
private CacheCoordinate cacheCoordinate;
@Getter
private final ImmutableBiMap<Station, Integer> permutation;
/**
* Creates a new bundle containing the given station and constraint manager.
* @param stationManager station manager to be bundled.
* @param constraintManager constraint manager to be bundled.
*/
public ManagerBundle(IStationManager stationManager, IConstraintManager constraintManager, String interferenceFolder) {
this.stationManager = stationManager;
this.constraintManager = constraintManager;
this.interferenceFolder = interferenceFolder;
cacheCoordinate = new CacheCoordinate(stationManager.getDomainHash(), constraintManager.getConstraintHash());
permutation = PermutationUtils.makePermutation(getStationManager().getStations());
}
public boolean isCompactInterference() {
return getConstraintManager() instanceof ChannelSpecificConstraintManager;
}
}
| 2,546
| 36.455882
| 120
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/data/DataManager.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/facade/datamanager/data/DataManager.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.facade.datamanager.data;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Preconditions;
import ca.ubc.cs.beta.stationpacking.cache.CacheCoordinate;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.ChannelSpecificConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.IConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.constraints.UnabridgedFormatConstraintManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.DomainStationManager;
import ca.ubc.cs.beta.stationpacking.datamanagers.stations.IStationManager;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Manages the data contained in different station config directories to make sure they are only read once.
* @author afrechet
*/
@Slf4j
public class DataManager {
/**
* File path suffix for a (station config / interference) domain file.
*/
public static String DOMAIN_FILE = "Domain.csv";
/**
* File path suffix for a (station config / interference) interference constraints file.
*/
public static String INTERFERENCES_FILE = "Interference_Paired.csv";
private HashMap<String, ManagerBundle> fData;
@Getter
private Map<CacheCoordinate, ManagerBundle> coordinateToBundle;
/**
* Create a new (empty) data manager.
*/
public DataManager()
{
fData = new HashMap<>();
coordinateToBundle = new HashMap<>();
}
public void loadMultipleConstraintSets(String constraintFolder) {
log.info("Looking in {} for station configuration folders", constraintFolder);
final File[] stationConfigurationFolders = new File(constraintFolder).listFiles(File::isDirectory);
log.info("Found {} station configuration folders", stationConfigurationFolders.length);
Arrays.stream(stationConfigurationFolders).forEach(folder -> {
try {
final String path = folder.getAbsolutePath();
log.info("Adding data for station configuration folder {}", path);
addData(folder.getAbsolutePath());
// add cache coordinate to map
final ManagerBundle bundle = getData(folder.getAbsolutePath());
log.info("Folder {} corresponds to coordinate {}", folder.getAbsolutePath(), bundle.getCacheCoordinate());
} catch (FileNotFoundException e) {
throw new IllegalStateException(folder.getAbsolutePath() + " is not a valid station configuration folder (missing Domain or Interference files?)", e);
}
});
}
/**
* Adds the data contained in the path to the data manager. True if the data was added, false
* if it was already contained.
* @param path to the folder where the data to add is contained.
* @return true if the data was added, false if it was already contained.
* @throws FileNotFoundException thrown if a file needed to add the data is not found.
*/
public boolean addData(String path) throws FileNotFoundException
{
ManagerBundle bundle = fData.get(path);
if (bundle != null)
{
return false;
}
else
{
final IStationManager stationManager = new DomainStationManager(path + File.separator + DOMAIN_FILE);
final IConstraintManager constraintManager;
//Try parsing unabridged.
Exception uaE = null;
IConstraintManager unabridgedConstraintManager = null;
try
{
unabridgedConstraintManager= new UnabridgedFormatConstraintManager(stationManager, path + File.separator + INTERFERENCES_FILE);
}
catch(Exception e)
{
uaE = e;
}
//Try parsing channel specific.
Exception csE = null;
IConstraintManager channelspecificConstraintManager = null;
try
{
channelspecificConstraintManager= new ChannelSpecificConstraintManager(stationManager, path + File.separator + INTERFERENCES_FILE);
}
catch(Exception e)
{
csE = e;
}
if(uaE != null && csE != null)
{
log.error("Could not parse interference data both in unabridged and channel specific formats.");
log.error("Unabridged format exception:",uaE);
log.error("Channel specific format exception:",csE);
throw new IllegalArgumentException("Unrecognized interference constraint format.");
}
else if(uaE == null && csE == null)
{
throw new IllegalStateException("Provided interference constraint format satisfies both unabridged and channel specific formats.");
}
else if(uaE == null)
{
log.info("Unabridged format recognized for interference constraints.");
constraintManager = unabridgedConstraintManager;
}
else {
log.info("Channel specific format recognized for interference constraints.");
constraintManager = channelspecificConstraintManager;
}
final ManagerBundle managerBundle = new ManagerBundle(stationManager, constraintManager, path);
fData.put(path, managerBundle);
coordinateToBundle.put(managerBundle.getCacheCoordinate(), managerBundle);
return true;
}
}
/**
* Returns a manager bundle corresponding to the given directory path. If the bundle does not exist,
* it is added (read) into the data manager and then returned.
* @param path path to the directory for which to get the bundle.
* @return a manager bundle corresponding to the given directory path.
* @throws FileNotFoundException thrown if a file needed to add the data is not found.
*/
public ManagerBundle getData(String path) throws FileNotFoundException
{
ManagerBundle bundle = fData.get(path);
if (bundle == null)
{
addData(path);
bundle = fData.get(path);
}
return bundle;
}
public ManagerBundle getData(CacheCoordinate coordinate) {
ManagerBundle bundle = coordinateToBundle.get(coordinate);
Preconditions.checkNotNull(bundle, "Unknown coordinate %s, known coordinates %s", coordinate, coordinateToBundle.keySet());
return bundle;
}
}
| 6,670
| 34.110526
| 154
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/ProblemIncrementor.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/ProblemIncrementor.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.polling;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.ISATFCInterruptible;
import ca.ubc.cs.beta.stationpacking.solvers.termination.ITerminationCriterion;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 15/10/15.
* Some SATFC methods delve into long blocks of code that will not periodically check for interrupt signals (because we didn't write them). However, often these code blocks expose an interrupt mechanism.
* This class provides an easy way to poll periodically to see if you should trigger this interrupt signal
*/
@Slf4j
public class ProblemIncrementor {
public static final int POLLING_TIME_IN_MS = 1000;
// A constantly increasing value that identifies the current problem being solved
private final AtomicLong problemID;
private final IPollingService pollingService;
private final Map<Long, ScheduledFuture<?>> idToFuture;
private final ISATFCInterruptible solver;
private final Lock lock;
public ProblemIncrementor(@NonNull IPollingService pollingService, @NonNull ISATFCInterruptible solver) {
this.solver = solver;
problemID = new AtomicLong();
this.pollingService = pollingService;
idToFuture = new HashMap<>();
lock = new ReentrantLock();
}
/**
* Call this method to schedule a task to periodically poll for whether or not the termination criterion says to stop. If it does, interrupt the solver.
* Must alternate calls between this and @link{#jobDone} to cancel the polling when the problem in question is finished solving
* @param criterion termination criterion to check
*/
public void scheduleTermination(ITerminationCriterion criterion) {
final long newProblemId = problemID.incrementAndGet();
log.trace("New problem ID {}", newProblemId);
final ScheduledFuture<?> scheduledFuture = pollingService.getService().scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
lock.lock();
long currentProblemId = problemID.get();
log.trace("Problem id is {} and we are {}", currentProblemId, newProblemId);
if (criterion.hasToStop() && currentProblemId == newProblemId) {
log.trace("Interupting problem {}", currentProblemId);
solver.interrupt();
}
} catch (Throwable t) {
log.error("Caught exception in ScheduledExecutorService for interrupting problem", t);
} finally {
lock.unlock();
}
}
}, POLLING_TIME_IN_MS, POLLING_TIME_IN_MS, TimeUnit.MILLISECONDS);
idToFuture.put(newProblemId, scheduledFuture);
}
/**
* Cancel polling for the current job
*/
public void jobDone() {
try {
lock.lock();
final long completedJobID = problemID.getAndIncrement();
final ScheduledFuture scheduledFuture = idToFuture.remove(completedJobID);
if (scheduledFuture != null) {
log.trace("Cancelling future for completed ID {}", completedJobID);
scheduledFuture.cancel(false);
}
} finally {
lock.unlock();
}
}
}
| 4,491
| 39.836364
| 202
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/PollingService.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/PollingService.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.polling;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import ca.ubc.cs.beta.aeatk.concurrent.threadfactory.SequentiallyNamedThreadFactory;
/**
* Created by newmanne on 15/10/15.
*/
public class PollingService implements IPollingService {
private final ScheduledExecutorService scheduledExecutorService;
public PollingService() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new SequentiallyNamedThreadFactory("SATFC Interrupt Polling"));
}
@Override
public ScheduledExecutorService getService() {
return scheduledExecutorService;
}
@Override
public void notifyShutdown() {
scheduledExecutorService.shutdown();
}
}
| 1,609
| 29.961538
| 141
|
java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/IPollingService.java
|
SATFC-release/satfc/src/main/java/ca/ubc/cs/beta/stationpacking/polling/IPollingService.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.polling;
import java.util.concurrent.ScheduledExecutorService;
/**
* Created by newmanne on 15/10/15.
* Wrapper to hold a ScheduledExecutor for polling jobs
*/
public interface IPollingService {
ScheduledExecutorService getService();
void notifyShutdown();
}
| 1,125
| 29.432432
| 86
|
java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/SATFCServerApplication.java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/SATFCServerApplication.java
|
/**
* Copyright 2015, 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.webapp;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.Filter;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.containment.transformer.ICacheEntryTransformer;
import ca.ubc.cs.beta.stationpacking.cache.containment.transformer.UHFRestrictionTransformer;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.ReflectionUtils;
import com.beust.jcommander.Parameter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlets.MetricsServlet;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import ca.ubc.cs.beta.aeatk.misc.jcommander.JCommanderHelper;
import ca.ubc.cs.beta.stationpacking.cache.ICacheEntryFilter;
import ca.ubc.cs.beta.stationpacking.cache.ICacheLocator;
import ca.ubc.cs.beta.stationpacking.cache.ISatisfiabilityCacheFactory;
import ca.ubc.cs.beta.stationpacking.cache.NewInfoEntryFilter;
import ca.ubc.cs.beta.stationpacking.cache.RedisCacher;
import ca.ubc.cs.beta.stationpacking.cache.SatisfiabilityCacheFactory;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import ca.ubc.cs.beta.stationpacking.webapp.filters.GzipRequestFilter;
import ca.ubc.cs.beta.stationpacking.webapp.parameters.SATFCServerParameters;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.JedisShardInfo;
/**
* Created by newmanne on 23/03/15.
*/
@Slf4j
@EnableScheduling
@SpringBootApplication
public class SATFCServerApplication {
private final static SATFCServerParameters parameters = new SATFCServerParameters();
public static void main(String[] args) {
// Jcommander will throw an exception if it sees parameters it does not know about, but these are possibly spring boot commands
final List<String> jcommanderArgs = new ArrayList<>();
final List<String> jcommanderFields = Lists.newArrayList("--help");
ReflectionUtils.doWithFields(SATFCServerParameters.class, field -> {
final Parameter annotation = field.getAnnotation(Parameter.class);
if (annotation != null) {
Collections.addAll(jcommanderFields, annotation.names());
}
});
for (String arg : args) {
for (String jcommanderField : jcommanderFields) {
final String[] split = arg.split("=");
if (split.length > 0 && split[0].equals(jcommanderField)) {
jcommanderArgs.add(arg);
break;
}
}
}
// Even though spring has its own parameter parsing, JComamnder gives tidier error messages
JCommanderHelper.parseCheckingForHelpAndVersion(jcommanderArgs.toArray(new String[jcommanderArgs.size()]), parameters);
parameters.validate();
log.info("Using the following command line parameters " + System.lineSeparator() + parameters.toString());
SpringApplication.run(SATFCServerApplication.class, args);
}
@Autowired
MetricRegistry registry;
@Bean
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
final ObjectMapper mapper = JSONUtils.getMapper();
mappingJacksonHttpMessageConverter.setObjectMapper(mapper);
return mappingJacksonHttpMessageConverter;
}
@Bean
RedisConnectionFactory redisConnectionFactory() {
return new JedisConnectionFactory(getShardInfo());
}
private JedisShardInfo getShardInfo() {
final SATFCServerParameters satfcServerParameters = satfcServerParameters();
final int timeout = (int) TimeUnit.SECONDS.toMillis(60);
return new JedisShardInfo(satfcServerParameters.getRedisURL(), satfcServerParameters.getRedisPort(), timeout);
}
@Bean
BinaryJedis binaryJedis() {
return new BinaryJedis(getShardInfo());
}
@Bean
RedisCacher cacher() {
return new RedisCacher(dataManager(), redisTemplate(), binaryJedis());
}
@Bean
StringRedisTemplate redisTemplate() {
return new StringRedisTemplate(redisConnectionFactory());
}
@Bean
ICacheLocator containmentCacheLocator() {
return new CacheLocator(satisfiabilityCacheFactory(), parameters);
}
@Bean
ISatisfiabilityCacheFactory satisfiabilityCacheFactory() {
final SATFCServerParameters satfcServerParameters = satfcServerParameters();
return new SatisfiabilityCacheFactory(satfcServerParameters.getNumPermutations(), satfcServerParameters.getSeed());
}
@Bean
DataManager dataManager() {
return new DataManager();
}
@Bean
SATFCServerParameters satfcServerParameters() {
return parameters;
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new MetricsServlet(registry), "/metrics/extra/*");
}
@Bean
public Filter gzipFilter() {
// Apply a filter to decompress incoming compressed requests
return new GzipRequestFilter();
}
@Bean
public ICacheEntryFilter cacheScreener() {
final ICacheEntryFilter screener;
final SATFCServerParameters parameters = satfcServerParameters();
switch (parameters.getCacheScreenerChoice()) {
case NEW_INFO:
screener = new NewInfoEntryFilter(containmentCacheLocator());
break;
case ADD_EVERYTHING:
screener = (coordinate, instance, result) -> true;
break;
case ADD_NOTHING:
screener = (coordinate, instance, result) -> false;
break;
default:
throw new IllegalStateException("Unrecognized value for " + parameters.getCacheScreenerChoice());
}
return screener;
}
@Bean
public ICacheEntryTransformer cacheEntryTransformer() {
final SATFCServerParameters parameters = satfcServerParameters();
return parameters.isCacheUHFOnly() ? new UHFRestrictionTransformer() : x -> x;
}
}
| 7,905
| 38.728643
| 135
|
java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/CacheLocator.java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/CacheLocator.java
|
/**
* Copyright 2015, 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.webapp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import com.google.common.collect.ImmutableSet;
import ca.ubc.cs.beta.stationpacking.cache.CacheCoordinate;
import ca.ubc.cs.beta.stationpacking.cache.ICacheLocator;
import ca.ubc.cs.beta.stationpacking.cache.ISatisfiabilityCacheFactory;
import ca.ubc.cs.beta.stationpacking.cache.RedisCacher;
import ca.ubc.cs.beta.stationpacking.cache.RedisCacher.ContainmentCacheInitData;
import ca.ubc.cs.beta.stationpacking.cache.containment.containmentcache.ISatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.webapp.parameters.SATFCServerParameters;
import lombok.extern.slf4j.Slf4j;
import net.jcip.annotations.ThreadSafe;
/**
* Created by newmanne on 25/03/15.
*/
@Slf4j
@ThreadSafe
public class CacheLocator implements ICacheLocator, ApplicationListener<ContextRefreshedEvent> {
private final Map<CacheCoordinate, ISatisfiabilityCache> caches;
private final ISatisfiabilityCacheFactory cacheFactory;
private final SATFCServerParameters parameters;
public CacheLocator(ISatisfiabilityCacheFactory cacheFactory, SATFCServerParameters parameters) {
this.cacheFactory = cacheFactory;
this.parameters = parameters;
caches = new HashMap<>();
}
@Override
public ISatisfiabilityCache locate(CacheCoordinate coordinate) {
ISatisfiabilityCache cache = caches.get(coordinate);
if (cache == null) {
throw new IllegalStateException("No cache was made for coordinate " + coordinate + ". Was the corresponding station configuration folder present at server start up?");
}
return cache;
}
// We want this to happen after the context has been brought up (so the error messages aren't horrific)
// Uses the context to pull out beans / command line arguments
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
final ApplicationContext context = event.getApplicationContext();
final RedisCacher cacher = context.getBean(RedisCacher.class);
final DataManager dataManager = context.getBean(DataManager.class);
// Set up the data manager
final String constraintFolder = parameters.getConstraintFolder();
dataManager.loadMultipleConstraintSets(constraintFolder);
log.info("Beginning to init caches");
final ContainmentCacheInitData containmentCacheInitData = cacher.getContainmentCacheInitData(parameters.getCacheSizeLimit(), parameters.isSkipSAT(), parameters.isSkipUNSAT(), parameters.isValidateSAT());
dataManager.getCoordinateToBundle().keySet().forEach(cacheCoordinate -> {
final ISatisfiabilityCache cache = cacheFactory.create(dataManager.getData(cacheCoordinate).getPermutation());
log.info("Cache created for coordinate " + cacheCoordinate);
caches.put(cacheCoordinate, cache);
if (containmentCacheInitData.getCaches().contains(cacheCoordinate)) {
cache.addAllSAT(containmentCacheInitData.getSATResults().get(cacheCoordinate));
cache.addAllUNSAT(containmentCacheInitData.getUNSATResults().get(cacheCoordinate));
}
});
}
@Override
public Set<CacheCoordinate> getCoordinates() {
return ImmutableSet.copyOf(caches.keySet());
}
}
| 4,424
| 42.382353
| 211
|
java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/rest/ContainmentCacheController.java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/rest/ContainmentCacheController.java
|
/**
* Copyright 2015, 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.webapp.rest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.annotation.PostConstruct;
import ca.ubc.cs.beta.stationpacking.cache.containment.transformer.ICacheEntryTransformer;
import ca.ubc.cs.beta.stationpacking.cache.containment.transformer.InstanceAndResult;
import ca.ubc.cs.beta.stationpacking.utils.StationPackingUtils;
import com.google.common.collect.Maps;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.Timer;
import com.google.common.collect.Queues;
import ca.ubc.cs.beta.stationpacking.base.Station;
import ca.ubc.cs.beta.stationpacking.base.StationPackingInstance;
import ca.ubc.cs.beta.stationpacking.cache.ICacheEntryFilter;
import ca.ubc.cs.beta.stationpacking.cache.ICacheLocator;
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.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.cache.containment.containmentcache.ISatisfiabilityCache;
import ca.ubc.cs.beta.stationpacking.facade.datamanager.data.DataManager;
import ca.ubc.cs.beta.stationpacking.solvers.base.SATResult;
import ca.ubc.cs.beta.stationpacking.solvers.base.SolverResult;
import ca.ubc.cs.beta.stationpacking.solvers.decorators.cache.ContainmentCacheProxy.ContainmentCacheRequest;
import ca.ubc.cs.beta.stationpacking.webapp.parameters.SATFCServerParameters;
import lombok.extern.slf4j.Slf4j;
@Controller
@Slf4j
@RequestMapping("/v1/cache")
public class ContainmentCacheController {
private final String JSON_CONTENT = "application/json";
@Autowired
ICacheLocator containmentCacheLocator;
@Autowired
RedisCacher cacher;
@Autowired
SATFCServerParameters parameters;
@Autowired
ICacheEntryFilter cacheEntryFilter;
@Autowired
ICacheEntryTransformer cacheEntryTransformer;
@Autowired
DataManager dataManager;
// Metrics
@Autowired
MetricRegistry registry;
private Meter cacheAdditions;
private Meter satCacheHits;
private Timer satCacheTimer;
private Meter unsatCacheHits;
private Timer unsatCacheTimer;
private volatile Map<Integer, Set<Station>> lastCachedAssignment = new HashMap<>();
private final Queue<ContainmentCacheRequest> pendingCacheAdditions = Queues.newArrayDeque();
@PostConstruct
void init() {
cacheAdditions = registry.meter("cache.sat.additions");
satCacheHits = registry.meter("cache.sat.hits");
satCacheTimer = registry.timer("cache.sat.timer");
unsatCacheHits = registry.meter("cache.unsat.hits");
unsatCacheTimer = registry.timer("cache.unsat.timer");
registry.register("cache.sat.hitrate.fifteenminute", new RatioGauge() {
@Override
protected Ratio getRatio() {
return Ratio.of(satCacheHits.getFifteenMinuteRate(), satCacheTimer.getFifteenMinuteRate());
}
});
registry.register("cache.unsat.hitrate.fifteenminute", new RatioGauge() {
@Override
protected Ratio getRatio() {
return Ratio.of(unsatCacheHits.getFifteenMinuteRate(), unsatCacheTimer.getFifteenMinuteRate());
}
});
registry.register("cache.sat.hitrate.overall", new RatioGauge() {
@Override
protected Ratio getRatio() {
return Ratio.of(satCacheHits.getCount(), satCacheTimer.getCount());
}
});
registry.register("cache.unsat.hitrate.overall", new RatioGauge() {
@Override
protected Ratio getRatio() {
return Ratio.of(unsatCacheHits.getCount(), unsatCacheTimer.getCount());
}
});
}
@ExceptionHandler(ClientAbortException.class)
void clientAbortException() {
// Nothing to do
log.trace("ClientAbortException ignored because it is expected behavior");
}
// note that while this is conceptually a GET request, the fact that we need to send json means that its simpler to achieve as a POST
@RequestMapping(value = "/query/SAT", method = RequestMethod.POST, produces = JSON_CONTENT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ContainmentCacheSATResult lookupSAT(
@RequestBody final ContainmentCacheRequest request
) {
final Timer.Context context = satCacheTimer.time();
try {
final StationPackingInstance instance = request.getInstance();
final String description = instance.hasName() ? instance.getName() : instance.getInfo();
log.info("Querying the SAT cache with coordinate {} for entry {}", request.getCoordinate(), description);
final ISatisfiabilityCache cache = containmentCacheLocator.locate(request.getCoordinate());
final ContainmentCacheSATResult containmentCacheSATResult;
if (parameters.getBadsets() != null) {
final Map<String, Set<String>> badsets = parameters.getBadsets();
final String auction = instance.getAuction();
containmentCacheSATResult = cache.proveSATBySuperset(instance, c -> {
if (c.getAuction() != null && auction != null) {
return !badsets.get(auction).contains(c.getAuction());
}
return true;
});
} else if (parameters.isExcludeSameAuction()) {
final String auction = instance.getAuction();
containmentCacheSATResult = cache.proveSATBySuperset(instance, c -> {
if (c.getAuction() != null && auction != null) {
return !c.getAuction().equals(auction);
}
return true;
});
} else {
containmentCacheSATResult = cache.proveSATBySuperset(instance);
}
if (containmentCacheSATResult.isValid()) {
log.info("Query for SAT cache with coordinate {} for entry {} is a hit", request.getCoordinate(), description);
satCacheHits.mark();
} else {
log.info("Query for SAT cache with coordinate {} for entry {} is a miss", request.getCoordinate(), description);
}
return containmentCacheSATResult;
} finally {
context.stop();
}
}
// note that while this is conceptually a GET request, the fact that we need to send json means that its simpler to achieve as a POST
@RequestMapping(value = "/query/UNSAT", method = RequestMethod.POST, produces = JSON_CONTENT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ContainmentCacheUNSATResult lookupUNSAT(
@RequestBody final ContainmentCacheRequest request
) {
final Timer.Context context = unsatCacheTimer.time();
try {
final StationPackingInstance instance = request.getInstance();
final String description = instance.hasName() ? instance.getName() : instance.getInfo();
log.info("Querying the UNSAT cache with coordinate {} for entry {}", request.getCoordinate(), description);
final ISatisfiabilityCache cache = containmentCacheLocator.locate(request.getCoordinate());
final ContainmentCacheUNSATResult result = cache.proveUNSATBySubset(instance);
if (result.isValid()) {
log.info("Query for UNSAT cache with coordinate {} for entry {} is a hit", request.getCoordinate(), description);
unsatCacheHits.mark();
} else {
log.info("Query for UNSAT cache with coordinate {} for entry {} is a miss", request.getCoordinate(), description);
}
return result;
} finally {
context.stop();
}
}
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void cache(
@RequestBody final ContainmentCacheRequest request
) {
// Just dump the entry and return - we don't want to delay the SATFC thread
pendingCacheAdditions.add(request);
}
@Scheduled(fixedDelay = 5000, initialDelay = 5000)
public void addCacheEntries() {
log.debug("Waking up to check list of potential cache additions");
while (!pendingCacheAdditions.isEmpty()) {
final ContainmentCacheRequest request = pendingCacheAdditions.poll();
final SolverResult result = request.getResult();
if ((result.getResult().equals(SATResult.UNSAT) && parameters.isSkipUNSAT()) || result.getResult().equals(SATResult.SAT) && parameters.isSkipSAT()) {
continue;
}
final StationPackingInstance instance = request.getInstance();
final String description = instance.hasName() ? instance.getName() : instance.getInfo();
final ISatisfiabilityCache cache = containmentCacheLocator.locate(request.getCoordinate());
final InstanceAndResult transformedInstanceAndResult = cacheEntryTransformer.transform(instance, result);
if (transformedInstanceAndResult != null) {
final StationPackingInstance transformedInstance = transformedInstanceAndResult.getInstance();
final SolverResult transformedResult = transformedInstanceAndResult.getResult();
if (cacheEntryFilter.shouldCache(request.getCoordinate(), transformedInstance, transformedResult)) {
final String key;
if (result.getResult().equals(SATResult.SAT)) {
final ContainmentCacheSATEntry entry = new ContainmentCacheSATEntry(transformedResult.getAssignment(), cache.getPermutation());
key = cacher.cacheResult(request.getCoordinate(), entry, transformedInstance.hasName() ? transformedInstance.getName() : null);
entry.setKey(key);
cache.add(entry);
lastCachedAssignment = transformedResult.getAssignment();
} else if (result.getResult().equals(SATResult.UNSAT)) {
final ContainmentCacheUNSATEntry entry = new ContainmentCacheUNSATEntry(transformedInstance.getDomains(), cache.getPermutation());
cache.add(entry);
key = cacher.cacheResult(request.getCoordinate(), entry, transformedInstance.hasName() ? transformedInstance.getName() : null);
entry.setKey(key);
} else {
throw new IllegalStateException("Tried adding a result that was neither SAT or UNSAT");
}
log.info("Adding entry to the cache with coordinate {} with key {}. Entry {}", request.getCoordinate(), key, description);
// add to permanent storage
cacheAdditions.mark();
} else {
log.info("Not adding entry {} to cache {}. No new info", request.getCoordinate(), description);
}
}
}
log.debug("Done checking potential cache additions");
}
@RequestMapping(value = "/filterSAT", method = RequestMethod.POST)
@ResponseBody
public void filterSATCache(@RequestParam(value = "strong", required = false, defaultValue = "true") boolean strong) {
containmentCacheLocator.getCoordinates().forEach(cacheCoordinate -> {
log.info("Finding SAT entries to be filtered at cacheCoordinate {} ({})", cacheCoordinate, strong);
final ISatisfiabilityCache cache = containmentCacheLocator.locate(cacheCoordinate);
List<ContainmentCacheSATEntry> SATPrunables = cache.filterSAT(dataManager.getData(cacheCoordinate).getStationManager(), strong);
log.info("Pruning {} SAT entries from Redis", SATPrunables.size());
cacher.deleteSATCollection(SATPrunables);
});
log.info("Filter completed");
}
@RequestMapping(value = "/filterUNSAT", method = RequestMethod.POST)
@ResponseBody
public void filterUNSATCache() {
containmentCacheLocator.getCoordinates().forEach(cacheCoordinate -> {
log.info("Finding UNSAT entries to be filtered at cacheCoordinate {}", cacheCoordinate);
final ISatisfiabilityCache cache = containmentCacheLocator.locate(cacheCoordinate);
final List<ContainmentCacheUNSATEntry> UNSATPrunables = cache.filterUNSAT();
log.info("Pruning {} UNSAT entries from Redis", UNSATPrunables.size());
cacher.deleteUNSATCollection(UNSATPrunables);
});
log.info("Filter completed");
}
/**
* Return the last solved SAT problem you know about
*/
@RequestMapping(value = "/previousAssignment", method = RequestMethod.GET)
@ResponseBody
public Map<Integer, Set<Station>> getPreviousAssignment() {
log.info("Returning the last cached SAT assignment");
return lastCachedAssignment;
}
/**
* Return the number of entries waiting to be filtered into the cache
*/
@RequestMapping(value = "/n_pending_additions", method = RequestMethod.GET)
@ResponseBody
public int getNumFiltering() {
return pendingCacheAdditions.size();
}
}
| 15,237
| 46.61875
| 161
|
java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/filters/GzipRequestFilter.java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/filters/GzipRequestFilter.java
|
package ca.ubc.cs.beta.stationpacking.webapp.filters;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.util.zip.GZIPInputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.http.protocol.HTTP;
import lombok.extern.slf4j.Slf4j;
/**
* Created by newmanne on 27/10/15.
* see http://stackoverflow.com/questions/20507007/http-request-compression
*/
@Slf4j
public class GzipRequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
final String contentEncoding = request.getHeader(HTTP.CONTENT_ENCODING);
if (contentEncoding != null && contentEncoding.contains("gzip")) {
log.trace("gzip request detected");
try {
final InputStream decompressStream = decompressStream(request.getInputStream());
req = new HttpServletRequestWrapper(request) {
@Override
public ServletInputStream getInputStream() throws IOException {
return new DecompressServletInputStream(decompressStream);
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(decompressStream));
}
};
} catch (IOException e) {
log.error("Error while handling a gzip request", e);
}
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
public static class DecompressServletInputStream extends ServletInputStream {
private InputStream inputStream;
public DecompressServletInputStream(InputStream input) {
inputStream = input;
}
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
try {
return inputStream.available() == 0;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
throw new UnsupportedOperationException();
}
}
/**
* Gzip magic number, fixed values in the beginning to identify the gzip
* format <br>
* http://www.gzip.org/zlib/rfc-gzip.html#file-format
*/
private static final byte GZIP_ID1 = 0x1f;
/**
* Gzip magic number, fixed values in the beginning to identify the gzip
* format <br>
* http://www.gzip.org/zlib/rfc-gzip.html#file-format
*/
private static final byte GZIP_ID2 = (byte) 0x8b;
/**
* Return decompression input stream if needed.
*
* @param input original stream
* @return decompression stream
* @throws IOException exception while reading the input
*/
public static InputStream decompressStream(InputStream input) throws IOException {
PushbackInputStream pushbackInput = new PushbackInputStream(input, 2);
byte[] signature = new byte[2];
pushbackInput.read(signature);
pushbackInput.unread(signature);
if (signature[0] == GZIP_ID1 && signature[1] == GZIP_ID2) {
return new GZIPInputStream(pushbackInput);
}
return pushbackInput;
}
}
| 4,315
| 30.05036
| 123
|
java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/parameters/SATFCServerParameters.java
|
SATFC-release/satfcserver/src/main/java/ca/ubc/cs/beta/stationpacking/webapp/parameters/SATFCServerParameters.java
|
package ca.ubc.cs.beta.stationpacking.webapp.parameters;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Preconditions;
import com.google.common.io.Files;
import ca.ubc.cs.beta.aeatk.misc.options.UsageTextField;
import ca.ubc.cs.beta.aeatk.options.AbstractOptions;
import ca.ubc.cs.beta.stationpacking.utils.JSONUtils;
import lombok.Getter;
import lombok.ToString;
/**
* Created by newmanne on 30/06/15.
*/
@ToString
@Parameters(separators = "=")
@UsageTextField(title="SATFCServer Parameters",description="Parameters needed to build SATFCServer")
public class SATFCServerParameters extends AbstractOptions {
@Parameter(names = "--redis.host", description = "host for redis")
@Getter
private String redisURL = "localhost";
@Parameter(names = "--redis.port", description = "port for redis")
@Getter
private int redisPort = 6379;
@Parameter(names = "--constraint.folder", description = "Folder containing all of the station configuration folders", required = true)
@Getter
private String constraintFolder;
@Parameter(names = "--seed", description = "Random seed")
@Getter
private long seed = 1;
@Parameter(names = "--cache.permutations", description = "The number of permutations for the containment cache to use. Higher numbers yield better performance with large caches, but are more memory expensive")
@Getter
private int numPermutations = 1;
@Parameter(names = "--cache.size.limit", description = "Only use the first limit entries from the cache", hidden = true)
@Getter
private long cacheSizeLimit = Long.MAX_VALUE;
@Parameter(names = "--skipSAT", description = "Do not load SAT entries from redis")
@Getter
private boolean skipSAT = false;
@Parameter(names = "--skipUNSAT", description = "Do not load UNSAT entries from redis; Do not cache UNSAT entries")
@Getter
private boolean skipUNSAT = true;
@Parameter(names = "--validateSAT", description = "Validate all SAT entries upon startup (slow)")
@Getter
private boolean validateSAT = false;
@Parameter(names = "--excludeSameAuction", description = "Do not count a solution if it is derived from the same auction as the problem", hidden = true)
@Getter
private boolean excludeSameAuction = false;
@Parameter(names = "--badSetFile", description = "JSON file listing, for some auctions, which auctions solutions are not allowed to come from", hidden = true)
private String badSetFilePath;
@Getter
private Map<String, Set<String>> badsets;
@Parameter(names = "--cache.screener", description = "Determine what goes into the cache", hidden = true)
@Getter
private CACHE_SCREENER_CHOICE cacheScreenerChoice = CACHE_SCREENER_CHOICE.NEW_INFO;
@Parameter(names = "--cache.UHF.only", description = "Only cache UHF portions of problems")
@Getter
private boolean cacheUHFOnly = true;
public enum CACHE_SCREENER_CHOICE {
NEW_INFO, ADD_EVERYTHING, ADD_NOTHING
}
public void validate() {
Preconditions.checkArgument(new File(constraintFolder).isDirectory(), "Provided constraint folder is not a directory", constraintFolder);
if (badSetFilePath != null) {
final File badSetFile = new File(badSetFilePath);
Preconditions.checkArgument(badSetFile.exists(), "Could not locate bad set file", badSetFilePath);
TypeReference<Map<String, Set<String>>> typeRef = new TypeReference<Map<String,Set<String>>>() {};
try {
badsets = JSONUtils.getMapper().readValue(Files.toString(badSetFile, Charset.defaultCharset()), typeRef);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
| 3,996
| 37.432692
| 213
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/LocomotionEvolution.java
|
/*
* Copyright 2020 Eric Medvet <eric.medvet@gmail.com> (as eric)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.units.erallab.evolution;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import it.units.erallab.evolution.builder.*;
import it.units.erallab.evolution.builder.evolver.*;
import it.units.erallab.evolution.builder.phenotype.*;
import it.units.erallab.evolution.builder.robot.*;
import it.units.erallab.evolution.utils.Utils;
import it.units.erallab.hmsrobots.core.controllers.Controller;
import it.units.erallab.hmsrobots.core.controllers.MultiLayerPerceptron;
import it.units.erallab.hmsrobots.core.controllers.PruningMultiLayerPerceptron;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedIzhikevicNeuron;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedLIFNeuron;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedLIFNeuronWithHomeostasis;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedSpikingFunction;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedAverageFrequencySpikeTrainToValueConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedMovingAverageSpikeTrainToValueConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedUniformValueToSpikeTrainConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedUniformWithMemoryValueToSpikeTrainConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.tasks.locomotion.Locomotion;
import it.units.erallab.hmsrobots.tasks.locomotion.Outcome;
import it.units.erallab.hmsrobots.util.RobotUtils;
import it.units.erallab.hmsrobots.viewers.drawers.Drawer;
import it.units.erallab.hmsrobots.viewers.drawers.Drawers;
import it.units.malelab.jgea.Worker;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Event;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.stopcondition.FitnessEvaluations;
import it.units.malelab.jgea.core.listener.*;
import it.units.malelab.jgea.core.listener.telegram.TelegramProgressMonitor;
import it.units.malelab.jgea.core.listener.telegram.TelegramUpdater;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.util.Misc;
import it.units.malelab.jgea.core.util.Pair;
import it.units.malelab.jgea.core.util.SequentialFunction;
import org.dyn4j.dynamics.Settings;
import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static it.units.erallab.hmsrobots.util.Utils.params;
import static it.units.malelab.jgea.core.listener.NamedFunctions.*;
import static it.units.malelab.jgea.core.util.Args.*;
/**
* @author eric
*/
public class LocomotionEvolution extends Worker {
private final static Settings PHYSICS_SETTINGS = new Settings();
public static class ValidationOutcome {
private final Event<?, ? extends Robot<?>, ? extends Outcome> event;
private final Map<String, Object> keys;
private final Outcome outcome;
public ValidationOutcome(Event<?, ? extends Robot<?>, ? extends Outcome> event, Map<String, Object> keys, Outcome outcome) {
this.event = event;
this.keys = keys;
this.outcome = outcome;
}
}
public static final int CACHE_SIZE = 1000;
public static final String MAPPER_PIPE_CHAR = "<";
public static final String SEQUENCE_SEPARATOR_CHAR = ">";
public static final String SEQUENCE_ITERATION_CHAR = ":";
public LocomotionEvolution(String[] args) {
super(args);
}
public static void main(String[] args) {
new LocomotionEvolution(args);
}
@Override
public void run() {
int spectrumSize = 10;
double spectrumMinFreq = 0d;
double spectrumMaxFreq = 5d;
double episodeTime = d(a("episodeTime", "10"));
double episodeTransientTime = d(a("episodeTransientTime", "1"));
double validationEpisodeTime = d(a("validationEpisodeTime", Double.toString(episodeTime)));
double validationEpisodeTransientTime = d(a("validationEpisodeTransientTime", Double.toString(episodeTransientTime)));
double videoEpisodeTime = d(a("videoEpisodeTime", "10"));
double videoEpisodeTransientTime = d(a("videoEpisodeTransientTime", "0"));
int nEvals = i(a("nEvals", "1000"));
int[] seeds = ri(a("seed", "0:1"));
String experimentName = a("expName", "short");
List<String> terrainNames = l(a("terrain", "hilly-1-10-rnd"));
List<String> targetShapeNames = l(a("shape", "biped-4x3"));
List<String> targetSensorConfigNames = l(a("sensorConfig", "spinedTouchSighted-f-f-0.01"));
List<String> transformationNames = l(a("transformation", "identity"));
List<String> evolverNames = l(a("evolver", "ES-40-0.35-f"));
List<String> mapperNames = l(a("mapper", "fixedHeteroQuantSpikeDist-1-unif_mem-50-avg_mem-5-50<snnQuantFuncGrid-QMSNd-1-1-lif_h-0-1-0.01"));
String bestFileName = a("bestFile", null);
String lastFileName = a("lastFile", null);
String allFileName = a("allFile", null);
String finalFileName = a("finalFile", null);
String validationFileName = a("validationFile", null);
boolean deferred = a("deferred", "true").startsWith("t");
String telegramBotId = a("telegramBotId", null);
long telegramChatId = Long.parseLong(a("telegramChatId", "0"));
List<String> serializationFlags = l(a("serialization", "")); //last,best,all,final
List<String> genotypeSerializationFlags = l(a("genoSerialization", "")); //last,best,all,final
boolean output = a("output", "false").startsWith("t");
List<String> validationTransformationNames = l(a("validationTransformation", "")).stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
List<String> validationTerrainNames = l(a("validationTerrain", "flat")).stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
List<String> fitnessMetrics = l(a("fitness", "velocity"));
String videoConfiguration = a("videoConfiguration", "basicWithMiniWorldAndBrain");
boolean detailedOutcome = a("detailedOutcome", "false").startsWith("t");
boolean cacheOutcome = a("cache", "false").startsWith("t");
Pair<Pair<Integer, Integer>, Function<String, Drawer>> drawerSupplier = getDrawerSupplierFromName(videoConfiguration);
Function<Outcome, Double> fitnessFunction = getFitnessFunctionFromName(fitnessMetrics.get(0));
Function<Outcome, Double>[] fitnessFunctions = getFitnessFunctionsFromName(fitnessMetrics);
//consumers
List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> keysFunctions = Utils.keysFunctions();
List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> basicFunctions = Utils.basicFunctions();
List<NamedFunction<Individual<?, ? extends Robot<?>, ? extends Outcome>, ?>> basicIndividualFunctions = Utils.individualFunctions(fitnessFunction);
List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> populationFunctions = Utils.populationFunctions(fitnessFunction);
List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> computationTimeFunctions = Utils.computationTimeFunctions();
List<NamedFunction<Event<?, ? extends Robot<?>, ? extends Outcome>, ?>> visualFunctions = Utils.visualFunctions(fitnessFunction);
List<NamedFunction<Outcome, ?>> basicOutcomeFunctions = Utils.basicOutcomeFunctions();
List<NamedFunction<Outcome, ?>> detailedOutcomeFunctions = Utils.detailedOutcomeFunctions(spectrumMinFreq, spectrumMaxFreq, spectrumSize);
List<NamedFunction<Outcome, ?>> visualOutcomeFunctions = Utils.visualOutcomeFunctions(spectrumMinFreq, spectrumMaxFreq);
Listener.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>> factory = Listener.Factory.deaf();
ProgressMonitor progressMonitor = new ScreenProgressMonitor(System.out);
if (bestFileName == null || output) {
factory = factory.and(new TabularPrinter<>(Misc.concat(List.of(
basicFunctions,
populationFunctions,
visualFunctions,
computationTimeFunctions,
NamedFunction.then(best(), basicIndividualFunctions),
NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), basicOutcomeFunctions),
NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), visualOutcomeFunctions)
))));
}
if (lastFileName != null) {
factory = factory.and(new CSVPrinter<>(Misc.concat(List.of(
keysFunctions,
basicFunctions,
populationFunctions,
NamedFunction.then(best(), basicIndividualFunctions),
NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), basicOutcomeFunctions),
detailedOutcome ? NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), detailedOutcomeFunctions) : List.of(),
NamedFunction.then(best(), Utils.serializationFunction(serializationFlags.contains("last"), solution())),
NamedFunction.then(best(), Utils.serializationFunction(genotypeSerializationFlags.contains("last"), genotype()))
)), new File(lastFileName)
).onLast());
}
if (bestFileName != null) {
factory = factory.and(new CSVPrinter<>(Misc.concat(List.of(
keysFunctions,
basicFunctions,
populationFunctions,
NamedFunction.then(best(), basicIndividualFunctions),
NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), basicOutcomeFunctions),
detailedOutcome ? NamedFunction.then(as(Outcome.class).of(fitness()).of(best()), detailedOutcomeFunctions) : List.of(),
NamedFunction.then(best(), Utils.serializationFunction(serializationFlags.contains("best"), solution())),
NamedFunction.then(best(), Utils.serializationFunction(genotypeSerializationFlags.contains("best"), genotype()))
)), new File(bestFileName)
));
}
if (allFileName != null) {
factory = factory.and(Listener.Factory.forEach(
event -> event.getOrderedPopulation().all().stream()
.map(i -> Pair.of(event, i))
.collect(Collectors.toList()),
new CSVPrinter<>(
Misc.concat(List.of(
NamedFunction.then(f("event", Pair::first), keysFunctions),
NamedFunction.then(f("event", Pair::first), basicFunctions),
NamedFunction.then(f("individual", Pair::second), basicIndividualFunctions),
NamedFunction.then(f("individual", Pair::second), Utils.serializationFunction(serializationFlags.contains("all"), solution())),
NamedFunction.then(f("individual", Pair::second), Utils.serializationFunction(genotypeSerializationFlags.contains("all"), genotype()))
)),
new File(allFileName)
)
));
}
if (finalFileName != null) {
Listener.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>> entirePopulationFactory = Listener.Factory.forEach(
event -> event.getOrderedPopulation().all().stream()
.map(i -> Pair.of(event, i))
.collect(Collectors.toList()),
new CSVPrinter<>(
Misc.concat(List.of(
NamedFunction.then(f("event", Pair::first), keysFunctions),
NamedFunction.then(f("event", Pair::first), basicFunctions),
NamedFunction.then(f("individual", Pair::second), basicIndividualFunctions),
NamedFunction.then(f("individual", Pair::second), Utils.serializationFunction(serializationFlags.contains("final"), solution())),
NamedFunction.then(f("individual", Pair::second), Utils.serializationFunction(genotypeSerializationFlags.contains("final"), genotype()))
)),
new File(finalFileName)
)
);
factory = factory.and(entirePopulationFactory.onLast());
}
//validation listener
if (validationFileName != null) {
if (!validationTerrainNames.isEmpty() && validationTransformationNames.isEmpty()) {
validationTransformationNames.add("identity");
}
if (validationTerrainNames.isEmpty() && !validationTransformationNames.isEmpty()) {
validationTerrainNames.add(terrainNames.get(0));
}
Listener.Factory<Event<?, ? extends Robot<?>, ? extends Outcome>> validationFactory = Listener.Factory.forEach(
Utils.validation(validationTerrainNames, validationTransformationNames, List.of(0), validationEpisodeTime),
new CSVPrinter<>(
Misc.concat(List.of(
NamedFunction.then(f("event", (ValidationOutcome vo) -> vo.event), basicFunctions),
NamedFunction.then(f("event", (ValidationOutcome vo) -> vo.event), keysFunctions),
NamedFunction.then(f("keys", (ValidationOutcome vo) -> vo.keys), List.of(
f("validation.terrain", (Map<String, Object> map) -> map.get("validation.terrain")),
f("validation.transformation", (Map<String, Object> map) -> map.get("validation.transformation")),
f("validation.seed", "%2d", (Map<String, Object> map) -> map.get("validation.seed"))
)),
NamedFunction.then(
f("outcome", (ValidationOutcome vo) -> vo.outcome.subOutcome(validationEpisodeTransientTime, validationEpisodeTime)),
basicOutcomeFunctions
),
detailedOutcome ?
NamedFunction.then(
f("outcome", (ValidationOutcome vo) -> vo.outcome.subOutcome(validationEpisodeTransientTime, validationEpisodeTime)),
detailedOutcomeFunctions
) : List.of()
)),
new File(validationFileName)
)
).onLast();
factory = factory.and(validationFactory);
}
if (telegramBotId != null && telegramChatId != 0) {
factory = factory.and(new TelegramUpdater<>(List.of(
Utils.lastEventToString(fitnessFunction),
Utils.fitnessPlot(fitnessFunction),
Utils.centerPositionPlot(),
Utils.bestVideo(videoEpisodeTransientTime, videoEpisodeTime, PHYSICS_SETTINGS, drawerSupplier)
), telegramBotId, telegramChatId));
progressMonitor = progressMonitor.and(new TelegramProgressMonitor(telegramBotId, telegramChatId));
}
//summarize params
L.info("Experiment name: " + experimentName);
L.info("N evaluations: " + nEvals);
L.info("Evolvers: " + evolverNames);
L.info("Mappers: " + mapperNames);
L.info("Fitness metrics: " + fitnessMetrics);
L.info("Shapes: " + targetShapeNames);
L.info("Sensor configs: " + targetSensorConfigNames);
L.info("Terrains: " + terrainNames);
L.info("Transformations: " + transformationNames);
L.info("Validations: " + Lists.cartesianProduct(validationTerrainNames, validationTransformationNames));
//start iterations
int nOfRuns = seeds.length * terrainNames.size() * targetShapeNames.size() * targetSensorConfigNames.size() * mapperNames.size() * transformationNames.size() * evolverNames.size();
int counter = 0;
for (int seed : seeds) {
for (String terrainName : terrainNames) {
for (String targetShapeName : targetShapeNames) {
for (String targetSensorConfigName : targetSensorConfigNames) {
for (String mapperName : mapperNames) {
for (String transformationName : transformationNames) {
for (String evolverName : evolverNames) {
counter = counter + 1;
final Random random = new Random(seed);
//prepare keys
Map<String, Object> keys = Map.ofEntries(
Map.entry("experiment.name", experimentName),
Map.entry("seed", seed),
Map.entry("terrain", terrainName),
Map.entry("shape", targetShapeName),
Map.entry("sensor.config", targetSensorConfigName),
Map.entry("mapper", mapperName),
Map.entry("transformation", transformationName),
Map.entry("evolver", evolverName),
Map.entry("fitness.metrics", fitnessMetrics)
);
Robot<?> target = new Robot<>(
Controller.empty(),
RobotUtils.buildSensorizingFunction(targetSensorConfigName).apply(RobotUtils.buildShape(targetShapeName))
);
//build evolver
Evolver<?, Robot<?>, Outcome> evolver;
try {
evolver = buildEvolver(evolverName, mapperName, target, fitnessFunctions);
} catch (ClassCastException | IllegalArgumentException e) {
e.printStackTrace();
L.warning(String.format(
"Cannot instantiate %s for %s: %s",
evolverName,
mapperName,
e
));
continue;
}
Listener<Event<?, ? extends Robot<?>, ? extends Outcome>> listener = Listener.all(List.of(
new EventAugmenter(keys),
factory.build()
));
if (deferred) {
listener = listener.deferred(executorService);
}
//optimize
Stopwatch stopwatch = Stopwatch.createStarted();
progressMonitor.notify(((float) counter - 1) / nOfRuns, String.format("(%d/%d); Starting %s", counter, nOfRuns, keys));
//build task
try {
Collection<Robot<?>> solutions = evolver.solve(
buildTaskFromName(transformationName, terrainName, episodeTime, random, cacheOutcome)
.andThen(o -> o.subOutcome(episodeTransientTime, episodeTime)),
new FitnessEvaluations(nEvals),
random,
executorService,
listener
);
progressMonitor.notify((float) counter / nOfRuns, String.format("(%d/%d); Done: %d solutions in %4ds", counter, nOfRuns, solutions.size(), stopwatch.elapsed(TimeUnit.SECONDS)));
} catch (Exception e) {
L.severe(String.format("Cannot complete %s due to %s",
keys,
e
));
e.printStackTrace(); // TODO possibly to be removed
}
}
}
}
}
}
}
}
factory.shutdown();
}
private static EvolverBuilder<?> getEvolverBuilderFromName(String name) {
String numGA = "numGA-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
String numGASpeciated = "numGASpec-(?<nPop>\\d+)-(?<nSpecies>\\d+)-(?<criterion>(" + Arrays.stream(DoublesSpeciated.SpeciationCriterion.values()).map(c -> c.name().toLowerCase(Locale.ROOT)).collect(Collectors.joining("|")) + "))";
String bitGA = "bitGA-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
String ternaryGA = "terGA-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
String cmaES = "CMAES";
String eS = "ES-(?<nPop>\\d+)-(?<sigma>\\d+(\\.\\d+)?)-(?<remap>(t|f))";
String bitNumGA = "bitNumGA-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
String biasedBitNumGA = "biasedBitNumGA-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
String bitNumMutation = "bitNumMut-(?<nPop>\\d+)-(?<diversity>(t|f))-(?<remap>(t|f))";
Map<String, String> params;
if ((params = params(numGA, name)) != null) {
return new DoublesStandard(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0.75d,
params.get("diversity").equals("t"),
params.get("diversity").equals("remap")
);
}
if ((params = params(bitGA, name)) != null) {
return new BinaryStandard(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0.75d,
params.get("diversity").equals("t"),
params.get("diversity").equals("remap")
);
}
if ((params = params(ternaryGA, name)) != null) {
return new IntegersStandard(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0.75d,
params.get("diversity").equals("t"),
params.get("remap").equals("t")
);
}
if ((params = params(bitNumGA, name)) != null) {
return new BinaryAndDoublesStandard(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0.75d,
params.get("diversity").equals("t"),
params.get("remap").equals("t")
);
}
if ((params = params(biasedBitNumGA, name)) != null) {
return new BinaryAndDoublesBiased(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0d,
params.get("diversity").equals("t"),
params.get("remap").equals("t")
);
}
if ((params = params(bitNumMutation, name)) != null) {
return new BinaryAndDoublesStandard(
Integer.parseInt(params.get("nPop")),
(int) Math.max(Math.round((double) Integer.parseInt(params.get("nPop")) / 10d), 3),
0d,
params.get("diversity").equals("t"),
params.get("remap").equals("t")
);
}
if ((params = params(numGASpeciated, name)) != null) {
return new DoublesSpeciated(
Integer.parseInt(params.get("nPop")),
Integer.parseInt(params.get("nSpecies")),
0.75d,
DoublesSpeciated.SpeciationCriterion.valueOf(params.get("criterion").toUpperCase())
);
}
if ((params = params(eS, name)) != null) {
return new ES(
Double.parseDouble(params.get("sigma")),
Integer.parseInt(params.get("nPop")),
params.get("remap").equals("t")
);
}
//noinspection UnusedAssignment
if ((params = params(cmaES, name)) != null) {
return new CMAES();
}
throw new IllegalArgumentException(String.format("Unknown evolver builder name: %s", name));
}
private static Function<Outcome, Double> getFitnessFunctionFromName(String name) {
String velocity = "velocity";
String roundedVelocity = "rounded-velocity";
String efficiency = "efficiency";
String avgSumOfAbsWeights = "avg-sum-abs-weights";
if (params(velocity, name) != null) {
return Outcome::getVelocity;
}
if (params(roundedVelocity, name) != null) {
return o -> (double) Math.round(o.getVelocity());
}
if (params(efficiency, name) != null) {
return Outcome::getCorrectedEfficiency;
}
if (params(avgSumOfAbsWeights, name) != null) {
return Outcome::getAverageSumOfAbsoluteWeights;
}
throw new IllegalArgumentException(String.format("Unknown fitness function name: %s", name));
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Function<Outcome, Double>[] getFitnessFunctionsFromName(List<String> names) {
Function[] fitnessMeasures = new Function[names.size()];
IntStream.range(0, names.size()).forEach(i -> fitnessMeasures[i] = getFitnessFunctionFromName(names.get(i)));
return fitnessMeasures;
}
private static Pair<Pair<Integer, Integer>, Function<String, Drawer>> getDrawerSupplierFromName(String name) {
String basic = "basic";
String basicWithMiniWorld = "basicWithMiniWorld";
String basicWithMiniWorldAndBrain = "basicWithMiniWorldAndBrain";
String basicWithMiniWorldAndBrainUsage = "basicWithMiniWorldAndBrainUsage";
if (params(basic, name) != null) {
return Pair.of(Pair.of(1, 1), Drawers::basic);
}
if (params(basicWithMiniWorld, name) != null) {
return Pair.of(Pair.of(1, 1), Drawers::basicWithMiniWorld);
}
if (params(basicWithMiniWorldAndBrain, name) != null) {
return Pair.of(Pair.of(1, 2), Drawers::basicWithMiniWorldAndBrain);
}
if (params(basicWithMiniWorldAndBrainUsage, name) != null) {
return Pair.of(Pair.of(1, 2), Drawers::basicWithMiniWorldAndBrainUsage);
}
throw new IllegalArgumentException(String.format("Unknown video configuration name: %s", name));
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static PrototypedFunctionBuilder<?, ?> getMapperBuilderFromName(String name) {
String binary = "binary-(?<value>\\d+(\\.\\d+)?)";
String ternary = "ternary-(?<value>\\d+(\\.\\d+)?)";
String fixedCentralized = "fixedCentralized";
String fixedHomoDistributed = "fixedHomoDist-(?<nSignals>\\d+)";
String fixedHomoNonDirDistributed = "fixedHomoNonDirDist-(?<nSignals>\\d+)";
String fixedHeteroDistributed = "fixedHeteroDist-(?<nSignals>\\d+)";
String fixedHomoQuantizedSpikingDistributed = "fixedHomoQuantSpikeDist-(?<nSignals>\\d+)" +
"-(?<iConv>(unif|unif_mem))-(?<iFreq>\\d+(\\.\\d+)?)-(?<oConv>(avg|avg_mem))(-(?<oMem>\\d+))?-(?<oFreq>\\d+(\\.\\d+)?)";
String fixedHomoQuantizedSpikingNonDirDistributed = "fixedHomoQuantSpikeNonDirDist-(?<nSignals>\\d+)" +
"-(?<iConv>(unif|unif_mem))-(?<iFreq>\\d+(\\.\\d+)?)-(?<oConv>(avg|avg_mem))(-(?<oMem>\\d+))?-(?<oFreq>\\d+(\\.\\d+)?)";
String fixedHeteroQuantizedSpikingDistributed = "fixedHeteroQuantSpikeDist-(?<nSignals>\\d+)" +
"-(?<iConv>(unif|unif_mem))-(?<iFreq>\\d+(\\.\\d+)?)-(?<oConv>(avg|avg_mem))(-(?<oMem>\\d+))?-(?<oFreq>\\d+(\\.\\d+)?)";
String fixedPhasesFunction = "fixedPhasesFunct-(?<f>\\d+)";
String fixedPhases = "fixedPhases-(?<f>\\d+)";
String fixedPhasesAndFrequencies = "fixedPhasesAndFrequencies";
String bodySin = "bodySin-(?<fullness>\\d+(\\.\\d+)?)-(?<minF>\\d+(\\.\\d+)?)-(?<maxF>\\d+(\\.\\d+)?)";
String bodyAndHomoDistributed = "bodyAndHomoDist-(?<fullness>\\d+(\\.\\d+)?)-(?<nSignals>\\d+)-(?<nLayers>\\d+)";
String sensorAndBodyAndHomoDistributed = "sensorAndBodyAndHomoDist-(?<fullness>\\d+(\\.\\d+)?)-(?<nSignals>\\d+)-(?<nLayers>\\d+)-(?<position>(t|f))";
String sensorCentralized = "sensorCentralized-(?<nLayers>\\d+)";
String mlp = "MLP-(?<ratio>\\d+(\\.\\d+)?)-(?<nLayers>\\d+)(-(?<actFun>(sin|tanh|sigmoid|relu)))?";
String pruningMlp = "pMLP-(?<ratio>\\d+(\\.\\d+)?)-(?<nLayers>\\d+)-(?<actFun>(sin|tanh|sigmoid|relu))-(?<pruningTime>\\d+(\\.\\d+)?)-(?<pruningRate>0(\\.\\d+)?)-(?<criterion>(weight|abs_signal_mean|random))";
String quantizedMsn = "QMSNd-(?<ratio>\\d+(\\.\\d+)?)-(?<nLayers>\\d+)-(?<spikeType>(lif|iz|lif_h))" +
"(-(?<lRestPot>-?\\d+(\\.\\d+)?)-(?<lThreshPot>-?\\d+(\\.\\d+)?)-(?<lambda>\\d+(\\.\\d+)?)(-(?<theta>\\d+(\\.\\d+)?))?)?" +
"(-(?<izParams>(regular_spiking_params)))?";
String quantizedMsnWithConverter = "QMSN-(?<ratio>\\d+(\\.\\d+)?)-(?<nLayers>\\d+)-(?<spikeType>(lif|iz|lif_h|lif_h_output|lif_h_io))" +
"(-(?<lRestPot>-?\\d+(\\.\\d+)?)-(?<lThreshPot>-?\\d+(\\.\\d+)?)-(?<lambda>\\d+(\\.\\d+)?)(-(?<theta>\\d+(\\.\\d+)?))?)?" +
"(-(?<izParams>(regular_spiking_params)))?" +
"-(?<iConv>(unif|unif_mem))-(?<iFreq>\\d+(\\.\\d+)?)-(?<oConv>(avg|avg_mem))(-(?<oMem>\\d+))?-(?<oFreq>\\d+(\\.\\d+)?)";
String oneHotMsnWithConverter = "HMSN-(?<ratio>\\d+(\\.\\d+)?)-(?<nLayers>\\d+)-(?<spikeType>(lif|iz|lif_h|lif_h_output|lif_h_io))" +
"(-(?<lRestPot>-?\\d+(\\.\\d+)?)-(?<lThreshPot>-?\\d+(\\.\\d+)?)-(?<lambda>\\d+(\\.\\d+)?)(-(?<theta>\\d+(\\.\\d+)?))?)?" +
"(-(?<izParams>(regular_spiking_params)))?";
String directNumGrid = "directNumGrid";
String functionNumGrid = "functionNumGrid";
String fgraph = "fGraph";
String functionGrid = "fGrid-(?<innerMapper>.*)";
String spikingFunctionGrid = "snnFuncGrid-(?<innerMapper>.*)";
String spikingQuantizedFunctionGrid = "snnQuantFuncGrid-(?<innerMapper>.*)";
Map<String, String> params;
//robot mappers
if ((params = params(binary, name)) != null) {
return new BinaryToDoubles(Double.parseDouble(params.get("value")));
}
if ((params = params(ternary, name)) != null) {
return new TernaryToDoubles(Double.parseDouble(params.get("value")));
}
//noinspection UnusedAssignment
if ((params = params(fixedCentralized, name)) != null) {
return new FixedCentralized();
}
if ((params = params(fixedHomoDistributed, name)) != null) {
return new FixedHomoDistributed(
Integer.parseInt(params.get("nSignals"))
);
}
if ((params = params(fixedHomoNonDirDistributed, name)) != null) {
return new FixedHomoNonDirectionalDistributed(
Integer.parseInt(params.get("nSignals"))
);
}
if ((params = params(fixedHeteroDistributed, name)) != null) {
return new FixedHeteroDistributed(
Integer.parseInt(params.get("nSignals"))
);
}
if ((params = params(fixedHomoQuantizedSpikingDistributed, name)) != null ||
(params = params(fixedHomoQuantizedSpikingNonDirDistributed, name)) != null) {
QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
if (params.containsKey("iConv")) {
switch (params.get("iConv")) {
case "unif":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
}
break;
case "unif_mem":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter();
}
break;
}
}
if (params.containsKey("oConv")) {
switch (params.get("oConv")) {
case "avg":
if (params.containsKey("oFreq")) {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
} else {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
}
break;
case "avg_mem":
if (params.containsKey("oFreq")) {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")),
Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
}
} else {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter();
}
}
break;
}
}
if ((params = params(fixedHomoQuantizedSpikingDistributed, name)) != null) {
return new FixedHomoQuantizedSpikingDistributed(
Integer.parseInt(params.get("nSignals")),
valueToSpikeTrainConverter,
spikeTrainToValueConverter
);
} else {
params = params(fixedHomoQuantizedSpikingNonDirDistributed, name);
return new FixedHomoQuantizedSpikingNonDirectionalDistributed(
Integer.parseInt(params.get("nSignals")),
valueToSpikeTrainConverter,
spikeTrainToValueConverter
);
}
}
if ((params = params(fixedHeteroQuantizedSpikingDistributed, name)) != null) {
QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
if (params.containsKey("iConv")) {
switch (params.get("iConv")) {
case "unif":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
}
break;
case "unif_mem":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter();
}
break;
}
}
if (params.containsKey("oConv")) {
switch (params.get("oConv")) {
case "avg":
if (params.containsKey("oFreq")) {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
} else {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
}
break;
case "avg_mem":
if (params.containsKey("oFreq")) {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")),
Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
}
} else {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter();
}
}
break;
}
}
return new FixedHeteroQuantizedSpikingDistributed(
Integer.parseInt(params.get("nSignals")),
valueToSpikeTrainConverter,
spikeTrainToValueConverter
);
}
if ((params = params(fixedPhasesFunction, name)) != null) {
return new FixedPhaseFunction(
Double.parseDouble(params.get("f")),
1d
);
}
if ((params = params(fixedPhases, name)) != null) {
return new FixedPhaseValues(
Double.parseDouble(params.get("f")),
1d
);
}
//noinspection UnusedAssignment
if ((params = params(fixedPhasesAndFrequencies, name)) != null) {
return new FixedPhaseAndFrequencyValues(
1d
);
}
if ((params = params(bodyAndHomoDistributed, name)) != null) {
return new BodyAndHomoDistributed(
Integer.parseInt(params.get("nSignals")),
Double.parseDouble(params.get("fullness"))
)
.compose(PrototypedFunctionBuilder.of(List.of(
new MLP(2d, 3, MultiLayerPerceptron.ActivationFunction.SIN),
new MLP(0.65d, Integer.parseInt(params.get("nLayers")))
)))
.compose(PrototypedFunctionBuilder.merger());
}
if ((params = params(sensorAndBodyAndHomoDistributed, name)) != null) {
return new SensorAndBodyAndHomoDistributed(
Integer.parseInt(params.get("nSignals")),
Double.parseDouble(params.get("fullness")),
params.get("position").equals("t")
)
.compose(PrototypedFunctionBuilder.of(List.of(
new MLP(2d, 3, MultiLayerPerceptron.ActivationFunction.SIN),
new MLP(1.5d, Integer.parseInt(params.get("nLayers")))
)))
.compose(PrototypedFunctionBuilder.merger());
}
if ((params = params(bodySin, name)) != null) {
return new BodyAndSinusoidal(
Double.parseDouble(params.get("minF")),
Double.parseDouble(params.get("maxF")),
Double.parseDouble(params.get("fullness")),
Set.of(BodyAndSinusoidal.Component.FREQUENCY, BodyAndSinusoidal.Component.PHASE, BodyAndSinusoidal.Component.AMPLITUDE)
);
}
if ((params = params(sensorCentralized, name)) != null) {
return new SensorCentralized()
.compose(PrototypedFunctionBuilder.of(List.of(
new MLP(2d, 3, MultiLayerPerceptron.ActivationFunction.SIN),
new MLP(1.5d, Integer.parseInt(params.get("nLayers")))
)))
.compose(PrototypedFunctionBuilder.merger());
}
//function mappers
if ((params = params(mlp, name)) != null) {
return new MLP(
Double.parseDouble(params.get("ratio")),
Integer.parseInt(params.get("nLayers")),
params.containsKey("actFun") ? MultiLayerPerceptron.ActivationFunction.valueOf(params.get("actFun").toUpperCase()) : MultiLayerPerceptron.ActivationFunction.TANH
);
}
if ((params = params(pruningMlp, name)) != null) {
return new PruningMLP(
Double.parseDouble(params.get("ratio")),
Integer.parseInt(params.get("nLayers")),
MultiLayerPerceptron.ActivationFunction.valueOf(params.get("actFun").toUpperCase()),
Double.parseDouble(params.get("pruningTime")),
Double.parseDouble(params.get("pruningRate")),
PruningMultiLayerPerceptron.Context.NETWORK,
PruningMultiLayerPerceptron.Criterion.valueOf(params.get("criterion").toUpperCase())
);
}
if ((params = params(quantizedMsn, name)) != null ||
(params = params(oneHotMsnWithConverter, name)) != null ||
(params = params(quantizedMsnWithConverter, name)) != null
) {
BiFunction<Integer, Integer, QuantizedSpikingFunction> neuronBuilder = null;
if (params.containsKey("spikeType") && params.get("spikeType").equals("lif")) {
if (params.containsKey("lRestPot") && params.containsKey("lThreshPot") && params.containsKey("lambda")) {
double restingPotential = Double.parseDouble(params.get("lRestPot"));
double thresholdPotential = Double.parseDouble(params.get("lThreshPot"));
double lambda = Double.parseDouble(params.get("lambda"));
neuronBuilder = (l, n) -> new QuantizedLIFNeuron(restingPotential, thresholdPotential, lambda);
} else {
neuronBuilder = (l, n) -> new QuantizedLIFNeuron();
}
}
if (params.containsKey("spikeType") && params.get("spikeType").equals("lif_h")) {
if (params.containsKey("lRestPot") && params.containsKey("lThreshPot") && params.containsKey("lambda") && params.containsKey("theta")) {
double restingPotential = Double.parseDouble(params.get("lRestPot"));
double thresholdPotential = Double.parseDouble(params.get("lThreshPot"));
double lambda = Double.parseDouble(params.get("lambda"));
double theta = Double.parseDouble(params.get("theta"));
neuronBuilder = (l, n) -> new QuantizedLIFNeuronWithHomeostasis(restingPotential, thresholdPotential, lambda, theta);
} else {
neuronBuilder = (l, n) -> new QuantizedLIFNeuronWithHomeostasis();
}
}
if (params.containsKey("spikeType") && params.get("spikeType").equals("lif_h_output")) {
int outputLayerIndex = Integer.parseInt(params.get("nLayers")) + 1;
if (params.containsKey("lRestPot") && params.containsKey("lThreshPot") && params.containsKey("lambda") && params.containsKey("theta")) {
double restingPotential = Double.parseDouble(params.get("lRestPot"));
double thresholdPotential = Double.parseDouble(params.get("lThreshPot"));
double lambda = Double.parseDouble(params.get("lambda"));
double theta = Double.parseDouble(params.get("theta"));
neuronBuilder = (l, n) -> (l == outputLayerIndex) ? new QuantizedLIFNeuronWithHomeostasis(restingPotential, thresholdPotential, lambda, theta) : new QuantizedLIFNeuron(restingPotential, thresholdPotential, lambda);
} else {
neuronBuilder = (l, n) -> (l == outputLayerIndex) ? new QuantizedLIFNeuronWithHomeostasis() : new QuantizedLIFNeuron();
}
}
if (params.containsKey("spikeType") && params.get("spikeType").equals("lif_h_io")) {
int outputLayerIndex = Integer.parseInt(params.get("nLayers")) + 1;
if (params.containsKey("lRestPot") && params.containsKey("lThreshPot") && params.containsKey("lambda") && params.containsKey("theta")) {
double restingPotential = Double.parseDouble(params.get("lRestPot"));
double thresholdPotential = Double.parseDouble(params.get("lThreshPot"));
double lambda = Double.parseDouble(params.get("lambda"));
double theta = Double.parseDouble(params.get("theta"));
neuronBuilder = (l, n) -> (l == outputLayerIndex || l == 0) ? new QuantizedLIFNeuronWithHomeostasis(restingPotential, thresholdPotential, lambda, theta) : new QuantizedLIFNeuron(restingPotential, thresholdPotential, lambda);
} else {
neuronBuilder = (l, n) -> (l == outputLayerIndex || l == 0) ? new QuantizedLIFNeuronWithHomeostasis() : new QuantizedLIFNeuron();
}
}
if (params.containsKey("spikeType") && params.get("spikeType").equals("iz")) {
if (params.containsKey("izParams")) {
QuantizedIzhikevicNeuron.IzhikevicParameters izhikevicParameters = QuantizedIzhikevicNeuron.IzhikevicParameters.valueOf(params.get("izParams").toUpperCase());
neuronBuilder = (l, n) -> new QuantizedIzhikevicNeuron(izhikevicParameters);
} else {
neuronBuilder = (l, n) -> new QuantizedIzhikevicNeuron();
}
}
if ((params = params(quantizedMsn, name)) != null) {
return new QuantizedMSN(
Double.parseDouble(params.get("ratio")),
Integer.parseInt(params.get("nLayers")),
neuronBuilder
);
}
if ((params = params(quantizedMsnWithConverter, name)) != null) {
QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
if (params.containsKey("iConv")) {
switch (params.get("iConv")) {
case "unif":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformValueToSpikeTrainConverter();
}
break;
case "unif_mem":
if (params.containsKey("iFreq")) {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter(Double.parseDouble(params.get("iFreq")));
} else {
valueToSpikeTrainConverter = new QuantizedUniformWithMemoryValueToSpikeTrainConverter();
}
break;
}
}
if (params.containsKey("oConv")) {
switch (params.get("oConv")) {
case "avg":
if (params.containsKey("oFreq")) {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
} else {
spikeTrainToValueConverter = new QuantizedAverageFrequencySpikeTrainToValueConverter();
}
break;
case "avg_mem":
if (params.containsKey("oFreq")) {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")),
Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Double.parseDouble(params.get("oFreq")));
}
} else {
if (params.containsKey("oMem")) {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter(Integer.parseInt(params.get("oMem")));
} else {
spikeTrainToValueConverter = new QuantizedMovingAverageSpikeTrainToValueConverter();
}
}
break;
}
}
return new QuantizedMSNWithConverters(
Double.parseDouble(params.get("ratio")),
Integer.parseInt(params.get("nLayers")),
neuronBuilder,
valueToSpikeTrainConverter,
spikeTrainToValueConverter
);
}
}
//noinspection UnusedAssignment
if ((params = params(fgraph, name)) != null) {
return new FGraph();
}
//misc
if ((params = params(functionGrid, name)) != null) {
return new FunctionGrid((PrototypedFunctionBuilder) getMapperBuilderFromName(params.get("innerMapper")));
}
if ((params = params(spikingFunctionGrid, name)) != null) {
return new FunctionGrid((PrototypedFunctionBuilder) getMapperBuilderFromName(params.get("innerMapper")));
}
if ((params = params(spikingQuantizedFunctionGrid, name)) != null) {
return new SpikingQuantizedFunctionGrid((PrototypedFunctionBuilder) getMapperBuilderFromName(params.get("innerMapper")));
}
//noinspection UnusedAssignment
if ((params = params(directNumGrid, name)) != null) {
return new DirectNumbersGrid();
}
//noinspection UnusedAssignment
if ((params = params(functionNumGrid, name)) != null) {
return new FunctionNumbersGrid();
}
throw new IllegalArgumentException(String.format("Unknown mapper name: %s", name));
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Evolver<?, Robot<?>, Outcome> buildEvolver(String evolverName, String robotMapperName, Robot<?>
target, Function<Outcome, Double>... outcomeMeasure) {
if (outcomeMeasure.length == 0) {
throw new IllegalArgumentException("At least one outcome measure needs to be specified");
}
PrototypedFunctionBuilder<?, ?> mapperBuilder = null;
for (String piece : robotMapperName.split(MAPPER_PIPE_CHAR)) {
if (mapperBuilder == null) {
mapperBuilder = getMapperBuilderFromName(piece);
} else {
mapperBuilder = mapperBuilder.compose((PrototypedFunctionBuilder) getMapperBuilderFromName(piece));
}
}
// TODO specify if measures need to be reversed or not
PartialComparator<Outcome> comparator = PartialComparator.from(Double.class).comparing(outcomeMeasure[0]).reversed();
for (int i = 1; i < outcomeMeasure.length; i++) {
PartialComparator<Outcome> temporaryComparator = PartialComparator.from(Double.class).comparing(outcomeMeasure[i]);
comparator = comparator.thenComparing(temporaryComparator);
}
return getEvolverBuilderFromName(evolverName).build(
(PrototypedFunctionBuilder) mapperBuilder,
target,
comparator
);
}
private static Function<Robot<?>, Outcome> buildTaskFromName(String transformationSequenceName, String
terrainSequenceName, double episodeT, Random random, boolean outcomeCaching) {
//for sequence, assume format '99:name>99:name'
//transformations
Function<Robot<?>, Robot<?>> transformation;
if (transformationSequenceName.contains(SEQUENCE_SEPARATOR_CHAR)) {
transformation = new SequentialFunction<>(getSequence(transformationSequenceName).entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> RobotUtils.buildRobotTransformation(e.getValue(), random)
)
));
} else {
transformation = RobotUtils.buildRobotTransformation(transformationSequenceName, random);
}
//terrains
Function<Robot<?>, Outcome> task;
if (terrainSequenceName.contains(SEQUENCE_SEPARATOR_CHAR)) {
task = new SequentialFunction<>(getSequence(terrainSequenceName).entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> buildLocomotionTask(e.getValue(), episodeT, random, outcomeCaching)
)
));
} else {
task = buildLocomotionTask(terrainSequenceName, episodeT, random, outcomeCaching);
}
return task.compose(transformation);
}
public static Function<Robot<?>, Outcome> buildLocomotionTask(String terrainName, double episodeT, Random random, boolean cache) {
if (!terrainName.contains("-rnd") && cache) {
return Misc.cached(new Locomotion(
episodeT,
Locomotion.createTerrain(terrainName),
PHYSICS_SETTINGS
), CACHE_SIZE);
}
return r -> new Locomotion(
episodeT,
Locomotion.createTerrain(terrainName.replace("-rnd", "-" + random.nextInt(10000))),
PHYSICS_SETTINGS
).apply(r);
}
public static SortedMap<Long, String> getSequence(String sequenceName) {
return new TreeMap<>(Arrays.stream(sequenceName.split(SEQUENCE_SEPARATOR_CHAR)).collect(Collectors.toMap(
s -> s.contains(SEQUENCE_ITERATION_CHAR) ? Long.parseLong(s.split(SEQUENCE_ITERATION_CHAR)[0]) : 0,
s -> s.contains(SEQUENCE_ITERATION_CHAR) ? s.split(SEQUENCE_ITERATION_CHAR)[1] : s
)));
}
}
| 51,502
| 51.340447
| 234
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/BinaryToDoubles.java
|
package it.units.erallab.evolution.builder;
import it.units.malelab.jgea.representation.sequence.bit.BitString;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class BinaryToDoubles implements PrototypedFunctionBuilder<BitString, List<Double>> {
private final double value;
public BinaryToDoubles(double value) {
this.value = value;
}
@Override
public Function<BitString, List<Double>> buildFor(List<Double> doubles) {
return bitString -> {
if (doubles.size() != bitString.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of values: %d expected, %d found",
doubles.size(),
bitString.size()
));
}
return bitString.stream().map(b -> b ? value : -value).collect(Collectors.toList());
};
}
@Override
public BitString exampleFor(List<Double> doubles) {
return new BitString(doubles.size());
}
}
| 980
| 26.25
| 92
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/PrototypedFunctionBuilder.java
|
package it.units.erallab.evolution.builder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author eric
*/
public interface PrototypedFunctionBuilder<A, B> {
Function<A, B> buildFor(B b);
A exampleFor(B b);
default <C> PrototypedFunctionBuilder<C, B> compose(PrototypedFunctionBuilder<C, A> other) {
PrototypedFunctionBuilder<A, B> thisB = this;
return new PrototypedFunctionBuilder<>() {
@Override
public Function<C, B> buildFor(B b) {
return thisB.buildFor(b).compose(other.buildFor(thisB.exampleFor(b)));
}
@Override
public C exampleFor(B b) {
return other.exampleFor(thisB.exampleFor(b));
}
};
}
static <A1, B1> PrototypedFunctionBuilder<List<A1>, List<B1>> of(List<PrototypedFunctionBuilder<A1, B1>> builders) {
return new PrototypedFunctionBuilder<>() {
@Override
public Function<List<A1>, List<B1>> buildFor(List<B1> b1s) {
if (b1s.size() != builders.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of arguments: %d expected, %d found",
builders.size(),
b1s.size()
));
}
return a1s -> {
if (a1s.size() != builders.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of arguments: %d expected, %d found",
builders.size(),
a1s.size()
));
}
List<B1> newB1s = new ArrayList<>(builders.size());
for (int i = 0; i < builders.size(); i++) {
newB1s.add(builders.get(i).buildFor(b1s.get(i)).apply(a1s.get(i)));
}
return newB1s;
};
}
@Override
public List<A1> exampleFor(List<B1> b1s) {
if (b1s.size() != builders.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of arguments: %d expected, %d found",
builders.size(),
b1s.size()
));
}
List<A1> a1s = new ArrayList<>(builders.size());
for (int i = 0; i < builders.size(); i++) {
a1s.add(builders.get(i).exampleFor(b1s.get(i)));
}
return a1s;
}
};
}
static <T> PrototypedFunctionBuilder<List<T>, List<List<T>>> merger() {
return new PrototypedFunctionBuilder<>() {
@Override
public Function<List<T>, List<List<T>>> buildFor(List<List<T>> lists) {
return ts -> {
List<List<T>> newLists = new ArrayList<>(lists.size());
int sum = lists.stream().mapToInt(List::size).sum();
if (ts.size() != sum) {
throw new IllegalArgumentException(String.format(
"Not enough values: %d instead of %d",
ts.size(),
sum
));
}
int c = 0;
for (List<T> list : lists) {
newLists.add(ts.subList(c, c + list.size()));
c = c + list.size();
}
return newLists;
};
}
@Override
public List<T> exampleFor(List<List<T>> lists) {
return lists.stream().flatMap(List::stream).collect(Collectors.toList());
}
};
}
}
| 3,315
| 30.283019
| 118
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/SpikingQuantizedFunctionGrid.java
|
package it.units.erallab.evolution.builder;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultivariateSpikingFunction;
import it.units.erallab.hmsrobots.util.Grid;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class SpikingQuantizedFunctionGrid implements PrototypedFunctionBuilder<List<Double>, Grid<QuantizedMultivariateSpikingFunction>> {
private final PrototypedFunctionBuilder<List<Double>, QuantizedMultivariateSpikingFunction> itemBuilder;
public SpikingQuantizedFunctionGrid(PrototypedFunctionBuilder<List<Double>, QuantizedMultivariateSpikingFunction> itemBuilder) {
this.itemBuilder = itemBuilder;
}
@Override
public Function<List<Double>, Grid<QuantizedMultivariateSpikingFunction>> buildFor(Grid<QuantizedMultivariateSpikingFunction> targetFunctions) {
return values -> {
Grid<QuantizedMultivariateSpikingFunction> functions = Grid.create(targetFunctions);
int c = 0;
for (Grid.Entry<QuantizedMultivariateSpikingFunction> entry : targetFunctions) {
if (entry.getValue() == null) {
continue;
}
int size = itemBuilder.exampleFor(entry.getValue()).size();
functions.set(
entry.getX(),
entry.getY(),
itemBuilder.buildFor(entry.getValue()).apply(values.subList(c, c + size))
);
c = c + size;
}
return functions;
};
}
@Override
public List<Double> exampleFor(Grid<QuantizedMultivariateSpikingFunction> functions) {
return Collections.nCopies(
functions.values().stream()
.filter(Objects::nonNull)
.mapToInt(f -> itemBuilder.exampleFor(f).size())
.sum(),
0d
);
}
}
| 1,815
| 32.018182
| 146
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/FunctionNumbersGrid.java
|
package it.units.erallab.evolution.builder;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.util.Grid;
import java.util.Arrays;
import java.util.function.Function;
/**
* @author eric on 2021/01/01 for VSREvolution
*/
public class FunctionNumbersGrid implements PrototypedFunctionBuilder<RealFunction, Grid<double[]>> {
@Override
public Function<RealFunction, Grid<double[]>> buildFor(Grid<double[]> grid) {
int targetLength = targetLength(grid);
return function -> {
if (function.getInputDimension() != 2 || function.getOutputDimension() != targetLength) {
throw new IllegalArgumentException(String.format(
"Wrong number of body function args: 2->%d expected, %d->%d found",
targetLength,
function.getInputDimension(),
function.getOutputDimension()
));
}
Grid<double[]> output = Grid.create(grid);
double w = output.getW();
double h = output.getH();
for (double x = 0; x < output.getW(); x++) {
for (double y = 0; y < output.getH(); y++) {
output.set((int) x, (int) y, function.apply(new double[]{x / (w - 1d), y / (h - 1d)}));
}
}
return output;
};
}
@Override
public RealFunction exampleFor(Grid<double[]> grid) {
int targetLength = targetLength(grid);
return RealFunction.build(d -> d, 2, targetLength);
}
private static int targetLength(Grid<double[]> grid) {
int[] lengths = grid.values().stream().mapToInt(v -> v.length).distinct().toArray();
if (lengths.length > 1) {
throw new IllegalArgumentException(String.format(
"Target grid elements must have all the same size, found % distinct sizes %s",
lengths.length,
Arrays.toString(lengths)
));
}
return lengths[0];
}
}
| 1,865
| 32.321429
| 101
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/DirectNumbersGrid.java
|
package it.units.erallab.evolution.builder;
import it.units.erallab.hmsrobots.util.Grid;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
/**
* @author eric on 2021/01/01 for VSREvolution
*/
public class DirectNumbersGrid implements PrototypedFunctionBuilder<List<Double>, Grid<double[]>> {
@Override
public Function<List<Double>, Grid<double[]>> buildFor(Grid<double[]> grid) {
int expectedLength = grid.values().stream().mapToInt(v -> v.length).sum();
return values -> {
if (expectedLength != values.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of values: %d expected, %d found",
expectedLength,
values.size()
));
}
int c = 0;
Grid<double[]> output = Grid.create(grid);
for (int x = 0; x < output.getW(); x++) {
for (int y = 0; y < output.getH(); y++) {
double[] local = values.subList(c, c + grid.get(x, y).length).stream().mapToDouble(d -> d).toArray();
c = c + grid.get(x, y).length;
output.set(x, y, local);
}
}
return output;
};
}
@Override
public List<Double> exampleFor(Grid<double[]> grid) {
return Collections.nCopies(
grid.values().stream().mapToInt(v -> v.length).sum(),
0d
);
}
}
| 1,358
| 28.543478
| 111
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/TernaryToDoubles.java
|
package it.units.erallab.evolution.builder;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TernaryToDoubles implements PrototypedFunctionBuilder<List<Integer>, List<Double>> {
private final double value;
public TernaryToDoubles(double value) {
this.value = value;
}
@Override
public Function<List<Integer>, List<Double>> buildFor(List<Double> doubles) {
return integers -> {
if (doubles.size() != integers.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of values: %d expected, %d found",
doubles.size(),
integers.size()
));
}
return integers.stream().map(i -> (i - 1) * value).collect(Collectors.toList());
};
}
@Override
public List<Integer> exampleFor(List<Double> doubles) {
return doubles.stream().map(d -> 3).collect(Collectors.toList());
}
}
| 947
| 26.085714
| 97
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/FunctionGrid.java
|
package it.units.erallab.evolution.builder;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.util.Grid;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class FunctionGrid implements PrototypedFunctionBuilder<List<Double>, Grid<TimedRealFunction>> {
private final PrototypedFunctionBuilder<List<Double>, TimedRealFunction> itemBuilder;
public FunctionGrid(PrototypedFunctionBuilder<List<Double>, TimedRealFunction> itemBuilder) {
this.itemBuilder = itemBuilder;
}
@Override
public Function<List<Double>, Grid<TimedRealFunction>> buildFor(Grid<TimedRealFunction> targetFunctions) {
return values -> {
Grid<TimedRealFunction> functions = Grid.create(targetFunctions);
int c = 0;
for (Grid.Entry<TimedRealFunction> entry : targetFunctions) {
if (entry.getValue() == null) {
continue;
}
int size = itemBuilder.exampleFor(entry.getValue()).size();
functions.set(
entry.getX(),
entry.getY(),
itemBuilder.buildFor(entry.getValue()).apply(values.subList(c, c + size))
);
c = c + size;
}
return functions;
};
}
@Override
public List<Double> exampleFor(Grid<TimedRealFunction> functions) {
return Collections.nCopies(
functions.values().stream()
.filter(Objects::nonNull)
.mapToInt(f -> itemBuilder.exampleFor(f).size())
.sum(),
0d
);
}
}
| 1,603
| 28.163636
| 108
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/BinaryAndDoublesStandard.java
|
package it.units.erallab.evolution.builder.evolver;
import com.google.common.collect.Range;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.Factory;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.StandardEvolver;
import it.units.malelab.jgea.core.evolver.StandardWithEnforcedDiversityEvolver;
import it.units.malelab.jgea.core.operator.Crossover;
import it.units.malelab.jgea.core.operator.GeneticOperator;
import it.units.malelab.jgea.core.operator.Mutation;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.selector.Last;
import it.units.malelab.jgea.core.selector.Tournament;
import it.units.malelab.jgea.core.util.Pair;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.UniformCrossover;
import it.units.malelab.jgea.representation.sequence.bit.BitFlipMutation;
import it.units.malelab.jgea.representation.sequence.bit.BitString;
import it.units.malelab.jgea.representation.sequence.bit.BitStringFactory;
import it.units.malelab.jgea.representation.sequence.numeric.GaussianMutation;
import it.units.malelab.jgea.representation.sequence.numeric.GeometricCrossover;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.List;
import java.util.Map;
/**
* @author eric
*/
public class BinaryAndDoublesStandard implements EvolverBuilder<Pair<BitString, List<Double>>> {
private final int nPop;
private final int nTournament;
private final double xOverProb;
private final boolean diversityEnforcement;
private final boolean remap;
public BinaryAndDoublesStandard(int nPop, int nTournament, double xOverProb, boolean diversityEnforcement, boolean remap) {
this.nPop = nPop;
this.nTournament = nTournament;
this.xOverProb = xOverProb;
this.diversityEnforcement = diversityEnforcement;
this.remap = remap;
}
@Override
public <T, F> Evolver<Pair<BitString, List<Double>>, T, F> build(PrototypedFunctionBuilder<Pair<BitString, List<Double>>, T> builder, T target, PartialComparator<F> comparator) {
Pair<BitString, List<Double>> sampleGenotype = builder.exampleFor(target);
int bitStringLength = sampleGenotype.first().size();
int doublesLength = sampleGenotype.second().size();
Factory<Pair<BitString, List<Double>>> factory = Factory.pair(
new BitStringFactory(bitStringLength),
new FixedLengthListFactory<>(doublesLength, new UniformDoubleFactory(-1d, 1d)));
Map<GeneticOperator<Pair<BitString, List<Double>>>, Double> geneticOperators = Map.of(
Mutation.pair(
new BitFlipMutation(.01d),
new GaussianMutation(.35d)
), 1d - xOverProb,
Crossover.pair(
new UniformCrossover<>(new BitStringFactory(bitStringLength)),
new GeometricCrossover(Range.closed(-.5d, 1.5d))
).andThen(
Mutation.pair(new BitFlipMutation(.01d), new GaussianMutation(.1d))
), xOverProb
);
if (!diversityEnforcement) {
return new StandardEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
geneticOperators,
new Tournament(nTournament),
new Last(),
nPop,
true,
remap
);
}
return new StandardWithEnforcedDiversityEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
geneticOperators,
new Tournament(nTournament),
new Last(),
nPop,
true,
remap,
100
);
}
}
| 3,831
| 38.102041
| 180
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/BinaryAndDoublesBiased.java
|
package it.units.erallab.evolution.builder.evolver;
import com.google.common.collect.Range;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.Factory;
import it.units.malelab.jgea.core.IndependentFactory;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.StandardEvolver;
import it.units.malelab.jgea.core.evolver.StandardWithEnforcedDiversityEvolver;
import it.units.malelab.jgea.core.operator.Crossover;
import it.units.malelab.jgea.core.operator.GeneticOperator;
import it.units.malelab.jgea.core.operator.Mutation;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.selector.Last;
import it.units.malelab.jgea.core.selector.Tournament;
import it.units.malelab.jgea.core.util.Pair;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.UniformCrossover;
import it.units.malelab.jgea.representation.sequence.bit.BitFlipMutation;
import it.units.malelab.jgea.representation.sequence.bit.BitString;
import it.units.malelab.jgea.representation.sequence.bit.BitStringFactory;
import it.units.malelab.jgea.representation.sequence.numeric.GaussianMutation;
import it.units.malelab.jgea.representation.sequence.numeric.GeometricCrossover;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.List;
import java.util.Map;
/**
* @author eric
*/
public class BinaryAndDoublesBiased implements EvolverBuilder<Pair<BitString, List<Double>>> {
private final int nPop;
private final int nTournament;
private final double xOverProb;
private final boolean diversityEnforcement;
private final boolean remap;
public BinaryAndDoublesBiased(int nPop, int nTournament, double xOverProb, boolean diversityEnforcement, boolean remap) {
this.nPop = nPop;
this.nTournament = nTournament;
this.xOverProb = xOverProb;
this.diversityEnforcement = diversityEnforcement;
this.remap = remap;
}
@Override
public <T, F> Evolver<Pair<BitString, List<Double>>, T, F> build(PrototypedFunctionBuilder<Pair<BitString, List<Double>>, T> builder, T target, PartialComparator<F> comparator) {
Pair<BitString, List<Double>> sampleGenotype = builder.exampleFor(target);
int bitStringLength = sampleGenotype.first().size();
IndependentFactory<BitString> biasedFactory = random -> {
BitString bitString = new BitString(bitStringLength);
for (int i = 0; i < bitStringLength / 3; i++) {
bitString.set(i, false);
}
for (int i = bitStringLength / 3; i < bitStringLength; i++) {
bitString.set(i, random.nextBoolean());
}
return bitString;
};
int doublesLength = sampleGenotype.second().size();
Factory<Pair<BitString, List<Double>>> factory = Factory.pair(
biasedFactory,
new FixedLengthListFactory<>(doublesLength, new UniformDoubleFactory(-1d, 1d)));
Map<GeneticOperator<Pair<BitString, List<Double>>>, Double> geneticOperators = Map.of(
Mutation.pair(
new BitFlipMutation(.01d),
new GaussianMutation(.35d)
), 1d - xOverProb,
Crossover.pair(
new UniformCrossover<>(new BitStringFactory(bitStringLength)),
new GeometricCrossover(Range.closed(-.5d, 1.5d))
).andThen(
Mutation.pair(new BitFlipMutation(.01d), new GaussianMutation(.1d))
), xOverProb
);
if (!diversityEnforcement) {
return new StandardEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
geneticOperators,
new Tournament(nTournament),
new Last(),
nPop,
true,
remap
);
}
return new StandardWithEnforcedDiversityEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
geneticOperators,
new Tournament(nTournament),
new Last(),
nPop,
true,
remap,
100
);
}
}
| 4,229
| 37.807339
| 180
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/EvolverBuilder.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.order.PartialComparator;
/**
* @author eric
*/
public interface EvolverBuilder<G> {
<T, F> Evolver<G, T, F> build(PrototypedFunctionBuilder<G, T> builder, T target, PartialComparator<F> comparator);
}
| 413
| 30.846154
| 116
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/ES.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.BasicEvolutionaryStrategy;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.List;
/**
* @author eric
*/
public class ES implements EvolverBuilder<List<Double>> {
private final double sigma;
private final int nPop;
private final boolean remap;
public ES(double sigma, int nPop, boolean remap) {
this.sigma = sigma;
this.nPop = nPop;
this.remap = remap;
}
@Override
public <T, F> Evolver<List<Double>, T, F> build(PrototypedFunctionBuilder<List<Double>, T> builder, T target, PartialComparator<F> comparator) {
int length = builder.exampleFor(target).size();
return new BasicEvolutionaryStrategy<>(
builder.buildFor(target),
new FixedLengthListFactory<>(length, new UniformDoubleFactory(-1d, 1d)),
comparator.comparing(Individual::getFitness),
sigma,
nPop,
nPop / 4,
1,
remap
);
}
}
| 1,339
| 30.904762
| 146
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/CMAES.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.CMAESEvolver;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.List;
/**
* @author eric
*/
public class CMAES implements EvolverBuilder<List<Double>> {
@Override
public <T,F> Evolver<List<Double>, T, F> build(PrototypedFunctionBuilder<List<Double>, T> builder, T target, PartialComparator<F> comparator) {
int length = builder.exampleFor(target).size();
return new CMAESEvolver<>(
builder.buildFor(target),
new FixedLengthListFactory<>(length, new UniformDoubleFactory(-1d, 1d)),
comparator.comparing(Individual::getFitness)
);
}
}
| 1,026
| 37.037037
| 145
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/DoublesSpeciated.java
|
package it.units.erallab.evolution.builder.evolver;
import com.google.common.collect.Range;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.tasks.locomotion.Outcome;
import it.units.erallab.hmsrobots.util.Domain;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.speciation.KMeansSpeciator;
import it.units.malelab.jgea.core.evolver.speciation.SpeciatedEvolver;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.distance.LNorm;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.numeric.GaussianMutation;
import it.units.malelab.jgea.representation.sequence.numeric.GeometricCrossover;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.function.Function;
/**
* @author eric
*/
public class DoublesSpeciated implements EvolverBuilder<List<Double>> {
private final static int SPECTRUM_SIZE = 8;
private final static double SPECTRUM_MIN_FREQ = 0d;
private final static double SPECTRUM_MAX_FREQ = 4d;
public enum SpeciationCriterion {GENOTYPE, POSTURE, CENTER, FOOTPRINTS}
private final int nPop;
private final int nSpecies;
private final double xOverProb;
private final SpeciationCriterion criterion;
public DoublesSpeciated(int nPop, int nSpecies, double xOverProb, SpeciationCriterion criterion) {
this.nPop = nPop;
this.nSpecies = nSpecies;
this.xOverProb = xOverProb;
this.criterion = criterion;
}
@Override
public <T, F> Evolver<List<Double>, T, F> build(PrototypedFunctionBuilder<List<Double>, T> builder, T target, PartialComparator<F> comparator) {
Function<Individual<List<Double>, T, F>, double[]> converter = switch (criterion) {
case GENOTYPE -> i -> i.getGenotype().stream().mapToDouble(Double::doubleValue).toArray();
case POSTURE -> i -> {
if (i.getFitness() instanceof Outcome) {
Outcome o = (Outcome) i.getFitness();
return o.getAveragePosture(8).values().stream().mapToDouble(b -> b ? 1d : 0d).toArray();
}
throw new IllegalStateException(String.format("Cannot obtain double[] from %s: Outcome expected", i.getFitness().getClass().getSimpleName()));
};
case CENTER -> i -> {
if (i.getFitness() instanceof Outcome) {
Outcome o = (Outcome) i.getFitness();
double[] xSpectrum = o.getCenterXPositionSpectrum(SPECTRUM_MIN_FREQ, SPECTRUM_MAX_FREQ, SPECTRUM_SIZE).values().stream()
.mapToDouble(d -> d)
.toArray();
double[] ySpectrum = o.getCenterYPositionSpectrum(SPECTRUM_MIN_FREQ, SPECTRUM_MAX_FREQ, SPECTRUM_SIZE).values().stream()
.mapToDouble(d -> d)
.toArray();
double[] angleSpectrum = o.getCenterAngleSpectrum(SPECTRUM_MIN_FREQ, SPECTRUM_MAX_FREQ, SPECTRUM_SIZE).values().stream()
.mapToDouble(d -> d)
.toArray();
double[] spectrum = new double[SPECTRUM_SIZE * 3];
System.arraycopy(xSpectrum, 0, spectrum, 0, SPECTRUM_SIZE);
System.arraycopy(ySpectrum, 0, spectrum, SPECTRUM_SIZE, SPECTRUM_SIZE);
System.arraycopy(angleSpectrum, 0, spectrum, 2 * SPECTRUM_SIZE, SPECTRUM_SIZE);
return spectrum;
}
throw new IllegalStateException(String.format("Cannot obtain double[] from %s: Outcome expected", i.getFitness().getClass().getSimpleName()));
};
case FOOTPRINTS -> i -> {
if (i.getFitness() instanceof Outcome) {
Outcome o = (Outcome) i.getFitness();
List<SortedMap<Domain, Double>> footprintsSpectra = o.getFootprintsSpectra(4, SPECTRUM_MIN_FREQ, SPECTRUM_MAX_FREQ, SPECTRUM_SIZE);
return footprintsSpectra.stream()
.map(SortedMap::values)
.flatMap(Collection::stream)
.mapToDouble(d -> d)
.toArray();
}
throw new IllegalStateException(String.format("Cannot obtain double[] from %s: Outcome expected", i.getFitness().getClass().getSimpleName()));
};
};
int length = builder.exampleFor(target).size();
return new SpeciatedEvolver<>(
builder.buildFor(target),
new FixedLengthListFactory<>(length, new UniformDoubleFactory(-1d, 1d)),
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new GaussianMutation(.35d), 1d - xOverProb,
new GeometricCrossover(Range.closed(-.5d, 1.5d)).andThen(new GaussianMutation(.1d)), xOverProb
),
nPop / nSpecies,
new KMeansSpeciator<>(
nSpecies,
-1,
new LNorm(2),
converter
),
0.75d,
true
);
}
}
| 4,986
| 43.132743
| 150
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/IntegersStandard.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.IndependentFactory;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.StandardEvolver;
import it.units.malelab.jgea.core.evolver.StandardWithEnforcedDiversityEvolver;
import it.units.malelab.jgea.core.operator.Mutation;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.selector.Last;
import it.units.malelab.jgea.core.selector.Tournament;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.ProbabilisticMutation;
import it.units.malelab.jgea.representation.sequence.UniformCrossover;
import java.util.List;
import java.util.Map;
/**
* @author eric
*/
public class IntegersStandard implements EvolverBuilder<List<Integer>> {
private final int nPop;
private final int nTournament;
private final double xOverProb;
private final boolean diversityEnforcement;
private final boolean remap;
public IntegersStandard(int nPop, int nTournament, double xOverProb, boolean diversityEnforcement, boolean remap) {
this.nPop = nPop;
this.nTournament = nTournament;
this.xOverProb = xOverProb;
this.diversityEnforcement = diversityEnforcement;
this.remap = remap;
}
@Override
public <T, F> Evolver<List<Integer>, T, F> build(PrototypedFunctionBuilder<List<Integer>, T> builder, T target, PartialComparator<F> comparator) {
int length = builder.exampleFor(target).size();
int maxValue = builder.exampleFor(target).get(0);
IndependentFactory<List<Integer>> factory = new FixedLengthListFactory<>(length, random -> random.nextInt(maxValue));
Mutation<Integer> mutation = (i, random) -> random.nextInt(maxValue);
double pMut = Math.max(0.01, 1d / (double) length);
if (!diversityEnforcement) {
return new StandardEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new ProbabilisticMutation<>(pMut, factory, mutation), 1d - xOverProb,
new UniformCrossover<>(factory)
.andThen(new ProbabilisticMutation<>(pMut, factory, mutation)), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap
);
}
return new StandardWithEnforcedDiversityEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new ProbabilisticMutation<>(1d / (double) length, factory, mutation), 1d - xOverProb,
new UniformCrossover<>(factory), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap,
100
);
}
}
| 3,031
| 35.53012
| 148
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/BinaryStandard.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.StandardEvolver;
import it.units.malelab.jgea.core.evolver.StandardWithEnforcedDiversityEvolver;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.selector.Last;
import it.units.malelab.jgea.core.selector.Tournament;
import it.units.malelab.jgea.representation.sequence.UniformCrossover;
import it.units.malelab.jgea.representation.sequence.bit.BitFlipMutation;
import it.units.malelab.jgea.representation.sequence.bit.BitString;
import it.units.malelab.jgea.representation.sequence.bit.BitStringFactory;
import java.util.Map;
/**
* @author eric
*/
public class BinaryStandard implements EvolverBuilder<BitString> {
private final int nPop;
private final int nTournament;
private final double xOverProb;
protected final boolean diversityEnforcement;
private final boolean remap;
public BinaryStandard(int nPop, int nTournament, double xOverProb, boolean diversityEnforcement, boolean remap) {
this.nPop = nPop;
this.nTournament = nTournament;
this.xOverProb = xOverProb;
this.diversityEnforcement = diversityEnforcement;
this.remap = remap;
}
@Override
public <T, F> Evolver<BitString, T, F> build(PrototypedFunctionBuilder<BitString, T> builder, T target, PartialComparator<F> comparator) {
int length = builder.exampleFor(target).size();
BitStringFactory factory = new BitStringFactory(length);
double pMut = Math.max(0.01, 1d / (double) length);
if (!diversityEnforcement) {
return new StandardEvolver<>(
builder.buildFor(target),
factory,
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new BitFlipMutation(pMut), 1d - xOverProb,
new UniformCrossover<>(factory)
.andThen(new BitFlipMutation(pMut)), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap
);
}
return new StandardWithEnforcedDiversityEvolver<>(
builder.buildFor(target),
new BitStringFactory(length),
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new BitFlipMutation(.01d), 1d - xOverProb,
new UniformCrossover<>(new BitStringFactory(length))
.andThen(new BitFlipMutation(pMut)), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap,
100
);
}
}
| 2,759
| 33.5
| 140
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/evolver/DoublesStandard.java
|
package it.units.erallab.evolution.builder.evolver;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.malelab.jgea.core.IndependentFactory;
import it.units.malelab.jgea.core.Individual;
import it.units.malelab.jgea.core.evolver.Evolver;
import it.units.malelab.jgea.core.evolver.StandardEvolver;
import it.units.malelab.jgea.core.evolver.StandardWithEnforcedDiversityEvolver;
import it.units.malelab.jgea.core.order.PartialComparator;
import it.units.malelab.jgea.core.selector.Last;
import it.units.malelab.jgea.core.selector.Tournament;
import it.units.malelab.jgea.representation.sequence.FixedLengthListFactory;
import it.units.malelab.jgea.representation.sequence.UniformCrossover;
import it.units.malelab.jgea.representation.sequence.numeric.GaussianMutation;
import it.units.malelab.jgea.representation.sequence.numeric.UniformDoubleFactory;
import java.util.List;
import java.util.Map;
/**
* @author eric
*/
public class DoublesStandard implements EvolverBuilder<List<Double>> {
private final int nPop;
private final int nTournament;
private final double xOverProb;
private final double sigmaMutation = 0.35;
protected final boolean diversityEnforcement;
private final boolean remap;
public DoublesStandard(int nPop, int nTournament, double xOverProb, boolean diversityEnforcement, boolean remap) {
this.nPop = nPop;
this.nTournament = nTournament;
this.xOverProb = xOverProb;
this.diversityEnforcement = diversityEnforcement;
this.remap = remap;
}
@Override
public <T, F> Evolver<List<Double>, T, F> build(PrototypedFunctionBuilder<List<Double>, T> builder, T target, PartialComparator<F> comparator) {
int length = builder.exampleFor(target).size();
IndependentFactory<List<Double>> doublesFactory = new FixedLengthListFactory<>(length, new UniformDoubleFactory(-1d, 1d));
if (!diversityEnforcement) {
return new StandardEvolver<>(
builder.buildFor(target),
doublesFactory,
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new GaussianMutation(sigmaMutation), 1d - xOverProb,
new UniformCrossover<>(doublesFactory).andThen(new GaussianMutation(sigmaMutation)), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap
);
}
return new StandardWithEnforcedDiversityEvolver<>(
builder.buildFor(target),
doublesFactory,
comparator.comparing(Individual::getFitness),
nPop,
Map.of(
new GaussianMutation(sigmaMutation), 1d - xOverProb,
new UniformCrossover<>(doublesFactory).andThen(new GaussianMutation(sigmaMutation)), xOverProb
),
new Tournament(nTournament),
new Last(),
nPop,
true,
remap,
100
);
}
}
| 2,914
| 35.4375
| 146
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedPhaseFunction.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.PhaseSin;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.ControllableVoxel;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.function.Function;
/**
* @author eric
*/
public class FixedPhaseFunction implements PrototypedFunctionBuilder<TimedRealFunction, Robot<?>> {
private final double frequency;
private final double amplitude;
public FixedPhaseFunction(double frequency, double amplitude) {
this.frequency = frequency;
this.amplitude = amplitude;
}
@Override
public Function<TimedRealFunction, Robot<?>> buildFor(Robot<?> robot) {
Grid<? extends ControllableVoxel> body = robot.getVoxels();
return function -> {
if (function.getInputDimension() != 2) {
throw new IllegalArgumentException(String.format(
"Wrong number of function input args: 2 expected, %d found",
function.getInputDimension()
));
}
return new Robot<>(
new PhaseSin(
frequency,
amplitude,
Grid.create(
body.getW(),
body.getH(),
(x, y) -> function.apply(0d, new double[]{
(double) x / (double) body.getW(),
(double) y / (double) body.getW()}
)[0]
)
),
SerializationUtils.clone(body)
);
};
}
@Override
public TimedRealFunction exampleFor(Robot<?> robot) {
return RealFunction.build(d -> d, 2, 1);
}
}
| 1,918
| 30.983333
| 99
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedPhaseValues.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.PhaseSin;
import it.units.erallab.hmsrobots.core.objects.ControllableVoxel;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class FixedPhaseValues implements PrototypedFunctionBuilder<List<Double>, Robot<?>> {
private final double frequency;
private final double amplitude;
public FixedPhaseValues(double frequency, double amplitude) {
this.frequency = frequency;
this.amplitude = amplitude;
}
@Override
public Function<List<Double>, Robot<?>> buildFor(Robot<?> robot) {
Grid<? extends ControllableVoxel> body = robot.getVoxels();
long nOfVoxel = body.values().stream().filter(Objects::nonNull).count();
return values -> {
if (nOfVoxel != values.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of values: %d expected, %d found",
nOfVoxel,
values.size()
));
}
int c = 0;
Grid<Double> phases = Grid.create(body);
for (Grid.Entry<?> entry : body) {
if (entry.getValue() != null) {
phases.set(entry.getX(), entry.getY(), values.get(c));
c = c + 1;
}
}
return new Robot<>(
new PhaseSin(frequency, amplitude, phases),
SerializationUtils.clone(body)
);
};
}
@Override
public List<Double> exampleFor(Robot<?> robot) {
long nOfVoxel = robot.getVoxels().values().stream().filter(Objects::nonNull).count();
return Collections.nCopies((int) nOfVoxel, 0d);
}
}
| 1,916
| 29.919355
| 92
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedPhaseAndFrequencyValues.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.TimeFunctions;
import it.units.erallab.hmsrobots.core.objects.ControllableVoxel;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializableFunction;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class FixedPhaseAndFrequencyValues implements PrototypedFunctionBuilder<List<Double>, Robot<?>> {
private final double amplitude;
public FixedPhaseAndFrequencyValues(double amplitude) {
this.amplitude = amplitude;
}
@Override
public Function<List<Double>, Robot<?>> buildFor(Robot<?> robot) {
Grid<? extends ControllableVoxel> body = robot.getVoxels();
long nOfVoxel = body.values().stream().filter(Objects::nonNull).count();
return values -> {
if (2 * nOfVoxel != values.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of values: %d expected, %d found",
nOfVoxel,
values.size()
));
}
int c = 0;
Grid<SerializableFunction<Double, Double>> functions = Grid.create(body);
for (Grid.Entry<?> entry : body) {
if (entry.getValue() != null) {
double f = values.get(c);
double phi = values.get(c + 1);
double finalAmplitude = amplitude;
functions.set(entry.getX(), entry.getY(), t -> finalAmplitude * Math.sin(2 * Math.PI * f * t + phi));
c = c + 2;
}
}
return new Robot<>(
new TimeFunctions(functions),
SerializationUtils.clone(body)
);
};
}
@Override
public List<Double> exampleFor(Robot<?> robot) {
long nOfVoxel = robot.getVoxels().values().stream().filter(Objects::nonNull).count();
return Collections.nCopies((int) nOfVoxel * 2, 0d);
}
}
| 2,119
| 32.125
| 111
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHeteroDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.function.Function;
/**
* @author eric
*/
public class FixedHeteroDistributed implements PrototypedFunctionBuilder<Grid<TimedRealFunction>, Robot<? extends SensingVoxel>> {
private final int signals;
public FixedHeteroDistributed(int signals) {
this.signals = signals;
}
@Override
public Function<Grid<TimedRealFunction>, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
Grid<int[]> dims = getIODims(robot);
Grid<? extends SensingVoxel> body = robot.getVoxels();
return functions -> {
//check
if (dims.getW() != functions.getW() || dims.getH() != functions.getH()) {
throw new IllegalArgumentException(String.format(
"Wrong size of functions grid: %dx%d expected, %dx%d found",
dims.getW(), dims.getH(),
functions.getW(), functions.getH()
));
}
for (Grid.Entry<int[]> entry : dims) {
if (entry.getValue() == null) {
continue;
}
if (functions.get(entry.getX(), entry.getY()).getInputDimension() != entry.getValue()[0]) {
throw new IllegalArgumentException(String.format(
"Wrong number of function input args at (%d,%d): %d expected, %d found",
entry.getX(), entry.getY(),
entry.getValue()[0],
functions.get(entry.getX(), entry.getY()).getInputDimension()
));
}
if (functions.get(entry.getX(), entry.getY()).getOutputDimension() != entry.getValue()[1]) {
throw new IllegalArgumentException(String.format(
"Wrong number of function output args at (%d,%d): %d expected, %d found",
entry.getX(), entry.getY(),
entry.getValue()[1],
functions.get(entry.getX(), entry.getY()).getOutputDimension()
));
}
}
//return
DistributedSensing controller = new DistributedSensing(body, signals);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), functions.get(entry.getX(), entry.getY()));
}
}
return new Robot<>(
controller,
SerializationUtils.clone(body)
);
};
}
@Override
public Grid<TimedRealFunction> exampleFor(Robot<? extends SensingVoxel> robot) {
return Grid.create(
getIODims(robot),
dim -> dim == null ? null : RealFunction.build(d -> d, dim[0], dim[1])
);
}
private Grid<int[]> getIODims(Robot<? extends SensingVoxel> robot) {
Grid<? extends SensingVoxel> body = robot.getVoxels();
return Grid.create(
body,
v -> v == null ? null : new int[]{
DistributedSensing.nOfInputs(v, signals),
DistributedSensing.nOfOutputs(v, signals)
}
);
}
}
| 3,425
| 36.23913
| 130
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/BodyAndHomoDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import it.units.erallab.hmsrobots.util.Utils;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class BodyAndHomoDistributed implements PrototypedFunctionBuilder<List<TimedRealFunction>, Robot<? extends SensingVoxel>> {
private final int signals;
private final double percentile;
public BodyAndHomoDistributed(int signals, double percentile) {
this.signals = signals;
this.percentile = percentile;
}
@Override
public Function<List<TimedRealFunction>, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
int w = robot.getVoxels().getW();
int h = robot.getVoxels().getH();
SensingVoxel voxelPrototype = robot.getVoxels().values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxelPrototype == null) {
throw new IllegalArgumentException("Target robot has no voxels");
}
int nOfInputs = DistributedSensing.nOfInputs(voxelPrototype, signals);
int nOfOutputs = DistributedSensing.nOfOutputs(voxelPrototype, signals);
//build body
return pair -> {
if (pair.size() != 2) {
throw new IllegalArgumentException(String.format(
"Wrong number of functions: 2 expected, %d found",
pair.size()
));
}
TimedRealFunction bodyFunction = pair.get(0);
TimedRealFunction brainFunction = pair.get(1);
//check function sizes
if (bodyFunction.getInputDimension() != 2 || bodyFunction.getOutputDimension() != 1) {
throw new IllegalArgumentException(String.format(
"Wrong number of body function args: 2->1 expected, %d->%d found",
bodyFunction.getInputDimension(),
bodyFunction.getOutputDimension()
));
}
if (brainFunction.getInputDimension() != nOfInputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of brain function input args: %d expected, %d found",
nOfInputs,
brainFunction.getInputDimension()
));
}
if (brainFunction.getOutputDimension() != nOfOutputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of brain function output args: %d expected, %d found",
nOfOutputs,
brainFunction.getOutputDimension()
));
}
//build body
Grid<Double> values = Grid.create(
w, h,
(x, y) -> bodyFunction.apply(0d, new double[]{(double) x / ((double) w - 1d), (double) y / ((double) h - 1d)})[0]
);
double threshold = new Percentile().evaluate(values.values().stream().mapToDouble(v -> v).toArray(), percentile);
values = Grid.create(values, v -> v >= threshold ? v : null);
values = Utils.gridLargestConnected(values, Objects::nonNull);
values = Utils.cropGrid(values, Objects::nonNull);
Grid<SensingVoxel> body = Grid.create(values, v -> (v != null) ? SerializationUtils.clone(voxelPrototype) : null);
if (body.values().stream().noneMatch(Objects::nonNull)) {
body = Grid.create(1, 1, SerializationUtils.clone(voxelPrototype));
}
//build brain
DistributedSensing controller = new DistributedSensing(body, signals);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(brainFunction));
}
}
return new Robot<>(controller, body);
};
}
@Override
public List<TimedRealFunction> exampleFor(Robot<? extends SensingVoxel> robot) {
SensingVoxel voxelPrototype = robot.getVoxels().values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxelPrototype == null) {
throw new IllegalArgumentException("Target robot has no voxels");
}
return List.of(
RealFunction.build(d -> d, 2, 1),
RealFunction.build(
d -> d,
DistributedSensing.nOfInputs(voxelPrototype, signals),
DistributedSensing.nOfOutputs(voxelPrototype, signals)
)
);
}
}
| 4,751
| 41.053097
| 130
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHomoNonDirectionalDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensingNonDirectional;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author eric
*/
public class FixedHomoNonDirectionalDistributed implements PrototypedFunctionBuilder<TimedRealFunction, Robot<? extends SensingVoxel>> {
private final int signals;
public FixedHomoNonDirectionalDistributed(int signals) {
this.signals = signals;
}
@Override
public Function<TimedRealFunction, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
int[] dim = getIODim(robot);
Grid<? extends SensingVoxel> body = robot.getVoxels();
int nOfInputs = dim[0];
int nOfOutputs = dim[1];
return function -> {
if (function.getInputDimension() != nOfInputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of function input args: %d expected, %d found",
nOfInputs,
function.getInputDimension()
));
}
if (function.getOutputDimension() != nOfOutputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of function output args: %d expected, %d found",
nOfOutputs,
function.getOutputDimension()
));
}
DistributedSensing controller = new DistributedSensingNonDirectional(body, signals);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(function));
}
}
return new Robot<>(
controller,
SerializationUtils.clone(body)
);
};
}
@Override
public TimedRealFunction exampleFor(Robot<? extends SensingVoxel> robot) {
int[] dim = getIODim(robot);
return RealFunction.build(d -> d, dim[0], dim[1]);
}
private int[] getIODim(Robot<? extends SensingVoxel> robot) {
Grid<? extends SensingVoxel> body = robot.getVoxels();
SensingVoxel voxel = body.values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxel == null) {
throw new IllegalArgumentException("Target robot has no voxels");
}
int nOfInputs = DistributedSensingNonDirectional.nOfInputs(voxel, signals);
int nOfOutputs = DistributedSensingNonDirectional.nOfOutputs(voxel, signals);
List<Grid.Entry<? extends SensingVoxel>> wrongVoxels = body.stream()
.filter(e -> e.getValue() != null)
.filter(e -> DistributedSensingNonDirectional.nOfInputs(e.getValue(), signals) != nOfInputs)
.collect(Collectors.toList());
if (!wrongVoxels.isEmpty()) {
throw new IllegalArgumentException(String.format(
"Cannot build %s robot mapper for this body: all voxels should have %d inputs, but voxels at positions %s have %s",
getClass().getSimpleName(),
nOfInputs,
wrongVoxels.stream()
.map(e -> String.format("(%d,%d)", e.getX(), e.getY()))
.collect(Collectors.joining(",")),
wrongVoxels.stream()
.map(e -> String.format("%d", DistributedSensingNonDirectional.nOfInputs(e.getValue(), signals)))
.collect(Collectors.joining(","))
));
}
return new int[]{nOfInputs, nOfOutputs};
}
}
| 3,920
| 39.42268
| 136
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/BodyAndSinusoidal.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.TimeFunctions;
import it.units.erallab.hmsrobots.core.objects.ControllableVoxel;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import it.units.erallab.hmsrobots.util.Utils;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
/**
* @author eric
*/
public class BodyAndSinusoidal implements PrototypedFunctionBuilder<Grid<double[]>, Robot<?>> {
public enum Component {FREQUENCY, AMPLITUDE, PHASE}
private final double minF;
private final double maxF;
private final double percentile;
private final Set<Component> components;
public BodyAndSinusoidal(double minF, double maxF, double percentile, Set<Component> components) {
this.minF = minF;
this.maxF = maxF;
this.percentile = percentile;
this.components = components;
}
@Override
public Function<Grid<double[]>, Robot<?>> buildFor(Robot<?> robot) {
ControllableVoxel voxelPrototype = robot.getVoxels().values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxelPrototype == null) {
throw new IllegalArgumentException("Target robot has no valid voxels");
}
//build body
return grid -> {
//check grid sizes
if (grid.getW() != robot.getVoxels().getW() || grid.getH() != robot.getVoxels().getH()) {
throw new IllegalArgumentException(String.format(
"Wrong grid size: %dx%d expected, %dx%d found",
robot.getVoxels().getW(), robot.getVoxels().getH(),
grid.getW(), grid.getH()
));
}
//check grid element size
if (grid.values().stream().anyMatch(v -> v.length != 1 + components.size())) {
Grid.Entry<double[]> firstWrong = grid.stream().filter(e -> e.getValue().length != 1 + components.size()).findFirst().orElse(null);
if (firstWrong == null) {
throw new NullPointerException("Unexpected empty wrong grid item");
}
throw new IllegalArgumentException(String.format(
"Wrong number of values in grid at %d,%d size: %d expected, %d found",
firstWrong.getX(), firstWrong.getY(),
1 + components.size(),
firstWrong.getValue().length
));
}
//build body
double threshold = percentile > 0 ? new Percentile().evaluate(grid.values().stream().mapToDouble(v -> v[0]).toArray(), percentile) : 0d;
Grid<double[]> cropped = Utils.cropGrid(Utils.gridLargestConnected(
Grid.create(grid, v -> v[0] >= threshold ? v : null),
Objects::nonNull
), Objects::nonNull);
Grid<ControllableVoxel> body = Grid.create(cropped, v -> (v != null) ? SerializationUtils.clone(voxelPrototype) : null);
if (body.values().stream().noneMatch(Objects::nonNull)) {
body = Grid.create(1, 1, SerializationUtils.clone(voxelPrototype));
}
//build controller
TimeFunctions controller = new TimeFunctions(Grid.create(
body.getW(),
body.getH(),
(x, y) -> {
int c = 1;
double freq;
double phase;
double amplitude;
double[] vs = cropped.get(x, y);
if (vs == null) {
vs = new double[1 + Component.values().length];
}
if (components.contains(Component.FREQUENCY)) {
freq = minF + (maxF - minF) * (clip(vs[c]) + 1d) / 2d;
c = c + 1;
} else {
freq = (minF + maxF) / 2d;
}
if (components.contains(Component.PHASE)) {
phase = Math.PI * (clip(vs[c]) + 1d) / 2d;
c = c + 1;
} else {
phase = 0d;
}
if (components.contains(Component.AMPLITUDE)) {
amplitude = (clip(vs[c]) + 1d) / 2d;
c = c + 1;
} else {
amplitude = 1d;
}
return t -> amplitude * Math.sin(2 * Math.PI * freq * t + phase);
}
));
return new Robot<>(controller, body);
};
}
private static double clip(double value) {
return Math.min(Math.max(value, -1), 1);
}
@Override
public Grid<double[]> exampleFor(Robot<?> robot) {
ControllableVoxel prototypeVoxel = robot.getVoxels().values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (prototypeVoxel == null) {
throw new IllegalArgumentException("Target robot has no valid voxels");
}
return Grid.create(robot.getVoxels().getW(), robot.getVoxels().getH(), new double[1 + components.size()]);
}
}
| 4,880
| 37.738095
| 142
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/SensorAndBodyAndHomoDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.core.sensors.Constant;
import it.units.erallab.hmsrobots.core.sensors.Sensor;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import it.units.erallab.hmsrobots.util.Utils;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
/**
* @author eric
*/
public class SensorAndBodyAndHomoDistributed implements PrototypedFunctionBuilder<List<TimedRealFunction>, Robot<? extends SensingVoxel>> {
private final int signals;
private final double percentile;
private final boolean withPositionSensors;
public SensorAndBodyAndHomoDistributed(int signals, double percentile, boolean withPositionSensors) {
this.signals = signals;
this.percentile = percentile;
this.withPositionSensors = withPositionSensors;
}
@Override
public Function<List<TimedRealFunction>, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
int w = robot.getVoxels().getW();
int h = robot.getVoxels().getH();
List<Sensor> prototypeSensors = getPrototypeSensors(robot);
int nOfInputs = DistributedSensing.nOfInputs(new SensingVoxel(prototypeSensors.subList(0, 1)), signals) + (withPositionSensors ? 2 : 0);
int nOfOutputs = DistributedSensing.nOfOutputs(new SensingVoxel(prototypeSensors.subList(0, 1)), signals);
//build body
return pair -> {
if (pair.size() != 2) {
throw new IllegalArgumentException(String.format(
"Wrong number of functions: 2 expected, %d found",
pair.size()
));
}
TimedRealFunction bodyFunction = pair.get(0);
TimedRealFunction brainFunction = pair.get(1);
//check function sizes
if (bodyFunction.getInputDimension() != 2 || bodyFunction.getOutputDimension() != prototypeSensors.size()) {
throw new IllegalArgumentException(String.format(
"Wrong number of body function args: 2->%d expected, %d->%d found",
prototypeSensors.size(),
bodyFunction.getInputDimension(),
bodyFunction.getOutputDimension()
));
}
if (brainFunction.getInputDimension() != nOfInputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of brain function input args: %d expected, %d found",
nOfInputs,
brainFunction.getInputDimension()
));
}
if (brainFunction.getOutputDimension() != nOfOutputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of brain function output args: %d expected, %d found",
nOfOutputs,
brainFunction.getOutputDimension()
));
}
//build body
Grid<double[]> values = Grid.create(
w, h,
(x, y) -> bodyFunction.apply(0d, new double[]{(double) x / ((double) w - 1d), (double) y / ((double) h - 1d)})
);
double threshold = new Percentile().evaluate(
values.values().stream().mapToDouble(SensorAndBodyAndHomoDistributed::max).toArray(),
percentile
);
values = Grid.create(values, vs -> max(vs) >= threshold ? vs : null);
values = Utils.gridLargestConnected(values, Objects::nonNull);
values = Utils.cropGrid(values, Objects::nonNull);
Grid<SensingVoxel> body = new Grid<>(values.getW(), values.getH(), null);
for (int x = 0; x < body.getW(); x++) {
for (int y = 0; y < body.getH(); y++) {
int rx = (int) Math.floor((double) x / (double) body.getW() * (double) w);
int ry = (int) Math.floor((double) y / (double) body.getH() * (double) h);
if (values.get(x, y) != null) {
List<Sensor> availableSensors = robot.getVoxels().get(rx, ry) != null ? robot.getVoxels().get(rx, ry).getSensors() : prototypeSensors;
body.set(x, y, new SensingVoxel(withPositionSensors ?
List.of(
SerializationUtils.clone(availableSensors.get(indexOfMax(values.get(x, y)))),
new Constant((double) x / ((double) body.getW() - 1d), (double) y / ((double) body.getH() - 1d))
) :
List.of(
SerializationUtils.clone(availableSensors.get(indexOfMax(values.get(x, y))))
)
));
}
}
}
if (body.values().stream().noneMatch(Objects::nonNull)) {
body = Grid.create(1, 1, new SensingVoxel(List.of(SerializationUtils.clone(prototypeSensors.get(indexOfMax(values.get(0, 0)))))));
}
//build brain
DistributedSensing controller = new DistributedSensing(body, signals);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(brainFunction));
}
}
return new Robot<>(controller, body);
};
}
static double max(double[] vs) {
double max = vs[0];
for (int i = 1; i < vs.length; i++) {
max = Math.max(max, vs[i]);
}
return max;
}
static int indexOfMax(double[] vs) {
int indexOfMax = 0;
for (int i = 1; i < vs.length; i++) {
if (vs[i] > vs[indexOfMax]) {
indexOfMax = i;
}
}
return indexOfMax;
}
@Override
public List<TimedRealFunction> exampleFor(Robot<? extends SensingVoxel> robot) {
List<Sensor> sensors = getPrototypeSensors(robot);
return List.of(
RealFunction.build(d -> d, 2, sensors.size()),
RealFunction.build(
d -> d,
DistributedSensing.nOfInputs(new SensingVoxel(sensors.subList(0, 1)), signals) + (withPositionSensors ? 2 : 0),
DistributedSensing.nOfOutputs(new SensingVoxel(sensors.subList(0, 1)), signals)
)
);
}
static List<Sensor> getPrototypeSensors(Robot<? extends SensingVoxel> robot) {
SensingVoxel voxelPrototype = robot.getVoxels().values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxelPrototype == null) {
throw new IllegalArgumentException("Target robot has no voxels");
}
if (voxelPrototype.getSensors().isEmpty()) {
throw new IllegalArgumentException("Target robot has no sensors");
}
if (voxelPrototype.getSensors().stream().mapToInt(s -> s.getDomains().length).distinct().count() != 1) {
throw new IllegalArgumentException(String.format(
"Target robot has sensors with different number of outputs: %s",
voxelPrototype.getSensors().stream().mapToInt(s -> s.getDomains().length).distinct()
));
}
return voxelPrototype.getSensors();
}
}
| 7,174
| 41.708333
| 146
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHeteroQuantizedSpikingDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedDistributedSpikingSensing;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedLIFNeuron;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.QuantizedMultivariateSpikingFunction;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.stv.QuantizedSpikeTrainToValueConverter;
import it.units.erallab.hmsrobots.core.controllers.snndiscr.converters.vts.QuantizedValueToSpikeTrainConverter;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.function.Function;
/**
* @author eric
*/
public class FixedHeteroQuantizedSpikingDistributed implements PrototypedFunctionBuilder<Grid<QuantizedMultivariateSpikingFunction>, Robot<? extends SensingVoxel>> {
private final int signals;
private final QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter;
private final QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter;
public FixedHeteroQuantizedSpikingDistributed(int signals, QuantizedValueToSpikeTrainConverter valueToSpikeTrainConverter, QuantizedSpikeTrainToValueConverter spikeTrainToValueConverter) {
this.signals = signals;
this.valueToSpikeTrainConverter = valueToSpikeTrainConverter;
this.spikeTrainToValueConverter = spikeTrainToValueConverter;
}
@Override
public Function<Grid<QuantizedMultivariateSpikingFunction>, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
Grid<int[]> dims = getIODims(robot);
Grid<? extends SensingVoxel> body = robot.getVoxels();
return functions -> {
//check
if (dims.getW() != functions.getW() || dims.getH() != functions.getH()) {
throw new IllegalArgumentException(String.format(
"Wrong size of functions grid: %dx%d expected, %dx%d found",
dims.getW(), dims.getH(),
functions.getW(), functions.getH()
));
}
for (Grid.Entry<int[]> entry : dims) {
if (entry.getValue() == null) {
continue;
}
if (functions.get(entry.getX(), entry.getY()).getInputDimension() != entry.getValue()[0]) {
throw new IllegalArgumentException(String.format(
"Wrong number of function input args at (%d,%d): %d expected, %d found",
entry.getX(), entry.getY(),
entry.getValue()[0],
functions.get(entry.getX(), entry.getY()).getInputDimension()
));
}
if (functions.get(entry.getX(), entry.getY()).getOutputDimension() != entry.getValue()[1]) {
throw new IllegalArgumentException(String.format(
"Wrong number of function output args at (%d,%d): %d expected, %d found",
entry.getX(), entry.getY(),
entry.getValue()[1],
functions.get(entry.getX(), entry.getY()).getOutputDimension()
));
}
}
//return
QuantizedDistributedSpikingSensing controller = new QuantizedDistributedSpikingSensing(body, signals, new QuantizedLIFNeuron(), valueToSpikeTrainConverter, spikeTrainToValueConverter);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), functions.get(entry.getX(), entry.getY()));
}
}
return new Robot<>(
controller,
SerializationUtils.clone(body)
);
};
}
@Override
public Grid<QuantizedMultivariateSpikingFunction> exampleFor(Robot<? extends SensingVoxel> robot) {
return Grid.create(
getIODims(robot),
dim -> dim == null ? null : QuantizedMultivariateSpikingFunction.build(d -> d, dim[0], dim[1])
);
}
private Grid<int[]> getIODims(Robot<? extends SensingVoxel> robot) {
Grid<? extends SensingVoxel> body = robot.getVoxels();
return Grid.create(
body,
v -> v == null ? null : new int[]{
DistributedSensing.nOfInputs(v, signals),
DistributedSensing.nOfOutputs(v, signals)
}
);
}
}
| 4,435
| 43.808081
| 190
|
java
|
null |
VSRCollectiveControlViaSNCA-main/src/main/java/it/units/erallab/evolution/builder/robot/FixedHomoDistributed.java
|
package it.units.erallab.evolution.builder.robot;
import it.units.erallab.evolution.builder.PrototypedFunctionBuilder;
import it.units.erallab.hmsrobots.core.controllers.DistributedSensing;
import it.units.erallab.hmsrobots.core.controllers.RealFunction;
import it.units.erallab.hmsrobots.core.controllers.TimedRealFunction;
import it.units.erallab.hmsrobots.core.objects.Robot;
import it.units.erallab.hmsrobots.core.objects.SensingVoxel;
import it.units.erallab.hmsrobots.util.Grid;
import it.units.erallab.hmsrobots.util.SerializationUtils;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author eric
*/
public class FixedHomoDistributed implements PrototypedFunctionBuilder<TimedRealFunction, Robot<? extends SensingVoxel>> {
private final int signals;
public FixedHomoDistributed(int signals) {
this.signals = signals;
}
@Override
public Function<TimedRealFunction, Robot<? extends SensingVoxel>> buildFor(Robot<? extends SensingVoxel> robot) {
int[] dim = getIODim(robot);
Grid<? extends SensingVoxel> body = robot.getVoxels();
int nOfInputs = dim[0];
int nOfOutputs = dim[1];
return function -> {
if (function.getInputDimension() != nOfInputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of function input args: %d expected, %d found",
nOfInputs,
function.getInputDimension()
));
}
if (function.getOutputDimension() != nOfOutputs) {
throw new IllegalArgumentException(String.format(
"Wrong number of function output args: %d expected, %d found",
nOfOutputs,
function.getOutputDimension()
));
}
DistributedSensing controller = new DistributedSensing(body, signals);
for (Grid.Entry<? extends SensingVoxel> entry : body) {
if (entry.getValue() != null) {
controller.getFunctions().set(entry.getX(), entry.getY(), SerializationUtils.clone(function));
}
}
return new Robot<>(
controller,
SerializationUtils.clone(body)
);
};
}
@Override
public TimedRealFunction exampleFor(Robot<? extends SensingVoxel> robot) {
int[] dim = getIODim(robot);
return RealFunction.build(d -> d, dim[0], dim[1]);
}
private int[] getIODim(Robot<? extends SensingVoxel> robot) {
Grid<? extends SensingVoxel> body = robot.getVoxels();
SensingVoxel voxel = body.values().stream().filter(Objects::nonNull).findFirst().orElse(null);
if (voxel == null) {
throw new IllegalArgumentException("Target robot has no voxels");
}
int nOfInputs = DistributedSensing.nOfInputs(voxel, signals);
int nOfOutputs = DistributedSensing.nOfOutputs(voxel, signals);
List<Grid.Entry<? extends SensingVoxel>> wrongVoxels = body.stream()
.filter(e -> e.getValue() != null)
.filter(e -> DistributedSensing.nOfInputs(e.getValue(), signals) != nOfInputs)
.collect(Collectors.toList());
if (!wrongVoxels.isEmpty()) {
throw new IllegalArgumentException(String.format(
"Cannot build %s robot mapper for this body: all voxels should have %d inputs, but voxels at positions %s have %s",
getClass().getSimpleName(),
nOfInputs,
wrongVoxels.stream()
.map(e -> String.format("(%d,%d)", e.getX(), e.getY()))
.collect(Collectors.joining(",")),
wrongVoxels.stream()
.map(e -> String.format("%d", DistributedSensing.nOfInputs(e.getValue(), signals)))
.collect(Collectors.joining(","))
));
}
return new int[]{nOfInputs, nOfOutputs};
}
}
| 3,737
| 37.9375
| 125
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.