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 |
---|---|---|---|---|---|---|
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/PartialOrder.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* PartialOrder maintain a partial order within a set of initial
* elements given a sequence of orderings specified (via update())
* in the form (node > {body})
*
* The associated iterator will iterate from smallest to largest.
*
* @param <T>
*/
public class PartialOrder<T> implements Iterable<T> {
class Node {
int level;
Set<T> edges;
public Node() {
level = -1;
edges = new HashSet<T>();
}
public Node(Collection<T> set) {
level = -1;
edges = new HashSet<T>(set);
}
void add(T element) {
edges.add(element);
}
void addAll(Collection<T> elements) {
edges.addAll(elements);
}
public String toString() {
String res = "Node(" + level + ",{";
String delimit = "";
for (T e: edges) {
res += delimit + e.toString();
delimit = ",";
}
return res + "})";
}
}
private Map<T,Node> graph;
private List<T> elements;
private Set<T> unbound;
public PartialOrder() {
graph = new HashMap<T,Node>();
elements = null;
unbound = new HashSet<>();
}
public PartialOrder(Map<T,Collection<T>> ingraph) {
this();
for (T key: ingraph.keySet()) {
graph.put(key,new Node(ingraph.get(key)));
}
}
public Map<T,Set<T>> getGraph() {
Map<T,Set<T>> res = new HashMap<>();
for (T key: graph.keySet()) {
res.put(key,graph.get(key).edges);
}
return res;
}
private int orderNodes (int level, Collection<T> keys) {
int res = level;
for (T key: keys) {
Node entry = graph.get(key);
if (entry == null) {
// Leaf nodes (no children)
entry = new Node();
graph.put(key,entry);
}
if (entry.level < level) {
entry.level = level;
res = Math.max(res,orderNodes(level+1,entry.edges));
}
}
return res;
}
private int orderNodes() {
return orderNodes(0,new ArrayList<>(graph.keySet()));
}
private void resetOrder() {
if (elements == null) return;
elements = null;
for (T key: graph.keySet()) {
graph.get(key).level = -1;
}
}
private void computeOrder() {
int size = orderNodes();
@SuppressWarnings("unchecked")
Set<T> level[] = new HashSet[size];
for (int index = 0; index<size; index++) {
level[index] = new HashSet<>();
}
Set<T> keySet = graph.keySet();
for (T key: keySet) {
level[graph.get(key).level].add(key);
}
elements = new ArrayList<>();
unbound.addAll(level[0]);
for (int index = 1; index<size; index++) {
elements.addAll(level[index]);
}
unbound.removeAll(elements);
elements.addAll(0,unbound);
//System.out.println("Processed Graph : " + graph);
}
public List<T> unbound() {
if (elements == null) {
computeOrder();
}
return new ArrayList<>(unbound);
}
public List<T> totalOrder() {
if (elements == null) {
computeOrder();
}
return elements;
}
public List<T> ordinalToEntry() {
return totalOrder();
}
public Map<T,Integer> entryToOrdinal() {
List<T> order = totalOrder();
Map<T,Integer> res = new HashMap<T,Integer>();
int index = 0;
for (T entry: order) {
res.put(entry,index);
index++;
}
return res;
}
public void update(T node, Collection<T> body) {
resetOrder();
Node entry = graph.get(node);
entry = (entry == null) ? new Node() : entry;
entry.addAll(body);
graph.put(node, entry);
}
public void update(Collection<T> nodes, Collection<T> body) {
if (nodes.isEmpty()) unbound.addAll(body);
for (T node: nodes) {
update(node,body);
}
}
public void update(T node, T body) {
Set<T> entry = new HashSet<T>();
entry.add(body);
update(node,entry);
}
public void update(Collection<T> nodes, T body) {
if (nodes.isEmpty()) unbound.add(body);
for (T node: nodes) {
update(node,body);
}
}
public void update(T node) {
resetOrder();
Node entry = graph.get(node);
entry = (entry == null) ? new Node() : entry;
graph.put(node, entry);
}
@Override
public Iterator<T> iterator() {
List<T> res = new ArrayList<T>(totalOrder());
Collections.reverse(res);
return res.iterator();
}
public static void main(String args[]) {
PartialOrder<String> order = new PartialOrder<>();
order.update("A","B");
order.update("A","C");
order.update("A","D");
List<String> Torder = order.totalOrder();
String delimitor = "";
for (String name: Torder) {
System.out.print(delimitor + name);
delimitor = " ";
}
System.out.println("");
order.update("D","C");
Torder = order.totalOrder();
delimitor = "";
for (String name: Torder) {
System.out.print(delimitor + name);
delimitor = " ";
}
System.out.println("");
order.update("C","B");
Torder = order.totalOrder();
delimitor = "";
for (String name: Torder) {
System.out.print(delimitor + name);
delimitor = " ";
}
System.out.println("");
order = new PartialOrder<>();
order.update("A","B");
order.update("A","C");
Torder = order.totalOrder();
delimitor = "";
for (String name: Torder) {
System.out.print(delimitor + name);
delimitor = " ";
}
System.out.println("");
}
}
| 5,461 | 21.11336 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/ArrayIterator.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
import java.util.Iterator;
public class ArrayIterator<T> implements Iterator<T> {
private int next;
private T[] array;
public ArrayIterator(T[] array) {
this.next = 0;
this.array = array;
}
@Override
public boolean hasNext() {
return next < array.length;
}
@Override
public T next() {
return array[next++];
}
}
| 569 | 16.272727 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/ID.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
/**
* ID implements a hierarchical naming scheme for Lustre.
*
*/
public class ID {
// Our objective is to encode hierarchy in signal names.
// We want to use the '_' character as a delimiter.
// It is easiest, however, to us a pair of characters.
// We will use 'x' as our second delimiter.
//
// quoted <-> raw
// xx <-> x
// x_ <-> _
// _ <-> .
//
// .binding.1.2.3
//
// A generated name will always start with a "." in the local context.
//
// An example dotted (translated) string might be:
//
// .nodeA_12.nodeB_2.x.3.4
//
// The would correspond to the encoded string:
//
// _nodeAx_12_nodeBx_2_x_3_4
//
// Which means (reading from right to left): the 4th expression in the
// 3rd expression constituting signal 'x' in the 2nd node call (nodeB)
// in the 12th node call (nodeA) of the current node.
//
// We have a partial ordering .. we can define a visitor that will
// provide us with a bottom-up node ordering.
//
static String dottedString(String arg) {
int size = arg.length();
String res = "";
for (int i=0;i<size;i++) {
char c = arg.charAt(i);
if (c == 'x') {
i++;
if (! (i < size)) break;
c = arg.charAt(i);
} else if (c == '_') {
c = '.';
}
res += c;
}
return res;
}
public static String cleanString(String arg) {
if (arg == null) return arg;
int size = arg.length();
String res = "";
for (int i=0;i<size;i++) {
char c = arg.charAt(i);
if (c == ' ') {
res += "_";
} else if (c == '|') {
res += "_";
} else if (c == '#') {
res += "_";
} else if (c == '(') {
res += "_";
} else if (c == ')') {
res += "_";
} else if (c == '=') {
res += "_";
} else if (c == '-') {
res += "_";
} else if (c == '/') {
res += "_";
} else if (c == '.') {
res += "_";
} else if (c == ',') {
res += "_";
} else if (c == '[') {
res += "_";
} else if (c == ']') {
res += "_";
} else {
res += c;
}
}
return res;
}
public static String encodeString(String arg) {
if (arg == null) return arg;
int size = arg.length();
String res = "";
for (int i=0;i<size;i++) {
char c = arg.charAt(i);
if (c == 'x') {
res += "xx";
} else if (c == '_') {
res += "x_";
} else {
res += c;
}
}
return res;
}
public static String decodeString(String arg) {
if (arg == null) return arg;
int size = arg.length();
String res = "";
for (int i=0;i<size;i++) {
char c = arg.charAt(i);
if (c == 'x') {
if (i+1>=arg.length()) {
res += c;
} else {
char c2 = arg.charAt(i+1);
if ((c2 == 'x') || (c2 == '_')){
res += c2;
i++;
} else {
res += c;
}
}
}
else{
res += c;
}
}
return res;
}
public static String location() {
return location(1);
}
public static String location(int depth) {
assert(depth >= 0);
StackTraceElement e = Thread.currentThread().getStackTrace()[2 + depth];
String res = e.getClassName() + ":" + e.getLineNumber();
res = res.substring(Math.max(0,res.length() - 37));
res = String.format("%-38s",res);
res += "| ";
return res;
}
}
| 3,726 | 22.29375 | 74 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/Rat.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Random;
import fuzzm.poly.EmptyIntervalException;
import fuzzm.value.hierarchy.EvaluatableValue;
import fuzzm.value.instance.BooleanValue;
import fuzzm.value.instance.IntegerValue;
import fuzzm.value.instance.RationalValue;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.CastExpr;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.IfThenElseExpr;
import jkind.lustre.NamedType;
import jkind.lustre.RealExpr;
import jkind.lustre.Type;
import jkind.util.BigFraction;
public class Rat {
public static final Random oracle = new Random();
public static BigFraction BigFractionFromString(String value){
String[] strs = value.split("/");
if (strs.length <= 2) {
BigInteger num = new BigInteger(strs[0]);
if (strs.length > 1) {
BigInteger denom = new BigInteger(strs[1]);
return new BigFraction(num, denom);
}
return new BigFraction(num);
}
else{
throw new IllegalArgumentException("Couldn't parse string argument \"" + value + "\" as a BigFraction");
}
}
public static NamedType TypeFromString(String type) {
if (type.equals("int")) return NamedType.INT;
if (type.equals("bool")) return NamedType.BOOL;
if (type.equals("real")) return NamedType.REAL;
throw new IllegalArgumentException("Couldn't interpret string argument \"" + type + "\" as a NamedType");
}
public static EvaluatableValue ValueFromTypedFraction(NamedType ntype, BigFraction fvalue) {
if (ntype == NamedType.REAL) return new RationalValue(fvalue);
if (fvalue.getDenominator().compareTo(BigInteger.ONE) == 0) {
if (ntype == NamedType.INT) return new IntegerValue(fvalue.getNumerator());
if (ntype == NamedType.BOOL) {
if (fvalue.getNumerator().compareTo(BigInteger.ZERO) == 0) return BooleanValue.FALSE;
if (fvalue.getNumerator().compareTo(BigInteger.ONE) == 0) return BooleanValue.TRUE;
}
}
throw new IllegalArgumentException("Value " + fvalue + " should be integral");
}
public static EvaluatableValue ValueFromString(String type, String value) {
BigFraction fvalue = BigFractionFromString(value);
NamedType ntype = TypeFromString(type);
return ValueFromTypedFraction(ntype,fvalue);
}
public static Expr toExpr(BigFraction x) {
Expr N = new RealExpr(new BigDecimal(x.getNumerator()));
Expr D = new RealExpr(new BigDecimal(x.getDenominator()));
if (x.getDenominator().equals(BigInteger.ONE)) {
return N;
}
System.out.println(ID.location() + "Rational : " + x);
Expr res = new BinaryExpr(N,BinaryOp.DIVIDE,D);
return res;
}
public static Expr cast(String name, Type type) {
Expr res = new IdExpr(name);
if (type == NamedType.BOOL) {
res = new IfThenElseExpr(res,new RealExpr(BigDecimal.ONE),new RealExpr(BigDecimal.ZERO));
} else if (type == NamedType.INT) {
res = new CastExpr(NamedType.REAL,res);
}
return res;
}
// this is purely for testing
protected static double pubBias (double rnd, int bias){
return bias(rnd, bias);
}
private static double bias(double rnd, int bias) {
assert(-1 <= bias && bias <= 1);
// So now we want to bias the selection towards the target
// in some reasonable way. We consider three cases and
// define three cutoff values in the range [0.0 .. 1.0):
//
// target to the left of range : 1/3
// target within the range : 1/2
// target to the right of range: 2/3
//
// We then use an (x-cutoff)^4 cumulative probability
// distribution. The 4th power is sharper than a
// simple quadratic but simpler to invert than a 3rd
// power.
//
// The result should be that we prefer values near the
// extremes of the range and prefer values closer to
// the target (when the target is not in range) by a
// 2:1 ratio.
//
double cutoff = 0.5 - bias*(0.5 - 1.0/3.0);
double sign = 0.0;
if (rnd < cutoff) {
rnd = rnd/cutoff;
sign = -cutoff;
} else {
rnd = (rnd - cutoff)/(1.0 - cutoff);
sign = (1.0 - cutoff);
}
rnd = cutoff + sign*Math.sqrt(Math.sqrt(rnd));
return rnd;
}
private static BigFraction biasedRandom(boolean biased, int bias, BigFraction min, BigFraction max) {
double drnd = biased ? bias(oracle.nextDouble(),bias) : oracle.nextDouble();
BigDecimal rnd = BigDecimal.valueOf(drnd);
BigFraction r = BigFraction.valueOf(rnd);
BigFraction offset = (max.subtract(min)).multiply(r);
BigFraction res = min.add(offset);
return res;
}
public static BigFraction biasedRandom(Type type, boolean biased, int bias, BigFraction min, BigFraction max) {
BigFraction res = null;
if (type == NamedType.REAL) {
res = biasedRandom(biased,bias,min,max);
} else if (type == NamedType.BOOL) {
if (min.compareTo(max) == 0) return min;
res = oracle.nextBoolean() ? BigFraction.ONE : BigFraction.ZERO;
} else {
// it should be an invariant that the denominator is ONE
BigFraction imin = roundUp(min);
BigFraction imax = roundDown(max);
if (imin.compareTo(imax) >= 0) {
if (imin.compareTo(imax) == 0) return imin;
throw new EmptyIntervalException();
}
res = biasedRandom(biased,bias,imin,imax.add(BigFraction.ONE));
res = res.subtract(imin);
BigInteger N = res.getNumerator();
BigInteger D = res.getDenominator();
BigInteger Q = N.divide(D);
res = new BigFraction(Q).add(imin);
}
assert(min.compareTo(res) <= 0) && (res.compareTo(max) <= 0);
return res;
}
public static BigFraction roundDown(BigFraction max) {
BigInteger div[] = max.getNumerator().divideAndRemainder(max.getDenominator());
BigInteger Q = div[0];
BigInteger R = div[1];
BigFraction res;
if (R.signum() == 0) {
res = new BigFraction(Q);
} else if (R.signum() < 0) {
res = new BigFraction(Q.subtract(BigInteger.ONE));
} else {
res = new BigFraction(Q);
}
assert(res.compareTo(max) <= 0) : "Rounding down : " + res + " <= " + max + " (" + Q + "*" + max.getDenominator() + " + " + R + ")";
assert(max.signum()*res.signum() >= 0) : "Rounding down : " + res + " <= " + max + " (" + Q + "*" + max.getDenominator() + " + " + R + ")" ;
assert(max.subtract(res).compareTo(BigFraction.ONE) <= 0);
return res;
}
public static BigFraction roundUp(BigFraction min) {
BigInteger div[] = min.getNumerator().divideAndRemainder(min.getDenominator());
BigInteger Q = div[0];
BigInteger R = div[1];
BigFraction res;
if (R.signum() == 0) {
res = new BigFraction(Q);
} else if (R.signum() > 0) {
res = new BigFraction(Q.add(BigInteger.ONE));
} else {
res = new BigFraction(Q);
}
assert(res.compareTo(min) >= 0) : "Rounding up : " + res + " >= " + min + " (" + Q + "*" + min.getDenominator() + " + " + R + ")";
assert(min.signum()*res.signum() >= 0) : "Rounding up : " + res + " >= " + min + " (" + Q + "*" + min.getDenominator() + " + " + R + ")";
assert(res.subtract(min).compareTo(BigFraction.ONE) <= 0);
return res;
}
}
| 7,198 | 34.117073 | 142 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/TypedName.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
import jkind.lustre.NamedType;
public class TypedName {
public final String name;
public final NamedType type;
public TypedName(String name, NamedType type) {
this.name = name.intern();
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof TypedName))
return false;
TypedName other = (TypedName) obj;
return name == other.name;
}
@Override
public String toString() {
return name;
}
}
| 921 | 17.816327 | 67 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/IDString.java | /*
* Copyright (C) 2018, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.util;
public class IDString {
private final String prefix;
private final String base;
private IDString(String prefix, String base) {
this.prefix = prefix;
this.base = ID.cleanString(base);
}
public static IDString newID(String base) {
return new IDString("",base);
}
public static IDString newID(String prefix, String base, long index) {
return new IDString(prefix + "_" + index,base);
}
public IDString index(long index) {
return newID(prefix,base,index);
}
public IDString prefix(String prefix) {
return new IDString(prefix,base);
}
public String name() {
return "__" + prefix + "_" + base;
}
@Override
public String toString() {
throw new IllegalArgumentException();
}
}
| 1,034 | 26.236842 | 74 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/heuristic/HeuristicInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.heuristic;
import fuzzm.lustre.BooleanCtx;
import fuzzm.lustre.generalize.PolyGeneralizationResult;
import fuzzm.util.RatSignal;
public interface HeuristicInterface {
String name();
boolean objective();
BooleanCtx hyp();
BooleanCtx constraint();
RatSignal target();
// Mark this feature as "in process"
void wait(boolean objective);
// Query the status of this feature
boolean ready();
// Resolve the feature as SAT
void sat(boolean objective, double time, RatSignal counterExample, PolyGeneralizationResult res);
// Resolve the feature as UNSAT
void unsat(boolean objective);
boolean done();
}
| 858 | 19.452381 | 98 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/heuristic/Features.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.heuristic;
import java.util.ArrayList;
import java.util.List;
import fuzzm.FuzzMConfiguration;
import fuzzm.util.ID;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
public class Features {
List<HeuristicInterface> body;
int totalSolutions;
int next;
public Features(FuzzMConfiguration cfg) {
//ExprVect v = new ExprVect(cfg.inputNames);
List<Expr> features;
List<String> properties = cfg.model.getMainNode().properties;
features = new ArrayList<>();
for (String name: properties) {
features.add(new IdExpr(name));
}
if (features.size() <= 0) {
System.out.println(ID.location() + "*** Error: Model Suggests no Fuzzable Features");
throw new RuntimeException();
}
body = new ArrayList<HeuristicInterface>();
int pcount = cfg.Proof ? 2 : -1;
for (int i=0;i<features.size();i++) {
Expr feature = features.get(i);
feature = cfg.constraints ? feature : new UnaryExpr(UnaryOp.NOT,feature);
body.add(new PropertyHeuristic(cfg.getSpan(),properties.get(i),feature,pcount));
}
totalSolutions = cfg.solutions;
next = 0;
}
public int size() {
return body.size();
}
public HeuristicInterface selectFeature(int featureID) {
return body.get(featureID);
}
public boolean done() {
if (totalSolutions == 0) return true;
boolean done = true;
for (HeuristicInterface I: body) {
done &= I.done();
}
return done;
}
public int nextFeatureID() throws FeatureException {
// TODO: We really want to be able to implement
// an arbitrary heuristic here ..
if (totalSolutions == 0) throw new FeatureException();
int featureID;
int tries = 0;
do {
featureID = next;
next = (next + 1) % body.size();
tries++;
} while ((! body.get(featureID).ready()) && (! (tries > body.size())));
if (tries > body.size()) {
throw new FeatureException();
}
totalSolutions = (totalSolutions < 0) ? -1 : totalSolutions-1;
return featureID;
}
}
| 2,249 | 24.862069 | 89 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/heuristic/FeatureException.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.heuristic;
public class FeatureException extends Exception {
private static final long serialVersionUID = 978083607871348822L;
}
| 358 | 21.4375 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/heuristic/PropertyHeuristic.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.heuristic;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import fuzzm.lustre.BooleanCtx;
import fuzzm.lustre.PolyConstraintCtx;
import fuzzm.lustre.generalize.PolyGeneralizationResult;
import fuzzm.lustre.generalize.ReMapExpr;
import fuzzm.poly.Variable;
import fuzzm.util.ID;
import fuzzm.util.IntervalVector;
import fuzzm.util.RatSignal;
import fuzzm.value.poly.GlobalState;
import jkind.lustre.Expr;
class ConstraintQueue {
private Queue<BooleanCtx> constraintHistory = new LinkedList<>();
private BooleanCtx allConstraints = new BooleanCtx();
public void popConstraint() {
//allConstraints.printDecls(ID.location());
if (constraintHistory.isEmpty()) return;
@SuppressWarnings("unused")
BooleanCtx drop = constraintHistory.poll();
//drop.printDecls(ID.location());
BooleanCtx res = new BooleanCtx();
for (BooleanCtx b: constraintHistory) {
res = res.and(b);
}
allConstraints = res;
//allConstraints.printDecls(ID.location());
return;
}
public void pushConstraint(BooleanCtx constraint) {
//constraint.printDecls(ID.location());
//allConstraints.printDecls(ID.location());
constraintHistory.add(constraint);
allConstraints = allConstraints.and(constraint);
//allConstraints.printDecls(ID.location());
}
public boolean isEmpty() {
return constraintHistory.isEmpty();
}
public BooleanCtx currentConstraint() {
return allConstraints;
}
}
class PossibleHistory {
ConstraintQueue cqueue = new ConstraintQueue();
BooleanCtx pending = null;
public void tryConstraint(BooleanCtx constraint) {
//System.out.println(ID.location() + "tryConstraint()");
//if (constraint != null) constraint.printDecls(ID.location());
if (pending != null) {
cqueue.pushConstraint(pending);
}
pending = constraint;
}
public void doConstraint(BooleanCtx constraint) {
//System.out.println(ID.location() + "doConstraint()");
//constraint.printDecls(ID.location());
tryConstraint(null);
cqueue.pushConstraint(constraint);
}
public boolean popConstraint() {
//System.out.println(ID.location() + "popConstraint()");
boolean justTrying = true;
if (pending == null) {
justTrying = false;
cqueue.popConstraint();
}
pending = null;
return justTrying;
}
public boolean isEmpty() {
return (pending == null) && cqueue.isEmpty();
}
public BooleanCtx currentConstraint() {
BooleanCtx res = cqueue.currentConstraint();
if (pending == null) return res;
return res.and(pending);
}
}
class UNSATTracker {
PossibleHistory history = new PossibleHistory();
private boolean unsat = false;
public BooleanCtx currentConstraint() {
return history.currentConstraint();
}
public void unsat() {
if (history.isEmpty()) {
unsat = true;
return;
}
history.popConstraint();
return;
}
public boolean done() {
return unsat;
}
}
class ProbeHeuristics extends UNSATTracker {
int maxEphemeral = 1;
int remainingEphemeral = 0;
private BooleanCtx doProposeHyp(List<Variable> targets, ReMapExpr remap) {
remainingEphemeral = maxEphemeral;
Collections.shuffle(targets);
Variable target = targets.get(0);
System.out.println(ID.location() + "Targeting : " + target.toString());
return new PolyConstraintCtx(target,remap);
}
private BooleanCtx doSampleHyp(List<Variable> targets, List<Variable> artifacts, ReMapExpr remap) {
int artifactCount = artifacts.size();
int options = targets.size() + artifacts.size();
maxEphemeral = maxEphemeral > artifactCount ? maxEphemeral : artifactCount;
int min = remainingEphemeral < options ? remainingEphemeral : options;
remainingEphemeral = (2*min + 5*remainingEphemeral)/8;
double p = (artifactCount*1.0)/(options*1.0);
List<Variable> src = (GlobalState.oracle().nextDouble() < p) ? artifacts : targets;
Collections.shuffle(src);
Variable target = src.get(0);
System.out.println(ID.location() + "Sampling : " + target.toString());
return new PolyConstraintCtx(target,remap);
}
protected void sat(PolyGeneralizationResult res) {
List<Variable> targets = res.result.getTargets();
List<Variable> artifacts = res.result.getArtifacts();
if (targets.isEmpty() && artifacts.isEmpty()) {
history.popConstraint();
} else {
BooleanCtx constraint;
if (artifacts.isEmpty() || ((! targets.isEmpty()) && (remainingEphemeral == 0))) {
constraint = doProposeHyp(targets,res.remap);
history.doConstraint(constraint);
} else {
constraint = doSampleHyp(targets,artifacts,res.remap);
history.tryConstraint(constraint);
}
}
return;
}
}
class HistoryHeuristics extends ProbeHeuristics {
int initializations = 0;
int k0 = -1;
double ktime0 = -1.0;
private void updateStats(int k, double ktime) {
if (initializations == 0) {
k0 = k;
ktime0 = ktime;
} else {
ktime0 = (ktime0*initializations + ktime)/(initializations + 1.0);
}
initializations += (initializations >= 99) ? 0 : 1;
}
public void sat(int k, double ktime, PolyGeneralizationResult res) {
updateStats(k,ktime);
if ((k != k0) || (ktime >= 1.2*ktime0)) {
boolean justTrying = history.popConstraint();
if (! justTrying) return;
}
super.sat(res);
}
}
class BoundHistory extends HistoryHeuristics {
int count;
public BoundHistory(int count) {
this.count = count;
}
private void countDown() {
count = (count <= 0) ? count : count - 1;
}
public void sat(int k, double ktime, PolyGeneralizationResult res) {
countDown();
super.sat(k,ktime,res);
}
public void unsat() {
countDown();
super.unsat();
}
@Override
public boolean done() {
return (count == 0) || super.done();
}
}
public class PropertyHeuristic implements HeuristicInterface {
final String name;
RatSignal lastCounterExample = new RatSignal();
boolean ready = true;
IntervalVector S;
Expr constraint;
BoundHistory history;
public PropertyHeuristic(IntervalVector S, String name, Expr constraint, int count) {
this.name = name;
this.constraint = constraint;
this.S = S;
//this.currHyp = new BooleanCtx();
this.history = new BoundHistory(count);
}
@Override
public String name() {
return name;
}
@Override
public boolean objective() {
return false;
}
@Override
public BooleanCtx hyp() {
BooleanCtx res = history.currentConstraint();
//res.printDecls(ID.location());
return res;
}
@Override
public BooleanCtx constraint() {
return new BooleanCtx(constraint);
}
@Override
public RatSignal target() {
return RatSignal.uniformRandom(lastCounterExample.size(), S);
}
@Override
public void wait(boolean objective) {
ready = false;
}
@Override
public boolean ready() {
return ready && (! history.done());
}
@Override
public void sat(boolean objective, double time, RatSignal counterExample, PolyGeneralizationResult res) {
lastCounterExample = counterExample;
ready = true;
int k = counterExample.size();
history.sat(k,time/k,res);
}
@Override
public void unsat(boolean objective) {
ready = true;
history.unsat();
}
@Override
public boolean done() {
return history.done();
}
}
| 8,258 | 28.183746 | 106 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/heuristic/FuzzHeuristic.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.heuristic;
import fuzzm.lustre.BooleanCtx;
import fuzzm.util.ID;
import fuzzm.util.RatSignal;
import jkind.lustre.BoolExpr;
import jkind.lustre.Expr;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
/***
*
* The SATMode tracks the known mode of a property based on previous
* attempts to satisfy or falsify the property. Presumably the
* mode starts out NONE. If the property can be satisfied, it will
* be TRUE and if it can be falsified it will be FALSE. If the
* property can be both satisfied and falsified, the mode will be
* SAT, otherwise it will be UNSAT.
*
*/
enum SATMode {
NONE,
TRUE,
FALSE,
SAT,
UNSAT;
private SATMode satTransition(boolean objective) {
switch (this) {
case NONE:
return objective ? TRUE : FALSE;
case TRUE:
return objective ? TRUE : SAT;
case FALSE:
return objective ? SAT : FALSE;
default:
return this;
}
}
SATMode unsat(int id) {
switch (this) {
case SAT:
return this;
default:
System.out.println(ID.location() + "id:" + id + " is now UNSAT");
return UNSAT;
}
}
boolean satisfiable() {
return this.equals(SAT);
}
boolean ready() {
return ! this.equals(UNSAT);
}
public SATMode sat(int id, boolean objective) {
SATMode mode = satTransition(objective);
if (! this.equals(SAT)) {
System.out.println(ID.location() + "id:" + id + " is now " + mode);
}
return mode;
}
}
/***
*
* The fuzz heuristic alternates attempts to satisfy and falsify
* a property. It tracks the mode of the property to ensure that
* the property is satisfiable.
*
*/
public abstract class FuzzHeuristic implements HeuristicInterface {
int id = -1;
private SATMode mode = SATMode.NONE;
boolean wait[] = { false, false };
private boolean priority = true;
private Expr property[] = { new BoolExpr(false), new BoolExpr(true)};
public FuzzHeuristic() {
}
public FuzzHeuristic(int id, Expr property) {
this.id = id;
setProperty(property);
}
static int index(boolean objective) {
return objective ? 1 : 0;
}
int index() {
return index(objective());
}
public BooleanCtx hyp() {
return new BooleanCtx();
}
public Expr prop() {
assert(property != null);
Expr prop = property[index()];
System.out.println(ID.location() + "Prop : " + prop);
return prop;
}
abstract public RatSignal target();
public BooleanCtx constraint() {
Expr prop = prop();
BooleanCtx res = new BooleanCtx();
return res.implies(prop);
}
protected final void setProperty(Expr property) {
this.property[index(true)] = property;
this.property[index(false)] = new UnaryExpr(UnaryOp.NOT,property);
}
public Expr getProperty() {
return property[index()];
}
protected void setPriority(boolean priority) {
this.priority = priority;
}
private void unwait(boolean objective) {
int index = index(objective);
wait[index] = false;
}
public void wait(boolean objective) {
int index = index(objective);
wait[index] = true;
}
private boolean waiting(boolean objective) {
return wait[index(objective)];
}
public boolean objective() {
return waiting(priority) ? (! priority) : priority;
}
public boolean ready() {
boolean readymode = mode.ready() && (! ((waiting(true) && waiting(false))));
return readymode;
}
public boolean satisfiable() {
return mode.satisfiable();
}
public void sat(boolean objective) {
mode = mode.sat(id,objective);
priority = waiting(objective) ? ! priority : priority;
unwait(objective);
}
abstract public void sat(boolean objective, RatSignal cex, BooleanCtx hyp);
public void unsat(boolean objective) {
mode = mode.unsat(id);
priority = waiting(objective) ? ! priority : priority;
unwait(objective);
}
}
| 4,081 | 21.677778 | 78 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/OutputEngine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeoutException;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.CounterExampleMessage;
import fuzzm.engines.messages.ExitException;
import fuzzm.engines.messages.ReceiveQueue;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.sender.FlowControlledPublisher;
import fuzzm.sender.OutputMsgTypes;
import fuzzm.sender.PrintSender;
import fuzzm.util.Debug;
import fuzzm.util.ID;
import fuzzm.util.RatSignal;
import fuzzm.util.RatVect;
import fuzzm.util.TypedName;
import jkind.lustre.NamedType;
/**
* The OutputEngine sits at the end of the processing pipeline and transmits
* test vectors. If a target is specified, it will send the vectors via UDP. If
* debug is specified, it dumps them to stdout.
*
* @param <Model>
*/
public class OutputEngine extends Engine {
static final public int TARGET_TIMEOUT_MS = 1;
static final public Duration CONFIG_SPEC_TRANSMIT_PERIOD = Duration.ofSeconds(5);
Instant lastConfigSpecSentInstant;
final PrintSender printSender;
final ReceiveQueue<TestVectorMessage> tvqueue;
final ReceiveQueue<CounterExampleMessage> cexqueue;
int sequenceID;
FlowControlledPublisher publisher;
private static final String EXCHANGE_NAME = "fuzzm-output-engine";
String configSpecMsg;
public OutputEngine(FuzzMConfiguration cfg, Director director) {
super(EngineName.OutputEngine, cfg, director);
tvqueue = new ReceiveQueue<TestVectorMessage>(QUEUE_SIZE_1M, this);
cexqueue = new ReceiveQueue<CounterExampleMessage>(0, this);
if (Debug.isEnabled()) {
printSender = new PrintSender();
} else {
printSender = null;
}
sequenceID = 0;
lastConfigSpecSentInstant = Instant.now();
configSpecMsg = "";
for (TypedName key : cfg.getSpan().keySet()) {
configSpecMsg = configSpecMsg.concat(" ");
configSpecMsg = configSpecMsg.concat(ID.decodeString(key.name));
configSpecMsg = configSpecMsg.concat(" ");
assert (cfg.getSpan().get(key).type instanceof NamedType);
configSpecMsg = configSpecMsg.concat(cfg.getSpan().get(key).type.toString());
}
if (cfg.target != null) {
try {
publisher = new FlowControlledPublisher(EXCHANGE_NAME, cfg.target);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
@Override
protected void handleMessage(TestVectorMessage m) {
if (m == null) {
throw new IllegalArgumentException();
}
tvqueue.push(m);
}
@Override
protected void handleMessage(CounterExampleMessage m) {
if (m == null) {
throw new IllegalArgumentException();
}
cexqueue.push(m);
}
private void processSocketTX() throws ExitException {
TestVectorMessage tv = tvqueue.pop_non_blocking();
if (tv != null) {
if (cfg.target != null) {
send(tv.signal, OutputMsgTypes.TEST_VECTOR_MSG_TYPE.toString());
}
if (printSender != null) {
printSender.send(tv);
}
}
CounterExampleMessage cex = cexqueue.pop_non_blocking();
if (cex != null) {
if (cfg.target != null) {
send(cex.counterExample, OutputMsgTypes.COUNTER_EXAMPLE_MSG_TYPE.toString());
}
if (printSender != null) {
printSender.send(cex);
}
}
}
public void send(RatSignal values, String routingKey) {
int time = 0;
for (RatVect rv : values) {
String value = "" + sequenceID + " " + time;
for (TypedName key : cfg.getSpan().keySet()) {
value = value.concat(" ");
assert (rv.containsKey(key));
value = value.concat(rv.get(key).getNumerator().toString());
if (key.type == NamedType.REAL) {
value = value.concat(" ");
value = value.concat(rv.get(key).getDenominator().toString());
}
}
// System.out.println(ID.location() + "UDP Sending Vector : " + txID);
try {
publisher.basicPublish(EXCHANGE_NAME, routingKey, null, value.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
sequenceID++;
time++;
}
}
public void sendConfigSpec() {
if (cfg.target != null) {
try {
publisher.basicPublish(EXCHANGE_NAME, OutputMsgTypes.CONFIG_SPEC_MSG_TYPE.toString(), null,
configSpecMsg.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
}
@Override
protected void main() {
System.out.println(ID.location() + name + " is starting ..");
sendConfigSpec();
try {
while (true) {
processSocketTX();
if (Instant.now().isAfter(lastConfigSpecSentInstant.plus(CONFIG_SPEC_TRANSMIT_PERIOD))) {
sendConfigSpec();
lastConfigSpecSentInstant = Instant.now();
}
}
} catch (ExitException e) {
}
if (cfg.target != null) {
try {
publisher.close();
} catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}
System.out.println(ID.location() + name + " is exiting.");
}
}
| 6,184 | 32.074866 | 107 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/GeneralizationEngine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.util.Map;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.CounterExampleMessage;
import fuzzm.engines.messages.ExitException;
import fuzzm.engines.messages.FeatureID;
import fuzzm.engines.messages.GeneralizedMessage;
import fuzzm.engines.messages.QueueName;
import fuzzm.engines.messages.ReceiveQueue;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.engines.messages.TransmitQueue;
import fuzzm.lustre.FuzzProgram;
import fuzzm.lustre.generalize.PolyGeneralizationResult;
import fuzzm.lustre.generalize.PolygonalGeneralizer;
import fuzzm.poly.RegionBounds;
import fuzzm.util.Debug;
import fuzzm.util.EvaluatableSignal;
import fuzzm.util.FuzzMInterval;
import fuzzm.util.FuzzmName;
import fuzzm.util.ID;
import fuzzm.util.IntervalVector;
import fuzzm.util.TypedName;
import jkind.lustre.Program;
/**
* The Generalization engine takes counter examples from the
* solver and generalizes them.
*
* @param <SModel>
*/
public class GeneralizationEngine extends Engine {
final ReceiveQueue<CounterExampleMessage> cequeue;
final TransmitQueue<GeneralizedMessage> genserver;
// final TransmitQueue<IntervalVectorMessage> intserver;
//List<VarDecl> inputNames;
// private static final SimulationResults TRUE = new ConcreteSimulationResults();
public GeneralizationEngine(FuzzMConfiguration cfg, Director director) {
super(EngineName.GeneralizationEngine, cfg, director);
cequeue = new ReceiveQueue<CounterExampleMessage>(0,this);
genserver = new TransmitQueue<GeneralizedMessage>(this,QueueName.GeneralizedMessage);
// intserver = new TransmitQueue<IntervalVectorMessage>(this,QueueName.IntervalVectorMessage);
this.tx.add(genserver);
// this.tx.add(intserver);
}
@Override
protected void handleMessage(CounterExampleMessage m) {
cequeue.push(m);
}
@Override
protected void handleMessage(TestVectorMessage m) {
assert(false);
}
// @SuppressWarnings("unused")
// private BooleanCtx packageAssertions (){
// List<Expr> assertions = model.getMainNode().assertions;
// BooleanCtx assertionCtx = new BooleanCtx(assertions);
//
// assertionCtx.bind(FuzzmName.assertion);
// Expr andedExpr = assertionCtx.getExpr();
//
// Expr assertExpr = new IdExpr(FuzzmName.assertion);
// Expr preassert = new UnaryExpr(UnaryOp.PRE, assertExpr);
//
// Expr arrowRHS = new BinaryExpr(preassert, BinaryOp.AND, andedExpr);
// Expr assertionRHS = new BinaryExpr(andedExpr, BinaryOp.ARROW, arrowRHS);
//
// assertExpr = assertionCtx.define(FuzzmName.assertion, NamedType.BOOL, assertionRHS);
// assertionCtx.setExpr(assertExpr);
// return assertionCtx;
// }
GeneralizedMessage generalizeCounterExample(CounterExampleMessage m) {
// For now we just generalize.
// TODO: we eventually want to target a vector.
int k = m.counterExample.size();
assert(k > 0);
//System.out.println(ID.location() + m);
Program testMain = FuzzProgram.fuzz(model,m.prop);
//System.out.println(ID.location() + "\n" + testMain);
EvaluatableSignal evaluatableCEX = m.counterExample.evaluatableSignal();
// Polygonal generalization ..
System.out.println(ID.location() + "Starting Generalization ..");
PolyGeneralizationResult polyCEX = PolygonalGeneralizer.generalizeInterface(evaluatableCEX,m.name,FuzzmName.fuzzProperty,m.fns,testMain);
if (Debug.isEnabled()) {
System.out.println(ID.location() + "Generalization : " + polyCEX);
//System.out.println(ID.location() + "ACL2 : " + polyCEX.toACL2());
}
// Event-based generalization ..
//
// Simulator genSim = Simulator.newSimulator(evaluatableCEX,m.fns, FuzzMName.fuzzProperty, testMain, TRUE);
// Generalizer generalizer = new Generalizer(genSim);
//
// List<SignalName> signalNames = m.counterExample.signalNames();
// Collections.shuffle(signalNames);
// Map<SignalName,EvaluatableValue> genMap = generalizer.eventBasedGeneralization(signalNames);
// IntervalSignal res = new IntervalSignal();
// for (int time=0;time<m.counterExample.size();time++) {
// IntervalVector iv = new IntervalVector();
// RatVect cv = m.counterExample.get(time);
// for (TypedName name : cv.keySet()) {
// SignalName sn = new SignalName(name,time);
// EvaluatableValue itz = genMap.get(sn);
// FuzzMInterval bkz = boundInterval(itz,cfg.getSpan().get(name));
// iv.put(name, bkz);
// }
// res.add(iv);
// }
/*
FuzzMModel cex = new FuzzMModel(testMain.getMainNode(),m.counterExample);
SimpleModel sm = cex.toSimpleModel();
Specification specification = new Specification(testMain.getMainNode(),testMain.functions,true,false);
// Modifies sm ..
try {
ModelReconstructionEvaluator.reconstruct(specification, sm, FuzzMName.fuzzProperty, k, true);
ModelGeneralizer mg = new ModelGeneralizer(specification,FuzzMName.fuzzProperty,sm,k);
//List<StreamIndex> z = m.signal.encode().keySet().stream().map(x -> StreamIndex.decode(x)).collect(Collectors.toList());
//Collections.shuffle(z);
//List<StreamIndex> streamIndices = new ArrayList<>();
//for (SignalName sn: signalNames) {
// streamIndices.add(new StreamIndex(sn.name,sn.time));
//}
Model gem;
{
long startTime = System.currentTimeMillis();
gem = mg.generalize();
long endTime = System.currentTimeMillis();
System.out.println(ID.location() + "JKind Generalization Time = " + (endTime - startTime) + " ms");
}
res = new IntervalSignal(k, testMain.getMainNode().inputs, gem, cfg.getSpan());
for (int time=0;time<res.size();time++) {
IntervalVector iv = res.get(time);
for (String name : iv.keySet()) {
SignalName sn = new SignalName(name,time);
//EvaluatableValue itz = genMap.get(sn);
FuzzMInterval bkz = iv.get(name);
//System.out.println(ID.location() + "Generalized Value " + sn + " : " + bkz); // + " ~=~ "+ itz);
//assert(itz.getLow().equals(bkz.min));
//assert(itz.getHigh().equals(bkz.max));
}
}
} catch (Throwable t) {
System.out.println(ID.location() + "JKind Generalization Failed : " + m);
System.out.flush();
throw new Error(t);
}
*/
if(m.id.constraintID == -1){
// here the span holds its default values
initSpan(polyCEX.result.intervalBounds(), m.id);
// now the span holds the (possibly new) actual input bounds(from vacuous constraint)
}
return new GeneralizedMessage(name,m,polyCEX);
}
// private FuzzMInterval boundInterval(EvaluatableValue itz, FuzzMInterval FuzzMInterval) {
// InstanceType<?> max = ((EvaluatableType<?>) itz).getHigh();
// InstanceType<?> min = ((EvaluatableType<?>) itz).getLow();
// BigFraction bmax = max.isFinite() ? ((RationalValue) max.rationalType()).value() : FuzzMInterval.max;
// BigFraction bmin = min.isFinite() ? ((RationalValue) min.rationalType()).value() : FuzzMInterval.min;
// return new FuzzMInterval(FuzzMInterval.type,bmin,bmax);
// }
private void initSpan (Map<TypedName,RegionBounds> zed, FeatureID cid) {
IntervalVector newSpan = new IntervalVector(cfg.getSpan());
for (TypedName name: zed.keySet()) {
if (newSpan.containsKey(name)) {
FuzzMInterval iv = newSpan.get(name);
RegionBounds bnd = zed.get(name);
newSpan.put(name, bnd.updateInterval(iv));
}
}
cfg.setSpan(newSpan);
System.out.println(ID.location() + "Updated Span : " + newSpan);
}
@Override
protected void main() {
System.out.println(ID.location() + name + " is starting ..");
try {
while (true) {
CounterExampleMessage cem = cequeue.pop();
try {
GeneralizedMessage res = generalizeCounterExample(cem);
genserver.push(res);
} catch (Throwable e) {
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
System.err.println(ID.location() + "** Generalization Exception : " + cause.getClass().getName());
}
}
} catch (ExitException e) {
}
System.out.println(ID.location() + name + " is exiting.");
}
}
| 8,203 | 35.300885 | 139 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/GeneratorEngine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.ExitException;
import fuzzm.engines.messages.GeneralizedMessage;
import fuzzm.engines.messages.QueueName;
import fuzzm.engines.messages.ReceiveQueue;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.engines.messages.TransmitQueue;
import fuzzm.poly.EmptyIntervalException;
import fuzzm.poly.VariableID;
import fuzzm.util.ID;
import fuzzm.util.Rat;
import fuzzm.util.RatSignal;
import jkind.util.BigFraction;
/**
* The Generator engine is responsible for instantiating the
* generalized counterexamples and producing test vectors.
*
* @param <Model>
*/
public class GeneratorEngine extends Engine {
final ReceiveQueue<GeneralizedMessage> gmqueue;
final TransmitQueue<TestVectorMessage> testserver;
//private boolean unbiased;
public GeneratorEngine(FuzzMConfiguration settings, Director director) {
super(EngineName.GeneratorEngine, settings, director);
gmqueue = new ReceiveQueue<GeneralizedMessage>(QUEUE_SIZE_1K,this);
testserver = new TransmitQueue<TestVectorMessage>(this,QueueName.TestVectorMessage);
this.tx.add(testserver);
//unbiased = settings.unbiased;
}
@Override
protected void handleMessage(GeneralizedMessage m) {
gmqueue.push(m);
}
RatSignal generateSignal(GeneralizedMessage gm, Map<VariableID,BigFraction> ctx) {
return gm.nextBiasedVector(Rat.oracle.nextBoolean(),min,max,cfg.getSpan(),ctx);
}
private static final BigInteger TWO = BigInteger.valueOf(2);
private BigInteger step = BigInteger.valueOf(100);
private BigFraction min = new BigFraction(BigInteger.valueOf(-100));
private BigFraction max = new BigFraction(BigInteger.valueOf( 100));
private BigInteger count = BigInteger.valueOf(100);
void generateTestVectors() throws ExitException {
GeneralizedMessage gm = gmqueue.pop();
while (true) {
if (gm.id.constraintID != -1) {
// TODO: We probably want to re-architect this a bit
long startTime = System.currentTimeMillis();
long totalSize = 0;
int size = gm.polyCEX.result.bytes();
Collection<VariableID> unbound = gm.polyCEX.result.unboundVariables(); // gm.generalizedCEX
for (@SuppressWarnings("unused") long n: gm) {
Map<VariableID,BigFraction> ctx = new HashMap<>();
for (VariableID vid: unbound) {
ctx.put(vid, Rat.biasedRandom(vid.name.name.type,false,0,min,max));
}
try {
RatSignal sig= generateSignal(gm,ctx);
TestVectorMessage m = new TestVectorMessage(name,gm,sig);
totalSize += size;
testserver.pushTest(m);
if (cfg.throttle) sleep(100);
} catch (EmptyIntervalException e) {
System.out.println(ID.location() + "Vector Generation Failure.");
System.exit(1);
}
}
long endTime = System.currentTimeMillis();
long delta = (endTime - startTime);
if (delta > 10) System.out.println(ID.location() + "Vector Generation Rate = " + (1000*totalSize)/delta + " fields/s");
count = count.subtract(BigInteger.ONE);
if (count.signum() <= 0) {
step = step.multiply(TWO);
count = step;
max = new BigFraction(step);
min = new BigFraction(step.negate());
}
}
GeneralizedMessage nx = gmqueue.pop_non_blocking();
if (nx != null) gm = nx;
}
}
@Override
protected void main() {
System.out.println(ID.location() + name + " is starting ..");
try {
generateTestVectors();
} catch (ExitException e) {
}
System.out.println(ID.location() + name + " is exiting.");
}
}
| 3,871 | 31.537815 | 123 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/SolverEngine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.math.BigInteger;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.ConstraintMessage;
import fuzzm.engines.messages.CounterExampleMessage;
import fuzzm.engines.messages.ExitException;
import fuzzm.engines.messages.QueueName;
import fuzzm.engines.messages.ReceiveQueue;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.engines.messages.TransmitQueue;
import fuzzm.engines.messages.UnsatMessage;
import fuzzm.lustre.FuzzProgram;
import fuzzm.lustre.optimize.PolygonalOptimizer;
import fuzzm.solver.Solver;
import fuzzm.solver.SolverResults;
import fuzzm.util.Debug;
import fuzzm.util.EvaluatableSignal;
import fuzzm.util.FuzzmName;
import fuzzm.util.ID;
import fuzzm.util.IntervalVector;
import fuzzm.util.RatSignal;
import fuzzm.util.RatVect;
import fuzzm.util.TypedName;
import jkind.lustre.Program;
import jkind.util.BigFraction;
/**
* The Solver Engine is responsible for invoking the solver
* (currently JKind) and obtaining a counterexample.
*
*/
public class SolverEngine extends Engine {
final ReceiveQueue<ConstraintMessage> cqueue;
final TransmitQueue<CounterExampleMessage> cexserver;
final TransmitQueue<UnsatMessage> satserver;
Solver slvr;
FuzzMConfiguration cfg;
// private static final SimulationResults TRUE = new ConcreteSimulationResults();
public SolverEngine(FuzzMConfiguration cfg, Director director) {
super(EngineName.SolverEngine, cfg, director);
// We limit ourselves to 4 active constraints ..
cqueue = new ReceiveQueue<ConstraintMessage>(4,this);
cexserver = new TransmitQueue<CounterExampleMessage>(this,QueueName.CounterExampleMessage);
satserver = new TransmitQueue<UnsatMessage>(this,QueueName.UnsatMessage);
this.tx.add(cexserver);
this.tx.add(satserver);
slvr = cfg.configureSolver();
this.cfg = cfg;
}
@Override
protected void handleMessage(ConstraintMessage m) {
cqueue.push(m);
}
@Override
protected void handleMessage(TestVectorMessage m) {
assert(false);
}
@Override
protected void main() {
System.out.println(ID.location() + name + " is starting ..");
try {
//int count = 0;
while (true) {
//waitForNextMessage();
ConstraintMessage m = cqueue.pop();
try {
// Make things stop early ..
//while (count > 1) {sleep(10000);}
//count++;
slvr.randomSolver();
//System.out.println(ID.location() + m);
Program solverMain = FuzzProgram.fuzz(model,m.hyp.implies(m.prop));
Program generalizeMain = FuzzProgram.fuzz(model,m.prop);
//System.out.println(ID.location() + "\n" + newMain);
SolverResults sr = slvr.invoke(solverMain);
RatSignal counterExample = sr.cex;
int k = counterExample.size();
if (k > 0) {
//System.err.println(ID.location() + "Solver Solution : " + sr);
//Map<String,EvaluatableValue> intervalValues[] = counterExample.intervalValues();
//EventBasedSimulator ratSim = new EventBasedIntervalSimulator(intervalValues, FuzzMName.fuzzProperty, newMain);
//IntervalOptimizer optimizer = new IntervalOptimizer(ratSim);
//System.out.println(ID.location() + "Initial Solution : " + k + "*" + counterExample.get(0).size());
EvaluatableSignal evaluatableCEX = counterExample.evaluatableSignal();
//System.out.println(ID.location() + "Simulating ..");
//Simulator evSim = Simulator.newSimulator(evaluatableCEX, sr.fns, FuzzMName.fuzzProperty, generalizeMain, TRUE);
//IntervalOptimizer evOpt = new IntervalOptimizer(evSim);
RatSignal targetSignal = m.optimizationTarget;
EvaluatableSignal evaluatableTarget = targetSignal.evaluatableSignal();
evaluatableTarget.normalize(evaluatableCEX);
if (Debug.isEnabled()) System.err.println(ID.location() + "Initial Solution : " + evaluatableCEX);
if (Debug.isEnabled()) System.err.println(ID.location() + "Optimization Target : " + evaluatableTarget);
//evaluatableCEX = evOpt.optimizeInterface(cfg.getSpan(), evaluatableCEX, evaluatableTarget);
//System.out.println(ID.location() + "Starting Optimization ..");
sr = PolygonalOptimizer.optimize(sr, targetSignal, m.name, FuzzmName.fuzzProperty, generalizeMain);
if (Debug.isEnabled()) System.out.println(ID.location() + "Optimized Solution : " + sr.cex);
// counterExample = evaluatableCEX.ratSignal();
//System.out.println(ID.location() + "Optimized Solution : " + sr.cex.size() + "*" + sr.cex.get(0).size());
cexserver.push(new CounterExampleMessage(name,m,sr));
} else {
satserver.push(new UnsatMessage(name,m,sr.time));
}
} catch (Throwable e) {
e.printStackTrace(System.err);
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
System.err.println(ID.location() + "** Solver Exception : " + cause.getClass().getName());
}
}
} catch (ExitException e) {
}
System.out.println(ID.location() + name + " is exiting.");
}
private static BigFraction abs (BigFraction a){
return (a.signum() < 0) ? a.negate() : a;
}
protected static RatSignal asteroidTarget (RatSignal target, RatSignal sln, IntervalVector span){
RatSignal res = new RatSignal();
for(int time = 0; time < target.size(); time++){
RatVect tv = target.get(time);
RatVect sv = sln.get(time);
for(TypedName key : tv.keySet()){
BigFraction targetVal = tv.get(key);
BigFraction slnVal = sv.get(key);
BigFraction distTargetToSln = abs (targetVal.subtract(slnVal));
BigFraction range = span.get(key).getRange();
if(distTargetToSln.compareTo(range.divide(BigInteger.valueOf(2))) < 0){
res.put(time, key, targetVal);
}
else if(slnVal.compareTo(targetVal) < 0){
res.put(time, key, targetVal.subtract(range));
}
else {
res.put(time, key, targetVal.add(range));
}
} // end for key
} // end for time
return res;
}
}
| 6,407 | 35.409091 | 125 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/Engine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.Message;
import fuzzm.engines.messages.MessageHandlerThread;
import fuzzm.engines.messages.TestVectorMessage;
import jkind.lustre.Program;
/**
* We extend the Engine class once for each stage in
* our processing pipeline.
*
* @param <Model>
*/
public abstract class Engine extends MessageHandlerThread implements Runnable {
protected final Program model;
protected final FuzzMConfiguration cfg;
private final Director director;
// Approximate queue size in bytes
static final int QUEUE_SIZE_1M = 1000000;
static final int QUEUE_SIZE_1K = 10000;
// The director process will read this from another thread,
// so we make it volatile
protected volatile Throwable throwable;
public Engine(EngineName name, FuzzMConfiguration cfg, Director director) {
super(name);
//this.name = name;
this.model = cfg.model;
this.cfg = cfg;
this.director = director;
}
protected abstract void main();
@Override
public void run() {
try {
main();
} catch (Throwable t) {
throwable = t;
}
}
public String getName() {
return name.toString();
}
public Throwable getThrowable() {
return throwable;
}
@Override
public void broadcast(Message message) {
director.broadcast(message);
}
@Override
public void broadcast(TestVectorMessage message) {
director.broadcast(message);
}
}
| 1,621 | 20.918919 | 79 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/TestHeuristicEngine.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.util.List;
import fuzzm.FuzzMConfiguration;
import fuzzm.engines.messages.ConstraintMessage;
import fuzzm.engines.messages.ExitException;
import fuzzm.engines.messages.ExitMessage;
import fuzzm.engines.messages.FeatureID;
import fuzzm.engines.messages.GeneralizedMessage;
import fuzzm.engines.messages.QueueName;
import fuzzm.engines.messages.ReceiveQueue;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.engines.messages.TransmitQueue;
import fuzzm.engines.messages.UnsatMessage;
import fuzzm.heuristic.FeatureException;
import fuzzm.heuristic.Features;
import fuzzm.heuristic.HeuristicInterface;
import fuzzm.lustre.BooleanCtx;
import fuzzm.util.ID;
import fuzzm.util.RatSignal;
import jkind.lustre.BoolExpr;
import jkind.lustre.VarDecl;
/**
* The Test Heuristic engine is responsible for choosing
* the next feature to attack.
*
* @param <Model>
*/
public class TestHeuristicEngine extends Engine {
final ReceiveQueue<GeneralizedMessage> genqueue;
final ReceiveQueue<UnsatMessage> unqueue;
final TransmitQueue<ConstraintMessage> testserver;
final TransmitQueue<ExitMessage> exitserver;
List<VarDecl> inputs;
Features featureList;
//int outstandingFeatures = 0;
//int minOutstanding = 0;
// TODO : replace this with something more elegant.
boolean boundLock = true;
FuzzMConfiguration cfg;
public TestHeuristicEngine(FuzzMConfiguration cfg, Director director) {
super(EngineName.TestHeuristicEngine, cfg, director);
inputs = model.getMainNode().inputs;
genqueue = new ReceiveQueue<GeneralizedMessage>(QUEUE_SIZE_1K,this);
unqueue = new ReceiveQueue<UnsatMessage>(QUEUE_SIZE_1K,this);
testserver = new TransmitQueue<ConstraintMessage>(this,QueueName.ConstraintMessage);
exitserver = new TransmitQueue<ExitMessage>(this,QueueName.ExitMessage);
this.tx.add(testserver);
this.tx.add(exitserver);
featureList = cfg.extractFeatures();
//outstandingFeatures = 0;
//minOutstanding = Math.min(4,featureList.size());
this.cfg = cfg;
}
@Override
protected void handleMessage(TestVectorMessage m) {
// TODO: something to update our statistics (?)
// If we ever want to process test vectors here, we
// need to add this thread to the testVectorEngines
// in the Director.
assert(false);
}
@Override
protected void handleMessage(GeneralizedMessage m) {
FeatureID cid = m.id;
int id = cid.constraintID;
if (id == -1) {
// TODO: clean up span/bound processing ..
boundLock = false;
return;
}
//outstandingFeatures--;
genqueue.push(m);
}
@Override
protected void handleMessage(UnsatMessage m) {
//outstandingFeatures--;
unqueue.push(m);
}
@Override
protected void main() {
//
// TODO: We have lots of work to do on the testing heuristics.
//
// We should probably spend our time initially establishing
// bounds on the input values and weeding out UNSAT features.
//
// It may then make sense to probe the state space randomly
// to identify low-hanging fruit.
//
// Ultimately we will want to take into consideration
// functional relationships between variables. This may
// help address state space concerns.
//
// We probably need a more wholistic approach to constraint
// selection, tracking property excitation and targeting
// those that are not meeting their distributions.
//
// The random walk heuristic may want to evaluate the random
// target points before calling the solver. There might be
// room for evaluating "genetic" algorithms, too.
//
// Along those lines, figuring out the dependencies of the
// "done" signal would be helpful in that department. Perhaps
// the genetic algorithm means generalizing one trace towards
// another while preserving "done".
//
// I suspect that some variation on generalization will be the
// right solution for generating nice distributions. In the
// mean time we need an algorithm that produces a reasonable
// distribution using only the solver.
//
System.out.println(ID.location() + name + " is starting ..");
try {
BooleanCtx vacHyp = new BooleanCtx();
BooleanCtx vacProp = new BooleanCtx(new BoolExpr(false));
RatSignal dummyTarget = new RatSignal();
FeatureID vacuousId = new FeatureID(-1, true);
ConstraintMessage cm = new ConstraintMessage(name,vacuousId,"NULL",vacHyp,vacProp,dummyTarget,dummyTarget);
System.out.println(ID.location() + "Sending input bound constraint: " + cm);
testserver.push(cm);
while(boundLock){
processQueues();
sleep(1000);
}
while (true) {
try {
int featureID = featureList.nextFeatureID();
HeuristicInterface Q = featureList.selectFeature(featureID);
FeatureID id = new FeatureID(featureID,Q.objective());
BooleanCtx hyp = Q.hyp(); // for WalkHeuristic, hyp is the bounding box (cube)
BooleanCtx prop = Q.constraint();
RatSignal genTarget = Q.target();
RatSignal optTarget = RatSignal.uniformRandom(genTarget.size(),cfg.getSpan());
Q.wait(Q.objective());
//System.out.println(ID.location() + "Constraint Generalization Target : " + genTarget);
//System.out.println(ID.location() + "Constraint Optimization Target : " + optTarget);
testserver.push(new ConstraintMessage(name,id,Q.name(),hyp,prop,optTarget,genTarget));
} catch (FeatureException f) {
if (done()) {
System.out.println(ID.location() + "*** Test Heuristic is sending Exit command ..");
exitserver.push(new ExitMessage(name));
break;
}
sleep(1000);
}
processQueues();
}
} catch (ExitException e) {
}
System.out.println(ID.location() + name + " is exiting.");
}
boolean done() {
return featureList.done();
}
void processQueues() throws ExitException {
if (exit) throw new ExitException();
while (genqueue.messageReady()) {
GeneralizedMessage m = genqueue.pop();
if (m.id.constraintID >= 0) {
HeuristicInterface Q = featureList.selectFeature(m.id.constraintID);
// TODO: Improve hyp generation w/non features
Q.sat(m.id.objective,m.time,m.counterExample,m.polyCEX);
}
}
while (unqueue.messageReady()) {
UnsatMessage m = unqueue.pop();
if (m.id.constraintID >= 0) {
HeuristicInterface Q = featureList.selectFeature(m.id.constraintID);
Q.unsat(m.id.objective);
}
}
}
}
| 6,682 | 32.752525 | 110 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/Director.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
import java.util.ArrayList;
import java.util.List;
import fuzzm.FuzzMConfiguration;
import fuzzm.Main;
import fuzzm.engines.messages.Message;
import fuzzm.engines.messages.MessageHandlerThread;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.util.ID;
/**
* The Director is the top level thread, responsible
* for accepting input, staging the other engines
* for execution, and ultimately shutting things down.
*
* @param <Model>
*/
public class Director extends MessageHandlerThread {
// public static final MessageSource NAME = MessageSource.Director;
private final FuzzMConfiguration settings;
//private final long startTime;
private final List<Engine> engines = new ArrayList<>();
private final List<Engine> testVecEngines = new ArrayList<>();
private final List<Thread> threads = new ArrayList<>();
public Director(FuzzMConfiguration settings) {
super(EngineName.DirectorEngine);
this.settings = settings;
//this.startTime = System.currentTimeMillis();
}
public void run() {
printHeader();
// writer.begin();
addShutdownHook();
createAndStartEngines();
while (!timeout() && someThreadAlive() && !someEngineFailed()) {
sleep(1000);
if (exit) break;
}
if (removeShutdownHook()) {
postProcessing();
reportFailures();
}
for (Thread x: threads) {
boolean done = false;
while (! done) {
try {
// Wait no more than 5 seconds
x.join(5000);
done = true;
} catch (InterruptedException e) {}
}
}
}
private void postProcessing() {
// writeUnknowns();
// writer.end();
// writeAdvice();
printSummary();
}
private final Thread shutdownHook = new Thread("shutdown-hook") {
@Override
public void run() {
Director.sleep(100);
postProcessing();
}
};
private void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
private boolean removeShutdownHook() {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
return true;
} catch (IllegalStateException e) {
// JVM already shutting down
return false;
}
}
private void createAndStartEngines() {
createEngines();
threads.forEach(Thread::start);
}
private void createEngines() {
addEngine(new TestHeuristicEngine(settings,this));
addEngine(new SolverEngine(settings,this));
addEngine(new GeneralizationEngine(settings,this));
if(! settings.noVectors){
addEngine(new GeneratorEngine(settings,this));
}
OutputEngine ope = new OutputEngine(settings,this);
addEngine(ope);
testVecEngines.add(ope);
}
private void addEngine(Engine engine) {
engines.add(engine);
threads.add(new Thread(engine, engine.getName()));
}
private boolean timeout() {
// long timeout = startTime + ((long) settings.timeout) * 1000;
return false; // System.currentTimeMillis() > timeout
}
private boolean someThreadAlive() {
return threads.stream().anyMatch(Thread::isAlive);
}
private boolean someEngineFailed() {
return engines.stream().anyMatch(e -> e.getThrowable() != null);
}
private void reportFailures() {
for (Engine engine : engines) {
if (engine.getThrowable() != null) {
System.out.println(engine.getName() + " process failed");
engine.getThrowable().printStackTrace();
}
}
}
private void printHeader() {
System.out.println("==========================================");
System.out.println(" FuzzM " + Main.VERSION);
System.out.println("==========================================");
}
public void broadcast(Message message) {
String msg = message.toString();
if (msg != "") {
System.out.println(ID.location() + msg);
}
for (Engine engine : engines) {
if (engine.name != message.source) {
engine.handleMessage(message);
}
}
}
public void broadcast(TestVectorMessage message) {
for (Engine engine : testVecEngines) {
engine.handleMessage(message);
}
}
/*
public Itinerary getValidMessageItinerary() {
List<EngineType> destinations = new ArrayList<>();
if (settings.reduceSupport) {
destinations.add(EngineType.REDUCE_SUPPORT);
}
return new Itinerary(destinations);
}
public Itinerary getInvalidMessageItinerary() {
List<EngineType> destinations = new ArrayList<>();
if (settings.smoothCounterexamples) {
destinations.add(EngineType.SMOOTHING);
}
if (settings.intervalGeneralization) {
destinations.add(EngineType.INTERVAL_GENERALIZATION);
}
return new Itinerary(destinations);
}
private double getRuntime() {
return (System.currentTimeMillis() - startTime) / 1000.0;
}
*/
private void printSummary() {
System.out.println(" -------------------------------------");
System.out.println(" --^^-- SUMMARY --^^--");
System.out.println(" -------------------------------------");
}
}
| 5,013 | 23.578431 | 68 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/EngineName.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines;
/**
* Enumeration of the various fuzzing engines
*/
public enum EngineName {
DirectorEngine,
TestHeuristicEngine,
SolverEngine,
GeneralizationEngine,
GeneratorEngine,
OutputEngine
}
| 425 | 18.363636 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/ResumeMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
/**
*
* Tells target queue to resume sending messages.
*
*/
public class ResumeMessage extends Message {
QueueName target;
public ResumeMessage(EngineName source, QueueName target) {
super(source,QueueName.ResumeMessage);
this.target = target;
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [Pipeline: Resume] " + target + " from " + source + ":" + sequence;
}
}
| 768 | 19.783784 | 86 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/UnsatMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
/**
* The Unsat message indicates that the constraint is not solvable.
*
* Generated by the Solver Engine.
* Consumed by the Test Heuristic Engines.
*/
public class UnsatMessage extends FeatureMessage {
final double time;
public UnsatMessage(EngineName source, FeatureID id, String name, long sequence, double time) {
super(source,QueueName.UnsatMessage,id,name,sequence);
this.time = time;
}
public UnsatMessage(EngineName source, ConstraintMessage m, double time) {
this(source,m.id,m.name,m.sequence,time);
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [UNSAT] " + sequence + ":" + id + " Time = " + time/1000.0 + " s";
}
}
| 1,044 | 23.880952 | 96 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/TransmitQueue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/**
* A queue for outgoing messages.
*/
public class TransmitQueue<M extends Message> extends TransmitQueueBase {
public TransmitQueue(MessageHandlerThread parent, QueueName queue) {
super(parent,queue);
}
public void push(M m) {
do {
if (paused()) {
//System.out.println(ID.location() + "[pause] " + parent.name);
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {}
}
//System.out.println(ID.location() + "[resume] " + parent.name);
}
} while (paused());
parent.broadcast(m);
}
public void pushTest(TestVectorMessage m) {
do {
if (paused()) {
//System.out.println(ID.location() + "[pause] " + parent.name);
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {};
}
//System.out.println(ID.location() + "[resume] " + parent.name);
}
} while (paused());
parent.broadcast(m);
}
}
| 1,185 | 21.807692 | 73 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/FeatureID.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/**
* The constraint ID ties the various messages back to
* a specific feature (and its polarity).
*
*/
public class FeatureID {
public int constraintID;
public boolean objective;
public FeatureID(int constraintID, boolean objective) {
this.constraintID = constraintID;
this.objective = objective;
}
@Override
public String toString() {
return "id:" + (objective ? "+" : "-") + Integer.toString(constraintID);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + constraintID;
result = prime * result + (objective ? 0 : 1);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof FeatureID)) {
return false;
}
FeatureID other = (FeatureID) obj;
if (constraintID != other.constraintID) {
return false;
}
if ( objective != other.objective) {
return false;
}
return true;
}
}
| 1,238 | 20 | 74 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/TransmitQueueBase.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/**
* The base class for outgoing message queues.
*/
public class TransmitQueueBase {
final protected MessageHandlerThread parent;
private int pauseRequests = 0;
final QueueName queue;
public TransmitQueueBase(MessageHandlerThread parent, QueueName queue) {
this.parent = parent;
this.queue = queue;
}
public boolean paused() {
return (pauseRequests > 0);
}
public synchronized void handleMessage(ResumeMessage m) {
//System.out.println(ID.location() + "Processing Resume Request " + m.toString() + " at " + this.queue + " in " + parent.name);
if (m.target == this.queue) {
if (pauseRequests > 0) pauseRequests--;
//System.out.println(ID.location() + "Acknowledging Pipeline Resume : " + m.toString());
}
if (pauseRequests <= 0) notifyAll();
}
public synchronized void handleMessage(PauseMessage m) {
//System.out.println(ID.location() + "Processing Pause Request " + m.toString() + " at " + this.queue + " in " + parent.name);
if (m.target == this.queue) {
//System.out.println(ID.location() + "Acknowledging Pipeline Pause : " + m.toString());
pauseRequests++;
}
}
}
| 1,373 | 26.48 | 130 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/PauseMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
/**
*
* A pause request message requests that the target queue stop
* sending messages.
*
*/
public class PauseMessage extends Message {
QueueName target;
public PauseMessage(EngineName source, QueueName target) {
super(source,QueueName.PauseMessage);
this.target = target;
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [Pipeline: Pause] " + target + " from " + source + ":" + sequence;
}
}
| 799 | 20.052632 | 85 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/ReceiveQueue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import java.util.LinkedList;
import java.util.Queue;
import fuzzm.util.ID;
/**
* A queue for incoming messages.
*/
public class ReceiveQueue<M extends Message> {
final Queue<M> queue;
public int volume;
private boolean paused;
final int volumeTrigger;
final MessageHandlerThread parent;
public ReceiveQueue(int volumeTrigger, MessageHandlerThread parent) {
this.volumeTrigger = volumeTrigger;
this.parent = parent;
this.volume = 0;
this.paused = false;
this.queue = new LinkedList<>();
}
// Messages coming in from other producers ..
// called by Director via handleMessage().
public void push(M message) {
boolean pause = false;
synchronized (queue) {
queue.add(message);
volume += message.bytes();
if (volumeTrigger > 0 && volume >= volumeTrigger && !paused) {
paused = true;
pause = true;
} else if (paused) {
System.out.println(ID.location() + message.source + " piling on the " + message.sourceQueue + " of " + parent.name);
}
}
if (pause) parent.broadcast(message.pauseRequest(parent.name));
synchronized (this) {
notifyAll();
}
}
// Consumer non-polling check ..
public boolean messageReady() {
return ! queue.isEmpty();
}
// Get a message for the consumer ..
public M pop() throws ExitException {
boolean resume = false;
M res = null;
if (parent.exit) throw new ExitException();
do {
if (queue.isEmpty()) {
//System.out.println(ID.location() + "[wait] " + parent.name);
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {}
}
//System.out.println(ID.location() + "[wake] " + parent.name);
if (parent.exit) throw new ExitException();
}
} while (queue.isEmpty());
synchronized (queue) {
res = queue.poll();
if (res == null) {
throw new IllegalArgumentException();
}
volume -= res.bytes();
if (volumeTrigger > 0 && (2*volume) < volumeTrigger && paused) {
paused = false;
resume = true;
}
}
if (resume) parent.broadcast(res.resumeRequest(parent.name));
return res;
}
// Get a message for the consumer ..
public M pop_non_blocking() throws ExitException {
boolean resume = false;
M res = null;
if (parent.exit)
throw new ExitException();
synchronized (queue) {
res = queue.poll();
if (res != null) {
volume -= res.bytes();
if (volumeTrigger > 0 && (2 * volume) < volumeTrigger && paused) {
paused = false;
resume = true;
}
}
}
if (resume)
parent.broadcast(res.resumeRequest(parent.name));
return res;
}
}
| 2,979 | 25.140351 | 121 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/Message.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
import fuzzm.value.poly.GlobalState;
/**
* The messages passed around the FuzzM ecosystem. Note that each
* message is associated with a specific constraint ID. Each message
* also contains a sequence identifier. The sequence identifier
* evolves over time and should be uniquely generated for each
* message. Note, however, that new messages often inherit a
* sequence identifier from their originating message.
*
*/
public abstract class Message {
final public long sequence;
final public EngineName source;
final public QueueName sourceQueue;
public Message(EngineName source, QueueName sourceQueue) {
this.source = source;
this.sourceQueue = sourceQueue;
this.sequence = GlobalState.next_sequence_id();
}
public Message(EngineName source, QueueName sourceQueue, long sequence) {
this.source = source;
this.sourceQueue = sourceQueue;
this.sequence = sequence;
}
public abstract void handleAccept(MessageHandler handler);
public Message pauseRequest(EngineName newsource) {
return new PauseMessage(newsource,this.sourceQueue);
}
public Message resumeRequest(EngineName newsource) {
return new ResumeMessage(newsource,this.sourceQueue);
}
public int bytes() {
return 1;
}
}
| 1,500 | 29.632653 | 74 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/ConstraintMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
import fuzzm.lustre.BooleanCtx;
import fuzzm.util.RatSignal;
/**
* The constraint message contains a constraint for the solver.
* Generated by the Test Heuristic Engine.
* Consumed by the Solver Engine.
*/
public class ConstraintMessage extends FeatureMessage {
public BooleanCtx prop;
public BooleanCtx hyp;
public RatSignal optimizationTarget;
public RatSignal generalizationTarget;
public ConstraintMessage(EngineName source, FeatureID id, String name, BooleanCtx hyp, BooleanCtx prop, RatSignal optimizationTarget, RatSignal generalizationTarget) {
super(source,QueueName.ConstraintMessage,id,name);
this.hyp = hyp;
this.prop = prop;
//assert(target.size() > 0);
assert(optimizationTarget != null);
assert(generalizationTarget != null);
this.optimizationTarget = optimizationTarget;
this.generalizationTarget = generalizationTarget;
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [Constraint] " + sequence + ":" + id + " : " + prop.getExpr();
}
}
| 1,375 | 27.081633 | 168 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/MessageHandler.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/* Base class for message handlers
*/
public abstract class MessageHandler {
public void handleMessage(Message message) {
message.handleAccept(this);
}
protected void handleMessage(CounterExampleMessage m) {
}
protected void handleMessage(GeneralizedMessage m) {
}
protected void handleMessage(TestVectorMessage m) {
}
protected void handleMessage(ConstraintMessage m) {
}
protected void handleMessage(UnsatMessage m) {
}
// protected void handleMessage(IntervalVectorMessage m) {}
protected void handleMessage(PauseMessage m) {
}
protected void handleMessage(ResumeMessage m) {
}
abstract protected void handleMessage(ExitMessage m);
}
| 920 | 19.466667 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/ExitException.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/**
* Exception thrown to indicate recipt of exit command
*/
public class ExitException extends Exception {
private static final long serialVersionUID = 1L;
}
| 408 | 20.526316 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/QueueName.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
/**
* Enumeration of the various queues in the system.
*/
public enum QueueName {
CounterExampleMessage,
ConstraintMessage,
ExitMessage,
GeneralizedMessage,
TestVectorMessage,
UnsatMessage,
PauseMessage,
ResumeMessage
}
| 474 | 18.791667 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/GeneralizedMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;
import fuzzm.engines.EngineName;
import fuzzm.lustre.BooleanCtx;
import fuzzm.lustre.ExprCtx;
import fuzzm.lustre.ExprSignal;
import fuzzm.lustre.generalize.PolyGeneralizationResult;
import fuzzm.poly.VariableID;
import fuzzm.util.FuzzmName;
import fuzzm.util.IntervalVector;
import fuzzm.util.RatSignal;
import jkind.lustre.BinaryOp;
import jkind.lustre.RealExpr;
import jkind.util.BigFraction;
/**
* The Generalized Message Iterator allows iteration over
* the entire state space of the generalized counterexample.
*
*/
class GeneralizedMessageIterator implements Iterator<Long> {
long count;
public static final long MAX_MODEL_SIZE = 1000L;
public GeneralizedMessageIterator() {
count = MAX_MODEL_SIZE;
}
@Override
public boolean hasNext() {
return count > 0;
}
@Override
public Long next() {
return new Long(count--);
}
}
/**
* The Generalized message contains a generalized solution to the
* constraint.
*
* Generated by the Generalization Engine.
* Consumed by the Evaluator and Test Heuristic Engines.
*/
public class GeneralizedMessage extends FeatureMessage implements Iterable<Long> {
public final double time;
public final RatSignal counterExample;
//public FuzzMModel cex;
//public List<VarDecl> inputNames;
public final RatSignal generalizationTarget;
//public final IntervalSignal generalizedCEX;
public final PolyGeneralizationResult polyCEX;
private GeneralizedMessage(EngineName source, FeatureID id, String name, double time, RatSignal generalizationTarget, RatSignal counterExample, PolyGeneralizationResult polyCEX, long sequence) {
super(source,QueueName.GeneralizedMessage,id,name,sequence);
assert(polyCEX.result.cex && !polyCEX.result.isNegated());
this.counterExample = counterExample;
//this.generalizedCEX = generalizedCEX;
//this.inputNames = inputNames;
assert(generalizationTarget != null);
//assert(target.size() > 0);
this.generalizationTarget = generalizationTarget;
this.polyCEX = polyCEX;
this.time = time;
}
public GeneralizedMessage(EngineName source, CounterExampleMessage m, PolyGeneralizationResult polyCEX) {
this(source,m.id,m.name,m.time,m.generalizationTarget,m.counterExample,polyCEX,m.sequence);
}
public RatSignal nextBiasedVector(boolean biased, BigFraction min, BigFraction max, IntervalVector span, Map<VariableID,BigFraction> ctx) {
return polyCEX.result.randomVector(biased,min,max,span,ctx);
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public Iterator<Long> iterator() {
return new GeneralizedMessageIterator();
}
@Override
public String toString() {
return "Message: [Generalized] " + sequence + ":" + id; // + " :\n" + generalizedCEX.toString();
}
// private static Expr inBounds(int time, TypedName name, BigFraction low, BigFraction hi) {
// Expr timeBound = new BinaryExpr(new IdExpr(FuzzMName.time),BinaryOp.EQUAL,new IntExpr(time));
// Expr hiBound = new BinaryExpr(Rat.cast(name.name, name.type),BinaryOp.LESSEQUAL,Rat.toExpr(hi));
// Expr lowBound = new BinaryExpr(Rat.toExpr(low),BinaryOp.LESSEQUAL,Rat.cast(name.name,name.type));
// Expr lohiBound = new BinaryExpr(hiBound,BinaryOp.AND,lowBound);
// //Expr outside = new UnaryExpr(UnaryOp.NOT,lohiBound);
// Expr outBound = new BinaryExpr(timeBound,BinaryOp.IMPLIES,lohiBound);
// return outBound;
// }
//
// private static Expr lowerBound(int time, TypedName name, BigFraction low) {
// Expr timeBound = new BinaryExpr(new IdExpr(FuzzMName.time),BinaryOp.EQUAL,new IntExpr(time));
// Expr lowBound = new BinaryExpr(Rat.toExpr(low),BinaryOp.LESSEQUAL,Rat.cast(name.name,name.type));
// //Expr outside = new UnaryExpr(UnaryOp.NOT,lohiBound);
// Expr outBound = new BinaryExpr(timeBound,BinaryOp.IMPLIES,lowBound);
// return outBound;
// }
//
// private static Expr upperBound(int time, TypedName name, BigFraction hi) {
// Expr timeBound = new BinaryExpr(new IdExpr(FuzzMName.time),BinaryOp.EQUAL,new IntExpr(time));
// Expr hiBound = new BinaryExpr(Rat.cast(name.name, name.type),BinaryOp.LESSEQUAL,Rat.toExpr(hi));
// //Expr outside = new UnaryExpr(UnaryOp.NOT,lohiBound);
// Expr outBound = new BinaryExpr(timeBound,BinaryOp.IMPLIES,hiBound);
// return outBound;
// }
// bounding_box = not body
// delay = pre bounding_box
// outside = not body
// rhs = (not body) OR (pre bounding_box)
// res = not body -> (not body) OR (pre bounding_box)
// private static Expr notAlways(IdExpr name,Expr body) {
// Expr outside = new UnaryExpr(UnaryOp.NOT,body);
// Expr delay = new UnaryExpr(UnaryOp.PRE,name);
// Expr rhs = new BinaryExpr(outside,BinaryOp.OR,delay);
// Expr res = new BinaryExpr(outside,BinaryOp.ARROW,rhs);
// return res;
// }
// public BooleanCtx bounds(IntervalVector span) {
// List<Expr> boundByTime = new ArrayList<>();
// for (int time=0;time<counterExample.size();time++) {
// IntervalVector iv = generalizedCEX.get(time);
// for (TypedName name: iv.keySet()) {
// FuzzMInterval z = iv.get(name);
// BigFraction low = z.min;
// BigFraction hi = z.max;
// BigFraction spanLow = span.get(name).min;
// BigFraction spanHigh = span.get(name).max;
// boolean redundantLow = low.compareTo(spanLow) <= 0;
// boolean redundantHigh = hi.compareTo(spanHigh) >= 0;
// if (! (redundantLow || redundantHigh)) {
// boundByTime.add(inBounds(time,name,low,hi));
// } else if (! redundantHigh) {
// boundByTime.add(upperBound(time,name,hi));
// } else if (! redundantLow) {
// boundByTime.add(lowerBound(time,name,low));
// }
// }
// }
// BooleanCtx ctx = new BooleanCtx(boundByTime);
// ctx.bind(FuzzMName.boundingBox + "__");
// Expr boundByTimeExpr = ctx.getExpr();
// IdExpr name = new IdExpr(FuzzMName.boundingBox);
// name = ctx.define(FuzzMName.boundingBox, NamedType.BOOL,notAlways(name,boundByTimeExpr));
// ctx.setExpr(name);
// return ctx;
// }
public BooleanCtx dot(IntervalVector span) {
int k = generalizationTarget.size();
ExprSignal inputs = span.getExprSignal(k);
inputs = inputs.sub(counterExample);
RatSignal vector = generalizationTarget.sub(counterExample);
ExprCtx dot = inputs.dot(vector, FuzzmName.pivotDot);
dot.op(BinaryOp.GREATEREQUAL,new RealExpr(BigDecimal.ZERO));
dot.bind(FuzzmName.pivotDot);
return new BooleanCtx(dot);
}
@Override
public int bytes() {
return 1 + counterExample.bytes() + polyCEX.result.bytes();
}
}
| 6,823 | 33.994872 | 195 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/ExitMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
/**
* The Exit message is a signal that the system should shut down.
*
* Generated by Any Engine.
* Consumed by Every Engine.
*/
public class ExitMessage extends Message {
public ExitMessage(EngineName source) {
super(source,QueueName.ExitMessage);
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [Pipeline: Exit] " + sequence;
}
@Override
public int bytes() {
return 1;
}
}
| 784 | 18.146341 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/CounterExampleMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
import fuzzm.lustre.BooleanCtx;
import fuzzm.lustre.evaluation.FunctionLookupEV;
import fuzzm.solver.SolverResults;
import fuzzm.util.RatSignal;
/**
* The Counter Example message contains a specific solution to the
* constraint.
*
* Generated by the Solver Engine.
* Consumed by the Generalization Engine.
*/
public class CounterExampleMessage extends FeatureMessage {
public final double time;
public final RatSignal counterExample;
public final FunctionLookupEV fns;
public final BooleanCtx hyp;
public final BooleanCtx prop;
public final RatSignal generalizationTarget;
public CounterExampleMessage(EngineName source, FeatureID id, String name, BooleanCtx hyp, BooleanCtx prop, RatSignal generalizationTarget, SolverResults sr, long sequence) {
super(source,QueueName.CounterExampleMessage,id,name,sequence);
//assert(target.size() > 0);
this.counterExample = sr.cex;
this.fns = sr.fns;
this.hyp = hyp;
this.prop = prop;
this.generalizationTarget = generalizationTarget;
this.time = sr.time;
}
public CounterExampleMessage(EngineName source, ConstraintMessage m, SolverResults sr) {
this(source, m.id,m.name,m.hyp,m.prop,m.generalizationTarget,sr,m.sequence);
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "Message: [CeX] " + sequence + ":" + id + " Time = " + time/1000.0 + " s"; // + " :\n" + counterExample.toString();
}
@Override
public int bytes() {
return 1 + counterExample.bytes();
}
}
| 1,839 | 27.75 | 176 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/MessageHandlerThread.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import java.util.ArrayList;
import java.util.Collection;
import fuzzm.engines.EngineName;
import fuzzm.util.ID;
/**
* As the Engine base class, Message Handler dictates
* how each engine responds to and sends messages.
*
*/
public abstract class MessageHandlerThread extends MessageHandler {
//protected final Queue<Message> incoming = new LinkedList<>();
public boolean exit = false;
public final EngineName name;
protected Collection<TransmitQueueBase> tx = new ArrayList<>();
public MessageHandlerThread(EngineName name) {
this.name = name;
}
// public void receiveMessage(Message message) {
// message.handleAccept(this);
// }
public static void sleep(int millis) {
boolean done = false;
while (!done) {
try {
Thread.sleep(millis);
done = true;
} catch (InterruptedException e) {}
}
}
//protected abstract boolean emptyMessageQueue();
/*
* protected void waitForNextMessage() throws ExitException {
while (emptyMessageQueue()) {
sleep(10);
processMessages();
}
}
*/
@Override
final public void handleMessage(PauseMessage m) {
for (TransmitQueueBase t: tx) {
t.handleMessage(m);
}
}
@Override
final public void handleMessage(ResumeMessage m) {
for (TransmitQueueBase t: tx) {
t.handleMessage(m);
}
}
@Override
final protected void handleMessage(ExitMessage m) {
System.out.println(ID.location() + name + " saw ExitMessage " + m.sequence + " from " + m.source);
exit = true;
}
abstract public void broadcast(Message message);
abstract public void broadcast(TestVectorMessage message);
}
| 1,836 | 21.402439 | 103 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/TestVectorMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
import fuzzm.util.RatSignal;
/**
* The Test Vector message contains a specific solution to the
* constraint.
*
* Consumed by the Output Engine.
*/
public class TestVectorMessage extends FeatureMessage {
public RatSignal signal;
public TestVectorMessage(EngineName source, FeatureID id, String name, RatSignal signal, long sequence) {
super(source,QueueName.TestVectorMessage,id,name,sequence);
this.signal = signal;
}
public TestVectorMessage(EngineName source, GeneralizedMessage m, RatSignal signal) {
this(source,m.id,m.name,signal,m.sequence);
}
@Override
public void handleAccept(MessageHandler handler) {
handler.handleMessage(this);
}
@Override
public String toString() {
return "";
//return "Message: [Vector] " + sequence + ":" + id + " : " + signal.toString();
}
@Override
public int bytes() {
return 1 + signal.bytes();
}
}
| 1,158 | 22.18 | 106 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/engines/messages/FeatureMessage.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.engines.messages;
import fuzzm.engines.EngineName;
/**
* Messages with references to features
*/
abstract public class FeatureMessage extends Message {
public final FeatureID id;
public final String name;
public FeatureMessage(EngineName source, QueueName queue, FeatureID id, String name, long sequence) {
super(source,queue,sequence);
this.id = id;
this.name = name;
}
public FeatureMessage(EngineName source, QueueName queue, FeatureID id, String name) {
super(source,queue);
this.id = id;
this.name = name;
}
}
| 762 | 24.433333 | 102 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/sender/PrintSender.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.sender;
import fuzzm.engines.messages.CounterExampleMessage;
import fuzzm.engines.messages.TestVectorMessage;
import fuzzm.util.ID;
import fuzzm.util.RatSignal;
import fuzzm.util.RatVect;
import fuzzm.util.TypedName;
/***
*
* The printSender class simply prints transmitted
* values to stdout.
*
*/
public class PrintSender extends Sender {
long count;
public PrintSender() {
this.count = 0;
}
@Override
public void send(TestVectorMessage tv) {
if (count % 10 == 0) {
ProcessRatSignal(tv.signal, "TestVect");
}
}
@Override
public void send(CounterExampleMessage cex) {
ProcessRatSignal(cex.counterExample, "CEX");
}
void ProcessRatSignal (RatSignal values, String label) {
count++;
int time = 0;
for (RatVect r: values) {
String value = "";
boolean delimit = false;
// Does this do it in an appropriate order?
for (TypedName key: r.keySet()) {
if (delimit) value = value.concat(" ");
value = value.concat(r.get(key).toString());
delimit = true;
}
System.out.println(ID.location() + label + " Vector[" + time + "] : " + value);
time++;
}
}
}
| 1,509 | 23.354839 | 91 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/sender/OutputMsgTypes.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.sender;
public enum OutputMsgTypes {
TEST_VECTOR_MSG_TYPE,
COUNTER_EXAMPLE_MSG_TYPE,
CONFIG_SPEC_MSG_TYPE,
}
| 347 | 20.75 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/sender/FlowControlledPublisher.java | /*
* Copyright (C) 2018, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.sender;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class FlowControlledPublisher {
String exchangeName;
String target;
public FlowControlledPublisher(String exchangeName, String target) throws IOException, TimeoutException {
super();
this.exchangeName = exchangeName;
this.target = target;
initConnection();
}
Channel pubChannel;
Connection pubConnection;
Channel flowCtrlChannel;
Connection flowCtrlConnection;
private void initConnection() throws TimeoutException, IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(target);
pubConnection = factory.newConnection();
pubChannel = pubConnection.createChannel();
pubChannel.exchangeDeclare(exchangeName, "direct");
flowCtrlConnection = factory.newConnection();
flowCtrlChannel = flowCtrlConnection.createChannel();
flowCtrlChannel.exchangeDeclare(exchangeName + "_FLOW_CTRL", BuiltinExchangeType.DIRECT);
String flowCtrlQueueName = flowCtrlChannel.queueDeclare().getQueue();
flowCtrlChannel.queueBind(flowCtrlQueueName, exchangeName + "_FLOW_CTRL", "FLOW_CTRL");
Consumer flowControlConsumer = new DefaultConsumer(flowCtrlChannel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) {
handleFlowControlMessage(consumerTag, envelope, properties, body);
}
};
flowCtrlChannel.basicConsume(flowCtrlQueueName, true, flowControlConsumer);
}
volatile long PauseCount = 0;
public void handleFlowControlMessage(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) {
String s = new String(body);
if (s.equals("PAUSE")) {
PauseCount++;
} else if (s.equals("RESUME")) {
if (PauseCount > 0) PauseCount--;
} else {
throw new IllegalArgumentException();
}
}
public void close() throws IOException, TimeoutException {
pubChannel.close();
pubConnection.close();
flowCtrlChannel.close();
flowCtrlConnection.close();
}
public void basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
throws TimeoutException, IOException {
while (true) {
try {
while (PauseCount > 0) ;
pubChannel.basicPublish(exchange, routingKey, props, body);
break;
} catch (IOException e) {
initConnection();
}
}
}
}
| 3,366 | 32.336634 | 112 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/sender/Sender.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.sender;
import fuzzm.engines.messages.CounterExampleMessage;
import fuzzm.engines.messages.TestVectorMessage;
/***
*
* The Sender class transmits fuzzing values to a target.
*
*/
public abstract class Sender {
abstract public void send(TestVectorMessage tv);
abstract public void send(CounterExampleMessage cex);
}
| 550 | 22.956522 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/BooleanValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.EvaluatableValue;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class BooleanValue extends BooleanType implements BooleanValueInterface {
public static final BooleanValue TRUE = new BooleanValue();
public static final BooleanValue FALSE = new BooleanValue();
protected BooleanValue() {
}
// and
@Override
public EvaluatableType<BooleanType> and(EvaluatableValue right) {
return ((BooleanValueInterface) right).and2(this);
}
@Override
public EvaluatableType<BooleanType> and2(BooleanValue left) {
return (left == TRUE) && (this == TRUE) ? TRUE : FALSE;
}
@Override
public EvaluatableType<BooleanType> and2(BooleanInterval left) {
return (this == TRUE) ? left : FALSE;
}
// or
@Override
public EvaluatableType<BooleanType> or(EvaluatableValue right) {
return ((BooleanValueInterface) right).or2(this);
}
@Override
public BooleanType or2(BooleanValue left) {
return ((left == TRUE) || (this == TRUE)) ? TRUE : FALSE;
}
@Override
public EvaluatableType<BooleanType> or2(BooleanInterval left) {
return (this == TRUE) ? TRUE : left;
}
// equalop
@Override
public EvaluatableType<BooleanType> equalop(EvaluatableValue right) {
return ((BooleanValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(BooleanValue left) {
return (this == left) ? TRUE : FALSE;
}
@Override
public EvaluatableType<BooleanType> equalop2(BooleanInterval left) {
return left;
}
// max
@Override
public BooleanType max(BooleanType right) {
return (((BooleanValue) right) == TRUE) ? right : this;
}
// min
@Override
public BooleanType min(BooleanType right) {
return (((BooleanValue) right) == FALSE) ? right : this;
}
// ite
@Override
public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right) {
return (this == TRUE) ? left : right;
}
// unary
@Override
public BooleanType not() {
return (this == TRUE) ? FALSE : TRUE;
}
// auxiliary
@Override
public boolean isAlwaysTrue() {
return this == TRUE;
}
@Override
public boolean isAlwaysFalse() {
return this == FALSE;
}
@Override
public String toString() {
return (this == TRUE) ? "T" : "F";
}
@Override
public int signum() {
return (this == TRUE) ? +1 : 0;
}
@Override
public IntegerType integerType() {
return (this == TRUE) ? new IntegerValue(BigInteger.ONE) : new IntegerValue(BigInteger.ZERO);
}
@Override
public RationalType rationalType() {
return (this == TRUE) ? new RationalValue(BigFraction.ONE) : new RationalValue(BigFraction.ZERO);
}
@Override
public BooleanType booleanType() {
return this;
}
@Override
public boolean equals(Object x) {
return (x == this);
}
@Override
public int hashCode() {
return (this == TRUE) ? 13 : 7 ;
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public boolean isFinite() {
return true;
}
@Override
public BigFraction getValue() {
return (this == TRUE) ? BigFraction.ONE : BigFraction.ZERO;
}
}
| 3,854 | 19.951087 | 99 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/RationalValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class RationalValue extends RationalType implements RationalValueInterface {
public BigFraction value;
public RationalValue(BigFraction value) {
this.value = value;
}
// divide
@Override
public RationalType divide(RationalType right) {
return ((RationalValueInterface) right).divide2(this);
}
@Override
public RationalType divide2(RationalValue left) {
return new RationalValue(left.value.divide(value));
}
@Override
public RationalType divide2(RationalInfinity left) {
return RationalInfinity.newRationalInfinity(left.signum() * signum());
}
// multiply
@Override
public RationalType multiply(NumericType<RationalType> right) {
return ((RationalValueInterface) right).multiply2(this);
}
@Override
public RationalType multiply2(RationalValue left) {
return new RationalValue(left.value.multiply(value));
}
@Override
public RationalType multiply2(RationalInfinity left) {
return RationalInfinity.newRationalInfinity(left.signum() * signum());
}
// plus
@Override
public RationalType plus(NumericType<RationalType> right) {
return ((RationalValueInterface) right).plus2(this);
}
@Override
public RationalType plus2(RationalValue left) {
return new RationalValue(left.value.add(value));
}
@Override
public RationalType plus2(RationalInfinity left) {
return left;
}
// less
@Override
public BooleanType less(NumericType<RationalType> right) {
return ((RationalValueInterface) right).less2(this);
}
@Override
public BooleanType less2(RationalValue left) {
return newBooleanType(left.value.compareTo(value) < 0);
}
@Override
public BooleanType less2(RationalInfinity left) {
return newBooleanType(left.signum() < 0);
}
// greater
@Override
public BooleanType greater(NumericType<RationalType> right) {
return ((RationalValueInterface) right).greater2(this);
}
@Override
public BooleanType greater2(RationalValue left) {
return newBooleanType(left.value.compareTo(value) > 0);
}
@Override
public BooleanType greater2(RationalInfinity left) {
return newBooleanType(left.signum() > 0);
}
// equalop
@Override
public BooleanType equalop(NumericType<RationalType> right) {
return ((RationalValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(RationalValue left) {
return newBooleanType(left.value.compareTo(value) == 0);
}
@Override
public BooleanType equalop2(RationalInfinity left) {
return newBooleanType(false);
}
// max
@Override
public RationalType max(RationalType right) {
return ((RationalValueInterface) right).max2(this);
}
@Override
public RationalType max2(RationalValue left) {
return value.compareTo(left.value) > 0 ? this : left;
}
@Override
public RationalType max2(RationalInfinity left) {
return left.signum() > 0 ? left : this;
}
// min
@Override
public RationalType min(RationalType right) {
return ((RationalValueInterface) right).min2(this);
}
@Override
public RationalType min2(RationalValue left) {
return value.compareTo(left.value) < 0 ? this : left;
}
@Override
public RationalType min2(RationalInfinity left) {
return left.signum() < 0 ? left : this;
}
// unary
@Override
public RationalType negate() {
return new RationalValue(value.negate());
}
// auxiliary
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof RationalValue))
return false;
RationalValue other = (RationalValue) obj;
return value.equals(other.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public String toString() {
return value.toString();
}
@Override
public int signum() {
return value.signum();
}
@Override
public IntegerType integerType() {
int sign = value.signum();
BigFraction half = new BigFraction(BigInteger.ONE,BigInteger.valueOf(2));
BigFraction absvalue = (sign < 0) ? value.negate() : value;
BigInteger intvalue = absvalue.add(half).floor();
intvalue = (sign < 0) ? intvalue.negate() : intvalue;
return new IntegerValue(intvalue);
}
@Override
public RationalType rationalType() {
return this;
}
@Override
public BooleanType booleanType() {
return (value.signum() != 0) ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public EvaluatableType<RationalType> newInterval(RationalType max) {
if (this.equals(max)) return this;
return new RationalInterval(this,max);
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public boolean isFinite() {
return true;
}
@Override
public RationalType abs() {
return value.signum() < 0 ? new RationalValue(value.negate()) : this;
}
@Override
public RationalType valueOf(BigInteger arg) {
return new RationalValue(new BigFraction(arg));
}
public BigFraction value() {
return value;
}
@Override
public BigFraction getValue() {
return value;
}
}
| 5,975 | 20.810219 | 83 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/RationalInterval.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.InstanceType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.RationalIntervalType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class RationalInterval extends RationalIntervalType {
RationalType min;
RationalType max;
public static final RationalInterval INFINITE_INTERVAL = new RationalInterval(RationalInfinity.NEGATIVE_INFINITY,RationalInfinity.POSITIVE_INFINITY);
public RationalInterval(RationalType min, RationalType max) {
this.min = min;
this.max = max;
}
public RationalInterval(BigFraction min, BigFraction max) {
assert(! min.equals(max));
this.min = new RationalValue(min);
this.max = new RationalValue(max);
}
public static EvaluatableType<RationalType> newRationalInterval(InstanceType<RationalType> min, InstanceType<RationalType> max) {
if (min.equals(max)) return min;
return new RationalInterval((RationalType) min,(RationalType) max);
}
@Override
public EvaluatableType<RationalType> newInterval(InstanceType<RationalType> min, InstanceType<RationalType> max) {
if (min.equals(max)) {
return min;
}
return new RationalInterval((RationalType) min, (RationalType) max);
}
@Override
public RationalType getLow() {
return min;
}
@Override
public RationalType getHigh() {
return max;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof RationalInterval))
return false;
RationalInterval other = (RationalInterval) obj;
return max.equals(other.max) && min.equals(other.min);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((max == null) ? 0 : max.hashCode());
result = prime * result + ((min == null) ? 0 : min.hashCode());
return result;
}
@Override
public String toString() {
return "[" + min + "," + max + "]";
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
}
| 2,764 | 24.136364 | 150 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/RationalValueInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
public interface RationalValueInterface /*extends NumericTypeInterface<RationalType>*/ {
RationalType divide(RationalType right);
RationalType divide2(RationalValue left);
RationalType divide2(RationalInfinity left);
RationalType plus(NumericType<RationalType> right);
RationalType plus2(RationalValue left);
RationalType plus2(RationalInfinity left);
RationalType multiply(NumericType<RationalType> right);
RationalType multiply2(RationalValue left);
RationalType multiply2(RationalInfinity left);
RationalType max(RationalType right);
RationalType max2(RationalValue left);
RationalType max2(RationalInfinity left);
RationalType min(RationalType right);
RationalType min2(RationalValue left);
RationalType min2(RationalInfinity left);
BooleanType less(NumericType<RationalType> right);
BooleanType less2(RationalValue left);
BooleanType less2(RationalInfinity left);
BooleanType greater(NumericType<RationalType> right);
BooleanType greater2(RationalValue left);
BooleanType greater2(RationalInfinity left);
BooleanType equalop(NumericType<RationalType> right);
BooleanType equalop2(RationalValue left);
BooleanType equalop2(RationalInfinity left);
}
| 1,556 | 30.14 | 88 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/BooleanInterval.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanIntervalType;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.EvaluatableValue;
import fuzzm.value.hierarchy.EvaluatableValueHierarchy;
import fuzzm.value.hierarchy.InstanceType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class BooleanInterval extends BooleanIntervalType implements BooleanValueInterface {
public static final BooleanInterval ARBITRARY = new BooleanInterval();
// and
@Override
public EvaluatableType<BooleanType> and(EvaluatableValue right) {
return ((BooleanValueInterface) right).and2(this);
}
@Override
public EvaluatableType<BooleanType> and2(BooleanValue left) {
return (left == BooleanValue.FALSE) ? left : ARBITRARY;
}
@Override
public EvaluatableType<BooleanType> and2(BooleanInterval left) {
return ARBITRARY;
}
// or
@Override
public EvaluatableType<BooleanType> or(EvaluatableValue right) {
return ((BooleanValueInterface) right).or2(this);
}
@Override
public EvaluatableType<BooleanType> or2(BooleanValue left) {
return (left == BooleanValue.TRUE) ? left : ARBITRARY;
}
@Override
public EvaluatableType<BooleanType> or2(BooleanInterval left) {
return ARBITRARY;
}
// equalop
@Override
public EvaluatableType<BooleanType> equalop(EvaluatableValue right) {
return ((BooleanValueInterface) right).equalop2(this);
}
@Override
public EvaluatableType<BooleanType> equalop2(BooleanValue left) {
return ARBITRARY;
}
@Override
public EvaluatableType<BooleanType> equalop2(BooleanInterval left) {
return ARBITRARY;
}
// ite
@Override
public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right) {
return ((EvaluatableValueHierarchy) left).join(right);
}
// unary
@Override
public EvaluatableType<BooleanType> not() {
return this;
}
// auxiliary
@Override
public BooleanType getLow() {
return BooleanValue.FALSE;
}
@Override
public BooleanType getHigh() {
return BooleanValue.TRUE;
}
@Override
public EvaluatableType<BooleanType> newInterval(InstanceType<BooleanType> min, InstanceType<BooleanType> max) {
if (min.equals(max)) return min;
return ARBITRARY;
}
@Override
public boolean equals(Object x) {
return (this == x);
}
@Override
public int hashCode() {
return 19;
}
@Override
public String toString() {
return "[F,T]";
}
@Override
public boolean isAlwaysTrue() {
return false;
}
@Override
public boolean isAlwaysFalse() {
return false;
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return this;
}
}
| 3,313 | 20.24359 | 112 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/IntegerValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
import jkind.util.Util;
public class IntegerValue extends IntegerType implements IntegerValueInterface {
public BigInteger value;
public IntegerValue(BigInteger value) {
this.value = value;
}
// int_divide
@Override
public IntegerType int_divide(IntegerType right) {
return ((IntegerValueInterface) right).int_divide2(this);
}
@Override
public IntegerType int_divide2(IntegerValue left) {
return new IntegerValue(Util.smtDivide(left.value,value));
}
@Override
public IntegerType int_divide2(IntegerInfinity left) {
return IntegerInfinity.newIntegerInfinity(left.signum() * signum());
}
// modulus
@Override
public EvaluatableType<IntegerType> modulus(IntegerType right) {
return ((IntegerValueInterface) right).modulus2(this);
}
@Override
public IntegerType modulus2(IntegerValue left) {
return new IntegerValue(left.value.mod(value));
}
@Override
public EvaluatableType<IntegerType> modulus2(IntegerInfinity left) {
// JKind uses BigInteger.mod() .. which always returns
// a non-negative number.
BigInteger maxvalue = value.abs().subtract(BigInteger.ONE);
IntegerValue max = new IntegerValue(maxvalue);
IntegerValue min = new IntegerValue(BigInteger.ZERO);
return min.newInterval(max);
}
// multiply
@Override
public IntegerType multiply(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).multiply2(this);
}
@Override
public IntegerType multiply2(IntegerValue left) {
return new IntegerValue(left.value.multiply(value));
}
@Override
public IntegerType multiply2(IntegerInfinity left) {
return IntegerInfinity.newIntegerInfinity(left.signum() * signum());
}
// plus
@Override
public IntegerType plus(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).plus2(this);
}
@Override
public IntegerType plus2(IntegerValue left) {
return new IntegerValue(left.value.add(value));
}
@Override
public IntegerType plus2(IntegerInfinity left) {
return left;
}
// less
@Override
public BooleanType less(NumericType<IntegerType> right) {
//if (Debug.enabled) System.out.println(ID.location() + "less(I) : " + this + " < " + right);
return ((IntegerValueInterface) right).less2(this);
}
@Override
public BooleanType less2(IntegerValue left) {
BooleanType res = newBooleanType(left.value.compareTo(value) < 0);
//if (Debug.enabled) System.err.println(ID.location() + "less2 : (" + left + " < " + this + ") = " + res);
return res;
}
@Override
public BooleanType less2(IntegerInfinity left) {
return newBooleanType(left.signum() < 0);
}
// greater
@Override
public BooleanType greater(NumericType<IntegerType> right) {
//if (Debug.enabled) System.out.println(ID.location() + "greater(I) : " + this + " > " + right);
return ((IntegerValueInterface) right).greater2(this);
}
@Override
public BooleanType greater2(IntegerValue left) {
BooleanType res = newBooleanType(left.value.compareTo(value) > 0);
//if (Debug.enabled) System.err.println(ID.location() + "greater2 : (" + left + " > " + this + ") = " + res);
return res;
}
@Override
public BooleanType greater2(IntegerInfinity left) {
return newBooleanType(left.signum() > 0);
}
// equalop
@Override
public BooleanType equalop(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(IntegerValue left) {
return newBooleanType(left.value.compareTo(value) == 0);
}
@Override
public BooleanType equalop2(IntegerInfinity right) {
return newBooleanType(false);
}
// max
@Override
public IntegerType max(IntegerType right) {
return ((IntegerValueInterface) right).max2(this);
}
@Override
public IntegerType max2(IntegerValue left) {
return (left.value.compareTo(value) > 0) ? left : this;
}
@Override
public IntegerType max2(IntegerInfinity left) {
return left.signum() > 0 ? left : this;
}
// min
@Override
public IntegerType min(IntegerType right) {
return ((IntegerValueInterface) right).min2(this);
}
@Override
public IntegerType min2(IntegerValue left) {
return (left.value.compareTo(value) < 0) ? left : this;
}
@Override
public IntegerType min2(IntegerInfinity left) {
return left.signum() < 0 ? left : this;
}
// unary
@Override
public IntegerType negate() {
return new IntegerValue(value.negate());
}
// auxiliary
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof IntegerValue))
return false;
IntegerValue other = (IntegerValue) obj;
return value.equals(other.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public String toString() {
return value.toString();
}
@Override
public int signum() {
return value.signum();
}
@Override
public IntegerType integerType() {
return this;
}
@Override
public RationalType rationalType() {
return new RationalValue(new BigFraction(value));
}
@Override
public BooleanType booleanType() {
return value.signum() != 0 ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public EvaluatableType<IntegerType> newInterval(IntegerType max) {
if (this.equals(max)) return this;
return new IntegerInterval(this,max);
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public boolean isFinite() {
return true;
}
@Override
public IntegerType abs() {
return value.signum() < 0 ? new IntegerValue(value.negate()) : this;
}
@Override
public IntegerType valueOf(BigInteger arg) {
return new IntegerValue(arg);
}
@Override
public BigFraction getValue() {
return new BigFraction(value);
}
}
| 6,752 | 21.814189 | 111 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/PolyValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import fuzzm.poly.PolyBase;
import fuzzm.poly.PolyBool;
import fuzzm.poly.VariableID;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class PolyValue extends IntegerType implements PolyValueInterface {
PolyBase poly;
public PolyValue(VariableID vid) {
Map<VariableID,BigFraction> newCoefs = new HashMap<VariableID,BigFraction>();
newCoefs.put(vid, BigFraction.ONE);
poly = new PolyBase(newCoefs);
}
public PolyValue(PolyBase poly) {
this.poly = poly;
}
@Override
public IntegerType int_divide(IntegerType right) {
if (right instanceof IntegerValue) return int_divide2((IntegerValue) right);
if (right instanceof IntegerInfinity) return int_divide2((IntegerInfinity) right);
return ((PolyValueInterface) right).int_divide2(this);
}
@Override
public IntegerType int_divide2(IntegerValue left) {
//PolyBase leftPoly = new PolyBase(new BigFraction(left.value));
BigFraction c = new BigFraction(left.value);
PolyBase res = this.poly.divide(c);
return new PolyValue(res);
}
@Override
public IntegerType int_divide2(IntegerInfinity left) {
return left;
}
@Override
public IntegerType multiply(NumericType<IntegerType> right) {
if (right instanceof IntegerValue) return multiply2((IntegerValue) right);
if (right instanceof IntegerInfinity) return multiply2((IntegerInfinity) right);
return ((PolyValueInterface) right).multiply2(this);
}
@Override
public IntegerType multiply2(IntegerValue left) {
//PolyBase leftPoly = new PolyBase(new BigFraction(left.value));
BigFraction c = new BigFraction(left.value);
PolyBase res = this.poly.multiply(c);
return new PolyValue(res);
}
@Override
public IntegerType multiply2(IntegerInfinity left) {
return left;
}
@Override
public IntegerType multiply2(PolyValue left) {
if (this.poly.isConstant()) {
return new PolyValue(left.poly.multiply(this.poly.getConstant()));
} else if (left.poly.isConstant()) {
return new PolyValue(this.poly.multiply(left.poly.getConstant()));
} else {
throw new IllegalArgumentException("Non-Linear Multiplication");
}
}
@Override
public IntegerType negate() {
PolyBase res = this.poly.negate();
return new PolyValue(res);
}
@Override
public boolean equals(Object x) {
return poly.equals(x);
}
@Override
public String toString() {
return poly.toString();
}
@Override
public IntegerType plus(NumericType<IntegerType> right) {
if (right instanceof IntegerValue) return plus2((IntegerValue) right);
if (right instanceof IntegerInfinity) return plus2((IntegerInfinity) right);
return ((PolyValueInterface) right).plus2(this);
}
@Override
public IntegerType plus2(IntegerValue left) {
PolyBase leftPoly = new PolyBase(new BigFraction(left.value));
PolyBase res = leftPoly.add(this.poly);
return new PolyValue(res);
}
@Override
public IntegerType plus2(IntegerInfinity left) {
return left;
}
@Override
public IntegerType plus2(PolyValue left) {
PolyBase leftPoly = left.poly;
PolyBase res = leftPoly.add(this.poly);
return new PolyValue(res);
}
@Override
public BooleanType less2(IntegerValue left) {
PolyBase rhs = this.poly;
//if (Debug.enabled) System.out.println(ID.location() + "less2 : " + left + " < " + rhs);
rhs = rhs.subtract(new BigFraction(left.value));
return new PolyBooleanValue(PolyBool.greater0(rhs));
}
@Override
public BooleanType less2(IntegerInfinity left) {
return left.signum() > 0 ? BooleanValue.FALSE : BooleanValue.TRUE;
}
@Override
public BooleanType less2(PolyValue left) {
PolyBase leftPoly = left.poly;
PolyBase rightPoly = this.poly;
PolyBase lhs = leftPoly.subtract(rightPoly);
return new PolyBooleanValue(PolyBool.less0(lhs));
}
@Override
public BooleanType less(NumericType<IntegerType> right) {
//if (Debug.enabled) System.out.println(ID.location() + "less(P) : " + this + " < " + right);
if (right instanceof IntegerValue) return greater2((IntegerValue) right);
if (right instanceof IntegerInfinity) return greater2((IntegerInfinity) right);
return ((PolyValueInterface) right).less2(this);
}
@Override
public BooleanType greater2(IntegerValue left) {
PolyBase rhs = this.poly;
//if (Debug.enabled) System.out.println(ID.location() + "greater2 : " + left + " > " + rhs);
rhs = rhs.subtract(new BigFraction(left.value));
return new PolyBooleanValue(PolyBool.less0(rhs));
}
@Override
public BooleanType greater2(IntegerInfinity left) {
return left.signum() > 0 ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public BooleanType greater2(PolyValue left) {
PolyBase leftPoly = left.poly;
PolyBase rightPoly = this.poly;
PolyBase lhs = leftPoly.subtract(rightPoly);
return new PolyBooleanValue(PolyBool.greater0(lhs));
}
@Override
public BooleanType greater(NumericType<IntegerType> right) {
//if (Debug.enabled) System.out.println(ID.location() + "greater(P) : " + this + " > " + right);
if (right instanceof IntegerValue) return less2((IntegerValue) right);
if (right instanceof IntegerInfinity) return less2((IntegerInfinity) right);
return ((PolyValueInterface) right).greater2(this);
}
@Override
public BooleanType equalop(NumericType<IntegerType> right) {
if (right instanceof IntegerValue) return equalop2((IntegerValue) right);
if (right instanceof IntegerInfinity) return equalop2((IntegerInfinity) right);
return ((PolyValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(IntegerValue left) {
PolyBase myPoly = this.poly;
if(myPoly.isConstant()){
if(myPoly.getConstant().equals(new BigFraction(left.value))){
return BooleanValue.TRUE;
}
}
return BooleanValue.FALSE;
}
@Override
public BooleanType equalop2(IntegerInfinity left) {
return BooleanValue.FALSE;
}
@Override
public BooleanType equalop2(PolyValue left) {
return new PolyBooleanValue(PolyBool.equal0(this.poly.subtract(left.poly)));
}
// Unimplemented methods ..
@Override
public BigFraction getValue() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType modulus2(IntegerValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> modulus2(IntegerInfinity left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType max2(IntegerValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType max2(IntegerInfinity left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType min2(IntegerValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType min2(IntegerInfinity left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType int_divide2(PolyValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType modulus2(PolyValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType max2(PolyValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType min2(PolyValue left) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> modulus(IntegerType right) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> newInterval(IntegerType max) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType abs() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType valueOf(BigInteger arg) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType max(IntegerType base) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType min(IntegerType base) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public boolean isFinite() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> integerType() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<RationalType> rationalType() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<BooleanType> booleanType() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public int signum() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public IntegerType newIntegerType(BigInteger value) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public RationalType newRationalType(BigFraction value) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public BooleanType newBooleanType(boolean value) {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
}
| 10,238 | 25.733681 | 98 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/IntegerValueInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
public interface IntegerValueInterface /*extends NumericTypeInterface<IntegerType>*/ {
IntegerType int_divide(IntegerType right);
IntegerType int_divide2(IntegerValue left);
IntegerType int_divide2(IntegerInfinity left);
EvaluatableType<IntegerType> modulus(IntegerType right);
IntegerType modulus2(IntegerValue left);
EvaluatableType<IntegerType> modulus2(IntegerInfinity left);
IntegerType max(IntegerType right);
IntegerType max2(IntegerValue left);
IntegerType max2(IntegerInfinity left);
IntegerType min(IntegerType right);
IntegerType min2(IntegerValue left);
IntegerType min2(IntegerInfinity left);
IntegerType multiply(NumericType<IntegerType> right);
IntegerType multiply2(IntegerValue left);
IntegerType multiply2(IntegerInfinity left);
IntegerType plus(NumericType<IntegerType> right);
IntegerType plus2(IntegerValue left);
IntegerType plus2(IntegerInfinity left);
BooleanType less(NumericType<IntegerType> right);
BooleanType less2(IntegerValue left);
BooleanType less2(IntegerInfinity left);
BooleanType greater(NumericType<IntegerType> right);
BooleanType greater2(IntegerValue left);
BooleanType greater2(IntegerInfinity left);
BooleanType equalop(NumericType<IntegerType> right);
BooleanType equalop2(IntegerValue left);
BooleanType equalop2(IntegerInfinity left);
}
| 1,742 | 30.690909 | 86 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/BooleanValueInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.EvaluatableValue;
public interface BooleanValueInterface {
EvaluatableType<BooleanType> not();
EvaluatableType<BooleanType> equalop(EvaluatableValue right);
EvaluatableType<BooleanType> equalop2(BooleanValue left);
EvaluatableType<BooleanType> equalop2(BooleanInterval left);
EvaluatableType<BooleanType> and(EvaluatableValue right);
EvaluatableType<BooleanType> and2(BooleanValue left);
EvaluatableType<BooleanType> and2(BooleanInterval left);
EvaluatableType<BooleanType> or(EvaluatableValue right);
EvaluatableType<BooleanType> or2(BooleanValue left);
EvaluatableType<BooleanType> or2(BooleanInterval left);
}
| 989 | 29.9375 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/IntegerInfinity.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class IntegerInfinity extends IntegerType implements IntegerValueInterface {
public static final IntegerInfinity POSITIVE_INFINITY = new IntegerInfinity();
public static final IntegerInfinity NEGATIVE_INFINITY = new IntegerInfinity();
private IntegerInfinity() {
}
public static IntegerType newIntegerInfinity(int sign) {
if (sign == 0) return new IntegerValue(BigInteger.ZERO);
return sign < 0 ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
// int_divide
@Override
public IntegerType int_divide(IntegerType right) {
return ((IntegerValueInterface) right).int_divide2(this);
}
@Override
public IntegerType int_divide2(IntegerValue left) {
// int/infinity;
throw new IllegalArgumentException();
}
@Override
public IntegerType int_divide2(IntegerInfinity left) {
// infinity/infinity
throw new IllegalArgumentException();
}
// modulus
@Override
public EvaluatableType<IntegerType> modulus(IntegerType right) {
return ((IntegerValueInterface) right).modulus2(this);
}
@Override
public IntegerType modulus2(IntegerValue left) {
// int % infinity;
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> modulus2(IntegerInfinity left) {
// infinity % infinity
throw new IllegalArgumentException();
}
// multiply
@Override
public IntegerType multiply(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).multiply2(this);
}
@Override
public IntegerType multiply2(IntegerValue left) {
return newIntegerInfinity(signum() * left.signum());
}
@Override
public IntegerType multiply2(IntegerInfinity left) {
return newIntegerInfinity(signum() * left.signum());
}
// plus
@Override
public IntegerType plus(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).plus2(this);
}
@Override
public IntegerType plus2(IntegerValue left) {
return this;
}
@Override
public IntegerType plus2(IntegerInfinity left) {
assert(left.signum() == signum());
return this;
}
// less
@Override
public BooleanType less(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).less2(this);
}
@Override
public BooleanType less2(IntegerValue left) {
return newBooleanType(0 < signum());
}
@Override
public BooleanType less2(IntegerInfinity left) {
return newBooleanType(left.signum() < signum());
}
// greater
@Override
public BooleanType greater(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).greater2(this);
}
@Override
public BooleanType greater2(IntegerValue left) {
return newBooleanType(0 > signum());
}
@Override
public BooleanType greater2(IntegerInfinity left) {
return newBooleanType(left.signum() > signum());
}
// equalop
@Override
public BooleanType equalop(NumericType<IntegerType> right) {
return ((IntegerValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(IntegerValue left) {
return newBooleanType(false);
}
@Override
public BooleanType equalop2(IntegerInfinity left) {
return newBooleanType(left.signum() == signum());
}
// max
@Override
public IntegerType max(IntegerType right) {
return ((IntegerValueInterface) right).max2(this);
}
@Override
public IntegerType max2(IntegerValue left) {
return signum() > 0 ? this :left;
}
@Override
public IntegerType max2(IntegerInfinity left) {
return signum() > left.signum() ? this : left;
}
// min
@Override
public IntegerType min(IntegerType right) {
return ((IntegerValueInterface) right).min2(this);
}
@Override
public IntegerType min2(IntegerValue left) {
return signum() < 0 ? this : left;
}
@Override
public IntegerType min2(IntegerInfinity left) {
return signum() < left.signum() ? this : left;
}
// unary
@Override
public IntegerType negate() {
return newIntegerInfinity(- signum());
}
// auxiliary
@Override
public EvaluatableType<IntegerType> newInterval(IntegerType max) {
if (this.equals(max)) return this;
return new IntegerInterval(this,max);
}
@Override
public boolean equals(Object obj) {
return (this == obj);
}
@Override
public int hashCode() {
return signum() < 0 ? -23 : 23;
}
@Override
public String toString() {
return "" + signum() + "/0";
}
@Override
public int signum() {
return (this == POSITIVE_INFINITY) ? +1 : -1;
}
@Override
public IntegerType integerType() {
return this;
}
@Override
public RationalType rationalType() {
return (signum() < 0) ? RationalInfinity.NEGATIVE_INFINITY : RationalInfinity.POSITIVE_INFINITY;
}
@Override
public BooleanType booleanType() {
return (signum() < 0) ? BooleanValue.FALSE : BooleanValue.TRUE;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public boolean isFinite() {
return false;
}
@Override
public IntegerType abs() {
return POSITIVE_INFINITY;
}
@Override
public IntegerType valueOf(BigInteger arg) {
return new IntegerValue(arg);
}
@Override
public BigFraction getValue() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
}
| 6,044 | 20.360424 | 98 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/PolyValueInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.IntegerType;
public interface PolyValueInterface extends IntegerValueInterface {
IntegerType int_divide2(PolyValue left);
IntegerType modulus2(PolyValue left);
IntegerType max2(PolyValue left);
IntegerType min2(PolyValue left);
IntegerType multiply2(PolyValue left);
IntegerType plus2(PolyValue left);
BooleanType less2(PolyValue left);
BooleanType greater2(PolyValue left);
BooleanType equalop2(PolyValue left);
}
| 739 | 27.461538 | 67 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/IntegerInterval.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.InstanceType;
import fuzzm.value.hierarchy.IntegerIntervalType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class IntegerInterval extends IntegerIntervalType {
IntegerType min;
IntegerType max;
public static final IntegerInterval INFINITE_INTERVAL = new IntegerInterval(IntegerInfinity.NEGATIVE_INFINITY,IntegerInfinity.POSITIVE_INFINITY);
public IntegerInterval(IntegerType min, IntegerType max) {
assert(! min.equals(max));
this.min = min;
this.max = max;
}
@Override
public IntegerType getLow() {
return min;
}
@Override
public IntegerType getHigh() {
return max;
}
@Override
public EvaluatableType<IntegerType> newInterval(InstanceType<IntegerType> min, InstanceType<IntegerType> max) {
if (min.equals(max)) return min;
return new IntegerInterval((IntegerType) min, (IntegerType) max);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof IntegerInterval))
return false;
IntegerInterval other = (IntegerInterval) obj;
return max.equals(other.max) && min.equals(other.min);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((max == null) ? 0 : max.hashCode());
result = prime * result + ((min == null) ? 0 : min.hashCode());
return result;
}
@Override
public String toString() {
return "[" + min + "," + max + "]";
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
}
| 2,348 | 23.216495 | 146 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/PolyBooleanValueInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
public interface PolyBooleanValueInterface extends BooleanValueInterface {
EvaluatableType<BooleanType> equalop2(PolyBooleanValue left);
EvaluatableType<BooleanType> and2(PolyBooleanValue left);
EvaluatableType<BooleanType> or2(PolyBooleanValue right);
}
| 591 | 27.190476 | 74 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/RationalInfinity.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.NumericType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public final class RationalInfinity extends RationalType implements RationalValueInterface {
public static final RationalInfinity POSITIVE_INFINITY = new RationalInfinity();
public static final RationalInfinity NEGATIVE_INFINITY = new RationalInfinity();
private RationalInfinity() {
}
public static RationalType newRationalInfinity(int sign) {
if (sign == 0) return new RationalValue(BigFraction.ZERO);
return (sign < 0) ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
}
// divide
@Override
public RationalType divide(RationalType right) {
return ((RationalValueInterface) right).divide2(this);
}
@Override
public RationalType divide2(RationalValue left) {
throw new IllegalArgumentException();
}
@Override
public RationalType divide2(RationalInfinity left) {
throw new IllegalArgumentException();
}
// multiply
@Override
public RationalType multiply(NumericType<RationalType> right) {
return ((RationalValueInterface) right).multiply2(this);
}
@Override
public RationalType multiply2(RationalValue left) {
return newRationalInfinity(left.signum() * signum());
}
@Override
public RationalType multiply2(RationalInfinity left) {
return newRationalInfinity(left.signum() * signum());
}
// plus
@Override
public RationalType plus(NumericType<RationalType> right) {
return ((RationalValueInterface) right).plus2(this);
}
@Override
public RationalType plus2(RationalValue left) {
return this;
}
@Override
public RationalType plus2(RationalInfinity left) {
assert(signum() == left.signum());
return this;
}
// less
@Override
public BooleanType less(NumericType<RationalType> right) {
return ((RationalValueInterface) right).less2(this);
}
@Override
public BooleanType less2(RationalValue left) {
return newBooleanType(0 < signum());
}
@Override
public BooleanType less2(RationalInfinity left) {
return newBooleanType(left.signum() < signum());
}
// greater
@Override
public BooleanType greater(NumericType<RationalType> right) {
return ((RationalValueInterface) right).greater2(this);
}
@Override
public BooleanType greater2(RationalValue left) {
return newBooleanType(0 > signum());
}
@Override
public BooleanType greater2(RationalInfinity left) {
return newBooleanType(left.signum() > signum());
}
// equalop
@Override
public BooleanType equalop(NumericType<RationalType> right) {
return ((RationalValueInterface) right).equalop2(this);
}
@Override
public BooleanType equalop2(RationalValue left) {
return newBooleanType(false);
}
@Override
public BooleanType equalop2(RationalInfinity left) {
return newBooleanType(left.signum() == signum());
}
// max
@Override
public RationalType max(RationalType right) {
return ((RationalValueInterface) right).max2(this);
}
@Override
public RationalType max2(RationalValue left) {
return signum() > 0 ? this : left;
}
@Override
public RationalType max2(RationalInfinity left) {
return signum() > left.signum() ? this : left;
}
// min
@Override
public RationalType min(RationalType right) {
return ((RationalValueInterface) right).min2(this);
}
@Override
public RationalType min2(RationalValue left) {
return signum() < 0 ? this : left;
}
@Override
public RationalType min2(RationalInfinity left) {
return signum() < left.signum() ? this : left;
}
// unary
@Override
public RationalType negate() {
return newRationalInfinity(- signum());
}
// auxiliary
@Override
public EvaluatableType<RationalType> newInterval(RationalType max) {
if (this.equals(max)) return this;
return new RationalInterval(this,max);
}
@Override
public boolean equals(Object x) {
return (this == x);
}
@Override
public int hashCode() {
return signum() < 0 ? -13 : 13;
}
@Override
public String toString() {
return "" + signum() + ".0/0.0";
}
@Override
public int signum() {
return (this == POSITIVE_INFINITY) ? +1 : -1;
}
@Override
public IntegerType integerType() {
return signum() > 0 ? IntegerInfinity.POSITIVE_INFINITY : IntegerInfinity.NEGATIVE_INFINITY;
}
@Override
public RationalType rationalType() {
return this;
}
@Override
public BooleanType booleanType() {
return (signum() > 0) ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE ;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public boolean isFinite() {
return false;
}
@Override
public RationalType abs() {
return POSITIVE_INFINITY;
}
@Override
public RationalType valueOf(BigInteger arg) {
return new RationalValue(new BigFraction(arg));
}
@Override
public BigFraction getValue() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
}
| 5,644 | 20.545802 | 94 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/instance/PolyBooleanValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.instance;
import java.math.BigInteger;
import fuzzm.poly.PolyBool;
import fuzzm.value.hierarchy.BooleanType;
import fuzzm.value.hierarchy.EvaluatableType;
import fuzzm.value.hierarchy.EvaluatableValue;
import fuzzm.value.hierarchy.EvaluatableValueHierarchy;
import fuzzm.value.hierarchy.IntegerType;
import fuzzm.value.hierarchy.RationalType;
import jkind.util.BigFraction;
public class PolyBooleanValue extends BooleanType implements PolyBooleanValueInterface {
public PolyBool value;
public PolyBooleanValue(PolyBool value) {
this.value = value;
}
// not()
@Override
public EvaluatableType<BooleanType> not() {
return new PolyBooleanValue(value.not());
}
// and()
@Override
public EvaluatableType<BooleanType> and(EvaluatableValue right) {
if (right instanceof BooleanValue) return and2((BooleanValue) right);
if (right instanceof BooleanInterval) return and2((BooleanInterval) right);
return ((PolyBooleanValueInterface) right).and2(this);
}
@Override
public EvaluatableType<BooleanType> and2(BooleanValue left) {
return (left == BooleanValue.TRUE) ? this : left;
}
@Override
public EvaluatableType<BooleanType> and2(BooleanInterval left) {
return left;
}
@Override
public EvaluatableType<BooleanType> and2(PolyBooleanValue left) {
return new PolyBooleanValue(this.value.and(left.value));
}
// or()
@Override
public EvaluatableType<BooleanType> or(EvaluatableValue right) {
if (right instanceof BooleanValue) return or2((BooleanValue) right);
if (right instanceof BooleanInterval) return or2((BooleanInterval) right);
return ((PolyBooleanValueInterface) right).or2(this);
}
@Override
public EvaluatableType<BooleanType> or2(BooleanValue left) {
return (left == BooleanValue.FALSE) ? this : left;
}
@Override
public EvaluatableType<BooleanType> or2(BooleanInterval left) {
return left;
}
@Override
public EvaluatableType<BooleanType> or2(PolyBooleanValue left) {
return new PolyBooleanValue(this.value.or(left.value));
}
// equal()
@Override
public EvaluatableType<BooleanType> equalop(EvaluatableValue right) {
if (right instanceof BooleanValue) return equalop2((BooleanValue) right);
if (right instanceof BooleanInterval) return equalop2((BooleanInterval) right);
return ((PolyBooleanValueInterface) right).equalop2(this);
}
@Override
public EvaluatableType<BooleanType> equalop2(BooleanValue left) {
return (left == BooleanValue.TRUE) ? this : new PolyBooleanValue(this.value.not());
}
@Override
public EvaluatableType<BooleanType> equalop2(BooleanInterval left) {
return left;
}
@Override
public EvaluatableType<BooleanType> equalop2(PolyBooleanValue left) {
return new PolyBooleanValue(this.value.iff(left.value));
}
// ite()
//
// Yeah .. this will be fun. For now I guess it is just a join.
// Unless they are boolean.
//
@Override
public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right) {
if (left instanceof BooleanType) {
return and(left).or(not().and(right));
}
// NOTE: what we need to do is "promote" the condition .. but that really
// only makes sense if we know "for sure" that we need the result of this
// computation .. which is to say: the simulation should *not* be event
// based. It should be a recursive decent evaluation. Everything old is
// new again. That is why our poly generalization is recursive decent.
return ((EvaluatableValueHierarchy) left).join(right);
}
// auxiliary
@Override
public boolean isAlwaysTrue() {
return value.isAlwaysTrue();
}
@Override
public boolean isAlwaysFalse() {
return value.isAlwaysFalse();
}
@Override
public BooleanType max(BooleanType right) {
throw new IllegalArgumentException();
}
@Override
public BooleanType min(BooleanType right) {
throw new IllegalArgumentException();
}
@Override
public boolean isFinite() {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> integerType() {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<RationalType> rationalType() {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<BooleanType> booleanType() {
return this;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!( obj instanceof PolyBooleanValue))
return false;
PolyBooleanValue other = (PolyBooleanValue) obj;
return value.equals(other.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return value.toString();
}
@Override
public int signum() {
throw new IllegalArgumentException();
}
@Override
public IntegerType newIntegerType(BigInteger value) {
return new IntegerValue(value);
}
@Override
public RationalType newRationalType(BigFraction value) {
return new RationalValue(value);
}
@Override
public BooleanType newBooleanType(boolean value) {
return value ? BooleanValue.TRUE : BooleanValue.FALSE;
}
@Override
public EvaluatableType<BooleanType> newBooleanInterval() {
return BooleanInterval.ARBITRARY;
}
@Override
public BigFraction getValue() {
// TODO Auto-generated method stub
throw new IllegalArgumentException();
}
}
| 5,513 | 23.726457 | 88 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/InstanceType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.util.BigFraction;
abstract public class InstanceType<T extends InstanceType<T>> extends EvaluatableType<T> {
abstract public T max(T base);
@SafeVarargs
public final T max(T other, T ... rest) {
T res = max(other);
for (T next: rest) {
res = res.max(next);
}
return res;
}
abstract public T min(T base);
@SafeVarargs
public final T min(T other, T ... rest) {
T res = min(other);
for (T next: rest) {
res = res.min(next);
}
return res;
}
abstract public EvaluatableType<T> newInterval(T max);
@Override
public final T getLow() {
@SuppressWarnings("unchecked")
T value = ((T) this);
return value;
}
@Override
public final T getHigh() {
@SuppressWarnings("unchecked")
T value = ((T) this);
return value;
}
abstract public boolean isFinite();
abstract public BigFraction getValue();
}
| 1,104 | 18.732143 | 90 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/BooleanIntervalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
abstract public class BooleanIntervalType extends IntervalType<BooleanType> implements BooleanTypeInterface {
@Override
abstract public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> not();
@Override
abstract public EvaluatableType<BooleanType> equalop(EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> and(EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> or(EvaluatableValue right);
@Override
public Type getType() {
return NamedType.BOOL;
}
}
| 909 | 23.594595 | 109 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/Joinable.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public interface Joinable<T extends InstanceType<T>> {
public EvaluatableType<T> join(EvaluatableValue right);
public EvaluatableType<T> join2(IntervalType<T> left);
public EvaluatableType<T> join2(T left);
}
| 455 | 27.5 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/NumericType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import java.math.BigInteger;
import fuzzm.util.Debug;
import fuzzm.util.ID;
public abstract class NumericType<T extends NumericType<T>> extends InstanceType<T> implements NumericTypeInterface<T>,Joinable<T> {
@Override
public final EvaluatableType<T> join(EvaluatableValue right) {
@SuppressWarnings("unchecked")
Joinable<T> rv = ((Joinable<T>) right);
@SuppressWarnings("unchecked")
T left = ((T) this);
return rv.join2(left);
}
@Override
public final EvaluatableType<T> join2(T left) {
return min(left).newInterval(max(left));
}
@Override
public final EvaluatableType<T> join2(IntervalType<T> left) {
return min(left.getLow()).newInterval(max(left.getHigh()));
}
@Override
abstract public EvaluatableType<T> newInterval(T max);
@Override
public final EvaluatableType<T> multiply(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface <T>) right);
return rv.multiply2(this);
}
@Override
public final EvaluatableType<T> multiply2(NumericIntervalType<T> left) {
T max2 = left.getHigh();
T min2 = left.getLow();
T p1 = multiply(min2);
T p2 = multiply(max2);
return p1.min(p2).newInterval(p1.max(p2));
}
@Override
public final T multiply2(NumericType<T> left) {
return left.multiply(this);
}
abstract public T multiply(NumericType<T> right);
@Override
public final EvaluatableType<T> plus(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.plus2(this);
}
@Override
public final EvaluatableType<T> plus2(NumericIntervalType<T> left) {
@SuppressWarnings("unchecked")
T right = ((T) this);
T min = left.getLow().plus(right);
T max = left.getHigh().plus(right);
return min.newInterval(max);
}
@Override
public final NumericType<T> plus2(NumericType<T> left) {
@SuppressWarnings("unchecked")
T right = ((T) this);
return left.plus(right);
}
abstract public T plus(NumericType<T> right);
@Override
public final EvaluatableType<BooleanType> less(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.less2(this);
};
@Override
public final EvaluatableType<BooleanType> less2(NumericIntervalType<T> left) {
// this assumes that min != max
if (this.greater(left.getHigh()).isAlwaysTrue()) return newBooleanType(true);
if (left.getLow().less(this).isAlwaysFalse()) return newBooleanType(false);
//System.out.println(ID.location() + "*** " + "("+ left + " < " + this + ") = [F,T}");
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> less2(NumericType<T> left) {
return left.less(this);
}
abstract public BooleanType less(NumericType<T> right);
@Override
public final EvaluatableType<BooleanType> greater(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.greater2(this);
}
@Override
public final EvaluatableType<BooleanType> greater2(NumericIntervalType<T> left) {
// this assumes that min != max
if (left.getLow().greater(this).isAlwaysTrue()) return newBooleanType(true);
if (this.less(left.getHigh()).isAlwaysFalse()) return newBooleanType(false);
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> greater2(NumericType<T> left) {
return left.greater(this);
}
abstract public BooleanType greater(NumericType<T> right);
@Override
public final EvaluatableType<BooleanType> equalop(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.equalop2(this);
}
@Override
public final EvaluatableType<BooleanType> equalop2(NumericIntervalType<T> left) {
// this assumes that min != max
EvaluatableType<BooleanType> res;
if (this.less(left.getLow()).isAlwaysTrue() || this.greater(left.getHigh()).isAlwaysTrue()) {
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + this + " < " + left.getLow() + " || " + left.getHigh() + " < " + this + ")");
res = newBooleanType(false);
} else {
res = newBooleanInterval();
}
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + left + " == " + this + ") = " + res);
return res;
}
@Override
public final EvaluatableType<BooleanType> equalop2(NumericType<T> left) {
return left.equalop(this);
}
abstract public BooleanType equalop(NumericType<T> right);
@Override
abstract public T negate();
abstract public T abs();
abstract public T valueOf(BigInteger arg);
}
| 4,916 | 28.094675 | 144 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/IntegerTypeInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public interface IntegerTypeInterface {
public EvaluatableType<IntegerType> int_divide(EvaluatableValue right);
public EvaluatableType<IntegerType> int_divide2(IntegerType left);
public EvaluatableType<IntegerType> int_divide2(IntegerIntervalType left);
public EvaluatableType<IntegerType> modulus(EvaluatableValue right);
public EvaluatableType<IntegerType> modulus2(IntegerType left);
public EvaluatableType<IntegerType> modulus2(IntegerIntervalType left);
}
| 714 | 31.5 | 75 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/RationalIntervalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
abstract public class RationalIntervalType extends NumericIntervalType<RationalType> implements RationalTypeInterface {
@Override
public final EvaluatableType<RationalType> divide(EvaluatableValue right) {
RationalTypeInterface rv = (RationalTypeInterface) right;
return rv.divide2(this);
}
@Override
public final EvaluatableType<RationalType> divide2(RationalType left) {
RationalType max = getHigh();
RationalType min = getLow();
assert(max.signum() == min.signum());
RationalType p1 = left.divide(max);
RationalType p2 = left.divide(min);
return newInterval(p1.min(p2),p1.max(p2));
}
@Override
public final EvaluatableType<RationalType> divide2(RationalIntervalType left) {
throw new IllegalArgumentException();
}
@Override
public final Type getType() {
return NamedType.REAL;
}
}
| 1,126 | 24.613636 | 119 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/EvaluatableValueHierarchy.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import java.math.BigInteger;
import jkind.util.BigFraction;
public abstract class EvaluatableValueHierarchy extends EvaluatableValue {
// BxV -> V
public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue getHigh() {
return this;
}
public EvaluatableValue getLow() {
return this;
}
abstract public int signum();
// Z
abstract public IntegerType newIntegerType(BigInteger value);
// Q
abstract public RationalType newRationalType(BigFraction value);
//abstract public BigFraction rationalValue();
// B
abstract public BooleanType newBooleanType (boolean value);
//abstract public boolean booleanValue();
abstract public EvaluatableType<BooleanType> newBooleanInterval();
public abstract EvaluatableValue join(EvaluatableValue right);
}
| 1,098 | 22.891304 | 77 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/NumericTypeInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public interface NumericTypeInterface<T extends NumericType<T>> {
EvaluatableType<T> multiply(EvaluatableValue right);
EvaluatableType<T> multiply2(NumericType<T> left);
EvaluatableType<T> multiply2(NumericIntervalType<T> left);
EvaluatableType<T> plus(EvaluatableValue right);
EvaluatableType<T> plus2(NumericType<T> left);
EvaluatableType<T> plus2(NumericIntervalType<T> left);
EvaluatableType<BooleanType> less(EvaluatableValue right);
EvaluatableType<BooleanType> less2(NumericType<T> left);
EvaluatableType<BooleanType> less2(NumericIntervalType<T> left);
EvaluatableType<BooleanType> greater(EvaluatableValue right);
EvaluatableType<BooleanType> greater2(NumericType<T> left);
EvaluatableType<BooleanType> greater2(NumericIntervalType<T> left);
EvaluatableType<BooleanType> equalop(EvaluatableValue right);
EvaluatableType<BooleanType> equalop2(NumericType<T> left);
EvaluatableType<BooleanType> equalop2(NumericIntervalType<T> left);
}
| 1,213 | 34.705882 | 68 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/NumericIntervalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import fuzzm.util.Debug;
import fuzzm.util.ID;
abstract public class NumericIntervalType<T extends NumericType<T>> extends IntervalType<T> implements NumericTypeInterface<T> {
@Override
public final EvaluatableType<T> multiply(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.multiply2(this);
}
@Override
public final EvaluatableType<T> multiply2(NumericIntervalType<T> left) {
T max1 = getHigh();
T max2 = left.getHigh();
T min1 = getLow();
T min2 = left.getLow();
T maxmin = max1.multiply2(min2);
T maxmax = max1.multiply(max2);
T minmin = min1.multiply(min2);
T minmax = min1.multiply(max2);
return newInterval(maxmin.min(maxmax,minmin,minmax),maxmin.max(maxmax,minmin,minmax));
}
@Override
public final EvaluatableType<T> multiply2(NumericType<T> left) {
T max1 = getHigh();
T min1 = getLow();
T p1 = max1.multiply(left);
T p2 = min1.multiply(left);
return newInterval(p1.min(p2),p1.max(p2));
}
@Override
public final EvaluatableType<T> plus(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.plus2(this);
}
@Override
public final EvaluatableType<T> plus2(NumericIntervalType<T> left) {
T min = left.getLow().plus(getLow());
T max = left.getHigh().plus(getHigh());
return newInterval(min,max);
}
@Override
public final EvaluatableType<T> plus2(NumericType<T> left) {
T min = left.plus(getLow());
T max = left.plus(getHigh());
return newInterval(min,max);
}
@Override
public final EvaluatableType<BooleanType> less(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.less2(this);
}
@Override
public final EvaluatableType<BooleanType> less2(NumericIntervalType<T> left) {
// this assumes that min != max
if (getLow().greater(left.getHigh()).isAlwaysTrue()) return newBooleanType(true);
if (left.getLow().less(getHigh()).isAlwaysFalse()) return newBooleanType(false);
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> less2(NumericType<T> left) {
// this assumes that min != max
if (getLow().greater(left).isAlwaysTrue()) return newBooleanType(true);
if (left.less(getHigh()).isAlwaysFalse()) return newBooleanType(false);
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> greater(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.greater2(this);
}
@Override
public final EvaluatableType<BooleanType> greater2(NumericIntervalType<T> left) {
// this assumes that min != max
if (left.getLow().greater(getHigh()).isAlwaysTrue()) return newBooleanType(true);
if (getLow().less(left.getHigh()).isAlwaysFalse()) return newBooleanType(false);
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> greater2(NumericType<T> left) {
// this assumes that min != max
if (left.greater(getHigh()).isAlwaysTrue()) return newBooleanType(true);
if ((getLow().less(left)).isAlwaysFalse()) return newBooleanType(false);
return newBooleanInterval();
}
@Override
public final EvaluatableType<BooleanType> equalop(EvaluatableValue right) {
@SuppressWarnings("unchecked")
NumericTypeInterface<T> rv = ((NumericTypeInterface<T>) right);
return rv.equalop2(this);
}
@Override
public final EvaluatableType<BooleanType> equalop2(NumericIntervalType<T> left) {
// TODO: we should probably keep this in the Value domain. (ie: do not use isTrue())
EvaluatableType<BooleanType> res;
if (left.getHigh().less(getLow()).isAlwaysTrue() || getHigh().less(left.getLow()).isAlwaysTrue()) {
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + left.getHigh() + " < " + getLow() + " || " + getHigh() + " < " + left.getLow() + ")");
res = newBooleanType(false);
} else {
res = newBooleanInterval();
}
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + left + " == " + this + ") = " + res);
return res;
}
@Override
public final EvaluatableType<BooleanType> equalop2(NumericType<T> left) {
// this assumes that min != max
EvaluatableType<BooleanType> res;
if (left.less(getLow()).isAlwaysTrue() || left.greater(getHigh()).isAlwaysTrue()) {
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + left + " < " + getLow() + " || " + getHigh() + " < " + left + ")");
res = newBooleanType(false);
} else {
res = newBooleanInterval();
}
if (Debug.isEnabled()) System.err.println(ID.location() + "(" + left + " == " + this + ") = " + res);
return res;
}
@Override
public final EvaluatableType<T> negate() {
return newInterval(getHigh().negate(),getLow().negate());
}
}
| 5,147 | 32.647059 | 153 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/IntegerType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import java.math.BigInteger;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
public abstract class IntegerType extends NumericType<IntegerType> implements IntegerTypeInterface {
@Override
public final EvaluatableType<IntegerType> int_divide(EvaluatableValue right) {
// System.out.println(ID.location() + this + "/" + right);
IntegerTypeInterface rv = ((IntegerTypeInterface) right);
EvaluatableType<IntegerType> res = rv.int_divide2(this);
//System.out.println(ID.location() + "(" + this + "/" + right + ") = " + res);
return res;
}
@Override
public final EvaluatableType<IntegerType> int_divide2(IntegerType left) {
return left.int_divide(this);
}
@Override
public final EvaluatableType<IntegerType> int_divide2(IntegerIntervalType left) {
IntegerType min = left.getLow();
IntegerType max = left.getHigh();
IntegerType q1 = min.int_divide(this);
IntegerType q2 = max.int_divide(this);
return q1.min(q2).newInterval(q1.max(q2));
}
abstract public IntegerType int_divide(IntegerType right);
@Override
public final EvaluatableType<IntegerType> modulus(EvaluatableValue right) {
IntegerTypeInterface rv = ((IntegerTypeInterface) right);
EvaluatableType<IntegerType> res = rv.modulus2(this);
//System.out.println(ID.location() + "(" + this + "%" + right + ") = " + res);
return res;
}
@Override
public final EvaluatableType<IntegerType> modulus2(IntegerType left) {
return left.modulus(this);
}
@Override
public final EvaluatableType<IntegerType> modulus2(IntegerIntervalType left) {
int sign = signum();
IntegerType modulus = (sign < 0) ? negate() : this;
IntegerType max = (IntegerType) modulus.minus(newIntegerType(BigInteger.ONE));
IntegerType min = newIntegerType(BigInteger.ZERO);
return min.newInterval(max);
}
abstract public EvaluatableType<IntegerType> modulus(IntegerType right);
@Override
public final Type getType() {
return NamedType.INT;
}
}
| 2,188 | 29.830986 | 100 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/BooleanType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import fuzzm.value.instance.BooleanInterval;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
public abstract class BooleanType extends InstanceType<BooleanType> implements BooleanTypeInterface, Joinable<BooleanType> {
@Override
abstract public EvaluatableValue ite(EvaluatableValue left, EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> not();
@Override
abstract public EvaluatableType<BooleanType> and(EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> or(EvaluatableValue right);
@Override
abstract public EvaluatableType<BooleanType> equalop(EvaluatableValue right);
@Override
abstract public BooleanType max(BooleanType right);
@Override
abstract public BooleanType min(BooleanType right);
@Override
public final Type getType() {
return NamedType.BOOL;
}
@Override
public final EvaluatableType<BooleanType> join(EvaluatableValue right) {
@SuppressWarnings("unchecked")
Joinable<BooleanType> rv = ((Joinable<BooleanType>) right);
return rv.join2(this);
}
@Override
public final EvaluatableType<BooleanType> join2(BooleanType left) {
return min(left).newInterval(max(left));
}
@Override
public final EvaluatableType<BooleanType> join2(IntervalType<BooleanType> left) {
return left;
}
@Override
public final EvaluatableType<BooleanType> newInterval(BooleanType max) {
if (this.equals(max)) return this;
return BooleanInterval.ARBITRARY;
}
}
| 1,727 | 24.411765 | 124 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/RationalTypeInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public interface RationalTypeInterface {
public EvaluatableType<RationalType> divide(EvaluatableValue right);
public EvaluatableType<RationalType> divide2(RationalType left);
public EvaluatableType<RationalType> divide2(RationalIntervalType left);
}
| 499 | 26.777778 | 73 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/EvaluatableType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
abstract public class EvaluatableType<T extends InstanceType<T>> extends EvaluatableValueHierarchy {
public abstract EvaluatableType<BooleanType> equalop(EvaluatableValue right);
public abstract EvaluatableType<T> join(EvaluatableValue right);
public abstract T getHigh();
public abstract T getLow();
abstract public EvaluatableType<IntegerType> integerType();
abstract public EvaluatableType<RationalType> rationalType();
abstract public EvaluatableType<BooleanType> booleanType();
@Override
public final EvaluatableValue cast(Type type) {
if (type == NamedType.BOOL) return booleanType();
if (type == NamedType.INT) return integerType();
if (type == NamedType.REAL) return rationalType();
throw new IllegalArgumentException();
}
}
| 1,066 | 27.837838 | 100 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/EvaluatableValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.BinaryOp;
import jkind.lustre.Type;
import jkind.lustre.UnaryOp;
import jkind.lustre.values.Value;
public abstract class EvaluatableValue extends Value {
@Override
public EvaluatableValue applyBinaryOp(BinaryOp op, Value arg) {
EvaluatableValue right = (EvaluatableValue) arg;
switch (op) {
case PLUS:
return plus(right);
case MINUS:
return minus(right);
case MULTIPLY:
return multiply(right);
case DIVIDE:
return divide(right);
case INT_DIVIDE:
return int_divide(right);
case MODULUS:
return modulus(right);
case EQUAL:
return equalop(right);
case NOTEQUAL:
return notequalop(right);
case GREATER:
return greater(right);
case LESS:
return less(right);
case GREATEREQUAL:
return greaterequal(right);
case LESSEQUAL:
return lessequal(right);
case OR:
return or(right);
case AND:
return and(right);
case XOR:
return xor(right);
case IMPLIES:
return implies(right);
case ARROW:
return arrow(right);
}
throw new IllegalArgumentException();
}
@Override
public EvaluatableValue applyUnaryOp(UnaryOp op) {
switch (op) {
case NEGATIVE: {
return negate();
}
case NOT: {
return not();
}
case PRE: {
return pre();
}
}
throw new IllegalArgumentException();
}
public EvaluatableValue arrow(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue pre() {
throw new IllegalArgumentException();
}
// N -> Q
public EvaluatableValue divide(EvaluatableValue right) {
throw new IllegalArgumentException();
}
// N -> N
public EvaluatableValue multiply(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue plus(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue negate() {
throw new IllegalArgumentException();
}
public EvaluatableValue minus(EvaluatableValue right) {
return plus(right.negate());
}
// V -> B
abstract public EvaluatableValue equalop(EvaluatableValue right);
public EvaluatableValue notequalop(EvaluatableValue right) {
return equalop(right).not();
}
// N -> B
public EvaluatableValue less(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue greater(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue greaterequal(EvaluatableValue right) {
return less(right).not();
}
public EvaluatableValue lessequal(EvaluatableValue right) {
return greater(right).not();
}
// Z -> Z
public EvaluatableValue int_divide(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue modulus(EvaluatableValue right) {
throw new IllegalArgumentException();
}
// B -> B
public EvaluatableValue and(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue or(EvaluatableValue right) {
throw new IllegalArgumentException();
}
public EvaluatableValue not() {
throw new IllegalArgumentException();
}
public EvaluatableValue xor(EvaluatableValue right) {
return equalop(right).not();
}
public EvaluatableValue implies(EvaluatableValue right) {
return not().or(right);
}
// Helper Functions
abstract public EvaluatableValue cast(Type type);
abstract public Type getType();
@Override
abstract public boolean equals(Object x);
@Override
abstract public int hashCode();
@Override
abstract public String toString();
}
| 3,842 | 22.290909 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/IntervalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public abstract class IntervalType<T extends InstanceType<T>> extends EvaluatableType<T> implements Joinable<T> {
@Override
abstract public T getLow();
@Override
abstract public T getHigh();
abstract public EvaluatableType<T> newInterval(InstanceType<T> min, InstanceType<T> max);
@Override
public final EvaluatableType<T> join(EvaluatableValue right) {
@SuppressWarnings("unchecked")
Joinable<T> rv = ((Joinable<T>) right);
return rv.join2(this);
}
@Override
public final EvaluatableType<T> join2(IntervalType<T> left) {
return newInterval(getLow().min(left.getLow()),getHigh().max(left.getHigh()));
}
@Override
public final EvaluatableType<T> join2(T left) {
return newInterval(getLow().min(left),getHigh().max(left));
}
// Perhaps these should be only in the instance hierarchy?
@Override
public final EvaluatableType<IntegerType> integerType() {
return ((InstanceType<IntegerType>) getLow().integerType()).newInterval((IntegerType) getHigh().integerType());
}
@Override
public final EvaluatableType<BooleanType> booleanType() {
return ((InstanceType<BooleanType>) getLow().booleanType()).newInterval((BooleanType) getHigh().booleanType());
}
@Override
public final EvaluatableType<RationalType> rationalType() {
return ((InstanceType<RationalType>) getLow().rationalType()).newInterval((RationalType) getHigh().rationalType());
}
@Override
public final int signum() {
int lowsig = getLow().signum();
int highsig = getHigh().signum();
if ((lowsig > 0) && (highsig > 0)) return +1;
if ((lowsig < 0) && (highsig < 0)) return -1;
return 0;
}
}
| 1,854 | 28.444444 | 117 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/RationalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
public abstract class RationalType extends NumericType<RationalType> implements RationalTypeInterface {
@Override
public final EvaluatableType<RationalType> divide(EvaluatableValue right) {
RationalTypeInterface rv = (RationalTypeInterface) right;
return rv.divide2(this);
}
@Override
public final EvaluatableType<RationalType> divide2(RationalType left) {
return this.divide(left);
}
@Override
public final EvaluatableType<RationalType> divide2(RationalIntervalType left) {
RationalType min = left.getLow();
RationalType max = left.getHigh();
RationalType q1 = min.divide(this);
RationalType q2 = max.divide(this);
return q1.min(q2).newInterval(q1.max(q2));
}
abstract public RationalType divide(RationalType right);
@Override
public final Type getType() {
return NamedType.REAL;
}
}
| 1,126 | 24.613636 | 103 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/IntegerIntervalType.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
abstract public class IntegerIntervalType extends NumericIntervalType<IntegerType> implements IntegerTypeInterface {
@Override
public EvaluatableType<IntegerType> int_divide(EvaluatableValue right) {
IntegerTypeInterface rv = ((IntegerTypeInterface) right);
return rv.int_divide2(this);
}
@Override
public EvaluatableType<IntegerType> int_divide2(IntegerType left) {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> int_divide2(IntegerIntervalType left) {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> modulus(EvaluatableValue right) {
IntegerTypeInterface rv = ((IntegerTypeInterface) right);
return rv.modulus2(this);
}
@Override
public EvaluatableType<IntegerType> modulus2(IntegerType left) {
throw new IllegalArgumentException();
}
@Override
public EvaluatableType<IntegerType> modulus2(IntegerIntervalType left) {
throw new IllegalArgumentException();
}
@Override
public final Type getType() {
return NamedType.BOOL;
}
}
| 1,356 | 24.12963 | 116 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/hierarchy/BooleanTypeInterface.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.hierarchy;
public interface BooleanTypeInterface {
public boolean isAlwaysTrue();
public boolean isAlwaysFalse();
}
| 353 | 19.823529 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/poly/RationalPoly.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.poly;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import fuzzm.poly.AbstractPoly;
import fuzzm.poly.PolyBase;
import fuzzm.poly.PolyBool;
import fuzzm.poly.VariableID;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.CastExpr;
import jkind.lustre.Expr;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
import jkind.util.BigFraction;
public class RationalPoly extends PolyEvaluatableValue {
AbstractPoly poly;
public RationalPoly(VariableID vid) {
Map<VariableID,BigFraction> newCoefs = new HashMap<VariableID,BigFraction>();
newCoefs.put(vid, BigFraction.ONE);
poly = new PolyBase(newCoefs);
}
public RationalPoly(AbstractPoly poly) {
this.poly = poly;
}
@Override
public EvaluatableValue cast(Type type) {
if (type == NamedType.REAL) return this;
if (type == NamedType.INT) {
AbstractPoly RWpoly = this.poly.rewrite(GlobalState.getRewrites());
BigInteger D = BigInteger.ONE;
if (RWpoly.isConstant()) {
BigFraction Nf = RWpoly.getConstant();
return new IntegerPoly(new PolyBase(new BigFraction(Nf.floor())));
}
if (RWpoly.divisible(D)) {
return new IntegerPoly(this.poly.div(D));
}
BigFraction cexF = RWpoly.evaluateCEX();
BigFraction kcex = new BigFraction(cexF.floor());
BigFraction mcex = cexF.subtract(kcex);
VariableID least = RWpoly.trailingVariable();
VariableID m = least.afterAlloc("m",NamedType.REAL,mcex);
VariableID k = m.afterAlloc("k",NamedType.INT,kcex);
AbstractPoly qpoly = PolyBase.qpoly(D,k,m);
AbstractPoly diff = RWpoly.subtract(qpoly);
VariableID max = diff.leadingVariable();
AbstractPoly rhs = diff.solveFor(max);
PolyBool eq = PolyBool.equal0(diff);
GlobalState.addRewrite(max,rhs);
GlobalState.addConstraint(eq);
AbstractPoly mp = new PolyBase(m);
PolyBool gt0 = PolyBool.greater0(mp.negate()).not();
PolyBool ltD = PolyBool.less0(mp.subtract(new BigFraction(D.abs())));
GlobalState.addConstraint(gt0.and(ltD));
Expr INT = GlobalState.getExpr();
int step = GlobalState.getStep();
GlobalState.addReMap(k, step, INT);
Expr RAT = ((CastExpr) INT).expr;
Expr REM = new BinaryExpr(RAT,BinaryOp.MINUS,new CastExpr(NamedType.REAL,INT));
GlobalState.addReMap(m, step, REM);
return new IntegerPoly(new PolyBase(k));
}
throw new IllegalArgumentException();
}
@Override
public EvaluatableValue multiply(EvaluatableValue arg) {
RationalPoly right = (RationalPoly) arg;
RationalPoly constant;
if (this.poly.isConstant()) {
constant = this;
} else {
constant = right;
right = this;
}
if (! constant.poly.isConstant()) throw new IllegalArgumentException();
return new RationalPoly(right.poly.multiply(constant.poly.getConstant()));
}
@Override
public EvaluatableValue negate() {
AbstractPoly res = this.poly.negate();
return new RationalPoly(res);
}
@Override
public String toString() {
return poly.toString();
}
@Override
public EvaluatableValue plus(EvaluatableValue arg) {
RationalPoly right = (RationalPoly) arg;
return new RationalPoly(this.poly.add(right.poly));
}
@Override
public EvaluatableValue less(EvaluatableValue arg) {
RationalPoly right = (RationalPoly) arg;
return new BooleanPoly(PolyBool.less0(this.poly.subtract(right.poly)));
}
@Override
public EvaluatableValue greater(EvaluatableValue arg) {
RationalPoly right = (RationalPoly) arg;
return new BooleanPoly(PolyBool.greater0(this.poly.subtract(right.poly)));
}
@Override
public EvaluatableValue equalop(EvaluatableValue arg) {
RationalPoly right = (RationalPoly) arg;
return new BooleanPoly(PolyBool.equal0(this.poly.subtract(right.poly)));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((poly == null) ? 0 : poly.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof RationalPoly))
return false;
RationalPoly other = (RationalPoly) obj;
return poly.equals(other.poly);
}
@Override
public Type getType() {
return NamedType.REAL;
}
@Override
public BigFraction cex() {
return poly.evaluateCEX();
}
@Override
public String toACL2() {
return poly.toACL2();
}
}
| 4,640 | 26.625 | 85 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/poly/GlobalState.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.poly;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import fuzzm.lustre.generalize.ReMapExpr;
import fuzzm.poly.AbstractPoly;
import fuzzm.poly.PolyBool;
import fuzzm.poly.VariableID;
import fuzzm.util.Debug;
import fuzzm.util.ID;
import jkind.lustre.Expr;
public class GlobalState {
private static Map<VariableID,AbstractPoly> rewrite = new HashMap<>();
private static PolyBool invariants = PolyBool.TRUE;
private static Random oracle = new Random();
public static ReMapExpr remap = new ReMapExpr();
public static Random oracle() {
return oracle;
}
private static long next_sequence = 0;
private static final Object seq_lock = new Object();
public static long next_sequence_id () {
synchronized (seq_lock) {
return next_sequence++;
}
}
public static void addReMap(VariableID key, int step, Expr value) {
assert(Thread.holdsLock(GlobalState.class));
remap.add(key,step,value);
}
// DAG : Oh, boy. Not as clean as I had hoped.
static Expr expr = null;
static int step = 0;
public static void pushExpr(int time, Expr value) {
assert(Thread.holdsLock(GlobalState.class));
assert(expr == null);
expr = value;
step = time;
}
public static Expr getExpr() {
return expr;
}
public static int getStep() {
return step;
}
public static Expr popExpr() {
assert(Thread.holdsLock(GlobalState.class));
Expr res = expr;
expr = null;
step = 0;
return res;
}
public static ReMapExpr getReMap() {
assert(Thread.holdsLock(GlobalState.class));
return remap;
}
public static void addRewrite(VariableID v, AbstractPoly p) {
assert(Thread.holdsLock(GlobalState.class));
rewrite.put(v, p);
}
public static Map<VariableID,AbstractPoly> getRewrites() {
assert(Thread.holdsLock(GlobalState.class));
return rewrite;
}
public static void addConstraint(PolyBool c) {
assert(Thread.holdsLock(GlobalState.class));
if (Debug.isEnabled()) System.out.println(ID.location() + "Adding Constraint : " + c);
assert(c.cex);
invariants = invariants.and(c);
if (Debug.isEnabled()) System.out.println(ID.location() + "Updated Constraint : " + invariants);
}
public static PolyBool getInvariants() {
assert(Thread.holdsLock(GlobalState.class));
return invariants;
}
public static void clearGlobalState() {
assert(Thread.holdsLock(GlobalState.class));
VariableID.clearGlobalState();
rewrite = new HashMap<>();
invariants = PolyBool.TRUE;
remap = new ReMapExpr();
}
}
| 2,871 | 25.841121 | 98 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/poly/PolyEvaluatableValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.poly;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.util.BigFraction;
public abstract class PolyEvaluatableValue extends EvaluatableValue implements Comparable<PolyEvaluatableValue> {
public abstract BigFraction cex();
@Override
public int compareTo(PolyEvaluatableValue o) {
return cex().compareTo(o.cex());
}
public abstract String toACL2();
}
| 605 | 22.307692 | 113 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/poly/IntegerPoly.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.poly;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import fuzzm.poly.AbstractPoly;
import fuzzm.poly.PolyBase;
import fuzzm.poly.PolyBool;
import fuzzm.poly.VariableID;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.Expr;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
import jkind.util.BigFraction;
import jkind.util.Util;
public class IntegerPoly extends PolyEvaluatableValue {
AbstractPoly poly;
public IntegerPoly(VariableID vid) {
Map<VariableID,BigFraction> newCoefs = new HashMap<VariableID,BigFraction>();
newCoefs.put(vid, BigFraction.ONE);
poly = new PolyBase(newCoefs);
}
public IntegerPoly(AbstractPoly poly) {
this.poly = poly;
}
@Override
public EvaluatableValue cast(Type type) {
if (type == NamedType.INT) return this;
if (type == NamedType.REAL) {
return new RationalPoly(poly);
}
throw new IllegalArgumentException();
}
@Override
public EvaluatableValue int_divide(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
if (! right.poly.isConstant()) throw new IllegalArgumentException();
BigFraction Df = right.poly.getConstant();
assert(Df.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger D = Df.getNumerator();
assert(D.signum() != 0);
AbstractPoly RWpoly = this.poly.rewrite(GlobalState.getRewrites());
if (RWpoly.isConstant()) {
BigFraction Nf = RWpoly.getConstant();
assert(Nf.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger N = Nf.getNumerator();
return new IntegerPoly(new PolyBase(new BigFraction(Util.smtDivide(N,D))));
}
if (RWpoly.divisible(D)) {
return new IntegerPoly(this.poly.div(D));
}
BigFraction cexF = RWpoly.evaluateCEX();
assert(cexF.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger cex = cexF.getNumerator();
BigInteger kcex = Util.smtDivide(cex,D);
BigInteger mcex = cex.mod(D);
VariableID least = RWpoly.trailingVariable();
VariableID m = least.afterAlloc("m",NamedType.INT,new BigFraction(mcex));
VariableID k = m.afterAlloc("k",NamedType.INT,new BigFraction(kcex));
AbstractPoly ipoly = PolyBase.qpoly(D,k,m);
AbstractPoly diff = RWpoly.subtract(ipoly);
VariableID max = diff.leadingVariable();
AbstractPoly rhs = diff.solveFor(max);
PolyBool eq = PolyBool.equal0(diff);
GlobalState.addRewrite(max,rhs);
GlobalState.addConstraint(eq);
AbstractPoly mp = new PolyBase(m);
PolyBool gt0 = PolyBool.greater0(mp.negate()).not();
PolyBool ltD = PolyBool.less0(mp.subtract(new BigFraction(D.abs())));
GlobalState.addConstraint(gt0.and(ltD));
Expr DIV = GlobalState.getExpr();
int step = GlobalState.getStep();
GlobalState.addReMap(k, step,DIV);
Expr DEN = ((BinaryExpr) DIV).right;
Expr NUM = ((BinaryExpr) DIV).left;
Expr MOD = new BinaryExpr(NUM,BinaryOp.MODULUS,DEN);
GlobalState.addReMap(m,step,MOD);
return new IntegerPoly(new PolyBase(k));
}
@Override
public EvaluatableValue modulus(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
if (! right.poly.isConstant()) throw new IllegalArgumentException();
BigFraction Df = right.poly.getConstant();
assert(Df.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger D = Df.getNumerator();
assert(D.signum() != 0);
AbstractPoly RWpoly = this.poly.rewrite(GlobalState.getRewrites());
if (RWpoly.isConstant()) {
BigFraction Nf = RWpoly.getConstant();
assert(Nf.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger N = Nf.getNumerator();
return new IntegerPoly(new PolyBase(new BigFraction(N.mod(D))));
}
if (RWpoly.divisible(D)) {
return new IntegerPoly(new PolyBase(new BigFraction(RWpoly.getConstant().getNumerator().mod(D))));
}
BigFraction cexF = RWpoly.evaluateCEX();
assert(cexF.getDenominator().compareTo(BigInteger.ONE) == 0);
BigInteger cex = cexF.getNumerator();
BigInteger kcex = Util.smtDivide(cex,D);
BigInteger mcex = cex.mod(D);
VariableID least = RWpoly.trailingVariable();
VariableID m = least.afterAlloc("m",NamedType.INT,new BigFraction(mcex));
VariableID k = m.afterAlloc("k",NamedType.INT,new BigFraction(kcex));
AbstractPoly ipoly = PolyBase.qpoly(D,k,m);
AbstractPoly diff = RWpoly.subtract(ipoly);
VariableID max = diff.leadingVariable();
AbstractPoly rhs = diff.solveFor(max);
PolyBool eq = PolyBool.equal0(diff);
GlobalState.addRewrite(max,rhs);
GlobalState.addConstraint(eq);
AbstractPoly mp = new PolyBase(m);
PolyBool gt0 = PolyBool.greater0(mp.negate()).not();
PolyBool ltD = PolyBool.less0(mp.subtract(new BigFraction(D.abs())));
GlobalState.addConstraint(gt0.and(ltD));
Expr MOD = GlobalState.getExpr();
int step = GlobalState.getStep();
GlobalState.addReMap(m,step, MOD);
Expr DEN = ((BinaryExpr) MOD).right;
Expr NUM = ((BinaryExpr) MOD).left;
Expr DIV = new BinaryExpr(NUM,BinaryOp.INT_DIVIDE,DEN);
GlobalState.addReMap(k,step,DIV);
return new IntegerPoly(mp);
}
@Override
public EvaluatableValue multiply(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
IntegerPoly constant;
if (this.poly.isConstant()) {
constant = this;
} else {
constant = right;
right = this;
}
if (! constant.poly.isConstant()) throw new IllegalArgumentException();
return new IntegerPoly(right.poly.multiply(constant.poly.getConstant()));
}
@Override
public EvaluatableValue negate() {
AbstractPoly res = this.poly.negate();
PolyEvaluatableValue value = new IntegerPoly(res);
//System.out.println(ID.location() + "(- " + this + ") evaluated to " + value + " [ " + value.cex() + "]");
return value;
}
@Override
public String toString() {
return poly.toString();
}
@Override
public EvaluatableValue plus(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
PolyEvaluatableValue value = new IntegerPoly(this.poly.add(right.poly));
//System.out.println(ID.location() + "(" + this + " + " + arg + ") evaluated to " + value + " [ " + value.cex() + "]");
return value;
}
@Override
public EvaluatableValue less(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
return new BooleanPoly(PolyBool.less0(this.poly.subtract(right.poly)));
}
@Override
public EvaluatableValue greater(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
return new BooleanPoly(PolyBool.greater0(this.poly.subtract(right.poly)));
}
@Override
public EvaluatableValue equalop(EvaluatableValue arg) {
IntegerPoly right = (IntegerPoly) arg;
return new BooleanPoly(PolyBool.equal0(this.poly.subtract(right.poly)));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((poly == null) ? 0 : poly.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (! (obj instanceof IntegerPoly))
return false;
IntegerPoly other = (IntegerPoly) obj;
return poly.equals(other.poly);
}
@Override
public Type getType() {
return NamedType.INT;
}
@Override
public BigFraction cex() {
return poly.evaluateCEX();
}
@Override
public String toACL2() {
return poly.toACL2();
}
}
| 7,550 | 31.269231 | 121 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/poly/BooleanPoly.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.poly;
import fuzzm.poly.PolyBool;
import fuzzm.poly.VariableBoolean;
import fuzzm.poly.VariableID;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
import jkind.lustre.values.Value;
import jkind.util.BigFraction;
public class BooleanPoly extends PolyEvaluatableValue {
public final static BooleanPoly TRUE = new BooleanPoly(PolyBool.TRUE);
public final static BooleanPoly FALSE = new BooleanPoly(PolyBool.FALSE);
public PolyBool value;
public BooleanPoly(PolyBool value) {
this.value = value;
}
public BooleanPoly(VariableID value) {
VariableBoolean var = new VariableBoolean(value);
this.value = PolyBool.boolVar(var);
}
// not()
@Override
public EvaluatableValue not() {
return new BooleanPoly(value.not());
}
@Override
public EvaluatableValue and(EvaluatableValue arg) {
BooleanPoly right = (BooleanPoly) arg;
return new BooleanPoly(value.and(right.value));
}
@Override
public EvaluatableValue or(EvaluatableValue arg) {
BooleanPoly right = (BooleanPoly) arg;
return new BooleanPoly(value.or(right.value));
}
@Override
public EvaluatableValue equalop(EvaluatableValue arg) {
BooleanPoly right = (BooleanPoly) arg;
return new BooleanPoly(value.iff(right.value));
}
public boolean isAlwaysTrue() {
return value.isAlwaysTrue();
}
public boolean isAlwaysFalse() {
return value.isAlwaysFalse();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!( obj instanceof BooleanPoly))
return false;
BooleanPoly other = (BooleanPoly) obj;
return value.equals(other.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + value.hashCode();
return result;
}
@Override
public String toString() {
return value.toString();
}
@Override
public EvaluatableValue cast(Type type) {
if (type == NamedType.BOOL) return this;
throw new IllegalArgumentException();
}
@Override
public Type getType() {
return NamedType.BOOL;
}
public Value ite(EvaluatableValue thenValue, EvaluatableValue elseValue) {
BooleanPoly thenArg = (BooleanPoly) thenValue;
BooleanPoly elseArg = (BooleanPoly) elseValue;
PolyBool p1 = value.and(thenArg.value);
PolyBool p2 = value.not().and(elseArg.value);
return new BooleanPoly(p1.or(p2));
}
@Override
public BigFraction cex() {
return (value.cex) ? BigFraction.ONE : BigFraction.ZERO;
}
@Override
public String toACL2() {
return value.toACL2();
}
}
| 2,810 | 21.488 | 75 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/bound/ComputedValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.bound;
import java.util.SortedSet;
import fuzzm.lustre.evaluation.IndexedEvaluator;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.Expr;
import jkind.lustre.Type;
public class ComputedValue extends InputValue {
public ComputedValue(IndexedEvaluator evaluator, Type type, SortedSet<Integer> defSet, SortedSet<Integer> nextSet) {
super(evaluator,null,type,defSet,nextSet);
}
@Override
public boolean setValue(EvaluatableValue value) {
assert(false);
return false;
}
@Override
public int stepValue(Expr expr, ContainsEvaluatableValue[] preState, ContainsEvaluatableValue[] currState) {
evaluator.updatePreState(preState);
evaluator.updateCurrState(currState);
EvaluatableValue newValue = (EvaluatableValue) expr.accept(evaluator);
EvaluatableValue oldValue = value;
//System.out.println(ID.location() + oldValue + " |-> " + newValue);
value = newValue;
return (! newValue.equals(oldValue)) ? 1 : 0;
}
@Override
public int initValue(Expr expr, ContainsEvaluatableValue[] preState) {
//System.out.println(ID.location() + "initValue() Evaluating : " + expr);
evaluator.updateCurrState(preState);
evaluator.updatePreState(preState);
//System.out.println(ID.location() + "initValue(" + expr + ")");
EvaluatableValue newValue = (EvaluatableValue) expr.accept(evaluator.initExtendedEvaluator);
EvaluatableValue oldValue = value;
//System.out.println(ID.location() + oldValue + " |-> " + newValue);
value = newValue;
return (! newValue.equals(oldValue)) ? 1 : 0;
}
}
| 1,766 | 30.553571 | 117 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/bound/InputValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.bound;
import java.util.SortedSet;
import fuzzm.lustre.evaluation.IndexedEvaluator;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.Expr;
import jkind.lustre.Type;
public class InputValue extends BoundValue {
protected EvaluatableValue value;
public InputValue(IndexedEvaluator evaluator, EvaluatableValue value, Type type, SortedSet<Integer> defSet, SortedSet<Integer> nextSet) {
super(evaluator,type,defSet,nextSet);
this.value = value;
}
@Override
public EvaluatableValue getValue() {
assert(value != null);
return value;
}
@Override
public int stepValue(Expr expr, ContainsEvaluatableValue[] preState, ContainsEvaluatableValue[] currState) {
// Always changes
return 1;
}
@Override
public int initValue(Expr expr, ContainsEvaluatableValue[] binding) {
// Always changes
return 1;
}
@Override
public boolean setValue(EvaluatableValue value) {
assert(value != null);
this.value = value;
return true;
}
}
| 1,204 | 21.735849 | 138 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/bound/ConstrainedValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.bound;
import java.util.TreeSet;
import fuzzm.lustre.evaluation.IndexedEvaluator;
import fuzzm.value.hierarchy.BooleanTypeInterface;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.Expr;
import jkind.lustre.NamedType;
public class ConstrainedValue extends BoundValue {
private boolean polarity;
EvaluatableValue value;
public ConstrainedValue(boolean polarity, IndexedEvaluator evaluator) {
super(evaluator,NamedType.BOOL,new TreeSet<Integer>(),new TreeSet<Integer>());
this.polarity = polarity;
value = (polarity ? evaluator.trueValue() : evaluator.falseValue());
}
@Override
public EvaluatableValue getValue() {
return value;
}
boolean checkValue(EvaluatableValue value) {
boolean res = polarity ? ((BooleanTypeInterface) value).isAlwaysTrue() : ((BooleanTypeInterface) value).isAlwaysFalse();
//System.out.println(ID.location() + "Asserting (" + value + " == " + polarity + ") = " + (res? "OK" : "Failed"));
return res;
// return polarity ? value.isTrue() : value.isFalse();
}
@Override
public int stepValue(Expr expr, ContainsEvaluatableValue[] preState, ContainsEvaluatableValue[] currState) {
evaluator.updatePreState(preState);
evaluator.updateCurrState(currState);
EvaluatableValue newValue = (EvaluatableValue) expr.accept(evaluator);
value = (polarity ? newValue : newValue.not());
return -1;
}
@Override
public int initValue(Expr expr, ContainsEvaluatableValue[] preState) {
evaluator.updatePreState(preState);
EvaluatableValue newValue = (EvaluatableValue) expr.accept(evaluator.initExtendedEvaluator);
value = (polarity ? newValue : newValue.not());
return -1;
}
@Override
public boolean setValue(EvaluatableValue value) {
assert(checkValue(value));
return false;
}
}
| 2,001 | 29.333333 | 122 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/bound/ContainsEvaluatableValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.bound;
import fuzzm.value.hierarchy.EvaluatableValue;
public interface ContainsEvaluatableValue {
public EvaluatableValue getValue();
}
| 370 | 22.1875 | 66 | java |
FuzzM | FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/value/bound/BoundValue.java | /*
* Copyright (C) 2017, Rockwell Collins
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the 3-clause BSD license. See the LICENSE file for details.
*
*/
package fuzzm.value.bound;
import java.util.SortedSet;
import java.util.TreeSet;
import fuzzm.lustre.evaluation.IndexedEvaluator;
import fuzzm.value.hierarchy.EvaluatableValue;
import jkind.lustre.Expr;
import jkind.lustre.Type;
public abstract class BoundValue implements ContainsEvaluatableValue {
// Before use the visitor must be bound;
protected IndexedEvaluator evaluator;
public final SortedSet<Integer> defSet;
public final SortedSet<Integer> nextSet;
public final Type type;
public BoundValue(IndexedEvaluator evaluator, Type type, SortedSet<Integer> defSet, SortedSet<Integer> nextSet) {
this.evaluator = evaluator;
this.type = type;
this.defSet = (defSet == null) ? new TreeSet<Integer>() : defSet;
this.nextSet = (nextSet == null) ? new TreeSet<Integer>() : nextSet;
}
// -1 : constraint (change?)
// 0 : no change
// +1 : change
abstract public int stepValue(Expr expr, ContainsEvaluatableValue preState[], ContainsEvaluatableValue currState[]);
abstract public int initValue(Expr expr, ContainsEvaluatableValue binding[]);
abstract public EvaluatableValue getValue();
abstract public boolean setValue(EvaluatableValue value);
@Override
public String toString() {
return getValue().toString();
}
}
| 1,459 | 29.416667 | 117 | java |
formal-verification | formal-verification-master/Deterrence.java | //import java.util.Random;
/*@ predicate states_initialised{L}(Deterrence [] states) =
@ states.length == Deterrence.numStates && !\fresh(states);
@*/
/*@ predicate state_valid{L}(Deterrence [] states, Deterrence state, int index) =
@ !\fresh(state) &&
states[state.index] == state &&
state.index == index &&
!\fresh(state.numIgnores) && state.numIgnores.length == Deterrence.ATTACK_TYPES && (\forall int j; j >= 0 && j < Deterrence.ATTACK_TYPES ==> state.numIgnores[j] >= 1) &&
!\fresh(state.numRetaliates) && state.numRetaliates.length == Deterrence.ATTACK_TYPES && (\forall int j; j >= 0 && j < Deterrence.ATTACK_TYPES ==> state.numRetaliates[j] >= 1) &&
!\fresh(state.retaliationTable) && state.retaliationTable.length == Deterrence.ATTACK_TYPES && (\forall int j; j >= 0 && j < Deterrence.ATTACK_TYPES ==> 0.0 <= state.retaliationTable[j] < 1.0);
@*/
/*@ predicate states_valid_up_to{L}(Deterrence [] states, integer k) =
@ (\forall int i; i >= 0 && i < k ==> states[i].index == i) &&
(\forall int i; i >= 0 && i < k ==> state_valid(states, states[i], i));
@*/
/*@ predicate states_valid{L}(Deterrence [] states) =
@ states.length == Deterrence.numStates && !\fresh(states) &&
@ (\forall int i, int j; i >= 0 && i < Deterrence.numStates && j >= 0 && j < Deterrence.numStates && i != j ==> states[i] != states[j]) &&
@ (\forall int i; i >= 0 && i < Deterrence.numStates ==> states[i].index == i) &&
(\forall int i; i >= 0 && i < Deterrence.numStates ==> state_valid(states, states[i], i));
@*/
/*@ logic integer attackStrength_logic(integer intensity) = intensity + 1;
@*/
/*@ logic real expectedValue_logic(integer intensity, integer numIgnores, integer numRetaliates, real ATTRIBUTION_PROBABILITY, real RETALIATION_EFFECT) =
attackStrength_logic(intensity)
* (numIgnores + numRetaliates * ((1.0 - ATTRIBUTION_PROBABILITY) - RETALIATION_EFFECT * ATTRIBUTION_PROBABILITY))
/ (numIgnores + numRetaliates);
@*/
//@+ CheckArithOverflow=no
public class Deterrence {
//private static final Random r = new Random(54321);
/*@ assigns \nothing;
ensures \result >= 0.0 && \result < 1.0;
@*/
private static double nextDouble() {
return 1.0/10.0;
//return r.nextDouble();
}
/*@ requires a > 0;
assigns \nothing;
@ ensures \result >= 0 && \result < a;
@*/
private static int nextInt(int a) {
return a - 1;
//return r.nextInt(a);
}
private static final int numStates = 100;
private static final int turnLength = 100;
private static final int numTurns = 10000;
private static final double mutateProbability = 0.05;
private static Deterrence[] states;
/*@ assigns \nothing;
ensures \result == val || \result == mutated;
@*/
private static double mutate(double val, double mutated) {
if (nextDouble() < mutateProbability)
return mutated;
else
return val;
}
/*@ assigns \nothing;
ensures \result == a || \result == b;
@*/
private static double choice(double a, double b) {
if (nextDouble() < 0.5)
return a;
else
return b;
}
/*@ requires states_valid(states);
assigns \nothing;
ensures (\forall int i; i >= 0 && i < numStates ==> states[i].value >= \result.value) &&
@ (\exists int i; i >= 0 && i < numStates && states[i] == \result);
@*/
private static Deterrence getWorst() {
Deterrence worst = states[0];
/*@
loop_invariant (\forall int j; j >= 0 && j < h ==> states[j].value >= worst.value) &&
(\exists int k; k >= 0 && k < h && states[k] == worst) &&
h >= 0 && h <= numStates;
loop_variant numStates - h;
@*/
for (int h = 1; h < numStates; h++) {
if (states[h].value < worst.value) {
worst = states[h];
}
}
return worst;
}
/*@ requires states_valid(states);
assigns \nothing;
ensures (\forall int i; i >= 0 && i < numStates ==> states[i].value <= \result.value) &&
(\exists int i; i >= 0 && i < numStates && states[i] == \result);
@*/
private static Deterrence getBest() {
Deterrence best = states[0];
/*@
loop_invariant (\forall int j; j >= 0 && j < h ==> states[j].value <= best.value) &&
(\exists int k; k >= 0 && k < h && states[k] == best) &&
h >= 0 && h <= numStates;
loop_variant numStates - h;
@*/
for (int h = 1; h < numStates; h++) {
if (states[h].value > best.value) {
best = states[h];
}
}
return best;
}
private static final double INITIAL_VALUE = 0.0;
private static final int ATTACK_TYPES = 10;
private static final double DEFENDER_COST = 0.5;
private static final double RETALIATION_COST = 0.75;
private static final double RETALIATION_EFFECT = 0.5;
//@ invariant irrational_valid: 0.0 <= IRRATIONAL_PROBABILITY <= 1.0;
//@ invariant attribution_valid: 0.0 <= ATTRIBUTION_PROBABILITY <= 1.0;
private static double IRRATIONAL_PROBABILITY;
private static double ATTRIBUTION_PROBABILITY;
/*@ requires 0 <= intensity < ATTACK_TYPES;
assigns \nothing;
@ ensures \result == attackStrength_logic(intensity);
@*/
private static int attackStrength(int intensity) {
return intensity + 1;
}
//@ invariant me_valid: state_valid(states, this, this.index);
private int index;
private double value;
private int [] numIgnores;
private int [] numRetaliates;
private double [] retaliationTable;
/*@ requires states_initialised(states) && 0 <= array_index < numStates &&
0.0 <= IRRATIONAL_PROBABILITY <= 1.0 &&
0.0 <= ATTRIBUTION_PROBABILITY <= 1.0 &&
states_valid_up_to(states, array_index);
assigns this.value, this.numIgnores, this.numRetaliates, this.retaliationTable, this.index, states[array_index];
@ ensures this.index == array_index && this.value == INITIAL_VALUE && states_initialised(states) &&
states_valid_up_to(states, array_index + 1);
@*/
private Deterrence(int array_index) {
//@ assert (\forall int i; i >= 0 && i < array_index ==> states[i] != this);
//@ assert states_valid_up_to(states, array_index);
value = INITIAL_VALUE;
//@ assert states_valid_up_to(states, array_index);
numIgnores = new int[ATTACK_TYPES];
//@ assert states_valid_up_to(states, array_index);
numRetaliates = new int[ATTACK_TYPES];
//@ assert states_valid_up_to(states, array_index);
retaliationTable = new double[ATTACK_TYPES];
//@ assert states_valid_up_to(states, array_index);
//@ assert this.value == INITIAL_VALUE;
/*@ loop_invariant (\forall int j; j >= 0 && j < i ==> numIgnores[j] >= 1 && numRetaliates[j] >= 1 && 0.0 <= retaliationTable[j] < 1.0) &&
i >= 0 && i <= ATTACK_TYPES && states_valid_up_to(states, array_index) && states_initialised(states);
loop_variant ATTACK_TYPES - i;
@*/
for (int i = 0; i < ATTACK_TYPES; i++) {
//@ assert states_valid_up_to(states, array_index);
retaliationTable[i] = nextDouble();
//@ assert states_valid_up_to(states, array_index);
numIgnores[i] = 1;
//@ assert states_valid_up_to(states, array_index);
numRetaliates[i] = 1;
//@ assert states_valid_up_to(states, array_index);
}
//@ assert states_valid_up_to(states, array_index);
//@ assert this.value == INITIAL_VALUE && states_initialised(states) && states_valid_up_to(states, array_index);
this.index = array_index;
states[this.index] = this;
//@ assert this.index == array_index && this.value == INITIAL_VALUE && states_initialised(states) && states_valid_up_to(states, array_index);
//@ assert state_valid(states, this, this.index);
//@ assert states_valid_up_to(states, array_index + 1);
}
/*@ requires !\fresh(a) && !\fresh(b);
assigns this.retaliationTable[0..this.retaliationTable.length-1], this.value;
ensures value == INITIAL_VALUE;
@*/
private void initialiseOffspring(Deterrence a, Deterrence b) {
value = INITIAL_VALUE;
/*@ loop_invariant i >= 0 && i <= ATTACK_TYPES &&
(\forall int j; j >= 0 && j < ATTACK_TYPES ==> 0.0 <= retaliationTable[j] < 1.0) &&
(\forall int j; j >= 0 && j < ATTACK_TYPES ==> 0.0 <= a.retaliationTable[j] < 1.0) &&
(\forall int j; j >= 0 && j < ATTACK_TYPES ==> 0.0 <= b.retaliationTable[j] < 1.0);
loop_variant ATTACK_TYPES - i;
@*/
for (int i = 0; i < ATTACK_TYPES; i++) {
retaliationTable[i] = mutate(choice(a.retaliationTable[i], b.retaliationTable[i]), nextDouble());
}
}
/*@ requires 0 <= intensity < ATTACK_TYPES && !\fresh(target) && RETALIATION_EFFECT >= 0.0;
assigns \nothing;
ensures \result <= attackStrength_logic(intensity) &&
\result == expectedValue_logic(intensity, target.numIgnores[intensity], target.numRetaliates[intensity], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT);
@*/
private static double expectedValue(int intensity, Deterrence target) {
return attackStrength(intensity)
* (target.numIgnores[intensity] + target.numRetaliates[intensity] * ((1.0 - ATTRIBUTION_PROBABILITY) - RETALIATION_EFFECT * ATTRIBUTION_PROBABILITY))
/ (target.numIgnores[intensity] + target.numRetaliates[intensity]);
}
/*@ requires !\fresh(target) && RETALIATION_EFFECT >= 0.0;
assigns \nothing;
ensures 0 <= \result < ATTACK_TYPES &&
(\forall int i; i >= 0 && i < ATTACK_TYPES ==>
expectedValue_logic(i, target.numIgnores[i], target.numRetaliates[i], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)
<=
expectedValue_logic(\result, target.numIgnores[\result], target.numRetaliates[\result], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)) &&
@ (\exists int i; i >= 0 && i < ATTACK_TYPES &&
expectedValue_logic(i, target.numIgnores[i], target.numRetaliates[i], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)
==
expectedValue_logic(\result, target.numIgnores[\result], target.numRetaliates[\result], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT));
@*/
private int highestExpectedValue(Deterrence target) {
int best = 0;
/*@
loop_invariant
(\forall int j; j >= 0 && j < h ==>
expectedValue_logic(j, target.numIgnores[j], target.numRetaliates[j], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)
<=
expectedValue_logic(best, target.numIgnores[best], target.numRetaliates[best], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)) &&
(\exists int k; k >= 0 && k < h &&
expectedValue_logic(k, target.numIgnores[k], target.numRetaliates[k], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)
==
expectedValue_logic(best, target.numIgnores[best], target.numRetaliates[best], ATTRIBUTION_PROBABILITY, RETALIATION_EFFECT)) &&
h >= 0 && h <= ATTACK_TYPES && best >= 0 && best < ATTACK_TYPES;
loop_variant ATTACK_TYPES - h;
@*/
for (int h = 1; h < ATTACK_TYPES; h++) {
if (expectedValue(h, target) > expectedValue(best, target)) {
best = h;
}
}
return best;
}
/*@ requires states_valid(states);
assigns \nothing;
ensures \result != this &&
@ states[\result.index] == \result &&
state_valid(states, \result, \result.index);
@*/
private Deterrence chooseOpponent() {
int choice = nextInt(states.length - 1);
//@ assert states[this.index] == this;
if (choice >= this.index)
choice++;
return states[choice];
}
/*@ requires states_valid(states) && RETALIATION_EFFECT >= 0.0;
ensures states_valid(states);
@*/
private void move() {
Deterrence defender = chooseOpponent();
int intensity;
if (nextDouble() < IRRATIONAL_PROBABILITY) {
intensity = nextInt(ATTACK_TYPES);
} else {
intensity = highestExpectedValue(defender);
}
//@ assert 0 <= intensity < ATTACK_TYPES;
if (nextDouble() < defender.retaliationTable[intensity]) {
if (nextDouble() < ATTRIBUTION_PROBABILITY) {
this.value -= attackStrength(intensity) * RETALIATION_EFFECT;
defender.value -= attackStrength(intensity) * RETALIATION_COST;
defender.numRetaliates[intensity]++;
} else {
this.value += attackStrength(intensity);
defender.value -= attackStrength(intensity) * RETALIATION_COST;
defender.numRetaliates[intensity]++;
}
} else {
this.value += attackStrength(intensity);
defender.value -= attackStrength(intensity) * DEFENDER_COST;
defender.numIgnores[intensity]++;
}
}
//@ requires RETALIATION_EFFECT >= 0.0;
public static void main(String[] args) {
/*@ loop_invariant 0 <= att <= 11;
loop_variant 10 - att;
@*/
for (int att = 0; att <= 10; att++) {
ATTRIBUTION_PROBABILITY = att * 0.1;
//@ assert 0.0 <= ATTRIBUTION_PROBABILITY <= 1.0;
/*@ loop_invariant 0 <= irr <= 11;
loop_variant 10 - irr;
@*/
for (int irr = 0; irr <= 10; irr++) {
IRRATIONAL_PROBABILITY = irr * 0.1;
//@ assert 0.0 <= IRRATIONAL_PROBABILITY <= 1.0;
states = new Deterrence[numStates];
//@ assert states_initialised(states);
/*@ loop_invariant
states_initialised(states) &&
states_valid_up_to(states, i) &&
i >= 0 && i <= numStates;
loop_variant numStates - i;
@*/
for (int i = 0; i < numStates; i++) {
new Deterrence(i);
}
//@ assert states_valid(states);
/*@ loop_invariant states_valid(states);
loop_variant numTurns - turn;
@*/
for (int turn = 0; turn < numTurns; turn++) {
/*@ loop_invariant i >= 0 && i <= numStates && states_valid(states);
loop_variant numStates - i;
@*/
for(int i = 0; i < numStates; i++) {
states[i].value = INITIAL_VALUE;
/*@ loop_invariant j >= 0 && j <= ATTACK_TYPES && states_valid(states);
loop_variant ATTACK_TYPES - j;
@*/
for (int j = 0; j < ATTACK_TYPES; j++) {
states[i].numIgnores[j] = 1;
states[i].numRetaliates[j] = 1;
}
}
/*@ loop_invariant states_valid(states);
loop_variant turnLength - step;
@*/
for (int step = 0; step < turnLength; step++) {
/*@ loop_invariant i >= 0 && i <= numStates && states_valid(states);
loop_variant numStates - i;
@*/
for(int i = 0; i < numStates; i++) {
states[i].move();
}
}
Deterrence worst = getWorst();
Deterrence best = getBest();
worst.initialiseOffspring(worst, best);
}
//@ assert states_valid(states);
//@ assert IRRATIONAL_PROBABILITY == irr * 0.1;
//@ assert ATTRIBUTION_PROBABILITY == att * 0.1;
printStuff(IRRATIONAL_PROBABILITY, ATTRIBUTION_PROBABILITY);
}
}
}
/*@ requires states_valid(states) && 0.0 <= IRRATIONAL_PROBABILITY <= 1.0 && 0.0 <= ATTRIBUTION_PROBABILITY <= 1.0;
assigns \nothing;
@*/
private static void printStuff(double IRRATIONAL_PROBABILITY, double ATTRIBUTION_PROBABILITY) {
System.out.print(IRRATIONAL_PROBABILITY);
System.out.print(", ");
System.out.print(ATTRIBUTION_PROBABILITY);
System.out.print(", ");
System.out.print(getLargestAverage());
System.out.println();
}
/*@ requires states_valid(states);
assigns \nothing;
@*/
private static double getLargestAverage() {
double [] averages = new double [ATTACK_TYPES];
/*@ loop_invariant i >= 0 && i <= ATTACK_TYPES;
loop_variant ATTACK_TYPES - i;
@*/
for(int i = 0; i < ATTACK_TYPES; i++) {
averages[i] = 0.0;
}
/*@ loop_invariant s >= 0 && s <= numStates;
loop_variant numStates - s;
@*/
for(int s = 0; s < numStates; s++) {
Deterrence state = states[s];
/*@ loop_invariant i >= 0 && i <= ATTACK_TYPES && !\fresh(state);
loop_variant ATTACK_TYPES - i;
@*/
for(int i = 0; i < ATTACK_TYPES; i++) {
averages[i] += state.retaliationTable[i];
}
}
/*@ loop_invariant i >= 0 && i <= ATTACK_TYPES;
loop_variant ATTACK_TYPES - i;
@*/
for(int i = 0; i < ATTACK_TYPES; i++) {
averages[i] /= numStates;
}
double largest = averages[0];
/*@ loop_invariant i >= 0 && i <= ATTACK_TYPES;
loop_variant ATTACK_TYPES - i;
@*/
for(int i = 1; i < ATTACK_TYPES; i++) {
if (averages[i] > largest)
largest = averages[i];
}
return largest;
}
}
| 17,603 | 38.648649 | 203 | java |
daala | daala-master/tools/java/src/intra/Intra2.java | /*Daala video codec
Copyright (c) 2012 Daala project contributors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
package intra;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import javax.imageio.ImageIO;
import org.ejml.alg.dense.linsol.LinearSolver;
import org.ejml.alg.dense.linsol.svd.SolvePseudoInverseSvd;
import org.ejml.data.DenseMatrix64F;
public class Intra2 {
public static final int MODES=10;
public static final int DISK_BLOCK_SIZE=4096;
public static final int STEPS=30;
public static final int BITS_PER_COEFF=6;
public static final double MAX_CG=BITS_PER_COEFF*-10*Math.log10(0.5);
public static final boolean USE_CG=true;
public static final boolean UPDATE_WEIGHT=false;
public static double DC_WEIGHT=66.07307086571254;
public static final int[] MODE_COLORS={
0xFF000000,
0xFFFFFFFF,
0xFFFF0000,
0xFFFFBF00,
0xFF80FF00,
0xFF00FF3F,
0xFF00FFFF,
0xFF0040FF,
0xFF7F00FF,
0xFFFF00C0,
};
protected final int B_SZ;
protected final String DATA_FOLDER;
protected final int[] INDEX;
class ModeData {
protected long numBlocks;
protected double weightTotal;
protected double[] mean=new double[2*B_SZ*2*B_SZ];
protected double[][] covariance=new double[2*B_SZ*2*B_SZ][2*B_SZ*2*B_SZ];
protected double[][] beta_1=new double[3*B_SZ*B_SZ][B_SZ*B_SZ];
protected double[] beta_0=new double[B_SZ*B_SZ];
protected double[] mse=new double[B_SZ*B_SZ];
protected void addBlock(double _weight,int[] _data) {
update(_weight,_data);
numBlocks++;
}
protected void removeBlock(double _weight,int[] _data) {
update(-_weight,_data);
numBlocks--;
}
private void update(double _weight,int[] _data) {
double[] delta=new double[2*B_SZ*2*B_SZ];
weightTotal+=_weight;
// online update of the mean
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
delta[i]=_data[INDEX[i]]-mean[i];
mean[i]+=delta[i]*_weight/weightTotal;
}
// online update of the covariance
for (int j=0;j<2*B_SZ*2*B_SZ;j++) {
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
covariance[j][i]+=delta[j]*delta[i]*_weight*(weightTotal-_weight)/weightTotal;
}
}
}
protected void computeBetas() {
DenseMatrix64F xtx=new DenseMatrix64F(3*B_SZ*B_SZ,3*B_SZ*B_SZ);
DenseMatrix64F xty=new DenseMatrix64F(3*B_SZ*B_SZ,B_SZ*B_SZ);
DenseMatrix64F b=new DenseMatrix64F(3*B_SZ*B_SZ,B_SZ*B_SZ);
// extract X^T*X and X^T*Y
for (int j=0;j<3*B_SZ*B_SZ;j++) {
for (int i=0;i<3*B_SZ*B_SZ;i++) {
xtx.set(j,i,covariance[j][i]/weightTotal);
}
for (int i=0;i<B_SZ*B_SZ;i++) {
xty.set(j,i,covariance[j][3*B_SZ*B_SZ+i]/weightTotal);
}
}
// compute b = (X^T*X)^-1 * X^T*Y
LinearSolver<DenseMatrix64F> solver=new SolvePseudoInverseSvd();
solver.setA(xtx);
solver.solve(xty,b);
// extract beta_1
// compute beta_0 = Y - X * beta_1
// compute MSE = Y^T*Y - Y^T*X * beta_1
for (int i=0;i<B_SZ*B_SZ;i++) {
beta_0[i]=mean[3*B_SZ*B_SZ+i];
mse[i]=covariance[3*B_SZ*B_SZ+i][3*B_SZ*B_SZ+i]/weightTotal;
for (int j=0;j<3*B_SZ*B_SZ;j++) {
beta_1[j][i]=b.get(j,i);
beta_0[i]-=beta_1[j][i]*mean[j];
mse[i]-=covariance[3*B_SZ*B_SZ+i][j]/weightTotal*beta_1[j][i];
}
}
}
protected double msePerCoeff(double[] _mse) {
double total_mse=0;
for (int j=0;j<B_SZ*B_SZ;j++) {
total_mse+=_mse[j];
}
return(total_mse/(B_SZ*B_SZ));
}
protected double cgPerCoeff(double[] _mse) {
double total_cg=0;
for (int j=0;j<B_SZ*B_SZ;j++) {
double cg=-10*Math.log10(_mse[j]/(covariance[3*B_SZ*B_SZ+j][3*B_SZ*B_SZ+j]/weightTotal));
/*if (cg>=MAX_CG) {
cg=MAX_CG;
}*/
total_cg+=cg;
}
return(total_cg/(B_SZ*B_SZ));
}
protected double predError(int[] _data,int _y) {
double pred=beta_0[_y];
for (int i=0;i<3*B_SZ*B_SZ;i++) {
pred+=_data[INDEX[i]]*beta_1[i][_y];
}
return(Math.abs(_data[INDEX[3*B_SZ*B_SZ+_y]]-pred));
}
protected void mseUpdateHelper(int[] _data,double _weight,double[] _mse) {
for (int j=0;j<B_SZ*B_SZ;j++) {
double e=predError(_data,j);
double se=e*e;
double wt=weightTotal+_weight;
double delta=se-mse[j];
_mse[j]=mse[j]+delta*_weight/wt;
}
}
protected void mseUpdate(int[] _data,double _weight) {
mseUpdateHelper(_data,_weight,mse);
}
protected double deltaBits(int[] _data,double _weight) {
double old_cg=cgPerCoeff(mse);
double[] tmp_mse=new double[B_SZ*B_SZ];
mseUpdateHelper(_data,_weight,tmp_mse);
update(_weight,_data);
double cg=cgPerCoeff(tmp_mse);
update(-_weight,_data);
return((weightTotal+_weight)*cg-weightTotal*old_cg);
}
};
public Intra2(int _blockSize,String _dataFolder) {
B_SZ=_blockSize;
DATA_FOLDER=_dataFolder;
INDEX=new int[4*B_SZ*B_SZ];
for (int i=0,j=0;j<B_SZ;j++) {
for (int k=0;k<B_SZ;k++) {
INDEX[i+0*B_SZ*B_SZ]=2*B_SZ*j+k;
INDEX[i+1*B_SZ*B_SZ]=2*B_SZ*j+(B_SZ+k);
INDEX[i+2*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+k;
INDEX[i+3*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+(B_SZ+k);
i++;
}
}
}
protected File[] getFiles() throws IOException {
File folder=new File(DATA_FOLDER);
File[] coeffFiles=folder.listFiles(new FilenameFilter() {
public boolean accept(File _file,String _filename) {
return(_filename.endsWith(".coeffs"));
}
});
if (coeffFiles==null) {
return(null);
}
Arrays.sort(coeffFiles);
File[] binFiles=new File[coeffFiles.length];
for (int i=0;i<coeffFiles.length;i++) {
binFiles[i]=new File(coeffFiles[i].getPath()+".bin");
if (!binFiles[i].exists()) {
System.out.println("Converting "+coeffFiles[i].getPath()+" to "+binFiles[i].getPath());
Scanner s=new Scanner(new BufferedInputStream(new FileInputStream(coeffFiles[i]),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(binFiles[i]),DISK_BLOCK_SIZE));
while (s.hasNextShort()) {
dos.writeShort(s.nextShort());
}
s.close();
dos.close();
}
}
return(binFiles);
}
protected ModeData[] loadData(File[] _files) throws IOException {
// initialize the modes
ModeData modeData[]=new ModeData[MODES];
for (int i=0;i<MODES;i++) {
modeData[i]=new ModeData();
}
double weight_sum=0;
long block_sum=0;
for (File file : _files) {
System.out.println("Loading "+file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step00.mode"),DISK_BLOCK_SIZE));
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
int mode=dis.readShort();
double weight=dis.readShort();
//System.out.println("mode="+mode+" weight="+weight);
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
if (weight>0) {
weight_sum+=weight;
block_sum++;
if (mode==0) {
weight=DC_WEIGHT;
}
modeData[mode].addBlock(weight,data);
}
dos.writeShort(mode);
dos.writeDouble(weight);
rgb[block]=MODE_COLORS[mode];
}
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step00.png"));
dos.close();
dis.close();
}
DC_WEIGHT=weight_sum/block_sum;
System.out.println("DC_WEIGHT="+DC_WEIGHT);
// correct the DC to use DC_WEIGHT
return(modeData);
}
protected void fitData(ModeData[] _modeData) {
// compute betas and MSE
for (int i=0;i<MODES;i++) {
System.out.println("mode "+i);
double[] old_mse=new double[B_SZ*B_SZ];
for (int j=0;j<B_SZ*B_SZ;j++) {
old_mse[j]=_modeData[i].mse[j];
}
_modeData[i].computeBetas();
for (int j=0;j<B_SZ*B_SZ;j++) {
System.out.println(" "+j+": "+old_mse[j]+"\t"+_modeData[i].mse[j]+"\t"+(_modeData[i].mse[j]-old_mse[j]));
}
}
}
protected static final int SPACE=4;
protected void printStats(ModeData[] _modeData) {
double mse_sum=0;
double cg_sum=0;
double weight=0;
for (int i=0;i<MODES;i++) {
double mse=_modeData[i].msePerCoeff(_modeData[i].mse);
double cg=_modeData[i].cgPerCoeff(_modeData[i].mse);
System.out.println(" "+i+": "+_modeData[i].numBlocks+"\t"+_modeData[i].weightTotal+"\t"+mse+"\t"+cg);
mse_sum+=_modeData[i].weightTotal*mse;
cg_sum+=_modeData[i].weightTotal*cg;
weight+=_modeData[i].weightTotal;
}
System.out.println("Total Weight "+weight);
System.out.println("Average MSE "+mse_sum/weight);
System.out.println("Average CG "+cg_sum/weight);
// make a "heat map" using the normalized beta_1
/*int w=SPACE+(2*B_SZ+SPACE)*B_SZ*B_SZ;
int h=SPACE+(2*B_SZ+SPACE)*MODES;
int[] rgb=new int[w*h];
for (int i=0;i<MODES;i++) {
int yoff=SPACE+i*(2*B_SZ+SPACE);
int xoff=SPACE;
for (int j=0;j<B_SZ*B_SZ;j++) {
rgb[w*(yoff+i)+xoff];
}
}*/
}
protected void processData(int step,ModeData[] _modeData,File[] _files) throws IOException {
for (File file : _files) {
System.out.println("Processing "+file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataInputStream dis2=new DataInputStream(new BufferedInputStream(new FileInputStream(file.getPath()+".step"+(step-1<10?"0"+(step-1):step-1)+".mode"),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step"+(step<10?"0"+step:step)+".mode"),DISK_BLOCK_SIZE));
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
if ((block&0x3fff)==0) {
System.out.println(block);
}
// load the data
int mode=dis.readShort();
double weight=dis.readShort();
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
int lastMode=dis2.readShort();
double lastWeight=dis2.readDouble();
if (weight>0) {
if (mode==0) {
weight=DC_WEIGHT;
lastWeight=DC_WEIGHT;
}
// compute error
double[] error=new double[MODES];
double[] cg=new double[MODES];
for (int i=0;i<MODES;i++) {
for (int j=0;j<B_SZ*B_SZ;j++) {
error[i]+=_modeData[i].predError(data,j);
}
if (USE_CG) {
cg[i]=_modeData[i].deltaBits(data,lastMode==i?-weight:weight);
}
}
double best=-Double.MAX_VALUE;
double nextBest=-Double.MAX_VALUE;
for (int j=0;j<MODES;j++) {
// lower SATD is better
double metric=error[lastMode]-error[j];
if (USE_CG) {
// greater CG is better
metric=lastMode==j?0:cg[lastMode]+cg[j];
}
if (metric>best) {
nextBest=best;
best=metric;
mode=j;
}
else {
if (metric>nextBest) {
nextBest=metric;
}
}
}
if (UPDATE_WEIGHT) {
weight=best-nextBest;
}
if (USE_CG) {
_modeData[lastMode].mseUpdate(data,-lastWeight);
_modeData[mode].mseUpdate(data,weight);
}
_modeData[lastMode].removeBlock(lastWeight,data);
_modeData[mode].addBlock(weight,data);
/*if (USE_CG) {
_modeData[lastMode].computeBetas();
_modeData[mode].computeBetas();
}*/
}
dos.writeShort(mode);
dos.writeDouble(weight);
rgb[block]=MODE_COLORS[mode];
}
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step"+(step<10?"0"+step:step)+".png"));
dis.close();
dis2.close();
dos.close();
}
}
public void run() throws Exception {
File[] files=getFiles();
if (files==null) {
System.out.println("No .coeffs files found in "+DATA_FOLDER+" folder. Enable the PRINT_BLOCKS ifdef and run:");
System.out.println(" for f in subset1-y4m/*.y4m; do ./init_intra_maps $f && ./init_intra_xform $f 2> $f.coeffs; done");
System.out.println("Move the *.coeffs files to "+DATA_FOLDER);
return;
}
// load the blocks
ModeData[] modeData=loadData(files);
long start=System.currentTimeMillis();
for (int k=1;k<=STEPS;k++) {
// update model
fitData(modeData);
printStats(modeData);
// reclassify blocks
processData(k,modeData,files);
long now=System.currentTimeMillis();
System.out.println("Step "+k+" took "+((now-start)/1000.0)+"s");
}
}
public static void main(String[] _args) throws Exception {
Intra2 intra=new Intra2(4,"data2");
intra.run();
}
};
| 14,224 | 28.269547 | 170 | java |
daala | daala-master/tools/java/src/intra/Intra.java | /*Daala video codec
Copyright (c) 2012 Daala project contributors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/
package intra;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import javax.imageio.ImageIO;
import org.ejml.alg.dense.linsol.LinearSolver;
import org.ejml.alg.dense.linsol.svd.SolvePseudoInverseSvd;
import org.ejml.data.DenseMatrix64F;
public class Intra {
public static final int MODES=10;
public static final int B_SZ=4;
public static final boolean DROP_MULTS=false;
public static final int MAX_MULTS=4*B_SZ*B_SZ;
public static final boolean USE_CG=false;
public static final int[] MODE_COLORS={
0xFF000000,
0xFFFFFFFF,
0xFFFF0000,
0xFFFFBF00,
0xFF80FF00,
0xFF00FF3F,
0xFF00FFFF,
0xFF0040FF,
0xFF7F00FF,
0xFFFF00C0,
};
public static final int[] INDEX;
public static final int DISK_BLOCK_SIZE=4096;
static {
// index the coefficients in block order
INDEX=new int[4*B_SZ*B_SZ];
for (int tmp=0,j=0;j<B_SZ;j++) {
for (int i=0;i<B_SZ;i++) {
INDEX[tmp+0*B_SZ*B_SZ]=2*B_SZ*j+i;
INDEX[tmp+1*B_SZ*B_SZ]=2*B_SZ*j+(B_SZ+i);
INDEX[tmp+2*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+i;
INDEX[tmp+3*B_SZ*B_SZ]=2*B_SZ*(B_SZ+j)+(B_SZ+i);
tmp++;
}
}
}
static class ModeData {
protected long numBlocks;
protected double weightTotal;
protected double[] mean=new double[2*B_SZ*2*B_SZ];
protected double[][] covariance=new double[2*B_SZ*2*B_SZ][2*B_SZ*2*B_SZ];
protected double[] scale=new double[2*B_SZ*2*B_SZ];
protected int[] numMults=new int[B_SZ*B_SZ];
protected boolean[][] mult=new boolean[3*B_SZ*B_SZ][B_SZ*B_SZ];
protected double[][] mseMasked=new double[3*B_SZ*B_SZ][B_SZ*B_SZ];
protected double[] mse=new double[B_SZ*B_SZ];
protected double[][] beta=new double[3*B_SZ*B_SZ][B_SZ*B_SZ];
protected double satd;
protected ModeData() {
for (int y=0;y<B_SZ*B_SZ;y++) {
numMults[y]=3*B_SZ*B_SZ;
for (int i=0;i<3*B_SZ*B_SZ;i++) {
mult[i][y]=true;
}
}
}
protected void addBlock(double _weight,int[] _data) {
double[] delta=new double[2*B_SZ*2*B_SZ];
numBlocks++;
weightTotal+=_weight;
// online update of the mean
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
delta[i]=_data[INDEX[i]]-mean[i];
mean[i]+=delta[i]*_weight/weightTotal;
}
// online update of the covariance
for (int j=0;j<2*B_SZ*2*B_SZ;j++) {
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
covariance[j][i]+=delta[j]*delta[i]*_weight*(weightTotal-_weight)/weightTotal;
}
}
}
protected void normalize() {
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
scale[i]=Math.sqrt(covariance[i][i]);
}
// compute C' = Sx * C * Sx
for (int j=0;j<2*B_SZ*2*B_SZ;j++) {
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
covariance[j][i]/=scale[j]*scale[i];
}
}
}
protected int coeffDrop() {
double delta=Double.MAX_VALUE;
int y=-1;
int c=-1;
for (int j=0;j<3*B_SZ*B_SZ;j++) {
for (int i=0;i<B_SZ*B_SZ;i++) {
if (mult[j][i]) {
if (mseMasked[j][i]-mse[i]<delta) {
delta=mseMasked[j][i]-mse[i];
y=i;
c=j;
}
}
}
}
mult[c][y]=false;
return(y);
}
protected double mse(int _y) {
return(mse(_y,false));
}
protected double mse(int _y,boolean _saveBeta) {
double yty=covariance[3*B_SZ*B_SZ+_y][3*B_SZ*B_SZ+_y];
double ytxb=0;
int xsize=numMults[_y];
if (xsize>0) {
if (xtx[xsize-1]==null) {
xty[xsize-1]=new DenseMatrix64F(xsize,1);
b[xsize-1]=new DenseMatrix64F(xsize,1);
}
xtx[xsize-1]=new DenseMatrix64F(xsize,xsize);
for (int ji=0,j=0;j<3*B_SZ*B_SZ;j++) {
if (mult[j][_y]) {
for (int ii=0,i=0;i<3*B_SZ*B_SZ;i++) {
if (mult[i][_y]) {
xtx[xsize-1].set(ji,ii,covariance[j][i]);
ii++;
}
}
xty[xsize-1].set(ji,0,covariance[j][3*B_SZ*B_SZ+_y]);
ji++;
}
}
solver.setA(xtx[xsize-1]);
solver.solve(xty[xsize-1],b[xsize-1]);
// compute y^T * x * beta
for (int ii=0,i=0;i<3*B_SZ*B_SZ;i++) {
if (mult[i][_y]) {
ytxb+=covariance[3*B_SZ*B_SZ+_y][i]*b[xsize-1].get(ii,0);
ii++;
}
}
// save beta for use with classification
if (_saveBeta) {
for (int ii=0,i=0;i<3*B_SZ*B_SZ;i++) {
if (mult[i][_y]) {
// beta' = Sx^-1 * beta * Sy -> beta = Sx * beta' * Sy^-1
beta[i][_y]=b[xsize-1].get(ii,0)*scale[3*B_SZ*B_SZ+_y]/scale[i];
ii++;
}
else {
beta[i][_y]=0;
}
}
}
}
return(yty-ytxb);
}
// compute the masked MSE's for a given y coefficient
protected void updateMasked(int _y) {
for (int i=0;i<3*B_SZ*B_SZ;i++) {
if (mult[i][_y]) {
mult[i][_y]=false;
numMults[_y]--;
mseMasked[i][_y]=mse(_y);
mult[i][_y]=true;
numMults[_y]++;
}
}
}
protected double predError(int[] _data,int _y) {
double pred=0;
for (int i=0;i<3*B_SZ*B_SZ;i++) {
pred+=_data[INDEX[i]]*beta[i][_y];
}
return(Math.abs(_data[INDEX[3*B_SZ*B_SZ+_y]]-pred));
}
protected double mseUpdate(double _error,int _y,int _weight) {
double se=_error*_error;
double wt=weightTotal+_weight;
double delta=se-mse[_y];
return(mse[_y]+delta*_weight/wt);
}
};
protected static LinearSolver<DenseMatrix64F> solver=new SolvePseudoInverseSvd();
protected static DenseMatrix64F[] xtx=new DenseMatrix64F[3*B_SZ*B_SZ];
protected static DenseMatrix64F[] xty=new DenseMatrix64F[3*B_SZ*B_SZ];
protected static DenseMatrix64F[] b=new DenseMatrix64F[3*B_SZ*B_SZ];
protected static double satdAverage(ModeData[] _modes) {
// compute online update of mean
return(0);
}
public static void main(String[] _args) throws IOException {
ModeData[] modeData=new ModeData[MODES];
// initialize the modes
for (int i=0;i<MODES;i++) {
modeData[i]=new ModeData();
}
// for each pass of k-means load the data
File folder=new File("data");
File[] coeffFiles=folder.listFiles(new FilenameFilter() {
public boolean accept(File _file,String _filename) {
return(_filename.endsWith(".coeffs"));
}
});
if (coeffFiles==null) {
System.out.println("No .coeffs files found in data/ folder. Enable the PRINT_BLOCKS ifdef and run:");
System.out.println(" for f in subset1-y4m/*.y4m; do ./init_intra_maps $f && ./init_intra_xform $f 2> $f.coeffs; done");
System.out.println("Move the *.coeffs files to tools/java/data");
System.exit(0);
}
Arrays.sort(coeffFiles);
File[] binFiles=new File[coeffFiles.length];
for (int i=0;i<coeffFiles.length;i++) {
binFiles[i]=new File(coeffFiles[i].getPath()+".bin");
if (!binFiles[i].exists()) {
System.out.println("Converting "+coeffFiles[i].getPath()+" to "+binFiles[i].getPath());
Scanner s=new Scanner(new BufferedInputStream(new FileInputStream(coeffFiles[i]),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(binFiles[i]),DISK_BLOCK_SIZE));
while (s.hasNextShort()) {
dos.writeShort(s.nextShort());
}
s.close();
dos.close();
}
}
for (File file : binFiles) {
System.out.println(file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step00.mode"),DISK_BLOCK_SIZE));
// 3 color planes, YUV
for (int pli=0;pli<1;pli++) {
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
System.out.println("nx="+nx+" ny="+ny);
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
int mode=dis.readShort();
int weight=dis.readShort();
//System.out.println("mode="+mode+" weight="+weight);
dos.writeShort(mode);
//dos.writeShort(weight);
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
if (weight>0) {
//modeData[mode].addBlock(mode==0?1:weight,data);
modeData[mode].addBlock(weight,data);
}
rgb[block]=MODE_COLORS[mode];
}
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step00.png"));
}
dos.close();
dis.close();
}
/*System.out.println("numBlocks="+modeData[0].numBlocks);
for (int i=0;i<3*B_SZ*B_SZ;i++) {
System.out.println(i+": "+modeData[0].mean[i]);
}
System.exit(0);*/
long last=System.currentTimeMillis();
for (int step=1;step<=30;step++) {
System.out.println("*** Starting step "+step);
// phase 1:
// normalize
// compute the metric (MSE or CG)
// sparsify (optional)
// compute beta
long modeStart=System.currentTimeMillis();
// for each mode
for (int mode=0;mode<MODES;mode++) {
ModeData md=modeData[mode];
md.normalize();
// compute MSE based on completely unmasked
double mse=0;
double cg=0;
for (int y=0;y<B_SZ*B_SZ;y++) {
md.mse[y]=md.mse(y,true);
cg+=-10*Math.log10(md.mse[y]);
mse+=md.mse[y];
}
System.out.println(" "+mode+": blocks="+md.numBlocks+"\tMSE="+mse+"\tCG="+cg);
double metric=USE_CG?cg:mse;
//System.out.println("before="+(System.currentTimeMillis()-modeStart));
int mults=(3*B_SZ*B_SZ)*(B_SZ*B_SZ);
if (DROP_MULTS) {
for (int y=0;y<B_SZ*B_SZ;y++) {
md.updateMasked(y);
}
//double rmseStart=Math.sqrt(md.total/(B_SZ*B_SZ));
for (;mults-->MAX_MULTS;) {
int y=modeData[mode].coeffDrop();
metric-=USE_CG?-10*Math.log10(md.mse[y]):md.mse[y];
md.mse[y]=md.mse(y,true);
metric+=USE_CG?-10*Math.log10(md.mse[y]):md.mse[y];
md.numMults[y]--;
md.updateMasked(y);
}
//double rmseEnd=Math.sqrt(md.total/(B_SZ*B_SZ));
/*System.out.println(mode+" "+rmseEnd+" "+(rmseEnd-rmseStart)+" took "+(modeEnd-modeStart)/1000.0);
for (int j=0;j<B_SZ;j++) {
String prefix=" ";
for (int i=0;i<B_SZ;i++) {
System.out.print(prefix+(md.numMults[j*B_SZ+i]));
prefix=" ";
}
prefix=" ";
for (int i=0;i<B_SZ;i++) {
System.out.print(prefix+md.mse[j*B_SZ+i]);
prefix=" ";
}
System.out.println();
}*/
}
//System.out.println("after="+(System.currentTimeMillis()-modeStart));
long modeEnd=System.currentTimeMillis();
modeStart=modeEnd;
}
ModeData[] oldModeData=modeData;
// reset the mode data
modeData=new ModeData[MODES];
for (int i=0;i<MODES;i++) {
modeData[i]=new ModeData();
}
double total_satd=0;
int total_blocks=0;
// re-classify the blocks based on the computed beta's
for (File file : binFiles) {
//System.out.print(file.getPath());
DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file),DISK_BLOCK_SIZE));
DataInputStream dis2=new DataInputStream(new BufferedInputStream(new FileInputStream(file.getPath()+".step"+(step-1<10?"0"+(step-1):step-1)+".mode"),DISK_BLOCK_SIZE));
DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file.getPath()+".step"+(step<10?"0"+step:step)+".mode"),DISK_BLOCK_SIZE));
// 3 color planes, YUV
for (int pli=0;pli<1;pli++) {
// read the plane size
int nx=dis.readShort();
int ny=dis.readShort();
int[] to=new int[MODES];
int[] from=new int[MODES];
double[] image_satd=new double[MODES];
int[] image_blocks=new int[MODES];
int[] rgb=new int[nx*ny];
for (int block=0;block<nx*ny;block++) {
// load the data
int mode=dis.readShort();
int weight=dis.readShort();
int oldMode=dis2.readShort();
int[] data=new int[2*B_SZ*2*B_SZ];
for (int i=0;i<2*B_SZ*2*B_SZ;i++) {
data[i]=dis.readShort();
}
//System.out.println("+++ block="+block+" mode="+mode+" weight="+weight);
if (weight>0) {
double[] errors=new double[MODES];
double[] bits=new double[MODES];
for (int j=0;j<MODES;j++) {
ModeData md=oldModeData[j];
for (int y=0;y<B_SZ*B_SZ;y++) {
double error=md.predError(data,y);
errors[j]+=error;
//int tmpWeight=j==0?1:weight;
bits[j]+=-10*Math.log10(md.mse[y]/md.mseUpdate(error,y,j==oldMode?-weight:weight));
/*System.out.println("mode="+j+" y="+y);
System.out.println(" old mse="+md.mse[y]);
double oldBits=-10*Math.log10(md.mse[y]);
System.out.println(" old bits="+oldBits);
System.out.println(" error="+error);
double mse=md.mseUpdate(error,y,-weight);
System.out.println(" new mse="+mse);
double newBits=-10*Math.log10(mse);
System.out.println(" new bits="+newBits);
double delta_bits=-10*Math.log10(md.mse[y]/mse);
System.out.println(" delta bits="+delta_bits);*/
}
}
double best=-Double.MAX_VALUE;
double nextBest=-Double.MAX_VALUE;
for (int j=0;j<MODES;j++) {
double metric=0;
if (USE_CG) {
if (oldMode!=j) {
// greater CG is better
metric=bits[oldMode]+bits[j];
}
}
else {
// lower SATD is better
metric=errors[oldMode]-errors[j];
}
/*for (int y=0;y<B_SZ*B_SZ;y++) {
// compute |y-x*B| the SATD (or L1-norm)
double error=md.predError(data,y);
metric+=USE_CG?-10*Math.log10(md.mse[y]/md.mseUpdate(error,y,weight)):error;
}
//System.out.println("mode="+j+" metric="+metric);
if (USE_CG) {
metric=-(mode_bits+metric);
}
if (metric<best) {
nextBest=best;
best=metric;
mode=j;
}
else {
if (metric<nextBest) {
nextBest=metric;
}
}*/
if (metric>best) {
nextBest=best;
best=metric;
mode=j;
}
else {
if (metric>nextBest) {
nextBest=metric;
}
}
}
//System.out.println("block="+block+" best="+best+" new_mode="+mode+" nextBest="+nextBest);
image_satd[mode]+=errors[mode];
image_blocks[mode]++;
if (mode!=oldMode) {
to[mode]++;
from[oldMode]++;
}
modeData[mode].addBlock(mode==0?1:best-nextBest,data);
//modeData[mode].addBlock(mode==0?1:weight,data);
//modeData[mode].addBlock(weight,data);
}
dos.writeShort(mode);
rgb[block]=MODE_COLORS[mode];
}
System.out.println("Image Average SATD");
int total_to=0;
int total_from=0;
int blocks=0;
for (int mode=0;mode<MODES;mode++) {
System.out.println(" "+mode+": "+image_satd[mode]/image_blocks[mode]+"\t"+image_blocks[mode]+"\t-"+from[mode]+"\t+"+to[mode]);
total_satd+=image_satd[mode];
total_to+=to[mode];
total_from+=from[mode];
blocks+=image_blocks[mode];
}
System.out.println("\t\t\t"+blocks+"\t-"+total_from+"\t+"+total_to);
//total_blocks+=blocks;
total_blocks+=nx*ny;
BufferedImage bi=new BufferedImage(nx,ny,BufferedImage.TYPE_INT_ARGB);
bi.setRGB(0,0,nx,ny,rgb,0,nx);
ImageIO.write(bi,"PNG",new File(file.getPath()+".step"+(step<10?"0"+step:step)+".png"));
}
dis.close();
dis2.close();
dos.close();
}
long now=System.currentTimeMillis();
System.out.println("*** Ending step "+step+" took "+(now-last)/1000.0);
//System.out.println("Step "+step+" took "+(now-last)/1000.0);
System.out.println("Average SATD: "+(total_satd/total_blocks));
}
}
};
| 17,194 | 29.379859 | 171 | java |
GraphifyEvolution | GraphifyEvolution-master/JavaAnalyser/src/test/java/JavaAnalyser/AppTest.java | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package JavaAnalyser;
import org.junit.Test;
import static org.junit.Assert.*;
public class AppTest {
@Test public void testAppHasAGreeting() {
App classUnderTest = new App();
// assertNotNull("app should have a greeting", classUnderTest.getGreeting());
}
}
| 356 | 22.8 | 84 | java |
GraphifyEvolution | GraphifyEvolution-master/JavaAnalyser/src/main/java/JavaAnalyser/App.java | /*
* This Java source file was generated by the Gradle 'init' task.
*/
package JavaAnalyser;
import com.github.javaparser.*;
import com.github.javaparser.ast.*;
import com.github.javaparser.ast.body.*;
import com.github.javaparser.ast.expr.*;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.resolution.UnsolvedSymbolException;
import com.github.javaparser.resolution.declarations.*;
import com.github.javaparser.resolution.types.ResolvedReferenceType;
import com.github.javaparser.resolution.types.ResolvedType;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserFieldDeclaration;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import com.github.javaparser.symbolsolver.utils.SymbolSolverCollectionStrategy;
import com.github.javaparser.utils.ProjectRoot;
import com.github.javaparser.utils.SourceRoot;
import com.github.javaparser.resolution.MethodUsage;
import javax.swing.text.html.Option;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import static java.lang.System.exit;
public class App {
public static void main(String[] args) {
//System.out.println("---");
//System.out.println(System.getProperty("java.version"));
if(args.length < 2 ) {//|| args.length > 3) {
System.out.println("Wrong number of arguments: " + args.length + ". Should be 2 or 3.");
}
String path = args[0];
String projectFolderPath = args[1];
String jdkPath = "/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/";
if(args.length == 3) {
jdkPath = args[2];
}
/*
CombinedTypeSolver combinedSolver = new CombinedTypeSolver(
new JavaParserTypeSolver(jdkPath),
new JavaParserTypeSolver(new File("/Users/kristiina/.gradle/caches/modules-2/files-2.1/")),
new JavaParserTypeSolver(new File(projectFolderPath)),
new ReflectionTypeSolver()
);
*/
//ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(combinedSolver));
//SymbolSolverCollectionStrategy symbolSolverCollectionStrategy = new SymbolSolverCollectionStrategy(parserConfiguration);
SymbolSolverCollectionStrategy symbolSolverCollectionStrategy = new SymbolSolverCollectionStrategy();
ProjectRoot projectRoot = symbolSolverCollectionStrategy.collect(Paths.get(projectFolderPath));
String[] split = path.split("/src/main/java/");
String last = split[split.length - 1];
ArrayList<Map<String,Object>> objects = new ArrayList<Map<String,Object>>();
for( SourceRoot sourceRoot : projectRoot.getSourceRoots()) {
try {
/*
sourceRoot.tryToParse();
List<CompilationUnit> cus = sourceRoot.getCompilationUnits();
System.out.println("number of cus: " + cus.size());
for( CompilationUnit cu: cus) {
Map<String,Object> object = new HashMap<>();
String packageDeclaration;
if(cu.getPackageDeclaration().isPresent()) {
packageDeclaration = cu.getPackageDeclaration().get().getNameAsString();
} else {
packageDeclaration = "?";
}
object.put("'key.package'", "'" + packageDeclaration + "'");
object.put("'key.entities'", handleCompilationUnit(cu));
// objects.add(object);
}
*/
sourceRoot.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_11);
CompilationUnit cu = sourceRoot.parse("", last);
Map<String,Object> object = new HashMap<>();
String packageDeclaration;
if(cu.getPackageDeclaration().isPresent()) {
packageDeclaration = cu.getPackageDeclaration().get().getNameAsString();
} else {
packageDeclaration = "?";
}
object.put("'key.package'", "'" + packageDeclaration + "'");
object.put("'key.entities'", handleCompilationUnit(cu));
objects.add(object);
break;
} catch (ParseProblemException e) {
// System.out.println("not found path for sourceRoot: " + sourceRoot);
} //catch (IOException e) {
// e.printStackTrace();
// }
}
System.out.println(objects);
}
private static void printNode(Node node, String prefix) {
String addInfo = "";
if(node.getClass() == Name.class) {
addInfo = " -- " + node.toString();
}
if(node.getClass() == SimpleName.class) {
addInfo = " -- " + node.toString();
}
System.out.println(prefix + "Node class: " + node.getClass() + addInfo);
for(Node entity: node.getChildNodes()) {
printNode(entity, " " + prefix);
}
}
private static Map<String,Object> handleInstruction(Node node) {
Map<String,Object> object = new HashMap<>();
String name = null;
String usr = null;
String typeString = null;
if(node.getClass() == ClassOrInterfaceType.class) {
ClassOrInterfaceType classOrInterfaceType = (ClassOrInterfaceType)node;
name = classOrInterfaceType.getNameAsString();
try {
usr = classOrInterfaceType.resolve().getQualifiedName();
} catch (UnsolvedSymbolException exception) {
usr = "??";
} catch (UnsupportedOperationException exception) {
usr = "??";
}
} else if (node.getClass() == MethodCallExpr.class) {
MethodCallExpr methodCallExpr = (MethodCallExpr) node;
name = methodCallExpr.getNameAsString();
try {
usr = methodCallExpr.resolve().getQualifiedSignature();
} catch (UnsolvedSymbolException exception) {
//usr = "??";
usr = methodCallExpr.getNameAsString();
} catch (RuntimeException exception) {
// sometimes if type of a parameter cannot be resolved a RuntimeException is thrown
usr = methodCallExpr.getNameAsString();
}
} else if (node.getClass() == MethodReferenceExpr.class) {
MethodReferenceExpr methodReferenceExpr = (MethodReferenceExpr)node;
try {
name = methodReferenceExpr.resolve().getName();
usr = methodReferenceExpr.resolve().getQualifiedSignature();
} catch (UnsolvedSymbolException exception) {
usr = methodReferenceExpr.toString();
name = methodReferenceExpr.toString();
} catch (UnsupportedOperationException expection) {
usr = methodReferenceExpr.toString();
name = methodReferenceExpr.toString();
} catch (RuntimeException exception) {
// sometimes unsolved type parameters cause a RuntimeException
usr = methodReferenceExpr.toString();
name = methodReferenceExpr.toString();
}
} else if (node.getClass() == FieldAccessExpr.class) {
try {
FieldAccessExpr fieldAccessExpr = (FieldAccessExpr) node;
name = fieldAccessExpr.getNameAsString();
/*
ResolvedValueDeclaration valueDeclaration = fieldAccessExpr.resolve();
if(valueDeclaration.getClass() == ResolvedFieldDeclaration.class) {
ResolvedFieldDeclaration resolvedFieldDeclaration = (ResolvedFieldDeclaration)valueDeclaration;
usr = resolvedFieldDeclaration.declaringType().getQualifiedName() + "." + name;
}
*/
Expression fieldScope = fieldAccessExpr.getScope();
String scope;
try {
scope = fieldScope.calculateResolvedType().asReferenceType().getQualifiedName();
} catch (UnsolvedSymbolException e) {
scope = "?";
} catch (UnsupportedOperationException e) {
scope = "?";
} catch (RuntimeException e) {
scope = "?";
}
String fieldName = fieldAccessExpr.getNameAsString();
String fullName = scope + "." + fieldName;
usr = fullName;
ResolvedType resolvedType = fieldAccessExpr.resolve().getType();
if (resolvedType.isPrimitive()) {
typeString = resolvedType.asPrimitive().name();
} else if (resolvedType.isReferenceType()) {
ResolvedReferenceType refType = resolvedType.asReferenceType();
typeString = refType.getQualifiedName();
}
} catch (UnsolvedSymbolException exception) {
usr = "??";
} catch (UnsupportedOperationException exception) {
typeString = "???";
}
} else if(node.getClass() == NameExpr.class) {
try {
NameExpr nameExpr = (NameExpr)node;
ResolvedValueDeclaration valueDeclaration = nameExpr.resolve();
name = nameExpr.getNameAsString();
if(valueDeclaration.getClass() == JavaParserFieldDeclaration.class) {
JavaParserFieldDeclaration resolvedFieldDeclaration = (JavaParserFieldDeclaration)valueDeclaration;
usr = resolvedFieldDeclaration.declaringType().getQualifiedName() + "." + name;
}
//usr = valueDeclaration.getClass().toString();
} catch (UnsolvedSymbolException exception) {
// no usr
// usr = "!!!!";
} catch (UnsupportedOperationException exception) {
// no usr
}
}
setStartEnd(node, object);
object.put("'key.kind'", "'" + node.getClass().toString() + "'");
if(usr != null) {
object.put("'key.usr'", "'" + usr + "'");
}
if(name != null) {
object.put("'key.name'", "'" + name + "'");
}
if(typeString != null) {
object.put("'key.type'", "'" + typeString + "'");
}
object.put("'key.kind'", "'" + node.getClass().toString() + "'");
List<Map<String,Object>> entities = new ArrayList<>();
for(Node child: node.getChildNodes()) {
entities.add(handleInstruction(child));
}
object.put("'key.entities'", entities);
return object;
}
private static Map<String,Object> handleParameter(Parameter node) {
Map<String,Object> object = new HashMap<>();
setStartEnd(node, object);
try {
Type type = node.getType();
ResolvedType resolvedType = type.resolve();
if (resolvedType.isPrimitive()) {
object.put("'key.type'", "'" + resolvedType.asPrimitive().name().replace('\'', '-') + "'");
} else if (resolvedType.isReferenceType()) {
ResolvedReferenceType refType = resolvedType.asReferenceType();
refType.getQualifiedName();
object.put("'key.typeUsr'", "'" + refType.getQualifiedName() + "'");
object.put("'key.type'", "'" + refType.getQualifiedName() + "'");
} else {
object.put("'key.type'", "'" + resolvedType.toString().replace('\'', '-') +"'");
}
} catch (UnsolvedSymbolException ex) {
object.put("'key.type'", "'??unresolved'");
} catch (UnsupportedOperationException ex) {
object.put("'key.type'", "'??unsupported'");
}
object.put("'key.name'", "'" + node.getNameAsString() + "'");
List<Map<String,Object>> entities = new ArrayList<>();
for(Node child: node.getChildNodes()) {
entities.add(handleInstruction(child));
}
object.put("'key.entities'", entities);
return object;
}
private static void setStartEnd(Node node, Map<String, Object> object) {
int start = -1;
int end = -1;
Optional<Position> optionalPositionEnd = node.getEnd();
Optional<Position> optionalPositionBegin = node.getBegin();
if(optionalPositionBegin.isPresent()) {
start = optionalPositionBegin.get().line;
}
if(optionalPositionEnd.isPresent()) {
end = optionalPositionEnd.get().line;
}
object.put("'key.startLine'", start);
object.put("'key.endLine'", end);
}
private static Map<String, Object> handleConstructor(ConstructorDeclaration constructor) {
Map<String,Object> object = new HashMap<>();
setStartEnd(constructor, object);
object.put("'key.name'", "'" + constructor.getNameAsString() + "'");
List<Map<String,Object>> annotations = new ArrayList<>();
for(AnnotationExpr annotation: constructor.getAnnotations()) {
annotations.add(handleAnnotation(annotation));
}
List<Map<String,Object>> modifiers = new ArrayList<>();
for(Modifier modifier: constructor.getModifiers()) {
modifiers.add(handleModifier(modifier));
}
object.put("'key.modifiers'", modifiers);
object.put("'key.annotations'", annotations);
int count = 1;
List<Map<String,Object>> parameters = new ArrayList<>();
for(Parameter parameter: constructor.getParameters()) {
Map<String,Object> handledParameter = handleParameter(parameter);
handledParameter.put("'key.position'", count);
parameters.add(handledParameter);
count++;
}
object.put("'key.parameters'", parameters); //TODO: parameters are added, why are they missing? missing from swift??
//String usr = constructor.getDeclarationAsString();
String usr;
try {
ResolvedConstructorDeclaration resolvedConstructor = constructor.resolve();
usr = resolvedConstructor.getQualifiedSignature(); //TODO: why does this not always work?
} catch (UnsolvedSymbolException exception) {
//usr = resolvedMethodDeclaration.getSignature(); //TODO: add class string?
usr = constructor.getName().toString();
}
object.put("'key.usr'", "'"+usr+"'");
object.put("'key.usr'", "'"+usr+"'");
object.put("'key.kind'", "'ConstructorDeclaration'");
ArrayList<Map<String,Object>> entities = new ArrayList<>();
entities.add(handleInstruction(constructor.getBody()));
object.put("'key.entities'", entities);
return object;
}
private static Map<String,Object> handleMethod(MethodDeclaration method) {
Map<String,Object> object = new HashMap<>();
/*
method:
- name
- usr
- /annotations
- /modifiers
- ?? overridden methods
- /return type
- arguments
- instructions
*/
setStartEnd(method, object);
object.put("'key.name'", "'" + method.getNameAsString() + "'");
List<Map<String,Object>> annotations = new ArrayList<>();
for(AnnotationExpr annotation: method.getAnnotations()) {
annotations.add(handleAnnotation(annotation));
}
List<Map<String,Object>> modifiers = new ArrayList<>();
for(Modifier modifier: method.getModifiers()) {
modifiers.add(handleModifier(modifier));
}
object.put("'key.modifiers'", modifiers);
object.put("'key.annotations'", annotations);
method.getDeclarationAsString();
method.getBody(); // handle instructions
int count = 1;
List<Map<String,Object>> parameters = new ArrayList<>();
for(Parameter parameter: method.getParameters()) {
Map<String,Object> handledParameter = handleParameter(parameter);
handledParameter.put("'key.position'", count);
parameters.add(handledParameter);
count++;
}
object.put("'key.parameters'", parameters); //TODO: parameters are added, why are they missing? missing from swift??
MethodDeclaration methodDeclaration = (MethodDeclaration)method;
ResolvedMethodDeclaration resolvedMethodDeclaration = methodDeclaration.resolve();
String type = "?";
try {
ResolvedType resolvedReturnType = resolvedMethodDeclaration.getReturnType();
String returnType = null;
if (resolvedReturnType.isPrimitive()) {
returnType = resolvedReturnType.asPrimitive().name();
} else if (resolvedReturnType.isReferenceType()) {
returnType = resolvedReturnType.asReferenceType().getQualifiedName();
} else {
returnType = "not defined!";
}
type = returnType;
} catch (UnsolvedSymbolException e) {
//
type = "??notdefined";
}
//String declaringType = resolvedMethodDeclaration.declaringType().getQualifiedName();
String usr;
try {
usr = resolvedMethodDeclaration.getQualifiedSignature(); //TODO: why does this not always work?
} catch (UnsolvedSymbolException exception) {
//usr = resolvedMethodDeclaration.getSignature(); //TODO: add class string?
usr = resolvedMethodDeclaration.getName();
}
object.put("'key.usr'", "'"+usr+"'");
object.put("'key.type'", "'"+type+"'");
if(method.isStatic()) {
object.put("'key.kind'", "'StaticMethodDeclaration'");
} else {
object.put("'key.kind'", "'InstanceMethodDeclaration'");
}
//TODO: add something else
ArrayList<Map<String,Object>> entities = new ArrayList<>();
if(method.getBody().isPresent()) {
entities.add(handleInstruction(method.getBody().get()));
}
object.put("'key.entities'", entities);
return object;
}
private static List<Map<String,Object>> handleVariable(FieldDeclaration field, String classUsr) {
List<Map<String,Object>> objects = new ArrayList<>();
NodeList<VariableDeclarator> variables = field.getVariables();
List<Map<String,Object>> annotations = new ArrayList<>();
for(AnnotationExpr annotation: field.getAnnotations()) {
annotations.add(handleAnnotation(annotation));
}
List<Map<String,Object>> modifiers = new ArrayList<>();
for(Modifier modifier: field.getModifiers()) {
modifiers.add(handleModifier(modifier));
}
for(VariableDeclarator variable: variables) {
Map<String,Object> object = new HashMap<>();
try {
ResolvedValueDeclaration resolvedValueDeclaration = variable.resolve();
ResolvedType type = resolvedValueDeclaration.getType();
resolvedValueDeclaration.getName();
if (type.isPrimitive()) {
object.put("'key.type'", "'" + type.asPrimitive().name() + "'");
} else if (type.isReferenceType()) {
ResolvedReferenceType refType = type.asReferenceType();
refType.getQualifiedName();
object.put("'key.typeUsr'", "'" + refType.getQualifiedName() + "'");
object.put("'key.type'", "'" + refType.getQualifiedName() + "'");
}
} catch (UnsolvedSymbolException ex) {
object.put("'key.type'", "'??unresolved'");
}
object.put("'key.name'", "'" + variable.getNameAsString() + "'");
object.put("'key.usr'", "'" + classUsr + "." + variable.getNameAsString() + "'");
setStartEnd(field, object);
object.put("'key.modifiers'", modifiers);
object.put("'key.annotations'", annotations);
if(field.isStatic()) {
object.put("'key.kind'", "'StaticVariableDeclaration'");
} else {
object.put("'key.kind'", "'InstanceVariableDeclaration'");
}
objects.add(object);
}
return objects;
}
private static Map<String,Object> handleAnnotation(AnnotationExpr node) {
Map<String,Object> object = new HashMap<>();
setStartEnd(node, object);
String name = node.getNameAsString();
object.put("'key.name'", "'" + name + "'");
object.put("'key.kind'", "'Annotation'");
return object;
}
private static Map<String,Object> handleModifier(Modifier node) {
Map<String,Object> object = new HashMap<>();
setStartEnd(node, object);
String name = node.getKeyword().name();
object.put("'key.name'", "'" + name + "'");
object.put("'key.kind'", "'Modifier'");
return object;
}
private static Map<String,Object> handeParent(ClassOrInterfaceType type) {
Map<String,Object> object = new HashMap<>();
setStartEnd(type, object);
String qualifiedName;
try {
ResolvedReferenceType resolvedType = type.resolve();
qualifiedName = resolvedType.getQualifiedName();
} catch (UnsolvedSymbolException exception) {
qualifiedName = type.getNameWithScope();
}
String name = type.getNameAsString();
object.put("'key.name'", "'" + name + "'");
object.put("'key.usr'", "'" + qualifiedName + "'");
object.put("'key.kind'", "'ClassReference'"); //TODO: add distinction if it is a class or interface?
return object;
}
private static List<Map<String,Object>> handleClass(ClassOrInterfaceDeclaration node) {
List<Map<String,Object>> objects = new ArrayList<>();
Map<String,Object> object = new HashMap<>();
setStartEnd(node, object);
object.put("'key.name'", "'" + node.getNameAsString() + "'");
if(node.isInterface()) {
object.put("'key.kind'", "'InterfaceDeclaration'");
} else {
object.put("'key.kind'", "'ClassDeclaration'");
}
if(node.getFullyQualifiedName().isPresent()) {
object.put("'key.usr'", "'" + node.getFullyQualifiedName().get() + "'");
}
object.put("'key.name'", "'" + node.getNameAsString() + "'");
List<Map<String,Object>> subEntities = new ArrayList<>();
for(BodyDeclaration member: node.getMembers()) {
if( member instanceof ConstructorDeclaration) {
subEntities.add(handleConstructor((ConstructorDeclaration) member));
}
}
for(MethodDeclaration method: node.getMethods()) {
subEntities.add(handleMethod(method));
}
for(FieldDeclaration fieldDeclaration: node.getFields()) {
subEntities.addAll(handleVariable(fieldDeclaration, node.getFullyQualifiedName().get()));
}
try {
ResolvedReferenceTypeDeclaration resolvedClass = node.resolve();
for(MethodUsage methodUsage: resolvedClass.getAllMethods()) {
ResolvedMethodDeclaration method = methodUsage.getDeclaration();
if(method.accessSpecifier() != AccessSpecifier.PRIVATE && !method.declaringType().equals(resolvedClass.asType())) {
// add inherited methods as declarations
Map<String, Object> methodObject = new HashMap<>();
methodObject.put("'key.name'", "'" + method.getName() + "'");
if (method.isStatic()) {
methodObject.put("'key.kind'", "'StaticMethodDeclaration'");
} else {
methodObject.put("'key.kind'", "'InstanceMethodDeclaration'");
}
methodObject.put("'key.usr'", "'" + method.getQualifiedSignature() + "'");
methodObject.put("'key.isMethodReference'", 1);
subEntities.add(methodObject);
}
}
} catch (UnsolvedSymbolException exception) {
// if we cannot resolve class, we cannot find inherited methods, so currently fail silently
}
object.put("'key.entities'", subEntities);
List<Map<String,Object>> annotations = new ArrayList<>();
for(AnnotationExpr annotationExpr: node.getAnnotations()) {
annotations.add(handleAnnotation(annotationExpr));
}
object.put("'key.annotations'", annotations);
List<Map<String,Object>> parents = new ArrayList<>();
for(ClassOrInterfaceType type: node.getExtendedTypes()) {
parents.add(handeParent(type));
}
for(ClassOrInterfaceType type: node.getImplementedTypes()) {
parents.add(handeParent(type));
}
object.put("'key.parents'", parents);
List<Map<String,Object>> modifiers = new ArrayList<>();
for(Modifier modifier: node.getModifiers()) {
modifiers.add(handleModifier(modifier));
}
object.put("'key.modifiers'", modifiers);
objects.add(object);
for(Node child: node.getChildNodes()) {
if(child.getClass() == ClassOrInterfaceDeclaration.class) {
ClassOrInterfaceDeclaration nestedClass = (ClassOrInterfaceDeclaration)child;
objects.addAll(handleClass(nestedClass));
}
if(child.getClass() == EnumDeclaration.class) {
EnumDeclaration nestedClass = (EnumDeclaration)child;
objects.addAll(handleEnum(nestedClass));
}
}
return objects;
}
public static List<Map<String,Object>> handleEnum(EnumDeclaration node) {
List<Map<String,Object>> objects = new ArrayList<>();
Map<String,Object> object = new HashMap<>();
setStartEnd(node, object);
object.put("'key.name'", "'" + node.getNameAsString() + "'");
object.put("'key.kind'", "'EnumDeclaration'");
if(node.getFullyQualifiedName().isPresent()) {
object.put("'key.usr'", "'" + node.getFullyQualifiedName().get() + "'");
}
object.put("'key.name'", "'" + node.getNameAsString() + "'");
List<Map<String,Object>> subEntities = new ArrayList<>();
for(MethodDeclaration method: node.getMethods()) {
subEntities.add(handleMethod(method));
}
for(FieldDeclaration fieldDeclaration: node.getFields()) {
subEntities.addAll(handleVariable(fieldDeclaration, node.getFullyQualifiedName().get()));
}
object.put("'key.entities'", subEntities);
List<Map<String,Object>> annotations = new ArrayList<>();
for(AnnotationExpr annotationExpr: node.getAnnotations()) {
annotations.add(handleAnnotation(annotationExpr));
}
object.put("'key.annotations'", annotations);
List<Map<String,Object>> parents = new ArrayList<>();
for(ClassOrInterfaceType type: node.getImplementedTypes()) {
parents.add(handeParent(type));
}
object.put("'key.parents'", parents);
List<Map<String,Object>> modifiers = new ArrayList<>();
for(Modifier modifier: node.getModifiers()) {
modifiers.add(handleModifier(modifier));
}
object.put("'key.modifiers'", modifiers);
objects.add(object);
for(Node child: node.getChildNodes()) {
if(child.getClass() == ClassOrInterfaceDeclaration.class) {
ClassOrInterfaceDeclaration nestedClass = (ClassOrInterfaceDeclaration)child;
objects.addAll(handleClass(nestedClass));
}
if(child.getClass() == EnumDeclaration.class) {
EnumDeclaration nestedClass = (EnumDeclaration)child;
objects.addAll(handleEnum(nestedClass));
}
}
return objects;
}
private static List<Map<String,Object>> handleCompilationUnit(CompilationUnit cu) {
List<Map<String,Object>> classes = new ArrayList<>();
NodeList<TypeDeclaration<?>> types = cu.getTypes();// --> other way of doing it
for(TypeDeclaration<?> type: types) {
if(type.isClassOrInterfaceDeclaration()) {
List<Map<String,Object>> objects = handleClass((ClassOrInterfaceDeclaration) type);
classes.addAll(objects);
} else if(type.isEnumDeclaration()) {
List<Map<String,Object>> objects = handleEnum((EnumDeclaration) type);
classes.addAll(objects);
} else if(type.isAnnotationDeclaration()) {
//TODO: what do we do here?
}
}
/*
List<Node> children = cu.getChildNodes();
for(Node child: children) {
// if PackageDeclaration --> which package it belongs to
// if ImportDeclaration --> which classes/libraries are imported
// if ClassOrInterfaceDeclaration --> class types
// if AnnotationDeclaration --> annotations?
// if EnumDeclaration --> enum --> TODO: implement enum
if(child.getClass() == ClassOrInterfaceDeclaration.class) {
Map<String,Object> foundClass = handleClass((ClassOrInterfaceDeclaration) child);
classes.add(foundClass);
}
}
*/
return classes;
}
/*
public static Map<String,Object> handleNode(Node node) {
Map<String,Object> object = new HashMap<>();
String kind = node.getClass().toString();
String name = null; // to be set
String usr = null; // to be set
String type = null; // to be set
ArrayList<Map<String,Object>> entities = new ArrayList<>();
if(node.getClass() == MethodDeclaration.class) {
MethodDeclaration method = (MethodDeclaration) node;
object = handleMethod(method);
} else if(node.getClass() == FieldDeclaration.class) {
FieldDeclaration variable = (FieldDeclaration)node;
object = handleVariable(variable);
} else {
//TODO: check what from here needs to stay
for(Node child: node.getChildNodes()) {
if (child.getClass() == SimpleName.class) {
SimpleName simpleName = (SimpleName) child;
name = simpleName.asString();
} else if (child.getClass() == Name.class) {
Name simpleName = (Name) child;
name = simpleName.asString();
} else {
Map<String, Object> childObject = handleNode(child);
entities.add(childObject);
}
}
if(node.getClass() == NameExpr.class) {
NameExpr nameExpr = (NameExpr)node;
try {
ResolvedType resolvedType = nameExpr.calculateResolvedType();
if (resolvedType.isPrimitive()) {
type = resolvedType.asPrimitive().name();
} else {
if (resolvedType.isReferenceType()) {
String qualifiedName = resolvedType.asReferenceType().getQualifiedName();
type = qualifiedName;
}
}
} catch (UnsolvedSymbolException e) {
type = "?";
} catch (UnsupportedOperationException e) {
type = "?";
} catch (RuntimeException e) {
type = "?";
}
try {
ResolvedValueDeclaration resolvedValueDeclaration = nameExpr.resolve();
if(resolvedValueDeclaration.isField()) {
ResolvedFieldDeclaration resolvedFieldDeclaration = resolvedValueDeclaration.asField();
String declaringTypeName = resolvedFieldDeclaration.declaringType().getQualifiedName();
usr = declaringTypeName + "." + nameExpr.getName();
}
} catch (UnsolvedSymbolException exception) {
//System.out.println("Cannot solve: " + nameExpr);
} catch (UnsupportedOperationException e) {
//
}
}
}
//TODO: move this under method handling
/*
if(node.getClass() == MethodCallExpr.class) {
MethodCallExpr methodCallExpr = (MethodCallExpr)node;
String scope = "";
try {
if (methodCallExpr.getScope().isPresent()) {
Expression methodScope = methodCallExpr.getScope().get();
ResolvedType resolvedType = methodScope.calculateResolvedType();
if (resolvedType.isReferenceType()) {
scope = resolvedType.asReferenceType().getQualifiedName();
} else {
scope = resolvedType.toString();
}
}
} catch (UnsolvedSymbolException e) {
scope = "?";
} catch (RuntimeException e) {
scope = "??";
}
String methodName = methodCallExpr.getNameAsString();
String fullName = scope + "." + methodName;
usr = fullName;
} else if(node.getClass() == FieldAccessExpr.class) {
FieldAccessExpr fieldAccessExpr = (FieldAccessExpr)node;
Expression fieldScope = fieldAccessExpr.getScope();
String scope;
try {
scope = fieldScope.calculateResolvedType().asReferenceType().getQualifiedName();
} catch (UnsolvedSymbolException e) {
scope = "?";
} catch (UnsupportedOperationException e) {
scope = "?";
} catch (RuntimeException e) {
scope = "?";
}
String fieldName = fieldAccessExpr.getNameAsString();
String fullName = scope + "." + fieldName;
usr = fullName;
}
*/
/*
int startLine;
int endLine;
try {
Optional<Range> optRange = node.getRange();
Range range = optRange.get();
startLine = range.begin.line;
endLine = range.end.line;
} catch (NoSuchElementException e) {
startLine = -1;
endLine = -1;
}
if(usr == null) {
usr = name;
}
object.put("'key.name'", "'"+name+"'");
object.put("'key.usr'", "'"+usr+"'");
object.put("'key.type'", "'"+type+"'");
object.put("'key.kind'", "'"+kind+"'");
object.put("'key.entities'", entities);
object.put("'key.startLine'", startLine);
object.put("'key.endLine'", endLine);
return object;
}
*/
}
| 36,292 | 36.570393 | 134 | java |
tquery | tquery-master/src/test/java/GroupQueryTest.java | import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.group.GroupQuery;
import java.io.IOException;
import java.io.StringReader;
import static jolie.js.JsUtils.parseJsonIntoValue;
public class GroupQueryTest {
public static void main( String[] args ) {
Value v = Value.create();
try {
parseJsonIntoValue(
new StringReader(
"{\"data\":[" +
"{\"year\":[2020],\"month\":[11],\"day\":[27],\"quality\":[\"poor\"]}," +
"{\"year\":[2020],\"month\":[11],\"day\":[29],\"quality\":[\"good\"]}," +
"{\"year\":[2020],\"month\":[11],\"day\":[29],\"quality\":[\"good\"]}" +
"]," +
"\"query\":{" +
"\"groupBy\":[" +
"{\"dstPath\":\"day\",\"srcPath\":\"day\",}" +
"]," +
"\"aggregate\":[" +
"{\"dstPath\":\"quality\"," +
"\"srcPath\":\"quality\"," +
"\"distinct\":false" +
"}]" +
"}" +
"}"
),
v,
false
);
System.out.println( Utils.valueToPrettyString( GroupQuery.group( v ) ) );
} catch ( IOException | FaultException e ) {
e.printStackTrace();
}
}
}
| 1,284 | 27.555556 | 85 | java |
tquery | tquery-master/src/test/java/PipelineQueryTest.java | import jolie.js.JsUtils;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.pipeline.PipelineQuery;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
public class PipelineQueryTest {
public static void main( String[] args ) throws IOException {
sleeplogQuery();
}
public static ValueVector biometricQuery() throws IOException {
String jsonString = Files.readString( Path.of( "release_test/data/biometric-0.json" ) );
StringReader reader = new StringReader( jsonString );
Value data = Value.create();
JsUtils.parseJsonIntoValue( reader, data, false );
jsonString = Files.readString( Path.of( "release_test/data/biometric-query.json" ) );
jsonString = jsonString.replaceAll( "//.+", "" );
reader = new StringReader( jsonString );
Value pipeline = Value.create();
JsUtils.parseJsonIntoValue( reader, pipeline, false );
Value request = Value.create();
request.children().put( "data", data.getChildren( "_" ) );
request.children().put( "pipeline", pipeline.getChildren( "_" ) );
// System.out.println( Utils.valueToPrettyString( request ) );
try {
Value response = PipelineQuery.pipeline( request );
// System.out.println( Utils.valueToPrettyString( response ) );
return response.getChildren( TQueryExpression.ResponseType.RESULT );
} catch ( FaultException e ) {
e.printStackTrace();
}
return null;
}
public static void sleeplogQuery() throws IOException {
String jsonString = Files.readString( Path.of( "release_test/data/sleeplog-0.json" ) );
StringReader reader = new StringReader( jsonString );
Value data = Value.create();
JsUtils.parseJsonIntoValue( reader, data, false );
jsonString = Files.readString( Path.of( "release_test/data/sleeplog-query.json" ) );
jsonString = jsonString.replaceAll( "//.+", "" );
reader = new StringReader( jsonString );
Value pipeline = Value.create();
JsUtils.parseJsonIntoValue( reader, pipeline, false );
Value request = Value.create();
request.children().put( "data", data.getChildren( "_" ) );
request.children().put( "pipeline", pipeline.getChildren( "_" ) );
request.getChildren( "pipeline" ).stream()
.filter( value -> value.hasChildren( "lookupQuery" ) )
.findAny().ifPresent( value -> {
try {
value.getFirstChild( "lookupQuery" ).children().put( "rightData", biometricQuery() );
} catch ( IOException e ) {
e.printStackTrace();
}
} );
// System.out.println( Utils.valueToPrettyString( request ) );
try {
Value response = PipelineQuery.pipeline( request );
System.out.println( Utils.valueToPrettyString( response ) );
} catch ( FaultException e ) {
e.printStackTrace();
}
}
}
| 2,892 | 31.875 | 90 | java |
tquery | tquery-master/src/test/java/LookupQueryTest.java | import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.lookup.LookupQuery;
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import static jolie.js.JsUtils.parseJsonIntoValue;
public class LookupQueryTest {
static final String PATH_TO_RESOURCES = "src/test/resources/lookup";
static final String QUERY = "query";
static final String RESULT = "result";
@Test
public void testEmptyDestPath() throws Exception {
final String fileName = "lookup_empty_dest_path.json";
test(fileName);
}
@Test
public void testEmptyLeftPath() throws Exception {
final String fileName = "lookup_empty_left_path.json";
test(fileName);
}
@Test
public void testEmptyRightPath() throws Exception {
final String fileName = "lookup_empty_right_path.json";
test(fileName);
}
@Test
public void testEmptyLeftData() throws Exception {
final String fileName = "lookup_empty_left_array.json";
test(fileName);
}
@Test
public void testEmptyRightData() throws Exception {
final String fileName = "lookup_empty_right_array.json";
test(fileName);
}
@Test
public void testSimplePath() throws Exception {
final String fileName = "lookup_simple_path.json";
test(fileName);
}
@Test
public void testCompoundPath() throws Exception {
final String fileName = "lookup_compound_path.json";
test(fileName);
}
private void test(String fileName) throws Exception {
Value value = Value.create();
parseJsonIntoValue(new FileReader(String.format("%s/%s", PATH_TO_RESOURCES, fileName)), value, false);
Value lookupRequest = value.getChildren(QUERY).first();
ValueVector actualResult = LookupQuery.lookup(lookupRequest).getChildren(RESULT);
ValueVector expectedResult = value.getChildren(RESULT);
String assertionMessage = String.format("Error in test %s: " +
"Actual result does not match the expected result.\n" +
"Expected: %s \n" +
"Actual: %s \n",
fileName, Utils.valueToPrettyString(expectedResult.first()), Utils.valueToPrettyString(actualResult.first()));
assert (Utils.checkVectorEquality(actualResult, expectedResult)) : assertionMessage;
}
}
| 2,463 | 30.589744 | 126 | java |
tquery | tquery-master/src/test/java/UnwindQueryTest.java | import jolie.js.JsUtils;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.unwind.UnwindQuery;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
public class UnwindQueryTest {
public static void main( String[] args ) throws IOException {
String jsonString = Files.readString( Path.of( "tests/data/sleeplog-5.json" ) );
StringReader reader = new StringReader( jsonString );
Value data = Value.create();
JsUtils.parseJsonIntoValue( reader, data, false );
ValueVector query = ValueVector.create();
query.get( 0 ).setValue( "M.D.L" );
Value request = Value.create();
request.children().put( "data", data.getChildren( "_" ) );
request.children().put( "query", query );
// System.out.println( Utils.valueToPrettyString( request ) );
long start = System.currentTimeMillis();
try {
Value response = UnwindQuery.unwind( request );
System.out.println( "Finished after: " + ( System.currentTimeMillis() - start ) + "ms" );
System.out.println(
"data: " + request.getFirstChild( "data" ).getChildren( "M" ).size() +
", result: " + response.getChildren( "result" ).size()
);
// System.out.println( Utils.valueToPrettyString( response ) );
} catch ( FaultException e ) {
e.printStackTrace();
}
}
}
| 1,433 | 30.173913 | 92 | java |
tquery | tquery-master/src/test/java/PipelineQueryTestBenchmark.java | import jolie.js.JsUtils;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.TQueryExpression;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.pipeline.PipelineQuery;
import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;
public class PipelineQueryTestBenchmark {
public static void main( String[] args ) throws IOException {
Value biometricData = getValueFromJson( "release_test/data/biometric-5.json" );
Value biometricQuery = getValueFromJson( "release_test/data/biometric-query.json" );
Value sleeplogData = getValueFromJson( "release_test/data/sleeplog-5.json" );
Value sleeplogQuery = getValueFromJson( "release_test/data/sleeplog-query.json" );
IntStream.range( 0, 3 ).mapToDouble( i ->
IntStream.range( 0, 20 ).parallel().map( _i -> {
LinkedList< ValueVector > lookupData = new LinkedList<>();
long bio_start = System.currentTimeMillis();
lookupData.add( performQuery( biometricData, biometricQuery ) );
long bioTime = System.currentTimeMillis() - bio_start;
long sleep_start = System.currentTimeMillis();
performQuery( sleeplogData, sleeplogQuery, lookupData );
long sleepTime = System.currentTimeMillis() - sleep_start;
long queryTime = bioTime + sleepTime;
System.out.println( "Benchmark time: " + queryTime + " milliseconds." );
return (int) queryTime;
} ).average().getAsDouble()
).average().ifPresent( avg -> System.out.println( "Benchmarks average: " + avg + " milliseconds" ) );
}
public static Value getValueFromJson( String filename ) throws IOException {
String jsonString = Files.readString( Path.of( filename ) );
StringReader reader = new StringReader( jsonString );
Value v = Value.create();
JsUtils.parseJsonIntoValue( reader, v, false );
return v;
}
public static ValueVector performQuery( Value data, Value pipeline ) {
return performQuery( data, pipeline, Collections.emptyList() );
}
public static ValueVector performQuery( Value data, Value pipeline, List< ValueVector > lookupData ) {
Value request = Value.create();
request.children().put( "data", data.getChildren( "_" ) );
request.children().put( "pipeline", pipeline.getChildren( "_" ) );
// System.out.println( Utils.valueToPrettyString( request ) );
request.getChildren( "pipeline" ).stream()
.filter( value -> value.hasChildren( "lookupQuery" ) )
.forEach( value ->
value.getFirstChild( "lookupQuery" ).children().put( "rightData", lookupData.remove( 0 ) )
);
try {
Value response = PipelineQuery.pipeline( request );
if ( data.getChildren( "_" ).get( 0 ).hasChildren("y") ) {
System.out.println(
"#q:" + response.getFirstChild( "result" ).getChildren( "quality" ).size()
+ "; #t:" + response.getFirstChild( "result" ).getChildren( "temperatures" ).size() );
}
// System.out.println( Utils.valueToPrettyString( response ) );
return response.getChildren( TQueryExpression.ResponseType.RESULT );
} catch ( FaultException e ) {
e.printStackTrace();
}
return null;
}
}
| 3,308 | 37.476744 | 103 | java |
tquery | tquery-master/src/test/java/RecursiveBackpressure.java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class RecursiveBackpressure {
private static List< ? > listOfList( Integer max ) {
List< ? >[] l = new List<?>[ max ];
IntStream.range( 0, max )
// .parallel()
.forEach( i -> l[ i ] = listOfList( max - 1 ) );
return Arrays.asList( l );
}
public static void main( String[] args ) {
long s = System.currentTimeMillis();
List< ? > l = listOfList( 11 );
long e = System.currentTimeMillis();
// System.out.println( l );
System.out.println( "done: " + ( e - s ) );
}
}
| 617 | 21.888889 | 54 | java |
tquery | tquery-master/src/test/java/DependableTasks.java | import java.sql.SQLOutput;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DependableTasks {
private static List< Task< List< ? > > > _listOfList( Integer max, ExecutorService executorService ) {
return IntStream.range( 0, max ).mapToObj( i -> {
List< Task< List < ? > > > tasks = _listOfList( max - 1, executorService );
Task< List < ? > > task = new Task< List< ? > >( t -> {
List< List< ? > > list = new LinkedList<>();
IntStream.range( 0, tasks.size() ).forEach( j ->
list.add( j, t.get( List.class, "sublist-" + j ) ) );
return list;
} );
IntStream.range( 0, tasks.size() ).forEach( j -> task.addDependency( "sublist-" + j, tasks.get( j ).future() ) );
task.run( executorService );
return task;
} ).collect( Collectors.toList() );
}
private static List< ? > listOfList( Integer max, ExecutorService executorService ) {
return _listOfList( max, executorService ).stream().map( t -> {
try {
return t.future().get();
} catch ( InterruptedException | ExecutionException e ) {
e.printStackTrace();
return Collections.emptyList();
}
} ).collect( Collectors.toList() );
}
public static void simpleExample() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool( 5 );
Task< Integer > ta = new Task< Integer >( t -> {
try {
Thread.sleep( 1000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
System.out.println( "A executed" );
return 5;
} ).run( executorService );
Task< Integer > tb = new Task< Integer >( t -> 5 + t.get( Integer.class, "A" ) )
.addDependency( "A", ta.future() )
.run( executorService );
System.out.println( tb.future().get() );
executorService.shutdown();
}
public static void main( String[] args ) {
ExecutorService executorService = Executors.newWorkStealingPool( 4 );
long s = System.currentTimeMillis();
List< ? > l = listOfList( 10, executorService );
long e = System.currentTimeMillis();
System.out.println( l );
System.out.println( "done: " + ( e - s ) );
executorService.shutdown();
}
}
class Task< T > {
private final Map< String, Object > data;
private final Map< String, CompletableFuture< Object > > dependencies;
private final Runnable r;
private final CompletableFuture< T > f;
private final String name;
public Task( Function< Task< T >, T > c ) {
this.data = new HashMap<>();
this.dependencies = new HashMap<>();
this.f = new CompletableFuture<>();
this.r = () -> f.complete( c.apply( this ) );
this.name = UUID.randomUUID().toString();
}
public Task( Function< Task< T >, T > c, String name ) {
this.data = new HashMap<>();
this.dependencies = new HashMap<>();
this.f = new CompletableFuture<>();
this.r = () -> f.complete( c.apply( this ) );
this.name = name;
}
public Task< T > addDependency( String name, CompletableFuture< ? > f ) {
this.dependencies.put( name, ( CompletableFuture< Object > ) f );
return this;
}
public Task< T > run( ExecutorService e ) {
e.submit( new Runnable() {
@Override
public void run() {
if ( dependencies.keySet().size() > 0 ) {
List< String > keys = new ArrayList<>( dependencies.keySet() );
keys.forEach( key -> {
if ( dependencies.get( key ).isDone() ) {
try {
data.put( key, dependencies.get( key ).get() );
dependencies.remove( key );
} catch ( Exception ex ) {
ex.printStackTrace();
e.shutdown();
}
}
} );
e.submit( this );
} else {
e.submit( r );
}
}
} );
return this;
}
public < R > R get( Class< R > c, String name ) {
return ( R ) data.get( name );
}
public CompletableFuture< T > future() {
return f;
}
} | 3,932 | 28.795455 | 120 | java |
tquery | tquery-master/src/test/java/MatchQueryTest.java | import jolie.runtime.FaultException;
import jolie.runtime.Value;
import jolie.runtime.ValueVector;
import joliex.tquery.engine.common.Utils;
import joliex.tquery.engine.group.GroupQuery;
import joliex.tquery.engine.match.MatchQuery;
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import static jolie.js.JsUtils.parseJsonIntoValue;
public class MatchQueryTest {
static final String PATH_TO_RESOURCES = "src/test/resources/match";
static final String QUERY = "query";
static final String RESULT = "result";
@Test
public void testEmptyDestPath() throws Exception {
final String fileName = "lookup_empty_dest_path.json";
test( fileName );
}
@Test
public void testEmptyLeftPath() throws Exception {
final String fileName = "lookup_empty_left_path.json";
test( fileName );
}
@Test
public void testEmptyRightPath() throws Exception {
final String fileName = "lookup_empty_right_path.json";
test( fileName );
}
@Test
public void testEmptyLeftData() throws Exception {
final String fileName = "lookup_empty_left_array.json";
test( fileName );
}
@Test
public void testEmptyRightData() throws Exception {
final String fileName = "lookup_empty_right_array.json";
test( fileName );
}
@Test
public void testSimplePath() throws Exception {
final String fileName = "lookup_simple_path.json";
test( fileName );
}
@Test
public void testCompoundPath() throws Exception {
final String fileName = "lookup_compound_path.json";
test( fileName );
}
private void test( String fileName ) throws Exception {
Value value = Value.create();
parseJsonIntoValue( new FileReader( String.format( "%s/%s", PATH_TO_RESOURCES, fileName ) ), value, false );
Value matchRequest = value.getChildren( QUERY ).first();
ValueVector actualResult = MatchQuery.match( matchRequest ).getChildren( RESULT );
ValueVector expectedResult = value.getChildren( RESULT );
String assertionMessage = String.format( "Error in test %s: " +
"Actual result does not match the expected result.\n" +
"Expected: %s \n" +
"Actual: %s \n",
fileName, Utils.valueToPrettyString( expectedResult.first() ), Utils.valueToPrettyString( actualResult.first() ) );
assert ( Utils.checkVectorEquality( actualResult, expectedResult ) ) : assertionMessage;
}
public static void main( String[] args ) {
Value v = Value.create();
try {
parseJsonIntoValue( new StringReader( "{\"data\": " + data + ", \"query\" : " + query + "}" ), v, false );
System.out.println( Utils.valueToPrettyString( MatchQuery.match( v ) ) );
} catch ( IOException | FaultException e ) {
e.printStackTrace();
}
}
private static final String data = "[\n" +
" {\n" +
" \"date\": [20201127],\n" +
" \"t\":[\n" +
" 37,\n" +
" 36,\n" +
" 36\n" +
" ],\n" +
" \"hr\":[\n" +
" 64,\n" +
" 58,\n" +
" 57\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"date\": [20201128],\n" +
" \"t\":[\n" +
" 37,\n" +
" 36,\n" +
" 36\n" +
" ],\n" +
" \"hr\":[\n" +
" 64,\n" +
" 58,\n" +
" 57\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"date\": [20201129],\n" +
" \"t\":[\n" +
" 37,\n" +
" 36,\n" +
" 36\n" +
" ],\n" +
" \"hr\":[\n" +
" 64,\n" +
" 58,\n" +
" 57\n" +
" ]\n" +
" },\n" +
" {\n" +
" \"date\": [20201130],\n" +
" \"t\":[\n" +
" 37,\n" +
" 36,\n" +
" 36\n" +
" ],\n" +
" \"hr\":[\n" +
" 64,\n" +
" 58,\n" +
" 57\n" +
" ]\n" +
" }\n" +
" ]";
private static final String query = "{\n" +
" \"or\": {\n" +
" \"left\": {\n" +
" \"equal\": {\n" +
" \"path\": \"date\",\n" +
" \"value\": 20201128\n" +
" }\n" +
" },\n" +
" \"right\": {\n" +
" \"or\": {\n" +
" \"left\": {\n" +
" \"equal\": {\n" +
" \"path\": \"date\",\n" +
" \"value\": 20201129\n" +
" }\n" +
" },\n" +
" \"right\": {\n" +
" \"equal\": {\n" +
" \"path\": \"date\",\n" +
" \"value\": 20201130\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
}
| 4,831 | 26.611429 | 121 | java |
tquery | tquery-master/src/test/java/old/UnwindQueryTest.java | package old;
class UnwindQueryTest {
//TODO (These tests are deprecated and need to be rewritten)
/*@Test
void test() {
Value unwindrequest = Value.create();
unwindrequest.getNewChild("query").setValue("awards.award");;
Value data = unwindrequest.getNewChild("data");
Value name = data.getNewChild("name");
name.getNewChild("first").setValue("Kristen");
name.getNewChild("last").setValue("Nyygard");
Value awards = data.getNewChild("awards");
awards.getNewChild("award").setValue("Rosing Prize");
awards.getNewChild("award").setValue("Turing Award");
awards.getNewChild("award").setValue("IEEE John von Neumann Medal");
ValueVector result = UnwindQuery.unwind(unwindrequest);
result.forEach(it -> System.out.println(it.toPrettyString()));
}*/
}
| 865 | 29.928571 | 76 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/GroupService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.group.GroupQuery;
public class GroupService {
static Value group( Value request ) throws FaultException {
return GroupQuery.group( request );
}
}
| 2,060 | 56.25 | 81 | java |
tquery | tquery-master/src/main/java/joliex/tquery/engine/ProjectService.java | /*******************************************************************************
* Copyright (C) 2018 by Larisa Safina <[email protected]> *
* Copyright (C) 2018 by Stefano Pio Zingaro <[email protected]> *
* Copyright (C) 2018 by Saverio Giallorenzo <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
* For details about the authors of this software, see the AUTHORS file. *
*******************************************************************************/
package joliex.tquery.engine;
import jolie.runtime.FaultException;
import jolie.runtime.Value;
import joliex.tquery.engine.project.ProjectQuery;
public class ProjectService {
static Value project( Value request ) throws FaultException {
return ProjectQuery.project( request );
}
} | 2,072 | 58.228571 | 81 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.