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/lustre/BindPre.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.lustre; import java.util.ArrayList; import java.util.List; import jkind.lustre.BoolExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.RealExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.TypeAwareAstMapVisitor; import jkind.translation.FlattenPres; /** * Bind expressions appearing in 'pre'. */ public class BindPre extends TypeAwareAstMapVisitor { public static Program program(Program program) { return new FlattenPres().visit(program); } private List<VarDecl> newLocals = new ArrayList<>(); private List<Equation> newEquations = new ArrayList<>(); private int counter = 0; @Override public Node visit(Node e) { NodeBuilder builder = new NodeBuilder(super.visit(e)); builder.addLocals(newLocals); builder.addEquations(newEquations); return builder.build(); } private IdExpr getFreshId() { return new IdExpr("~bindPre" + counter++); } @Override public Expr visit(UnaryExpr e) { Expr x = e.expr.accept(this); if (e.op == UnaryOp.PRE && !(x instanceof IdExpr || x instanceof IntExpr || x instanceof BoolExpr || x instanceof RealExpr)) { IdExpr id = getFreshId(); newLocals.add(new VarDecl(id.id, getType(e.expr))); newEquations.add(new Equation(id,x)); return new UnaryExpr(e.op, id); } else { return new UnaryExpr(e.op,x); } } }
1,916
27.61194
134
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/ACExprCtx.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.lustre; import java.util.ArrayList; import java.util.Collection; import java.util.List; import fuzzm.util.IDString; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.NamedType; public class ACExprCtx extends ExprCtx { protected List<Expr> exprList = new ArrayList<>(); protected BinaryOp op; public ACExprCtx(NamedType type, BinaryOp op, Expr defaultValue) { super(type,defaultValue); this.op = op; } public ACExprCtx(NamedType type, BinaryOp op) { this(type, op, ExprCtx.defaultValue(type)); } public ACExprCtx(BinaryOp op, ExprCtx arg) { super(arg); this.op = op; add(arg.getExpr()); } public ACExprCtx(ACExprCtx arg) { super(arg); exprList = new ArrayList<>(arg.exprList); op = arg.op; } private Expr treeExprRec(int min, int max) { int span = max - min; if (span == 0) return exprList.get(min); if (span == 1) return new BinaryExpr(exprList.get(min),op,exprList.get(max)); int half = span/2; Expr left = treeExprRec(min,min+half); Expr right = treeExprRec(min+half+1,max); return new BinaryExpr(left,op,right); } private Expr treeExpr() { int size = exprList.size(); if (size <= 0) return super.getExpr(); return treeExprRec(0,size-1); } private Expr bindExprRec(int min, int max,int index, IDString base) { int span = max - min; if (span == 0) return exprList.get(min); if (span == 1) return new BinaryExpr(exprList.get(min),op,exprList.get(max)); int half = span/2; Expr left = bindExprRec(min,min+half,index*2+1,base); Expr right = bindExprRec(min+half+1,max,index*2,base); Expr res = define(base.index(index),type,new BinaryExpr(left,op,right)); return res; } @Override public ExprCtx bind(IDString base) { int size = exprList.size(); if (size <= 0) return new ExprCtx(super.bind(base)); Expr lastExpr = bindExprRec(0,size-1,1,base); setExpr(lastExpr); return new ExprCtx(super.bind(base)); } @Override public void setExpr(Expr expr) { exprList.clear(); exprList.add(expr); } @Override public Expr getExpr() { Expr res = treeExpr(); return res; } public void add(Expr expr) { exprList.add(expr); } public void add(ACExprCtx expr) { assert(type.equals(expr.type)); super.add(expr); exprList.addAll(expr.exprList); } public void addAll(Collection<Expr> args) { exprList.addAll(args); } @Override public String toString() { return getExpr().toString(); } }
2,701
22.293103
79
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/LiftBooleans.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.lustre; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import fuzzm.util.PartialOrder; import jkind.lustre.Equation; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.builders.ProgramBuilder; public class LiftBooleans { Map<String,List<String>> newNodeOutputs; List<String> newOutputs; int count; private LiftBooleans(Map<String,List<String>> newNodeOutputs) { this.newNodeOutputs = newNodeOutputs; this.newOutputs = null; this.count = 0; } public static Program lift(Program program) { PartialOrder<String> order = OrderNodes.computeOrder(program); ProgramBuilder pb = new ProgramBuilder(program); LiftBooleans res = new LiftBooleans(new HashMap<String,List<String>>()); Map<String,Node> nmap = new HashMap<String,Node>(); for (Node n: program.nodes) { nmap.put(n.id,n); } for (String nodeName: order) { Node n = nmap.get(nodeName); n = res.updateNode(n); nmap.put(nodeName, n); } pb.clearNodes(); pb.addNodes(nmap.values()); return pb.build(); } private Node updateNode(Node e) { NodeBuilder nb = new NodeBuilder(e); // Transfer all boolean locals to output newOutputs = new ArrayList<String>(); count = 0; nb.clearLocals(); for (VarDecl vd: e.locals) { if (vd.type == NamedType.BOOL) { newOutputs.add(vd.id); } else { nb.addLocal(vd); } } nb.clearEquations(); for (Equation eq: e.equations) { // Update all of the equations and // collect all of the new outputs nb.addEquation(updateEquation(eq)); } List<VarDecl> outDecls = new ArrayList<VarDecl>(); for (String s: newOutputs) { outDecls.add(new VarDecl(s,NamedType.BOOL)); } nb.addOutputs(outDecls); newNodeOutputs.put(e.id, newOutputs); return nb.build(); } private Equation updateEquation(Equation e) { if (e.expr instanceof NodeCallExpr) { NodeCallExpr call = (NodeCallExpr) e.expr; List<IdExpr> lhs = new ArrayList<IdExpr>(e.lhs); assert(newNodeOutputs.containsKey(call.node)); for (String s: newNodeOutputs.get(call.node)) { String newID = "_" + call.node + count + "_" + s; newOutputs.add(newID); lhs.add(new IdExpr(newID)); } count++; e = new Equation(e.location,lhs,e.expr); } return e; } }
2,692
24.647619
74
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/ExtractProperties.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.lustre; import java.util.ArrayList; import java.util.List; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.visitors.AstIterVisitor; public class ExtractProperties extends AstIterVisitor { private String mainName; private List<Expr> properties; private ExtractProperties(String mainName, List<Expr> properties) { this.mainName = mainName; this.properties = properties; } public static List<Expr> mainProperties(String mainName, Program program) { ExtractProperties res = new ExtractProperties(mainName,new ArrayList<Expr>()); res.visit(program); return res.properties; } @Override public Void visit(Node node) { if (node.id.equals(mainName)) { List<String> oldprops = node.properties; for (String s: oldprops) { properties.add(new IdExpr(s)); } } return null; } }
1,117
21.816327
80
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/PolyConstraintCtx.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.lustre; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import fuzzm.lustre.generalize.ReMapExpr; import fuzzm.poly.AbstractPoly; import fuzzm.poly.PolyBase; import fuzzm.poly.Variable; import fuzzm.poly.VariableBoolean; import fuzzm.poly.VariableID; import fuzzm.poly.VariableRelation; import fuzzm.util.FuzzmName; import fuzzm.util.ID; import fuzzm.util.IDString; import fuzzm.util.StepExpr; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.util.BigFraction; public class PolyConstraintCtx extends BooleanCtx { public PolyConstraintCtx(Variable v, ReMapExpr remap) { VariableID vid = v.vid; IDString name = IDString.newID(vid.name.name.name); Expr check = (v instanceof VariableBoolean) ? boolCheck((VariableBoolean) v,remap) : polyCheck((VariableRelation) v, remap); IdExpr polyConstraint = constraint(name,check); this.setExpr(polyConstraint); PolyConstraintCtx.index++; } private Expr boolCheck(VariableBoolean v, ReMapExpr remap) { VariableID vid = v.vid; String name = ID.cleanString(vid.name.name.name); StepExpr vstep = remap.get(vid).iterator().next(); Expr id = new IdExpr(name); Expr polycheck = v.isNegated() ? id : new UnaryExpr(UnaryOp.NOT,id); Expr timecheck = new BinaryExpr(new IdExpr(FuzzmName.time.name()),BinaryOp.EQUAL,new IntExpr(BigInteger.valueOf(vstep.step))); Expr check = new IfThenElseExpr(timecheck,polycheck,new BoolExpr(true)); return check; } private Expr polyCheck(VariableRelation v, ReMapExpr remap) { VariableID vid = v.vid; IDString name = IDString.newID(vid.name.name.name); NamedType type = vid.name.name.type; AbstractPoly poly = v.poly; BigInteger D = poly.leastCommonDenominator(); poly = poly.subtract(new PolyBase(vid)); poly = poly.multiply(new BigFraction(D)); Map<Integer,Collection<Expr>> stepPoly = new HashMap<>(); for (VariableID pvar : poly.getVariables()) { StepExpr e = remap.get(pvar).iterator().next(); Expr vexpr = cast(pvar.name.name.type,type,e.expr); BigInteger C = poly.getCoefficient(pvar).getNumerator(); Expr vcoef = cast(NamedType.INT,type,new IntExpr(C)); Expr expr = new BinaryExpr(vcoef,BinaryOp.MULTIPLY,vexpr); Collection<Expr> vals = stepPoly.containsKey(e.step) ? stepPoly.get(e.step) : new ArrayList<>(); vals.add(expr); stepPoly.put(e.step,vals); } Expr ite = cast(NamedType.INT,type,new IntExpr(BigInteger.ZERO)); int maxtime = 0; for (Integer time: stepPoly.keySet()) { maxtime = (time > maxtime) ? time : maxtime; BigInteger zero = (time == 0) ? poly.getConstant().getNumerator() : BigInteger.ZERO; Expr res = cast(NamedType.INT,type,new IntExpr(zero)); for (Expr e: stepPoly.get(time)) { res = new BinaryExpr(e,BinaryOp.PLUS,res); } Expr cond = new BinaryExpr(new IdExpr(FuzzmName.time.name()),BinaryOp.EQUAL,new IntExpr(BigInteger.valueOf(time))); ite = new IfThenElseExpr(cond, res, ite); } IdExpr polyCoeff = this.define(name(FuzzmName.polyTerm,name), type, ite); IdExpr polyExpr = poly(name,type,polyCoeff); Expr zero = cast(NamedType.INT,type,new IntExpr(BigInteger.ZERO)); BinaryOp op = v.binaryOp(); Expr polycheck = new UnaryExpr(UnaryOp.NOT,new BinaryExpr(polyExpr,op,zero)); Expr timecheck = new BinaryExpr(new IdExpr(FuzzmName.time.name()),BinaryOp.EQUAL,new IntExpr(BigInteger.valueOf(maxtime))); Expr check = new IfThenElseExpr(timecheck,polycheck,new BoolExpr(true)); return check; } private IdExpr poly(IDString name, NamedType type, Expr expr) { IdExpr z = this.declare(name(FuzzmName.polyEval,name), type); Expr poly = new BinaryExpr(expr,BinaryOp.ARROW,new BinaryExpr(new UnaryExpr(UnaryOp.PRE,z),BinaryOp.PLUS,expr)); this.define(z, poly); return z; } private IdExpr constraint(IDString name, Expr expr) { IdExpr z = this.declare(name(FuzzmName.polyConstraint,name), NamedType.BOOL); Expr poly = new BinaryExpr(expr,BinaryOp.ARROW,new BinaryExpr(new UnaryExpr(UnaryOp.PRE,z),BinaryOp.AND,expr)); this.define(z, poly); return z; } private static long index = 0; private static IDString name(String prefix, IDString name) { return name.prefix(prefix).index(index); } private static Expr cast(NamedType src, NamedType dst, Expr e) { if (src == dst) return e; return new CastExpr(dst, e); } }
5,406
40.592308
134
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/SignalName.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.lustre; import fuzzm.util.ID; import fuzzm.util.TypedName; public class SignalName { public final TypedName name; public final int time; public SignalName(TypedName name, int time) { this.name = name; this.time = time; } public static String toString(String name, int time) { String res = ID.decodeString(name); res = res + ((time >= 0) ? "~" + time : ""); return res; } @Override public String toString() { return toString(name.name,time); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + time; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (! (obj instanceof SignalName)) return false; SignalName other = (SignalName) obj; if (!name.equals(other.name)) return false; if (time != other.time) return false; return true; } }
1,239
20.016949
67
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/LustreCtx.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.lustre; import java.util.ArrayList; import java.util.Collection; import fuzzm.util.IDString; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; public class LustreCtx { public Collection<Equation> eqs; public Collection<VarDecl> decls; public LustreCtx() { eqs = new ArrayList<>(); decls = new ArrayList<>(); } public LustreCtx(LustreCtx arg) { this.eqs = new ArrayList<>(arg.eqs); this.decls = new ArrayList<>(arg.decls); } public IdExpr define(IDString name, NamedType type, Expr body) { IdExpr stepID = new IdExpr(name.name()); eqs.add(new Equation(stepID,body)); decls.add(new VarDecl(name.name(),type)); return stepID; } public void define(IdExpr lhs, Expr rhs) { eqs.add(new Equation(lhs,rhs)); } public IdExpr declare(IDString name, NamedType type) { IdExpr stepID = new IdExpr(name.name()); decls.add(new VarDecl(name.name(),type)); return stepID; } public void add(LustreCtx arg) { eqs.addAll(arg.eqs); decls.addAll(arg.decls); } // public void printDecls(String loc) { // for (VarDecl v: decls) { // System.out.println(loc + v); // } // } }
1,502
22.123077
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/RemoveEnumTypes.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.lustre; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.EnumType; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.SubrangeIntType; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.AstMapVisitor; public class RemoveEnumTypes extends AstMapVisitor { public static Program program(Program program) { return new RemoveEnumTypes().visit(program); } static Collection<Expr> typeConstraints; @Override public Node visit(Node e) { typeConstraints = new ArrayList<Expr>(); Node newNode = super.visit(e); NodeBuilder b = new NodeBuilder(newNode); b.addAssertions(typeConstraints); Node res = b.build(); typeConstraints = null; return res; } private static Expr newConstraint(String name, BigInteger low, BigInteger high) { Expr var = new IdExpr(name); Expr upper = new IntExpr(high); Expr lower = new IntExpr(low); Expr lb = new BinaryExpr(lower,BinaryOp.LESSEQUAL,var); Expr ub = new BinaryExpr(var,BinaryOp.LESSEQUAL,upper); return new BinaryExpr(lb,BinaryOp.AND,ub); } @Override public VarDecl visit(VarDecl e) { if (e.type instanceof EnumType) { EnumType et = (EnumType) e.type; BigInteger low = BigInteger.ZERO; BigInteger high = BigInteger.valueOf(et.values.size() - 1); Expr constraint = newConstraint(e.id,low,high); typeConstraints.add(constraint); return new VarDecl(e.id, NamedType.INT); } else if (e.type instanceof SubrangeIntType) { SubrangeIntType sit = (SubrangeIntType) e.type; BigInteger low = sit.low; BigInteger high = sit.high; Expr constraint = newConstraint(e.id,low,high); typeConstraints.add(constraint); return new VarDecl(e.id, NamedType.INT); } else { return e; } } }
2,356
29.61039
82
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/AddSignals.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.lustre; import java.util.List; import fuzzm.util.FuzzmName; import fuzzm.util.IDString; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; import jkind.lustre.builders.NodeBuilder; public class AddSignals { public static Program addTime(Program program) { MainBuilder mb = new MainBuilder(program); Node node = program.getMainNode(); node = add_time_to_main(node); mb.updateMainNode(node); return mb.build(); } // public static Program add_done(Program program, String done) { // MainBuilder mb = new MainBuilder(program); // Node main = program.getMainNode(); // //if (containsDone(main,done)) { // // System.out.println(ID.location() + "Linking in Done signal"); // // main = link_done_in_main(main,done); // //} else { // //if (done.equals(FuzzMSettings.doneName_default)) { // // System.out.println(ID.location() + "Warning: Assuming always DONE"); // main = add_done_to_main(main); // //} else { // // throw new IllegalArgumentException("Specified DONE signal \"" + done + "\" not found among main model outputs"); // //} // //} // mb.updateMainNode(main); // return mb.build(); // } public static boolean containsDone(Node main, String done) { List<VarDecl> z = main.outputs; for (VarDecl v: z) { if ((v.id.equals(done)) && (v.type == NamedType.BOOL)) { return true; } } return false; } private static Node add_time_to_main(Node node) { // _k = 0 -> ((pre _k) + 1); NodeBuilder nb = new NodeBuilder(node); IDString time = FuzzmName.time; nb.addOutput(new VarDecl(time.name(),NamedType.INT)); IdExpr k = new IdExpr(time.name()); Expr pre = new UnaryExpr(UnaryOp.PRE, k); Expr one = new IntExpr(1); Expr plus = new BinaryExpr(pre, BinaryOp.PLUS, one); Expr zero = new IntExpr(0); Expr rhs = new BinaryExpr(zero,BinaryOp.ARROW,plus); nb.addEquation(new Equation(k,rhs)); return nb.build(); } // private static Node add_done_to_main(Node node) { // // Rather than one cycle, allow it to be anything .. // // _done = true -> false; // NodeBuilder nb = new NodeBuilder(node); // nb.addOutput(new VarDecl(FuzzmName.done,NamedType.BOOL)); // IdExpr done = new IdExpr(FuzzmName.done); // Expr T = new BoolExpr(true); // //Expr F = new BoolExpr(false); // //Expr rhs = new BinaryExpr(T,BinaryOp.ARROW,F); // nb.addEquation(new Equation(done,T)); // return nb.build(); // } // private static Node link_done_in_main(Node node, String done) { // // _done = done; // NodeBuilder nb = new NodeBuilder(node); // nb.addOutput(new VarDecl(FuzzMName.done,NamedType.BOOL)); // IdExpr newDone = new IdExpr(FuzzMName.done); // IdExpr oldDone = new IdExpr(done); // nb.addEquation(new Equation(newDone,oldDone)); // return nb.build(); // } }
3,264
29.801887
120
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/SignalCtx.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.lustre; import java.util.ArrayList; import java.util.Collection; import java.util.List; import fuzzm.util.FuzzmName; import fuzzm.util.IDString; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; public class SignalCtx extends ExprCtx { private List<Expr> exprList = new ArrayList<>(); private Expr time = new IdExpr(FuzzmName.time.name()); public SignalCtx(NamedType type) { super(type, ExprCtx.defaultValue(type)); } public void add(ExprCtx arg) { assert(type.equals(arg.type)); super.add(arg); exprList.add(arg.getExpr()); } // We assume that signals are added sequentially .. public void add(SignalCtx arg) { assert(type.equals(arg.type)); super.add(arg); exprList.addAll(arg.exprList); } public void add(Expr arg) { exprList.add(arg); } public void add(Collection<Expr> arg) { exprList.addAll(arg); } public void setTime(Expr time) { this.time = time; } private static Expr alternation(Expr time, int pivot, Expr left, Expr right) { Expr test = new BinaryExpr(time,BinaryOp.LESSEQUAL,new IntExpr(pivot)); return new IfThenElseExpr(test,left,right); } private Expr bindExprRec(int min, int max,int index, IDString base) { int span = max - min; if (span == 0) return exprList.get(min); if (span == 1) return alternation(time,min,exprList.get(min),exprList.get(max)); int half = span/2; Expr left = bindExprRec(min,min+half,index*2+1,base); Expr right = bindExprRec(min+half+1,max,index*2,base); Expr res = define(base.index(index),type,alternation(time,min+half,left,right)); return res; } @Override public ExprCtx bind(IDString base) { int size = exprList.size(); if (size <= 0) return new ExprCtx(super.bind(base)); Expr lastExpr = bindExprRec(0,size-1,1,base); setExpr(lastExpr); return new ExprCtx(super.bind(base)); } }
2,211
25.023529
82
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/DropProperties.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.lustre; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.AstMapVisitor; public class DropProperties extends AstMapVisitor { public static Program drop(Program program) { return new DropProperties().visit(program); } @Override public Node visit(Node node) { NodeBuilder nb = new NodeBuilder(node); nb.clearProperties(); return nb.build(); } }
662
21.862069
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/ExprCtx.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.lustre; import java.math.BigDecimal; import fuzzm.util.IDString; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.RealExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.VarDecl; public class ExprCtx extends LustreCtx { private Expr defaultExpr; NamedType type; protected static Expr defaultValue(NamedType type) { // We use "true" for boolean default because our AC is usually AND if (type == NamedType.BOOL) return new BoolExpr(true); if (type == NamedType.INT) return new IntExpr(0); if (type == NamedType.REAL) return new RealExpr(BigDecimal.ZERO); assert(false); return null; } public ExprCtx(NamedType type) { this.type = type; defaultExpr = defaultValue(type); } public ExprCtx(NamedType type, Expr defaultValue) { this.type = type; defaultExpr = defaultValue; } public ExprCtx(NamedType type, LustreCtx arg) { super(arg); this.type = type; defaultExpr = defaultValue(type); } public ExprCtx(ExprCtx arg) { super(arg); this.type = arg.type; this.defaultExpr = arg.getExpr(); } public Expr getExpr() { return defaultExpr; } public void setExpr(Expr expr) { this.defaultExpr = expr; } public ExprCtx bind(IDString varName) { IdExpr name = new IdExpr(varName.name()); eqs.add(new Equation(name, getExpr())); decls.add(new VarDecl(varName.name(),type)); setExpr(name); return this; } public Expr op(BinaryOp op, Expr arg) { Expr res = new BinaryExpr(getExpr(),op,arg); setExpr(res); switch (op) { case EQUAL: case NOTEQUAL: case GREATER: case GREATEREQUAL: case LESS: case LESSEQUAL: this.type = NamedType.BOOL; default: break; } return res; } public Expr op(BinaryOp op, ExprCtx earg) { add(earg); return op(op,earg.getExpr()); } public Expr op(UnaryOp op) { Expr res = new UnaryExpr(op,getExpr()); setExpr(res); return res; } public Expr cast(NamedType type) { Expr res = new CastExpr(type,getExpr()); setExpr(res); this.type = type; return res; } }
2,493
20.5
68
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/PreDependency.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.lustre; import java.util.HashSet; import java.util.Set; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.visitors.ExprIterVisitor; public class PreDependency extends ExprIterVisitor { private Set<String> preSet; protected PreDependency() { preSet = new HashSet<>(); } static PreDependency computeDependencies(Expr e) { PreDependency initVisitor = new PreDependency(); e.accept(initVisitor); return initVisitor; } Set<String> getPreSet() { return preSet; } @Override public Void visit(IdExpr e) { preSet.add(e.id); return null; } @Override public Void visit(UnaryExpr e) { if (e.op.equals(UnaryOp.PRE)) { assert(false); } super.visit(e); return null; } @Override public Void visit(BinaryExpr e) { if (e.op.equals(BinaryOp.ARROW)) { e.right.accept(this); } else { e.left.accept(this); e.right.accept(this); } return null; } }
1,273
17.735294
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/RenameNodes.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.lustre; import java.util.Map; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.builders.NodeBuilder; import jkind.lustre.visitors.AstMapVisitor; public class RenameNodes extends AstMapVisitor { private Map<String,String> rw; private RenameNodes(Map<String,String> rw) { this.rw = rw; } public static Program rename(Program program, Map<String,String> rw) { RenameNodes res = new RenameNodes(rw); return res.visit(program); } @Override public Node visit(Node node) { if (rw.containsKey(node.id)) { NodeBuilder NodeB = new NodeBuilder(node); NodeB.setId(rw.get(node.id)); Node z = NodeB.build(); return z; } return node; } }
915
20.809524
71
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/OrderNodes.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.lustre; import java.util.HashSet; import java.util.Set; import fuzzm.util.PartialOrder; import jkind.lustre.Node; import jkind.lustre.NodeCallExpr; import jkind.lustre.Program; import jkind.lustre.visitors.AstIterVisitor; public class OrderNodes extends AstIterVisitor { private PartialOrder<String> order; private Set<String> body; private OrderNodes() { body = null; order = new PartialOrder<String>(); } public static PartialOrder<String> computeOrder(Program program) { OrderNodes res = new OrderNodes(); res.visit(program); return res.order; } @Override public Void visit(NodeCallExpr call) { body.add(call.node); return null; } @Override public Void visit(Node node) { body = new HashSet<String>(); super.visit(node); order.update(node.id,body); return null; } }
1,043
19.076923
67
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/ExprSignal.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.lustre; import java.math.BigDecimal; import fuzzm.util.IDString; import fuzzm.util.RatSignal; import fuzzm.util.Signal; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.IdExpr; import jkind.lustre.NamedType; import jkind.lustre.RealExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.util.BigFraction; public class ExprSignal extends Signal<ExprVect> { private static final long serialVersionUID = -7854773286758238743L; public ExprSignal() { super(); } public ExprSignal(RatSignal s) { super(); for (int time=0;time<s.size();time++) { add(new ExprVect(s.get(time))); } } public ExprSignal(int size, ExprVect v) { super(); for (int time=0;time<size;time++) { add(v); } } public ExprCtx dot(ExprSignal x, IDString dotName) { // dot = (if (t=0) a*x .. 0) + (0 -> (pre dot)) int size = Math.min(x.size(),size()); SignalCtx signalCtx = new SignalCtx(NamedType.REAL); for (int time=0; time<size;time++) { signalCtx.add(get(time).dot(x.get(time)).bind(dotName.index(time))); } RealExpr zero = new RealExpr(BigDecimal.ZERO); signalCtx.add(zero); ExprCtx dotExpr = signalCtx.bind(dotName); dotExpr.op(BinaryOp.PLUS,new BinaryExpr(zero,BinaryOp.ARROW,new UnaryExpr(UnaryOp.PRE,new IdExpr(dotName.name())))); dotExpr = dotExpr.bind(dotName); return dotExpr; } public ExprCtx dot(RatSignal x, IDString dotName) { return dot(new ExprSignal(x),dotName); } public ExprSignal mul(BigFraction M) { ExprSignal res = new ExprSignal(); for (ExprVect v: this) { res.add(v.mul(M)); } return res; } public ExprSignal add(ExprSignal x) { ExprSignal res = new ExprSignal(); int size = Math.max(size(),x.size()); for (int i=0;i<size;i++) { res.add(get(i).add(x.get(i))); } return res; } public ExprSignal add(RatSignal x) { return add(new ExprSignal(x)); } public ExprSignal sub(ExprSignal x) { ExprSignal res = new ExprSignal(); int size = Math.max(size(),x.size()); for (int i=0;i<size;i++) { res.add(get(i).sub(x.get(i))); } return res; } public ExprSignal sub(RatSignal x) { return sub(new ExprSignal(x)); } @Override public ExprVect get(int time) { if (time < size()) { return super.get(time); } return new ExprVect(); } @Override public ExprVect set(int time, ExprVect value) { if (time < size()) { return super.set(time,value); } for (int i=size();i<time;i++) { add(new ExprVect()); } add(value); return value; } }
2,750
21.735537
118
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/PolySimulationResults.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.lustre.evaluation; import fuzzm.value.hierarchy.BooleanTypeInterface; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.instance.BooleanValue; public class PolySimulationResults extends SimulationResults { public EvaluatableValue result; public PolySimulationResults() { result = BooleanValue.TRUE; } private PolySimulationResults(EvaluatableValue result) { this.result = result; } @Override public PolySimulationResults and(EvaluatableValue result) { EvaluatableValue res = this.result.and(result); //if (Debug.isEnabled()) System.out.println(ID.location() + "Accumulated Simulation Results : " + res); return new PolySimulationResults(res); } @Override public boolean isSatisfactory() { return (! ((BooleanTypeInterface) result).isAlwaysFalse()); } @Override public BooleanTypeInterface result() { return (BooleanTypeInterface) result; } @Override public String toString() { return result.toString(); } }
1,194
22.9
105
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/DepthFirstSimulator.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.lustre.evaluation; import java.util.List; import fuzzm.poly.PolyBool; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.util.EvaluatableVector; import fuzzm.util.ID; import fuzzm.util.IDString; import fuzzm.util.ProofWriter; import fuzzm.util.StringMap; import fuzzm.util.TypedName; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.poly.BooleanPoly; import fuzzm.value.poly.GlobalState; import fuzzm.value.poly.PolyEvaluatableValue; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.Value; import jkind.lustre.visitors.TypeReconstructor; import jkind.util.Util; public abstract class DepthFirstSimulator extends BaseEvaluatableValueEvaluator { //private final int k; protected final StringMap<Type> types; private final StringMap<Expr> equations = new StringMap<Expr>(); private final List<Expr> assertions; private final TypeReconstructor tx; protected int step = 0; private EvaluatableSignal state; private int thms = 0; protected DepthFirstSimulator(FunctionLookupEV fns, Program prog) { super(fns); Node node = prog.getMainNode(); for (Equation eq : node.equations) { equations.put(((IdExpr) eq.lhs.get(0)).id,eq.expr); } assertions = node.assertions; types = new StringMap<Type>(Util.getTypeMap(node)); tx = new TypeReconstructor(prog); tx.setNodeContext(node); } public PolyBool simulateProperty(EvaluatableSignal state, String name, IDString property) { assert(step == 0); int k = state.size(); System.out.println(ID.location() + "Counterexample Depth : " + k); this.state = new EvaluatableSignal(state); EvaluatableValue accumulatedAssertions = BooleanPoly.TRUE; EvaluatableValue nextAccumulator; for (int time = 0; time < k; time++) { step = time; for (Expr asrt: assertions) { PolyEvaluatableValue asv = (PolyEvaluatableValue) eval(asrt); assert(asv.cex().signum() != 0); nextAccumulator = accumulatedAssertions.and(asv); assert(((PolyEvaluatableValue) accumulatedAssertions).cex().signum() != 0); if (Debug.isEnabled()) { System.out.println(ID.location() + "Assertion " + asrt + " evaluated to " + asv + " [" + asv.cex() + "]"); System.out.println(ID.location() + "Accumulated Assertions [" + thms + "] " + nextAccumulator); String asvString = asv.toACL2(); String preString = ((PolyEvaluatableValue) accumulatedAssertions).toACL2(); String postString = ((PolyEvaluatableValue) nextAccumulator).toACL2(); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),asvString,preString,postString); System.out.println(ID.location() + "Accumulated Assertions [" + thms + "] " + nextAccumulator); thms++; } accumulatedAssertions = nextAccumulator; assert(step == time); } } step = k-1; Expr propExpr = equations.get(property.name()); PolyEvaluatableValue propVal = (PolyEvaluatableValue) eval(propExpr); if (Debug.isEnabled()) System.out.println(ID.location() + name + " = " + propExpr + " evaluated to " + propVal + " [" + propVal.cex() + "]"); PolyEvaluatableValue constraintVal = (PolyEvaluatableValue) propVal.not(); assert(constraintVal.cex().signum() != 0); EvaluatableValue accumulatedConstraints = accumulatedAssertions.and(constraintVal); if (Debug.isEnabled()) { System.out.println(ID.location() + "Constraint not(" + propExpr + ") evaluated to " + constraintVal + " [" + constraintVal.cex() + "]"); System.out.println(ID.location() + "Final Constraint [" + thms + "] " + accumulatedConstraints); String propString = constraintVal.toACL2(); String preString = ((PolyEvaluatableValue) accumulatedAssertions).toACL2(); String postString = ((PolyEvaluatableValue) accumulatedConstraints).toACL2(); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),propString,preString,postString); System.out.println(ID.location() + "Accumulated Constriant [" + thms + "] " + accumulatedConstraints); thms++; } PolyBool polyConstraint = ((BooleanPoly) accumulatedConstraints).value; PolyBool globalInvariants = GlobalState.getInvariants(); PolyBool finalConstraint = polyConstraint.and(globalInvariants); if (Debug.isEnabled()) { System.err.println(ID.location() + "Accumulated Constraints : " + polyConstraint); System.err.println(ID.location() + "Global Invariants : " + globalInvariants); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),polyConstraint.toACL2(),globalInvariants.toACL2(),finalConstraint.toACL2()); System.out.println(ID.location() + "Final Constraint [" + thms + "] " + finalConstraint); thms++; } return finalConstraint; } @Override public abstract Value visit(IfThenElseExpr e); @Override public Value visit(IdExpr e) { EvaluatableVector v = state.get(step); TypedName tname = new TypedName(e.id,(NamedType) types.get(e.id)); if (v.containsKey(tname)) { PolyEvaluatableValue res = (PolyEvaluatableValue) v.get(tname); if (Debug.isEnabled()) System.out.println(ID.location() + e.id + " evaluated to " + res + " [" + res.cex() + "] in time step " + step); return res; } Expr expr = equations.get(e.id); if (expr == null) { System.out.println(ID.location() + "Warning: using default value for " + e); return getDefaultValue(e); } PolyEvaluatableValue value = (PolyEvaluatableValue) eval(expr); if (Debug.isEnabled()) System.out.println(ID.location() + e.id + " = " + expr + " evaluated to " + value + " [" + value.cex() + "] in time step " + step); state.set(new TypedName(e.id,(NamedType) types.get(e.id)),step,value); return value; } abstract protected Value getDefaultValue(IdExpr e); protected Type typeOf(Expr expr) { return expr.accept(tx); } @Override public Value visit(BinaryExpr e) { if (e.op == BinaryOp.ARROW) { if (step == 0) { return e.left.accept(this); } else { return e.right.accept(this); } } else { return super.visit(e); } } @Override public Value visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { assert(step > 0); step--; Value value = e.expr.accept(this); step++; return value; } else { return super.visit(e); } } }
6,709
35.666667
156
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/FunctionLookupEV.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.lustre.evaluation; import java.util.List; import fuzzm.util.Rat; import fuzzm.value.hierarchy.EvaluatableValue; import jkind.lustre.NamedType; public class FunctionLookupEV extends FunctionLookup<EvaluatableValue> { public FunctionSignature fsig; public FunctionLookupEV(FunctionSignature fsig) { super(fsig.keySet()); this.fsig = fsig; } public List<NamedType> getArgTypes(String function) { return fsig.getArgTypes(function); } public NamedType getFnType(String function) { return fsig.getFnType(function); } public void addEncodedString(String entry) { // String is of the form: // fname ftype tvalue [argtype argvalue]* String[] split = entry.split(" "); if (! (split.length >= 3 && (split.length % 2 == 1))) { throw new IllegalArgumentException("Expected string of the form 'fname ftype tvalue [argtype argvalue]*' but got: '" + entry + "'"); } String fname = split[0]; String ftype = split[1]; String fvalue = split[2]; EvaluatableValue evalue = Rat.ValueFromString(ftype, fvalue); EvaluatableArgList args = new EvaluatableArgList(); for (int index=3;index<split.length;index+=2) { String argType = split[index]; String argValue = split[index+1]; args.add(Rat.ValueFromString(argType, argValue)); } set(fname,args,evalue); } }
1,530
26.339286
135
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/ConcreteSimulationResults.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.lustre.evaluation; import fuzzm.value.hierarchy.BooleanTypeInterface; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.instance.BooleanValue; public class ConcreteSimulationResults extends SimulationResults { EvaluatableValue result; public ConcreteSimulationResults() { result = BooleanValue.TRUE; } private ConcreteSimulationResults(EvaluatableValue result) { this.result = result; } @Override public ConcreteSimulationResults and(EvaluatableValue result) { return new ConcreteSimulationResults(this.result.and(result)); } @Override public boolean isSatisfactory() { return ((BooleanTypeInterface) result).isAlwaysTrue(); } @Override public BooleanTypeInterface result() { return (BooleanTypeInterface) result; } @Override public String toString() { return result.toString(); } }
1,066
21.229167
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/FunctionSignature.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.lustre.evaluation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import jkind.lustre.Function; import jkind.lustre.NamedType; import jkind.lustre.VarDecl; public class FunctionSignature { final private Map<String,List<NamedType>> signatures; final private Map<String,NamedType> fout; private static List<NamedType> typeListFromVarDecl(List<VarDecl> args) { List<NamedType> res = new ArrayList<>(); for (VarDecl vd: args) { res.add((NamedType) vd.type); } return res; } public Collection<String> keySet() { return signatures.keySet(); } public FunctionSignature(List<Function> flist) { signatures = new HashMap<>(); fout = new HashMap<>(); for (Function f: flist) { assert(f.outputs.size() <= 1); signatures.put(f.id, typeListFromVarDecl(f.inputs)); if (f.outputs.size() > 1) throw new IllegalArgumentException(); fout.put(f.id,(NamedType) f.outputs.get(0).type); } } public List<NamedType> getArgTypes(String function) { List<NamedType> res = signatures.get(function); if (res == null) throw new IllegalArgumentException(); return res; } public NamedType getFnType(String function) { return fout.get(function); } @Override public String toString() { String res = "Function Signatures :\n\n"; for (String fn: fout.keySet()) { String delimit = ""; String args = "("; for (NamedType type: getArgTypes(fn)) { args += delimit + type; delimit = ","; } args += ")"; res += fn + args + ":" + getFnType(fn) + "\n"; } return res; } }
1,870
23.618421
73
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/InitIndexedEvaluator.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.lustre.evaluation; import java.util.Arrays; import fuzzm.lustre.indexed.IndexedIdExpr; import fuzzm.value.bound.ContainsEvaluatableValue; import jkind.lustre.IdExpr; import jkind.lustre.values.Value; public class InitIndexedEvaluator extends InitEvaluatableValueEvaluator { public InitIndexedEvaluator(BaseEvaluatableValueEvaluator evaluator) { super(evaluator); } ContainsEvaluatableValue preState[]; @Override public Value visit(IdExpr e) { if (preState == null) { System.out.println("Unbound State"); assert(false); } ContainsEvaluatableValue cev = preState[((IndexedIdExpr) e).index]; if (cev == null) { System.out.println("Unbound Variable : " + e.id + " with index " + ((IndexedIdExpr) e).index); System.out.println("Current State : " + Arrays.toString(preState)); assert(false); } Value res = cev.getValue(); if (res == null) { System.out.println("Unbound Variable : " + e.id + " with index " + ((IndexedIdExpr) e).index); System.out.println("Current State : " + Arrays.toString(preState)); assert(false); } return res; } }
1,314
26.395833
97
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/PolyFunctionLookup.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.lustre.evaluation; import java.util.ArrayList; import java.util.Collection; import java.util.List; import fuzzm.poly.VariableID; import fuzzm.value.poly.BooleanPoly; import fuzzm.value.poly.IntegerPoly; import fuzzm.value.poly.PolyEvaluatableValue; import fuzzm.value.poly.RationalPoly; import jkind.lustre.NamedType; public class PolyFunctionLookup { final FunctionSignature sigs; final FunctionLookup<PolyEvaluatableValue> polyValues; final FunctionLookup<VariableID> varValues; final FunctionLookup<List<PolyEvaluatableValue>> polyArgs; final FunctionLookup<List<VariableID>> varArgs; public PolyFunctionLookup(FunctionSignature fns) { sigs = fns; polyValues = new FunctionLookup<>(fns.keySet()); polyArgs = new FunctionLookup<>(fns.keySet()); varValues = new FunctionLookup<>(fns.keySet()); varArgs = new FunctionLookup<>(fns.keySet()); } // public PolyFunctionLookup(FunctionSignature sigs, FunctionLookup<PolyEvaluatableValue> values, FunctionLookup<List<PolyEvaluatableValue>> args) { // this.sigs = sigs; // this.values = values; // this.args = args; // } static PolyEvaluatableValue toPEV(VariableID varid) { if (varid.name.name.type == NamedType.BOOL) { return(new BooleanPoly(varid)); // return (varid.cex.compareTo(BigFraction.ZERO) == 0) ? BooleanPoly.FALSE : BooleanPoly.TRUE; } if (varid.name.name.type == NamedType.INT) { return new IntegerPoly(varid); } if (varid.name.name.type == NamedType.REAL) { return new RationalPoly(varid); } throw new IllegalArgumentException(); } public List<NamedType> getArgTypes(String function) { return sigs.getArgTypes(function); } public NamedType getFnType(String function) { return sigs.getFnType(function); } public PolyEvaluatableValue getFnPolyValue(String function, EvaluatableArgList args) { return polyValues.get(function, args); } public VariableID getFnVarValue(String function, EvaluatableArgList args) { return varValues.get(function, args); } public void setFnValue(String function, EvaluatableArgList args, VariableID value) { varValues.set(function, args, value); polyValues.set(function, args, toPEV(value)); } public List<PolyEvaluatableValue> getArgPolyValues(String function, EvaluatableArgList args) { return this.polyArgs.get(function, args); } public List<VariableID> getArgVarValues(String function, EvaluatableArgList args) { return this.varArgs.get(function, args); } public void setArgValues(String function, EvaluatableArgList args, List<VariableID> argv) { varArgs.set(function, args, argv); List<PolyEvaluatableValue> pargv = new ArrayList<>(); for (VariableID v: argv) { pargv.add(toPEV(v)); } this.polyArgs.set(function, args, pargv); } public List<PolyEvaluatableValue> getFnNthArgs(String function, int index) { Collection<List<PolyEvaluatableValue>> z = polyArgs.getValues(function); List<PolyEvaluatableValue> res = new ArrayList<>(); for (List<PolyEvaluatableValue> arg: z) { res.add(arg.get(index)); } return res; } public List<PolyEvaluatableValue> getFnValues(String function) { return new ArrayList<>(polyValues.getValues(function)); } @Override public String toString() { String res = sigs.toString() + "\n"; res += "Function Value Polys:\n\n"; res += polyValues.toString() + "\n"; res += "Function Argument Polys:\n\n"; res += polyArgs.toString() + "\n"; return res; } }
3,779
30.5
148
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/EvaluatableArgList.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.lustre.evaluation; import java.util.ArrayList; import fuzzm.value.hierarchy.EvaluatableValue; public class EvaluatableArgList extends ArrayList<EvaluatableValue> { private static final long serialVersionUID = 7204007336721147321L; @Override public String toString() { String res = "("; String delimit = ""; for (int index = 0; index<size(); index++) { res += delimit + get(index); delimit = ","; } return res + ")"; } }
672
20.709677
69
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/EvaluatableValueEvaluator.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.lustre.evaluation; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.Value; public abstract class EvaluatableValueEvaluator extends BaseEvaluatableValueEvaluator { public InitEvaluatableValueEvaluator initExtendedEvaluator; public EvaluatableValueEvaluator(FunctionLookupEV fns) { super(fns); this.initExtendedEvaluator = new InitEvaluatableValueEvaluator(this); } @Override public Value visit(BinaryExpr e) { if (e.op.equals(BinaryOp.ARROW)) { return e.right.accept(this); } return super.visit(e); } @Override public Value visit(UnaryExpr e) { if (e.op.equals(UnaryOp.PRE)) { return e.expr.accept(initExtendedEvaluator); } return super.visit(e); } }
1,015
22.627907
87
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/Simulator.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.lustre.evaluation; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.instance.BooleanValue; import fuzzm.value.instance.IntegerValue; import fuzzm.value.instance.RationalValue; import jkind.lustre.BoolExpr; import jkind.lustre.IntExpr; import jkind.lustre.Program; import jkind.lustre.RealExpr; import jkind.util.BigFraction; public class Simulator extends EventBasedSimulator { public static Simulator newSimulator(EvaluatableSignal inputs, FunctionLookupEV fns, String property, Program specNode, SimulationResults res) { Simulator genSim; try { genSim = new Simulator(inputs,fns,property,specNode,res); } catch (Throwable t) { Debug.setEnabled(true); try { System.err.println("Retry failed Simulation .."); genSim = new Simulator(inputs,fns,property,specNode,res); } catch (Throwable z) { System.err.flush(); throw z; } } return genSim; } protected Simulator(EvaluatableSignal inputs, FunctionLookupEV fns, String property, Program specNode, SimulationResults res) { super(inputs,fns,property,specNode,res); } @Override public EvaluatableValue visit(IntExpr arg0) { return new IntegerValue(arg0.value); } @Override public EvaluatableValue visit(RealExpr arg0) { return new RationalValue(BigFraction.valueOf(arg0.value)); } @Override public EvaluatableValue visit(BoolExpr arg0) { return arg0.value ? BooleanValue.TRUE : BooleanValue.FALSE; } @Override public EvaluatableValue trueValue() { return BooleanValue.TRUE; } @Override public EvaluatableValue falseValue() { return BooleanValue.FALSE; } }
1,899
25.388889
145
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/IndexedEvaluator.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.lustre.evaluation; import java.util.SortedSet; import fuzzm.lustre.indexed.IndexedIdExpr; import fuzzm.value.bound.ComputedValue; import fuzzm.value.bound.ConstrainedValue; import fuzzm.value.bound.ContainsEvaluatableValue; import fuzzm.value.bound.InputValue; import fuzzm.value.hierarchy.EvaluatableValue; import jkind.lustre.IdExpr; import jkind.lustre.Type; import jkind.lustre.values.Value; public abstract class IndexedEvaluator extends EvaluatableValueEvaluator { private ContainsEvaluatableValue currState[]; public IndexedEvaluator(FunctionLookupEV fns) { super(fns); initExtendedEvaluator = new InitIndexedEvaluator(this); } @Override public Value visit(IdExpr e) { //System.out.println(ID.location() + e + " index: " + ((IndexedIdExpr) e).index); Value res = currState[((IndexedIdExpr) e).index].getValue(); assert(res != null); return res; } public void updateCurrState(ContainsEvaluatableValue currState[]) { this.currState = currState; } public void updatePreState(ContainsEvaluatableValue preState[]) { ((InitIndexedEvaluator) this.initExtendedEvaluator).preState = preState; } public InputValue inputValue(EvaluatableValue value, Type type, SortedSet<Integer> defSet, SortedSet<Integer> nextSet) { return new InputValue(this,value,type,defSet,nextSet); } public ComputedValue computedValue(Type type, SortedSet<Integer> defSet, SortedSet<Integer> nextSet) { return new ComputedValue(this,type,defSet,nextSet); } public ConstrainedValue constrainedValue(boolean polarity) { return new ConstrainedValue(polarity,this); } abstract public EvaluatableValue trueValue(); abstract public EvaluatableValue falseValue(); }
1,917
28.96875
121
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/FunctionLookup.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.lustre.evaluation; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class FunctionLookup<T> { final private Map<String,Map<EvaluatableArgList,T>> fmap; public Collection<String> keySet() { return fmap.keySet(); } public FunctionLookup(Collection<String> fns) { fmap = new HashMap<>(); for (String fn: fns) { fmap.put(fn, new HashMap<>()); } } public Set<EvaluatableArgList> getInstances(String fn) { Map<EvaluatableArgList,T> m1 = fmap.get(fn); if (m1 == null) throw new IllegalArgumentException(); return m1.keySet(); } public Collection<T> getValues(String fn) { Map<EvaluatableArgList,T> m1 = fmap.get(fn); if (m1 == null) throw new IllegalArgumentException(fn + " not found in FunctionLookup " + this.toString()); return m1.values(); } public T get(String fn, EvaluatableArgList args) { Map<EvaluatableArgList,T> m1 = fmap.get(fn); if (m1 == null) throw new IllegalArgumentException(fn + " not found in FunctionLookup " + this.toString()); T value = m1.get(args); if (value == null) { throw new IllegalArgumentException(fn + args.toString() + " not found in Map " + toString(fn,m1)); } return value; } public void set(String fn, EvaluatableArgList args, T value) { Map<EvaluatableArgList,T> m1 = fmap.get(fn); if (m1 == null) throw new IllegalArgumentException(fn + " not found in FunctionLookup " + this.toString()); m1.put(args, value); fmap.put(fn,m1); } private String toString(String fn, Map<EvaluatableArgList,T> fmap) { String res = ""; for (EvaluatableArgList arg: fmap.keySet()) { res += " " + fn + arg + ": " + fmap.get(arg) + "\n"; } res += "\n"; return res; } @Override public String toString() { String res = "{Functions:\n"; for (String fn: fmap.keySet()) { res += toString(fn,fmap.get(fn)); } return res + "}\n"; } }
2,131
25.987342
109
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/EventBasedSimulator.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.lustre.evaluation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import fuzzm.lustre.SignalName; import fuzzm.lustre.StepDependency; import fuzzm.lustre.indexed.IndexIdentifiers; import fuzzm.util.EvaluatableSignal; import fuzzm.util.PartialOrder; import fuzzm.util.TypedName; import fuzzm.value.bound.BoundValue; import fuzzm.value.hierarchy.EvaluatableValue; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.VarDecl; public abstract class EventBasedSimulator extends IndexedEvaluator { class ExtendedHashMap<T> extends HashMap<T,Set<T>> { private static final long serialVersionUID = -7814687305325701160L; public void update(T key, T value) { Set<T> values = get(key); values = (values == null) ? new HashSet<T>() : values; values.add(value); put(key,values); } public void updateAll(Collection<T> keys, T value) { for (T key: keys) { update(key,value); } } } protected final Node main; protected final List<String> indexToName; protected final Map<String,Integer> nameToIndex; protected final BoundValue binding[][]; protected Expr equation[]; //protected final String property; protected final int k; public EventBasedSimulator(EvaluatableSignal inputs, FunctionLookupEV fns, String property, Program model, SimulationResults res) { super(fns); Node specNode = model.getMainNode(); k = inputs.size(); //this.property = property; Map<String,Type> typeMap = new HashMap<>(); for (VarDecl vd: specNode.inputs) { typeMap.put(vd.id, vd.type); } for (VarDecl vd: specNode.outputs) { typeMap.put(vd.id, vd.type); } for (VarDecl vd: specNode.locals) { typeMap.put(vd.id, vd.type); } PartialOrder<String> order = new PartialOrder<>(); Collection<String> empty = new ArrayList<String>(); for (VarDecl vd: specNode.inputs) { order.update(vd.id,empty); } ExtendedHashMap<String> nextSGraph = new ExtendedHashMap<>(); for (Equation eq: specNode.equations) { //System.out.println("Equation : " + eq); StepDependency deps = StepDependency.computeDependencies(eq.expr); Set<String> preSet = deps.getPreSet(); Set<String> depSet = deps.getDepSet(); //StringJoiner joiner1 = new StringJoiner(",","",""); //preSet.forEach(joiner1::add); //System.out.println("preSet : {" + joiner1 + "}"); //StringJoiner joiner2 = new StringJoiner(",","",""); //depSet.forEach(joiner2::add); //System.out.println("depSet : {" + joiner2 + "}"); assert(eq.lhs.size() == 1); String id = eq.lhs.get(0).id; order.update(depSet,id); nextSGraph.updateAll(preSet,id); } // Assertions must all be true. Assertions will // be identified as numbers in the form of strings. List<String> inputNames = specNode.inputs.stream().map(x -> x.id).collect(Collectors.toList()); Integer assertionID = 0; List<String> assertionIDs = new ArrayList<>(); for (Expr ex: specNode.assertions) { //System.out.println(ID.location() + "Assertion " + assertionID + " : " + ex); StepDependency deps = StepDependency.computeDependencies(ex); Set<String> preSet = deps.getPreSet(); Set<String> depSet = deps.getDepSet(); String assertionName = assertionID.toString(); assertionIDs.add(assertionName); order.update(depSet,assertionName); nextSGraph.updateAll(preSet,assertionName); assertionID += 1; } // There is an interaction between the total order and the scheduling of events. // The events are processed from lowest to highest. Thus, we may attempt to // schedule an event with a high total order even before all of its predecessors // have been processed. However, it will not be evaluated until after those // predecessors because they have a lower total order. indexToName = order.totalOrder(); //System.out.println(ID.location() + "indexToName : " + indexToName); List<String> unboundNames = order.unbound(); //System.out.println(ID.location() + "unboundNames : " + unboundNames); int totalBindings = indexToName.size(); // Construct a mapping from names to indices. nameToIndex = new HashMap<>(); for (int index = 0; index<indexToName.size(); index++) { nameToIndex.put(indexToName.get(index),index); } assert(nameToIndex.containsKey(property)); // Index all of the identifiers in the model. main = IndexIdentifiers.indexIdentifiers(specNode,nameToIndex); Map<String,Set<String>> currSGraph = order.getGraph(); @SuppressWarnings("unchecked") SortedSet<Integer> currIGraph[] = new SortedSet[indexToName.size()]; @SuppressWarnings("unchecked") SortedSet<Integer> nextIGraph[] = new SortedSet[indexToName.size()]; for (String key: currSGraph.keySet()) { Collection<String> sset = currSGraph.get(key); TreeSet<Integer> iset = new TreeSet<>(); for (String s: sset) { iset.add(nameToIndex.get(s)); } currIGraph[nameToIndex.get(key)] = iset; } for (String key: nextSGraph.keySet()) { Collection<String> sset = nextSGraph.get(key); TreeSet<Integer> iset = new TreeSet<>(); for (String s: sset) { iset.add(nameToIndex.get(s)); } nextIGraph[nameToIndex.get(key)] = iset; } // Initialize equations and Bound Values .. binding = new BoundValue[k][totalBindings]; equation = new Expr[totalBindings]; for (String name: inputNames) { // Some inputs may not appear in one or more of the graphs above .. //System.out.println(ID.location() + "Name : " + name); //assert(nameToIndex.containsKey(name)); int index = nameToIndex.get(name); SortedSet<Integer> currSet = currIGraph[index]; SortedSet<Integer> nextSet = nextIGraph[index]; TypedName tname = new TypedName(name,(NamedType) typeMap.get(name)); for (int time=0;time<k;time++) { binding[time][index] = inputValue(inputs.get(time).get(tname),typeMap.get(name),currSet,nextSet); } equation[index] = new IntExpr(0); } for (Equation e: main.equations) { String name = e.lhs.get(0).id; int index = nameToIndex.get(name); SortedSet<Integer> currSet = currIGraph[index]; SortedSet<Integer> nextSet = nextIGraph[index]; for (int time=0;time<k;time++) binding[time][index] = computedValue(typeMap.get(name),currSet,nextSet); equation[index] = e.expr; } assertionID = 0; for (Expr ex: main.assertions) { String assertionName = assertionID.toString(); int index = nameToIndex.get(assertionName); for (int time=0;time<k;time++) binding[time][index] = constrainedValue(true); equation[index] = ex; assertionID += 1; } // Express the property as a constraint .. binding[k-1][nameToIndex.get(property)] = constrainedValue(false); @SuppressWarnings("unchecked") TreeSet<Integer> activeInputs[] = new TreeSet[k]; TreeSet<Integer> inputSet = new TreeSet<>(); for (String name: unboundNames) { inputSet.add(nameToIndex.get(name)); } for (String name: inputNames) { inputSet.add(nameToIndex.get(name)); } // System.out.println("Sorted Inputs :" + inputSet); for (int time=0;time<k;time++) { activeInputs[time] = inputSet; } SimulationResults satisfied = simulateSystem(activeInputs,res); // The property must be false in the final time step. assert(satisfied.isSatisfactory()); } public BoundValue getBinding(String name, int time) { return binding[time][nameToIndex.get(name)]; } public SimulationResults simulateSystem(String name, int time, EvaluatableValue value, SimulationResults res) { int index = nameToIndex.get(name); binding[time][index].setValue(value); @SuppressWarnings("unchecked") TreeSet<Integer> activeInputs[] = new TreeSet[k]; TreeSet<Integer> inputSet = new TreeSet<>(); inputSet.add(index); activeInputs[time] = inputSet; return simulateSystem(activeInputs,res); } public SimulationResults isConsistent(Map<SignalName,EvaluatableValue> newValues, SimulationResults res) { Map<SignalName,EvaluatableValue> oldValues = new HashMap<>(); @SuppressWarnings("unchecked") TreeSet<Integer> activeInputs[] = new TreeSet[k]; for (int time=0;time<k;time++) { activeInputs[time] = new TreeSet<>(); } for (SignalName si: newValues.keySet()) { String name = si.name.name; int time = si.time; int index = nameToIndex.get(name); oldValues.put(si, getBinding(name,time).getValue()); activeInputs[si.time].add(index); binding[time][index].setValue(newValues.get(si)); } SimulationResults consistencyResult = simulateSystem(activeInputs,res); if (! consistencyResult.isSatisfactory()) { for (SignalName si: oldValues.keySet()) { String name = si.name.name; int time = si.time; int index = nameToIndex.get(name); binding[time][index].setValue(oldValues.get(si)); } if (! simulateSystem(activeInputs,res).isSatisfactory()) assert(false); } return consistencyResult; } public SimulationResults isConsistent(SignalName si, EvaluatableValue value, SimulationResults res) { String name = si.name.name; int time = si.time; EvaluatableValue oldValue = getBinding(name,time).getValue(); //System.out.println(ID.location()); //System.out.println(ID.location() + "Checking : " + si + " = " + value); SimulationResults consistent = simulateSystem(name,time,value,res); if (! consistent.isSatisfactory()) { //System.out.println(ID.location()); //System.out.println(ID.location() + "Retracting .."); //System.out.println(ID.location()); simulateSystem(name,time,oldValue,res); } else { //System.out.println(ID.location() + "Consistent."); } return consistent; } public SimulationResults simulateSystem(TreeSet<Integer> inputs[], SimulationResults res) { // null input entries == empty sets. TreeSet<Integer> currQueue; TreeSet<Integer> nextQueue = new TreeSet<>(); // So our simulation will take place starting from time 0 and incrementing forward. // We have two defSets .. one for the current time step and one for the next time step. // When we update our tick, we transfer the next to the current and clear the next. // Initial simulation .. // int spot = 0; // // TODO: Somehow this does not use the IndexedEvaluator class in any useful capacity. // Perhaps we should figure out why ?? //System.out.println(ID.location() + "Initial Bindings : " + binding[0]); for (int time=0;time<k;time++) { currQueue = nextQueue; nextQueue = new TreeSet<>(); if (inputs[time] != null) currQueue.addAll(inputs[time]); while (! currQueue.isEmpty()) { int index = currQueue.pollFirst(); BoundValue x = binding[time][index]; Expr ex = equation[index]; //System.out.println("Binding Equation : " + indexToName.get(index) + "<" + index + "> = " + ex); //if (spot == 0) { // System.out.println(ID.location() + "Simulating : " + indexToName.get(index)); // + " = " + x); //} //spot = (spot + 1) % 10000; int change = (time == 0) ? x.initValue(ex,binding[0]) : x.stepValue(ex,binding[time-1],binding[time]); //System.out.println(indexToName.get(index) + ((change != 0) ? " updated to " : " stayed at ") + x.getValue()); if (change != 0) { if (change < 0) { //if (Debug.isEnabled()) System.out.println(ID.location() + "Simulation[" + time + "] " + indexToName.get(index) + " : Update"); res = res.and(x.getValue()); if (! res.isSatisfactory()) return res; } else { //System.out.println(ID.location() + "Simulation[" + time + "] " + indexToName.get(index) + " = " + x.getValue() + " *"); currQueue.addAll(x.defSet); nextQueue.addAll(x.nextSet); } } else { //System.out.println(ID.location() + "Simulation[" + time + "] " + indexToName.get(index) + " = " + x.getValue()); } //if (Debug.isEnabled()) System.out.println(ID.location() + "[" + time + "] " + indexToName.get(index) + " := (" + x.getValue() + ")"); } } return res; } }
12,431
36.221557
139
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/PolyFunctionMap.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.lustre.evaluation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import fuzzm.util.Rat; import fuzzm.util.RatVect; import fuzzm.util.TypedName; public class PolyFunctionMap { private class FunctionMap { List<TypedName> args; TypedName value; public FunctionMap(List<TypedName> args, TypedName value) { this.args = args; this.value = value; } } Map<String,List<FunctionMap>> fmaplist; public PolyFunctionMap() { fmaplist = new HashMap<>(); } public FunctionLookupEV updateFunctions(RatVect env, FunctionLookupEV oldfns) { FunctionLookupEV res = new FunctionLookupEV(oldfns.fsig); for (String fn: fmaplist.keySet()) { for (FunctionMap fmap: fmaplist.get(fn)) { EvaluatableArgList args = new EvaluatableArgList(); for (TypedName arg: fmap.args) { args.add(Rat.ValueFromTypedFraction(arg.type,env.get(arg))); } res.set(fn, args, Rat.ValueFromTypedFraction(fmap.value.type,env.get(fmap.value))); } } return res; } public void updateFnMap(String fn, List<TypedName> args, TypedName value) { List<FunctionMap> Lfmap = (fmaplist.containsKey(fn)) ? fmaplist.get(fn) : new ArrayList<>(); Lfmap.add(new FunctionMap(args,value)); fmaplist.put(fn, Lfmap); } }
1,502
25.368421
94
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/SimulationResults.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.lustre.evaluation; import fuzzm.value.hierarchy.BooleanTypeInterface; import fuzzm.value.hierarchy.EvaluatableValue; abstract public class SimulationResults { abstract public SimulationResults and(EvaluatableValue result); abstract public boolean isSatisfactory(); abstract public BooleanTypeInterface result(); @Override abstract public String toString(); }
591
27.190476
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/InitEvaluatableValueEvaluator.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.lustre.evaluation; import fuzzm.value.hierarchy.EvaluatableValue; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IntExpr; import jkind.lustre.RealExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.Value; public class InitEvaluatableValueEvaluator extends BaseEvaluatableValueEvaluator { BaseEvaluatableValueEvaluator evaluator; public InitEvaluatableValueEvaluator(BaseEvaluatableValueEvaluator evaluator) { super(evaluator.fns); this.evaluator = evaluator; } @Override public Value visit(BinaryExpr e) { if (e.op.equals(BinaryOp.ARROW)) { return e.left.accept(this); } return super.visit(e); } @Override public Value visit(UnaryExpr e) { if (e.op.equals(UnaryOp.PRE)) { assert(false); } return super.visit(e); } @Override public Value visit(IdExpr e) { return evaluator.visit(e); } @Override public EvaluatableValue visit(IntExpr e) { return evaluator.visit(e); } @Override public EvaluatableValue visit(RealExpr e) { return evaluator.visit(e); } @Override public EvaluatableValue visit(BoolExpr e) { return evaluator.visit(e); } @Override public EvaluatableValue visit(FunctionCallExpr e) { return evaluator.visit(e); } }
1,592
20.527027
82
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/evaluation/BaseEvaluatableValueEvaluator.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.lustre.evaluation; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.EvaluatableValueHierarchy; import fuzzm.value.hierarchy.InstanceType; import fuzzm.value.instance.BooleanInterval; import fuzzm.value.instance.IntegerInterval; import fuzzm.value.instance.RationalInterval; import jkind.lustre.BinaryExpr; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.Expr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.RealExpr; import jkind.lustre.UnaryExpr; import jkind.lustre.values.Value; import jkind.lustre.visitors.Evaluator; public abstract class BaseEvaluatableValueEvaluator extends Evaluator { protected FunctionLookupEV fns; public BaseEvaluatableValueEvaluator(FunctionLookupEV fns) { this.fns = fns; } @Override public Value visit(BinaryExpr e) { //System.out.println(ID.location() + "BinaryExpr : " + e); Expr leftExpr = e.left; Expr rightExpr = e.right; EvaluatableValue leftValue = (EvaluatableValue) leftExpr.accept(this); EvaluatableValue rightValue = (EvaluatableValue) rightExpr.accept(this); EvaluatableValue res = leftValue.applyBinaryOp(e.op,rightValue); //System.out.println(ID.location() + "((" + leftValue + ") " + e.op + " (" + rightValue + ")) := (" + res + ")"); return res; } @Override public Value visit(UnaryExpr e) { //System.out.println("UnaryExpr : " + e); EvaluatableValue z = ((EvaluatableValue) e.expr.accept(this)); EvaluatableValue res = z.applyUnaryOp(e.op); //if (Debug.isEnabled()) System.out.println(ID.location() + "(" + e.op + " (" + z + ")) := (" + res + ")"); return res; } @Override public Value visit(IfThenElseExpr e) { Expr testExpr = e.cond; Expr thenExpr = e.thenExpr; Expr elseExpr = e.elseExpr; EvaluatableValue testValue = (EvaluatableValue) testExpr.accept(this); EvaluatableValue thenValue = (EvaluatableValue) thenExpr.accept(this); EvaluatableValue elseValue = (EvaluatableValue) elseExpr.accept(this); EvaluatableValue res = ((EvaluatableValueHierarchy)testValue).ite(thenValue,elseValue); //if (Debug.isEnabled()) System.out.println(ID.location() + "((" + testValue + ") ? (" + thenValue + ") : (" + elseValue + ")) := (" + res + ")"); return res; } @Override public EvaluatableValue visit(CastExpr e) { EvaluatableValue res = (EvaluatableValue) e.expr.accept(this); return res.cast(e.type); } @Override abstract public EvaluatableValue visit(IntExpr e); @Override abstract public EvaluatableValue visit(RealExpr e); @Override abstract public EvaluatableValue visit(BoolExpr e); EvaluatableValue arbitraryValue(NamedType type) { if (type == NamedType.BOOL) return BooleanInterval.ARBITRARY; if (type == NamedType.INT) return IntegerInterval.INFINITE_INTERVAL; if (type == NamedType.REAL) return RationalInterval.INFINITE_INTERVAL; throw new IllegalArgumentException(); } @Override public EvaluatableValue visit(FunctionCallExpr e) { //System.out.println(ID.location() + "Evaluating : " + e); EvaluatableArgList args = new EvaluatableArgList(); boolean all_instance_values = true; for (Expr v: e.args) { EvaluatableValue ev = (EvaluatableValue) v.accept(this); if (! (ev instanceof InstanceType<?>)) { all_instance_values = false; break; } args.add(ev); } return (all_instance_values) ? fns.get(e.function, args) : arbitraryValue(fns.getFnType(e.function)); } }
3,745
32.747748
148
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/optimize/PolygonalOptimizer.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.lustre.optimize; import fuzzm.lustre.generalize.PolyGeneralizationResult; import fuzzm.lustre.generalize.PolygonalGeneralizer; import fuzzm.solver.SolverResults; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.util.ID; import fuzzm.util.IDString; import fuzzm.util.ProofWriter; import fuzzm.util.RatSignal; import jkind.lustre.Program; public class PolygonalOptimizer { public static SolverResults optimize(SolverResults sln, RatSignal target, String name, IDString property, Program main) { //System.out.println(ID.location() + sln); EvaluatableSignal cex = sln.cex.evaluatableSignal(); PolyGeneralizationResult res = PolygonalGeneralizer.generalizeInterface(cex, name, property, sln.fns, main); // System.err.println(ID.location() + "Solution poly = " + res.result); SolverResults opsln = res.result.optimize(sln,res.fmap,target); if (Debug.proof()) { ProofWriter.printEval(ID.location(), "optEval_" + property.name(), res.result.toACL2(), opsln.cex.toACL2()); } return opsln; } }
1,274
32.552632
122
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/optimize/IntervalOptimizer.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.lustre.optimize; import java.util.Collections; import java.util.List; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.ConcreteSimulationResults; import fuzzm.lustre.evaluation.SimulationResults; import fuzzm.lustre.evaluation.Simulator; import fuzzm.lustre.generalize.Generalizer; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.util.ID; import fuzzm.util.IntervalVector; import fuzzm.util.TypedName; import fuzzm.value.hierarchy.EvaluatableType; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.EvaluatableValueHierarchy; public class IntervalOptimizer extends Generalizer { private static final SimulationResults TRUE = new ConcreteSimulationResults(); public IntervalOptimizer(Simulator simulator) { super(simulator); } /*static UnboundFraction round(UnboundFraction x) { BigInteger N = x.getNumerator(); int s = N.signum(); N = N.abs(); BigInteger D = x.getDenominator(); BigInteger QR[] = N.divideAndRemainder(D); BigInteger Q = QR[0]; BigInteger R = QR[1]; if (R.shiftLeft(1).compareTo(D) >= 0) { Q = Q.add(BigInteger.ONE); } return new UnboundFraction((s < 0) ? Q.negate() : Q); } static ValueInterval round(ValueInterval x) { UnboundFraction min = round(x.getLow()); UnboundFraction max = round(x.getHigh()); return new ValueInterval(min,max); }*/ public EvaluatableSignal optimizeInterface(IntervalVector span, EvaluatableSignal originalSignal, EvaluatableSignal targetSignal) { EvaluatableSignal evaluatableCEX; try { evaluatableCEX = optimize(span,originalSignal,targetSignal); } catch (Throwable t) { Debug.setEnabled(true); try { System.err.println(ID.location() + "Retry Failed Simulation .."); evaluatableCEX = optimize(span,originalSignal,targetSignal); } catch (Throwable z) { System.err.println(ID.location() + "Re-Caught Exception"); System.err.flush(); throw z; } } return evaluatableCEX; } private EvaluatableSignal optimize(IntervalVector span, EvaluatableSignal originalSignal, EvaluatableSignal targetSignal) { // // For now I have removed the vector optimization. // int k = originalSignal.size(); List<SignalName> allSignals = span.elaborate(k); Collections.shuffle(allSignals); EvaluatableSignal result = new EvaluatableSignal(originalSignal); for (int i=0;i<2;i++) { for (SignalName sn: allSignals) { int time = sn.time; TypedName name = sn.name; EvaluatableValue targetValue = targetSignal.get(time).get(name); //if (Debug.isEnabled()) System.err.println(ID.location() + "Optimizing " + name); EvaluatableValue resultValue = result.get(time).get(name); if (! targetValue.equals(resultValue)) { try { resultValue = optimize(sn,targetValue); } catch (Throwable t) { Debug.setEnabled(true); try { System.err.println(ID.location() + "Retry Failed Simulation .."); resultValue = optimize(sn,targetValue); } catch (Throwable z) { System.err.flush(); throw z; } } //System.out.println(ID.location() + "Done."); result.get(time).put(name,resultValue); } } } return result; } private EvaluatableValue optimize(SignalName sn, EvaluatableValue targetValue) { //System.err.println(ID.location() + sn.name + " target " + targetValue) ; //System.err.println(ID.location() + sn.name + " is currently " + simulator.getBinding(sn.name, sn.time).getValue()) ; EvaluatableValue interval = generalize(sn); //System.err.println(ID.location() + sn.name + " must lie in this interval : " + interval); EvaluatableValue resultValue; EvaluatableValue ratTarget = ((EvaluatableType<?>) targetValue).rationalType(); EvaluatableValue ratInterval = ((EvaluatableType<?>) interval).rationalType(); if (((EvaluatableValueHierarchy) ratTarget.minus(((EvaluatableValueHierarchy) ratInterval).getLow())).signum() < 0) { resultValue = ((EvaluatableValueHierarchy)interval).getLow(); } else if (((EvaluatableValueHierarchy)((EvaluatableValueHierarchy)ratInterval).getHigh().minus(ratTarget)).signum() < 0) { resultValue = ((EvaluatableValueHierarchy)interval).getHigh(); } else { resultValue = targetValue; } //System.out.println(ID.location() + "We choose you : " + resultValue); if (! simulator.isConsistent(sn,resultValue,TRUE).isSatisfactory()) assert(false); return resultValue; } }
4,667
34.633588
132
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/IntegerIntervalGeneralizer.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.lustre.generalize; import java.math.BigInteger; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.IntegerType; import fuzzm.value.instance.IntegerValue; public class IntegerIntervalGeneralizer extends ContinuousIntervalGeneralizer<IntegerType> { @Override protected boolean isZero(IntegerType x) { boolean res = (x.signum() == 0); //System.out.println(ID.location() + "(" + x + " == 0) = " + res); return res; } @Override protected IntegerType half(EvaluatableValue x) { IntegerValue two = new IntegerValue(BigInteger.valueOf(2)); IntegerType res = (IntegerType) x; int sign = res.signum(); res = res.abs().int_divide(two); res = (sign < 0) ? res.negate() : res; //System.out.println(ID.location() + "1/2 of " + x + " is " + res); return res; } }
1,034
26.236842
92
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/Generalizer.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.lustre.generalize; import java.util.HashMap; import java.util.List; import java.util.Map; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.Simulator; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.value.bound.BoundValue; 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 fuzzm.value.instance.BooleanInterval; import fuzzm.value.instance.IntegerInfinity; import fuzzm.value.instance.IntegerInterval; import fuzzm.value.instance.RationalInfinity; import fuzzm.value.instance.RationalInterval; import jkind.lustre.NamedType; import jkind.lustre.Type; public class Generalizer { protected final Simulator simulator; ValueGeneralizer<BooleanType> booleanGen = new DiscreteIntervalGeneralizer<BooleanType>(); ValueGeneralizer<IntegerType> intervalGen = new DiscreteIntervalGeneralizer<IntegerType>(); ValueGeneralizer<IntegerType> integerGen = new IntegerIntervalGeneralizer(); ValueGeneralizer<RationalType> rationalGen = new RationalIntervalGeneralizer(); private static final EvaluatableType<IntegerType> integerMaxInterval = new IntegerInterval(IntegerInfinity.NEGATIVE_INFINITY,IntegerInfinity.POSITIVE_INFINITY); private static final EvaluatableType<RationalType> rationalMaxInterval = new RationalInterval(RationalInfinity.NEGATIVE_INFINITY,RationalInfinity.POSITIVE_INFINITY); private static final EvaluatableType<BooleanType> boolMaxInterval = BooleanInterval.ARBITRARY; public Generalizer(Simulator simulator) { this.simulator = simulator; } private Map<SignalName,EvaluatableValue> generalize(List<SignalName> indicies) { Map<SignalName,EvaluatableValue> res = new HashMap<>(); //System.out.println(ID.location()); //System.out.println(ID.location() + "Starting Event Driven Generalization .."); //System.out.println(ID.location()); for (SignalName si : indicies) { if (Debug.isEnabled()) System.err.println(ID.location() + "Generalizing : " + si + " .."); EvaluatableValue interval = generalize(si); if (Debug.isEnabled()) System.err.println(ID.location() + "Generalization : " + si + " = " + interval); res.put(si, interval); } //System.out.println(ID.location()); //System.out.println(ID.location() + "Generalization Complete."); //System.out.println(ID.location()); return res; } public Map<SignalName,EvaluatableValue> eventBasedGeneralization(List<SignalName> signalNames) { Map<SignalName,EvaluatableValue> genMap; { long startTime = System.currentTimeMillis(); try { genMap = generalize(signalNames); } catch (Throwable t) { Debug.setEnabled(true); try { System.err.println("Retry failed Simulation .."); genMap = generalize(signalNames); } catch (Throwable z) { System.err.flush(); throw z; } } long endTime = System.currentTimeMillis(); System.out.println(ID.location() + "Event Based Generalization Time = " + (endTime - startTime) + " ms"); } return genMap; } // All of this case splitting could be avoided if the generalization class extended // the appropriate types. Or, more to the point, if generalization were part of the // interface. public EvaluatableValue generalize(SignalName si) { BoundValue bv = simulator.getBinding(si.name.name, si.time); EvaluatableValue curr = bv.getValue(); Type type = bv.type; if (type == NamedType.INT) { @SuppressWarnings("unchecked") EvaluatableType<IntegerType> intCurr = (EvaluatableType<IntegerType>) curr; //System.out.println(ID.location() + "Generalizing : " + si); EvaluatableValue res = integerGen.generalize(simulator, si, intCurr, integerMaxInterval); //System.out.println(ID.location() + "Done : " + si + " = " + res); return res; } else if (type == NamedType.BOOL) { @SuppressWarnings("unchecked") EvaluatableType<BooleanType> boolCurr = (EvaluatableType<BooleanType>) curr; return booleanGen.generalize(simulator, si, boolCurr, boolMaxInterval); } else if (type == NamedType.REAL) { @SuppressWarnings("unchecked") EvaluatableType<RationalType> rationalCurr = (EvaluatableType<RationalType>) curr; return rationalGen.generalize(simulator, si, rationalCurr, rationalMaxInterval); } else { @SuppressWarnings("unchecked") EvaluatableType<IntegerType> rangeCurr = (EvaluatableType<IntegerType>) curr; return intervalGen.generalize(simulator, si, rangeCurr, integerMaxInterval); } } }
4,782
39.880342
166
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/DepthFirstPolyGeneralizer.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.lustre.generalize; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import fuzzm.lustre.evaluation.DepthFirstSimulator; import fuzzm.lustre.evaluation.EvaluatableArgList; import fuzzm.lustre.evaluation.FunctionLookupEV; import fuzzm.lustre.evaluation.PolyFunctionLookup; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.poly.PolyBase; import fuzzm.poly.PolyBool; import fuzzm.poly.VariableID; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.util.Rat; import fuzzm.util.TypedName; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.InstanceType; import fuzzm.value.poly.BooleanPoly; import fuzzm.value.poly.GlobalState; import fuzzm.value.poly.IntegerPoly; import fuzzm.value.poly.PolyEvaluatableValue; import fuzzm.value.poly.RationalPoly; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.CastExpr; import jkind.lustre.Expr; import jkind.lustre.FunctionCallExpr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.Program; import jkind.lustre.RealExpr; import jkind.lustre.Type; import jkind.lustre.values.Value; import jkind.util.BigFraction; public class DepthFirstPolyGeneralizer extends DepthFirstSimulator { final PolyFunctionLookup ftable; final PolyFunctionMap fmap; public DepthFirstPolyGeneralizer(FunctionLookupEV fns, Program prog) { super(fns,prog); ftable = new PolyFunctionLookup(fns.fsig); fmap = new PolyFunctionMap(); addGlobalUFInvariants(fns); } static List<PolyEvaluatableValue> nthArgs(int n, Collection<EvaluatableArgList> args) { List<PolyEvaluatableValue> res = new ArrayList<>(); for (EvaluatableArgList inst: args) { res.add((PolyEvaluatableValue) inst.get(n)); } return res; } private void orderInvariants(NamedType type, List<PolyEvaluatableValue> nth) { if (nth.size() > 1) { PolyEvaluatableValue prev = nth.get(0); for (int index = 1; index<nth.size(); index++) { PolyEvaluatableValue curr = nth.get(index); int sign = prev.compareTo(curr); BooleanPoly res = BooleanPoly.TRUE; if (type == NamedType.BOOL) { res = (BooleanPoly) prev.implies(curr); } else { if (sign == 0) { res = (BooleanPoly) prev.lessequal(curr); } else { res = (BooleanPoly) prev.less(curr); } } GlobalState.addConstraint(res.value); prev = curr; } } } private void addGlobalUFInvariants(FunctionLookupEV fns) { for (String fn: fns.keySet()) { for (EvaluatableArgList args: fns.getInstances(fn)) { BigFraction fnValue = ((InstanceType<?>) fns.get(fn, args)).getValue(); String prefix = "UF_" + fn + args.toString(); String fnvarname = prefix + ".cex = " + fnValue; VariableID fnvar = VariableID.postAlloc(fnvarname,fns.fsig.getFnType(fn),fnValue); ftable.setFnValue(fn, args, fnvar); List<VariableID> argv = new ArrayList<>(); List<TypedName> argvars = new ArrayList<>(); int index = 0; for (EvaluatableValue arg: args) { BigFraction argValue = ((InstanceType<?>) arg).getValue(); String base = prefix + "_arg" + index + ".cex = " + argValue ; VariableID z = VariableID.postAlloc(base,fns.fsig.getArgTypes(fn).get(index),argValue); argvars.add(z.name.name); argv.add(z); index++; } ftable.setArgValues(fn, args, argv); fmap.updateFnMap(fn, argvars, fnvar.name.name); } } for (String fn: fns.keySet()) { List<NamedType> argtypes = ftable.getArgTypes(fn); if (Debug.isEnabled()) System.out.println(ID.location() + "Adding " + fn + " argument order invariants .. "); for (int index = 0; index<argtypes.size(); index++) { List<PolyEvaluatableValue> nth = ftable.getFnNthArgs(fn,index); Collections.sort(nth); // From smallest to largest .. orderInvariants(argtypes.get(index),nth); } // No need to constrain UF outputs .. //System.out.println(ID.location() + "Adding " + fn + " value order invariants .. "); //List<PolyEvaluatableValue> values = ftable.getFnValues(fn); //Collections.sort(values); //orderInvariants(ftable.getFnType(fn),values); } if (Debug.isEnabled()) System.out.println(ID.location() + "Function Table:"); if (Debug.isEnabled()) System.out.println(ftable.toString()); } @Override public Value visit(IfThenElseExpr e) { Expr testExpr = e.cond; Expr thenExpr = e.thenExpr; Expr elseExpr = e.elseExpr; Value res; BooleanPoly testValue = (BooleanPoly) testExpr.accept(this); if (testValue.isAlwaysTrue()) { res = thenExpr.accept(this); } else if (testValue.isAlwaysFalse()) { res = elseExpr.accept(this); } else { Type et = typeOf(thenExpr); if (et == NamedType.BOOL) { EvaluatableValue thenValue = (EvaluatableValue) thenExpr.accept(this); EvaluatableValue elseValue = (EvaluatableValue) elseExpr.accept(this); res = testValue.ite(thenValue,elseValue); } else { PolyBool tv = testValue.value; if (tv.cex) { GlobalState.addConstraint(tv); res = thenExpr.accept(this); } else { GlobalState.addConstraint(tv.not()); res = elseExpr.accept(this); } } } return res; } @Override public EvaluatableValue visit(IntExpr arg0) { return new IntegerPoly(new PolyBase(new BigFraction(arg0.value))); } @Override public EvaluatableValue visit(RealExpr arg0) { return new RationalPoly(new PolyBase(BigFraction.valueOf(arg0.value))); } @Override public EvaluatableValue visit(BoolExpr arg0) { return arg0.value ? new BooleanPoly(PolyBool.TRUE) : new BooleanPoly(PolyBool.FALSE); } @Override public EvaluatableValue visit(CastExpr e) { EvaluatableValue arg = (EvaluatableValue) e.expr.accept(this); GlobalState.pushExpr(step, e); EvaluatableValue res = arg.cast(e.type); Expr r = GlobalState.popExpr(); assert(r == e); return res; } @Override public Value visit(BinaryExpr e) { if (e.op == BinaryOp.INT_DIVIDE) { EvaluatableValue L = (EvaluatableValue) e.left.accept(this); EvaluatableValue R = (EvaluatableValue) e.right.accept(this); GlobalState.pushExpr(step, e); Value res = L.int_divide(R); Expr r = GlobalState.popExpr(); assert(r == e); return res; } else if (e.op == BinaryOp.MODULUS){ EvaluatableValue L = (EvaluatableValue) e.left.accept(this); EvaluatableValue R = (EvaluatableValue) e.right.accept(this); GlobalState.pushExpr(step, e); Value res = L.modulus(R); Expr r = GlobalState.popExpr(); assert(r == e); return res; } else { return super.visit(e); } } @Override public EvaluatableValue visit(FunctionCallExpr e) { String fn = e.function; List<EvaluatableValue> polyArgs = new ArrayList<>(); EvaluatableArgList cexArgs = new EvaluatableArgList(); List<NamedType> argtypes = ftable.getArgTypes(e.function); int index = 0; for (Expr v: e.args) { PolyEvaluatableValue ev = (PolyEvaluatableValue) v.accept(this); polyArgs.add(ev); cexArgs.add(Rat.ValueFromTypedFraction(argtypes.get(index), ev.cex())); index++; } List<VariableID> ufVarArgs = ftable.getArgVarValues(fn,cexArgs); index = 0; for (Expr v: e.args) { GlobalState.addReMap(ufVarArgs.get(index), step, v); index++; } // From the function name and the arguments we can get // the poly args and the poly return value. List<PolyEvaluatableValue> ufPolyArgs = ftable.getArgPolyValues(fn,cexArgs); PolyEvaluatableValue ufPolyValue = ftable.getFnPolyValue(fn, cexArgs); index = 0; for (EvaluatableValue v: polyArgs) { BooleanPoly res = (BooleanPoly) v.equalop(ufPolyArgs.get(index)); if (Debug.isEnabled()) System.out.println(ID.location() + "Adding " + e.function + " Instance Constraint"); GlobalState.addConstraint(res.value); index++; } if (Debug.isEnabled()) System.out.println(ID.location() + e + " evaluated to " + ufPolyValue + " [" + ufPolyValue.cex() + "]"); GlobalState.addReMap(ftable.getFnVarValue(fn,cexArgs), step, e); return ufPolyValue; } @Override protected PolyEvaluatableValue getDefaultValue(IdExpr e) { Type type = types.get(e.id); if (type == NamedType.BOOL) { return BooleanPoly.FALSE; } if (type == NamedType.INT) { return new IntegerPoly(new PolyBase()); } if (type == NamedType.REAL) { return new RationalPoly(new PolyBase()); } throw new IllegalArgumentException(); } }
8,863
32.575758
129
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/ValueGeneralizer.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.lustre.generalize; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.Simulator; import fuzzm.value.hierarchy.EvaluatableType; import fuzzm.value.hierarchy.InstanceType; interface ValueGeneralizer<T extends InstanceType<T>> { abstract public EvaluatableType<T> generalize(Simulator simulator, SignalName si, EvaluatableType<T> curr, EvaluatableType<T> maxInterval); }
611
28.142857
140
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/RationalIntervalGeneralizer.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.lustre.generalize; import java.math.BigInteger; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.EvaluatableValueHierarchy; import fuzzm.value.hierarchy.RationalType; import fuzzm.value.instance.RationalValue; import jkind.util.BigFraction; public class RationalIntervalGeneralizer extends ContinuousIntervalGeneralizer<RationalType> { public static final RationalType RATIONAL_EPSILON = new RationalValue(new BigFraction(BigInteger.ONE, BigInteger.valueOf(10000))); public static final RationalType TWO = new RationalValue(new BigFraction(BigInteger.valueOf(2))); @Override protected boolean isZero(RationalType x) { return ((EvaluatableValueHierarchy)x.abs().minus(RATIONAL_EPSILON)).signum() < 0; } @Override protected RationalType half(EvaluatableValue x) { return ((RationalType) x).divide(TWO); } }
1,077
29.8
131
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/DiscreteIntervalGeneralizer.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.lustre.generalize; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.ConcreteSimulationResults; import fuzzm.lustre.evaluation.SimulationResults; import fuzzm.lustre.evaluation.Simulator; import fuzzm.value.hierarchy.EvaluatableType; import fuzzm.value.hierarchy.InstanceType; public class DiscreteIntervalGeneralizer<T extends InstanceType<T>> implements ValueGeneralizer<T> { private static final SimulationResults TRUE = new ConcreteSimulationResults(); public EvaluatableType<T> generalize(Simulator simulator, SignalName si, EvaluatableType<T> curr, EvaluatableType<T> maxInterval) { if (simulator.isConsistent(si,maxInterval,TRUE).isSatisfactory()) { return maxInterval; } return curr; } }
952
30.766667
132
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/PolyGeneralizationResult.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.lustre.generalize; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.poly.PolyBool; public class PolyGeneralizationResult { public final PolyBool result; public final PolyFunctionMap fmap; public final ReMapExpr remap; public PolyGeneralizationResult(PolyBool res, PolyFunctionMap fmap, ReMapExpr remap) { this.result = res; this.fmap = fmap; this.remap = remap; } }
616
24.708333
87
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/ContinuousIntervalGeneralizer.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.lustre.generalize; import java.math.BigInteger; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.ConcreteSimulationResults; import fuzzm.lustre.evaluation.SimulationResults; import fuzzm.lustre.evaluation.Simulator; import fuzzm.value.hierarchy.EvaluatableType; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.NumericType; abstract public class ContinuousIntervalGeneralizer<T extends NumericType<T>> implements ValueGeneralizer<T> { Simulator simulator; private static final SimulationResults TRUE = new ConcreteSimulationResults(); @Override public EvaluatableType<T> generalize(Simulator simulator, SignalName si, EvaluatableType<T> curr, EvaluatableType<T> maxInterval) { this.simulator = simulator; //System.err.println(ID.location() + si.name + " is currently " + curr); curr = generalizeIntervalLow(si,curr,maxInterval); //System.err.println(ID.location() + si.name + " after low generalization " + curr); curr = generalizeIntervalHigh(si,curr,maxInterval); //System.err.println(ID.location() + si.name + " after high generalization " + curr); return curr; } abstract protected boolean isZero(T x); abstract protected T half(EvaluatableValue x); protected EvaluatableType<T> generalizeIntervalLow(SignalName si, EvaluatableType<T> curr, EvaluatableType<T> maxInterval) { T maxLow = maxInterval.getLow(); EvaluatableType<T> next = maxLow.newInterval(curr.getHigh()); if (simulator.isConsistent(si,next,TRUE).isSatisfactory()) { return next; } T a = curr.getLow(); T b = ((! maxLow.isFinite()) && (maxLow.signum() < 0)) ? getLowerBound(si, curr) : maxLow; // Invariant b < true lower bound <= a while (true) { //System.err.println(ID.location() + b + " < true lower bound <= " + a + " <= " + curr.getLow()); T delta = half(a.minus(b)); if (isZero(delta)) { return a.newInterval(curr.getHigh()); } @SuppressWarnings("unchecked") T guess = (T) a.minus(delta); next = guess.newInterval(curr.getHigh()); if (simulator.isConsistent(si, next,TRUE).isSatisfactory()) { a = guess; } else { b = guess; } } } protected EvaluatableType<T> generalizeIntervalHigh(SignalName si, EvaluatableType<T> curr, EvaluatableType<T> maxInterval) { T maxHigh = maxInterval.getHigh(); EvaluatableType<T> next = curr.getLow().newInterval(maxHigh); if (simulator.isConsistent(si, next,TRUE).isSatisfactory()) { return next; } T a = curr.getHigh(); T b = ((! maxHigh.isFinite()) && (maxHigh.signum() > 0)) ? getUpperBound(si, curr) : maxHigh; // Invariant a <= true upper bound < b while (true) { //System.err.println(ID.location() + curr.getHigh() + " <= " + a + " <= true upper bound < " + b); T delta = half(b.minus(a)); if (isZero(delta)) { return curr.getLow().newInterval(a); } T guess = (T) a.plus(delta); next = curr.getLow().newInterval(guess); if (simulator.isConsistent(si, next,TRUE).isSatisfactory()) { a = guess; } else { b = guess; } } } private T getUpperBound(SignalName si, EvaluatableType<T> curr) { T high = curr.getHigh(); T gap = high.valueOf(BigInteger.ONE); T two = high.valueOf(BigInteger.valueOf(2)); while (true) { high = high.plus(gap); gap = gap.multiply(two); EvaluatableType<T> next = curr.getLow().newInterval(high); //System.out.println(ID.location() + "Checking Interval (upper) : " + next); if (simulator.isConsistent(si, next,TRUE).isSatisfactory()) { curr = next; } else { return high; } } } private T getLowerBound(SignalName si, EvaluatableType<T> curr) { T low = curr.getLow(); T gap = low.valueOf(BigInteger.ONE); T two = low.valueOf(BigInteger.valueOf(2)); while (true) { @SuppressWarnings("unchecked") T val = (T) low.minus(gap); low = val; gap = gap.multiply(two); EvaluatableType<T> next = low.newInterval(curr.getHigh()); //System.out.println(ID.location() + "Checking Interval (lower) : " + next); if (simulator.isConsistent(si, next,TRUE).isSatisfactory()) { curr = next; } else { return low; } } } }
4,349
32.72093
132
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/ReMapExpr.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.lustre.generalize; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import fuzzm.poly.VariableID; import fuzzm.poly.VariableRole; import fuzzm.util.StepExpr; import jkind.lustre.Expr; import jkind.lustre.IdExpr; public class ReMapExpr { /*** * This class allows us to map generalized variables back to * expressions in the Lustre model. Note that get() will * return the original input */ private Map<VariableID,Collection<StepExpr>> remap; public ReMapExpr() { remap = new HashMap<>(); } public ReMapExpr add(VariableID key, int step, Expr value) { Collection<StepExpr> values = remap.containsKey(key) ? remap.get(key) : new ArrayList<>(); values.add(new StepExpr(step,value)); remap.put(key, values); return this; } private static Expr namedExpr(VariableID key) { return new IdExpr(key.name.name.name); } public Collection<StepExpr> get(VariableID key) { Collection<StepExpr> values; if (remap.containsKey(key)) { values = new ArrayList<>(remap.get(key)); } else { values = new ArrayList<>(); Expr zed = (key.role == VariableRole.AUXILIARY) ? key.cexExpr() : namedExpr(key); int time = (key.role == VariableRole.AUXILIARY) ? 0 : key.name.time; values.add(new StepExpr(time,zed)); } return values; } }
1,708
28.982456
98
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/generalize/PolygonalGeneralizer.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.lustre.generalize; import java.util.Collections; import java.util.List; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.FunctionLookupEV; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.poly.PolyBase; import fuzzm.poly.PolyBool; import fuzzm.poly.VariableID; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.util.ID; import fuzzm.util.IDString; import fuzzm.value.hierarchy.BooleanType; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.IntegerType; import fuzzm.value.hierarchy.RationalType; import fuzzm.value.poly.BooleanPoly; import fuzzm.value.poly.GlobalState; import fuzzm.value.poly.IntegerPoly; import fuzzm.value.poly.RationalPoly; import jkind.lustre.Program; import jkind.util.BigFraction; public class PolygonalGeneralizer { protected final DepthFirstPolyGeneralizer simulator; public PolygonalGeneralizer(FunctionLookupEV fev, Program program) { this.simulator = new DepthFirstPolyGeneralizer(fev, program); } private PolyBool generalize(EvaluatableSignal cex, String name, IDString property) { //System.out.println(ID.location() + "Counterexample Depth : " + cex.size()); EvaluatableSignal state = new EvaluatableSignal(); List<SignalName> signals = cex.getSignalNames(); Collections.shuffle(signals); for (SignalName sn: signals) { //System.out.println(ID.location() + "Counterexample Depth : " + state.size()); EvaluatableValue value = cex.get(sn.name,sn.time); if (value instanceof BooleanType) { BigFraction vx = ((BooleanType) value).getValue(); VariableID vid = VariableID.principleAlloc(sn,vx); state.set(sn.name,sn.time,new BooleanPoly(vid)); } else if (value instanceof IntegerType) { BigFraction vx = ((IntegerType) value).getValue(); VariableID vid = VariableID.principleAlloc(sn,vx); state.set(sn.name,sn.time,new IntegerPoly(new PolyBase(vid))); } else if (value instanceof RationalType) { BigFraction vx = ((RationalType) value).getValue(); VariableID vid = VariableID.principleAlloc(sn,vx); state.set(sn.name,sn.time,new RationalPoly(new PolyBase(vid))); } else { throw new IllegalArgumentException(); } } PolyBool polyRes = simulator.simulateProperty(state, name, property); if (! (polyRes.cex && !polyRes.isNegated())) { System.err.println(ID.location() + polyRes.toString()); assert(false); } polyRes = polyRes.normalize(); if (Debug.isEnabled()) { System.out.println(ID.location() + "Cex : " + cex); System.out.println(ID.location() + "Generalization Result : " + polyRes); } return polyRes; } public static PolyGeneralizationResult generalizeInterface(EvaluatableSignal cex, String name, IDString property, FunctionLookupEV fns, Program testMain) { PolyGeneralizationResult res; synchronized (GlobalState.class) { long startTime = System.currentTimeMillis(); try { PolygonalGeneralizer pgen2 = new PolygonalGeneralizer(fns,testMain); PolyBool g2 = pgen2.generalize(cex,name,property); assert(g2.cex && !g2.isNegated()); PolyFunctionMap fmap = pgen2.simulator.fmap; res = new PolyGeneralizationResult(g2,fmap,GlobalState.getReMap()); } catch (Throwable t) { System.err.println(ID.location() + "Retrying failed PolyGeneralization .."); t.printStackTrace(); Debug.setEnabled(true); Debug.setProof(true); try { System.err.println(ID.location() + "Property : " + name); System.err.println(ID.location() + "Initial CEX : " + cex); System.err.println(ID.location() + "Initial FNS : " + fns); PolygonalGeneralizer pgen2 = new PolygonalGeneralizer(fns,testMain); PolyBool g2 = pgen2.generalize(cex,name,property); PolyFunctionMap fmap = pgen2.simulator.fmap; res = new PolyGeneralizationResult(g2,fmap,GlobalState.getReMap()); } catch (Throwable z) { System.err.flush(); System.exit(1); throw z; } } long endTime = System.currentTimeMillis(); System.out.println(ID.location() + "Polygonal Generalization Time = " + (endTime - startTime) + " ms"); GlobalState.clearGlobalState(); } return res; } }
4,433
37.224138
156
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexedIdExpr.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.lustre.indexed; import jkind.lustre.IdExpr; public class IndexedIdExpr extends IdExpr { public int index; public IndexedIdExpr(IdExpr x, int index) { super(x.location,x.id); this.index = index; } public IndexedIdExpr(String id, int index) { super(id); this.index = index; } public <T> T accept(IndexedExprVisitor<T> visitor) { return visitor.visit(this); } public String toString() { return super.toString() + "<" + index + ">"; } }
681
21.733333
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexedExprVisitor.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.lustre.indexed; import jkind.lustre.visitors.ExprVisitor; public interface IndexedExprVisitor<T> extends ExprVisitor<T> { public T visit(IndexedIdExpr e); }
385
23.125
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexedAstMapVisitor.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.lustre.indexed; import jkind.lustre.Ast; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.VarDecl; import jkind.lustre.visitors.AstMapVisitor; public class IndexedAstMapVisitor extends AstMapVisitor implements IndexedExprVisitor<Expr>,IndexedASTVisitor<Ast,Expr> { @Override public Expr visit(IndexedIdExpr e) { Expr res = visit((IdExpr) e); if (res instanceof IndexedIdExpr) { return res; } return new IndexedIdExpr((IdExpr) res,e.index); } @Override public IndexedVarDecl visit(IndexedVarDecl e) { VarDecl res = visit((VarDecl) e); if (res instanceof IndexedVarDecl) { return (IndexedVarDecl) res; } return new IndexedVarDecl((VarDecl) res,e.index); } }
941
23.153846
121
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexedVarDecl.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.lustre.indexed; import jkind.lustre.Type; import jkind.lustre.VarDecl; public class IndexedVarDecl extends VarDecl { public int index; public IndexedVarDecl(VarDecl x, int index) { super(x.location,x.id,x.type); this.index = index; } public IndexedVarDecl(String id, Type type, int index) { super(id,type); this.index = index; } }
572
21.038462
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexIdentifiers.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.lustre.indexed; import java.util.Map; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.Node; import jkind.lustre.VarDecl; public class IndexIdentifiers extends IndexedAstMapVisitor { private Map<String,Integer> nameToIndex; private IndexIdentifiers(Map<String,Integer> nameToIndex) { this.nameToIndex = nameToIndex; } public static Node indexIdentifiers(Node node, Map<String,Integer> nameToIndex) { IndexIdentifiers res = new IndexIdentifiers(nameToIndex); return (Node) node.accept(res); } public Expr visit(IdExpr e) { String name = e.id; Integer index = nameToIndex.get(name); if (index == null) System.out.println("IndexIdentifer Missing Name : " + name); assert(index != null); return new IndexedIdExpr((IdExpr) e,index); } public IndexedVarDecl visit(VarDecl e) { String name = e.id; Integer index = nameToIndex.get(name); if (index == null) System.out.println("IndexIdentifer Missing Name : " + name); assert(index != null); return new IndexedVarDecl((VarDecl) e,index); } }
1,280
25.6875
82
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/lustre/indexed/IndexedASTVisitor.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.lustre.indexed; import jkind.lustre.visitors.AstVisitor; public interface IndexedASTVisitor<A,E extends A> extends AstVisitor<A,E> { public IndexedVarDecl visit(IndexedVarDecl e); }
410
24.6875
75
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableID.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.poly; import java.math.BigDecimal; import fuzzm.lustre.SignalName; import fuzzm.util.OrderedObject; import fuzzm.util.TypedName; import fuzzm.value.poly.GlobalState; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.BoolExpr; import jkind.lustre.Expr; import jkind.lustre.IntExpr; import jkind.lustre.NamedType; import jkind.lustre.RealExpr; import jkind.util.BigFraction; public class VariableID extends OrderedObject implements Comparable<VariableID> { public final SignalName name; public BigFraction cex; public final VariableRole role; private VariableID(String name, VariableRole vrole, NamedType type, BigFraction cex) { super(); name = "|" + name + "_#" + count + "|"; this.name = new SignalName(new TypedName(name,type),-1); this.cex = cex; this.role = vrole; } private VariableID(SignalName nameIn, VariableRole vrole, BigFraction cex){ super(); assert(Thread.holdsLock(GlobalState.class)); this.name = nameIn; this.cex = cex; this.role = vrole; } private VariableID(SignalName nameIn, VariableRole vroll){ this(nameIn,vroll,BigFraction.ZERO); } private VariableID(String nameIn, VariableRole vroll, NamedType type) { this(new SignalName(new TypedName(nameIn,type),0),vroll,BigFraction.ZERO); } public BigFraction getCex() { assert(wellOrdered()); assert(cex != null); return cex; } public void setCex(BigFraction cex) { this.cex = cex; } public Expr cexExpr() { return (name.name.type == NamedType.BOOL) ? new BoolExpr(cex.signum() != 0) : (name.name.type == NamedType.INT) ? new IntExpr(cex.getNumerator()) : new BinaryExpr(new RealExpr(new BigDecimal(cex.getNumerator())),BinaryOp.DIVIDE, new RealExpr(new BigDecimal(cex.getDenominator()))); } private static VariableID last = null; public static VariableID postAlloc(String base, NamedType type, BigFraction cex) { //System.out.println(ID.location(2) + "postAlloc()"); VariableID res = new VariableID(base,VariableRole.AUXILIARY,type,cex); if (first == null) { first = res; } res.insertAfter(last); last = res; assert(first.wellOrdered()); assert(last != null && first != null && last.next == null); return res; } public VariableID afterAlloc(String base, NamedType type, BigFraction cex) { //System.out.println(ID.location(2) + "afterAlloc(" + this + ":" + this.level() + ")"); VariableID res = new VariableID(base,VariableRole.AUXILIARY,type,cex); res.insertAfter(this); if (last.equals(this)) { last = res; } assert(first.wellOrdered()); if (! (last != null && first != null && last.next == null)) { assert(false); } return res; } private static VariableID first = null; public static VariableID principleAlloc(String base, NamedType type, BigFraction cex) { //System.out.println(ID.location(2) + "preAlloc()"); VariableID res = new VariableID(base,VariableRole.PRINCIPLE,type,cex); if (last == null) { last = res; } first = (VariableID) res.insertBefore(first); assert(first.wellOrdered()); assert(last != null && first != null && last.next == null); return res; } public static VariableID principleAlloc(SignalName nameIn, BigFraction cex) { //System.out.println(ID.location(2) + "preAlloc()"); VariableID res = new VariableID(nameIn,VariableRole.PRINCIPLE,cex); if (last == null) { last = res; } first = (VariableID) res.insertBefore(first); assert(first.wellOrdered()); assert(last != null && first != null && last.next == null); return res; } @Override public int compareTo(VariableID arg0) { return (id() == arg0.id()) ? 0 : ((level() < arg0.level()) ? -1 : 1); } @Override public String toString() { return name.toString(); } public String toACL2() { return "(id " + name.toString() + " " + ((name.name.type == NamedType.BOOL) ? ((cex.signum() == 0) ? "nil" : "t") : cex.toString()) + ")"; } public String toACL2(String cex) { return "(id " + name.toString() + " " + cex + ")"; } public static void clearGlobalState() { count = 0; last = null; first = null; } }
4,386
28.05298
146
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/PolyBool.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.poly; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.solver.SolverResults; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.util.IntervalVector; import fuzzm.util.ProofWriter; import fuzzm.util.RatSignal; import fuzzm.util.TypedName; import jkind.util.BigFraction; abstract public class PolyBool { public static final PolyBool TRUE = new TruePolyBool(true,new VariableList()); public static final PolyBool FALSE = new FalsePolyBool(false,new VariableList()); public boolean cex; final VariableList body; @Override abstract public String toString(); abstract public String toACL2(); protected PolyBool() { this.body = new VariableList(); this.cex = true; } protected PolyBool(VariableList body) { this.body = body; this.cex = true; for (Variable v: body) { this.cex &= v.cex; } } protected PolyBool(boolean cex, VariableList body) { this.body = body; this.cex = cex; } protected PolyBool(Variable c) { this.body = new VariableList(c); this.cex = c.cex; } public static PolyBool boolVar(VariableBoolean c) { return c.isNegated() ? new FalsePolyBool(c) : new TruePolyBool(c); } public static PolyBool less0(AbstractPoly arg) { // // We need to normalize these expressions immediately. // // Ax + poly < 0 //if (Debug.isEnabled()) System.out.println(ID.location() + "less0 : (" + arg + ") < 0"); if (arg.isConstant()) { return (arg.getConstant().signum() < 0) ? TRUE : FALSE; } PolyBool res = VariableBound.normalizePolyLess0(arg, RelationType.EXCLUSIVE, FeatureType.FEATURE, TargetType.CHAFF); if (Debug.proof()) { ProofWriter.printRefinement(ID.location(),"less0","(< " + arg.toACL2() + " 0)" , res.toACL2()); } return res; } public static PolyBool greater0(AbstractPoly arg) { //if (Debug.isEnabled()) System.out.println(ID.location() + "greater0 : (" + arg + ") > 0"); // x + poly > 0 if (arg.isConstant()) { return (arg.getConstant().signum() > 0) ? TRUE : FALSE; } PolyBool res = VariableBound.normalizePolyGreater0(arg, RelationType.EXCLUSIVE, FeatureType.FEATURE, TargetType.CHAFF); if (Debug.proof()) { ProofWriter.printRefinement(ID.location(),"greater0","(< 0 " + arg.toACL2() + ")" , res.toACL2()); } return res; } public static PolyBool equal0(AbstractPoly arg) { //System.out.println(ID.location() + "equal0(" + arg + ")"); if (arg.isConstant()) { return (arg.getConstant().signum() == 0) ? TRUE : FALSE; } PolyBool res = VariableBound.normalizePolyEquality0(arg, FeatureType.FEATURE, TargetType.CHAFF); if (Debug.proof()) { ProofWriter.printRefinement(ID.location(),"equal0","(= 0 " + arg.toACL2() + ")" , res.toACL2()); } return res; } // private int features() { // int res = 0; // for (Variable vc: body) { // res += vc.countFeatures(); // } // return res; // } private static PolyBool and_true(PolyBool x, PolyBool y) { // If either input were negated, they would evaluate to false. assert(! x.isNegated()); assert(! y.isNegated()); VariableList xbody = x.body; VariableList ybody = y.body; PolyBool res = new TruePolyBool(x.cex && y.cex,VariableList.andTT(xbody,ybody)); return res; } private static PolyBool and_false(PolyBool x, PolyBool y) { assert(x.isNegated() && y.isNegated()); PolyBool res = new FalsePolyBool(x.cex || y.cex,VariableList.andFF(x.body,y.body)); if (Debug.isEnabled()) System.out.println(ID.location() + "andFalse: (" + x + " and "+ y + ") = " + res); return res; } private static PolyBool and_true_false(PolyBool x, PolyBool y) { assert(! x.isNegated() && y.isNegated()); PolyBool res = new FalsePolyBool(! x.cex || y.cex,VariableList.andTF(x.body,y.body)); if (Debug.isEnabled()) System.out.println(ID.location() + "andTrueFalse: (" + x + " and "+ y + ") = " + res); return res; } private static PolyBool and(PolyBool x, PolyBool y) { //System.out.println(ID.location() + "x = " + x); //System.out.println(ID.location() + "y = " + y); if (x.isAlwaysTrue()) return y; if (y.isAlwaysTrue()) return x; if (x.isAlwaysFalse() || y.isAlwaysFalse()) return PolyBool.FALSE; PolyBool res; if (x.cex) { if (y.cex) { res = and_true(x,y); } else { res = and_true_false(x,y); } } else if (y.cex) { res = and_true_false(y,x); } else { res = and_false(x,y); } if (Debug.isEnabled()) { System.out.println(ID.location() + "and(" + x + "," + y + ") =" + res); } //Debug.setProof(true); if (Debug.proof()) { ProofWriter.printRefinement(ID.location(),"and","(and " + x.toACL2() + y.toACL2() + ")", res.toACL2()); } //Debug.setProof(false); return res; } public abstract boolean isNegated(); public abstract boolean isAlwaysFalse(); public abstract boolean isAlwaysTrue(); abstract public PolyBool not(); public PolyBool and(PolyBool arg) { PolyBool res = and(this,arg); if (Debug.isEnabled()) System.out.println(ID.location() + this.bytes() + " and " + arg.bytes() + " := " + res.bytes()); return res; } public PolyBool or(PolyBool arg) { PolyBool res = and(this.not(),arg.not()); res = res.not(); if (Debug.isEnabled()) System.out.println(ID.location() + this.bytes() + " or " + arg.bytes() + " := " + res.bytes()); return res; } public PolyBool iff(PolyBool value) { // (iff a b) = (or (and a b) (and (not a) (not b))) PolyBool a = this; PolyBool b = value; PolyBool m1 = and(a,b); PolyBool m2 = and(a.not(),b.not()); //System.out.println(ID.location() + "a = " + a); //System.out.println(ID.location() + "b = " + b); PolyBool res = m1.or(m2); // if (a.cex && b.cex) { // //System.out.println(ID.location() + "case 1: TT"); // res = and(a,b); // } else if (!a.cex && !b.cex) { // //System.out.println(ID.location() + "case 2: FF"); // a = a.not(); // b = b.not(); // res = and(a,b); // } else if (a.cex && !b.cex) { // //System.out.println(ID.location() + "case 3: TF"); // res = and(a,b.not()).not(); // } else { // //System.out.println(ID.location() + "case 4: FT"); // res = and(a.not(),b).not(); // } //System.out.println(ID.location() + "iff = " + res); return res; } abstract public List<Variable> getArtifacts(); abstract public List<Variable> getTargets(); public RatSignal randomVector(boolean biased, BigFraction min, BigFraction max, IntervalVector span, Map<VariableID,BigFraction> ctx) { assert(cex && !isNegated()); RatSignal res; try { res = body.randomVector(biased, min, max, span, ctx); } catch (Throwable t) { System.err.println(ID.location() + "*** Failing Example " + this.toString()); throw t; } return res; } // public static PolyBool range(VariableID v, BigFraction min, BigFraction max) { // PolyBase minP = new PolyBase(min); // PolyBase maxP = new PolyBase(max); // VariableGreater gt = new VariableGreater(v,v.cex.compareTo(min) >= 0,RelationType.INCLUSIVE,minP,FeatureType.FEATURE); // VariableLess lt = new VariableLess(v,v.cex.compareTo(max) <= 0,RelationType.INCLUSIVE,maxP,FeatureType.FEATURE); // return new TruePolyBool(new VariableInterval(gt,lt)); // } abstract public PolyBool normalize(); public int bytes() { return body.size(); } public Collection<VariableID> unboundVariables() { return body.unboundVariables(); } public Map<TypedName,RegionBounds> intervalBounds() { Map<VariableID,RegionBounds> r1 = body.intervalBounds(); Map<TypedName,RegionBounds> res = new HashMap<>(); for (VariableID vid: r1.keySet()) { TypedName name = vid.name.name; if (! res.containsKey(name)) { res.put(name, r1.get(vid)); } else { res.put(name, r1.get(vid).union(res.get(name))); } } return res; } abstract public SolverResults optimize(SolverResults cex, PolyFunctionMap fmap, RatSignal target); }
8,443
30.625468
136
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableRole.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.poly; public enum VariableRole { PRINCIPLE, AUXILIARY; }
285
18.066667
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/RestrictionResult.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.poly; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class RestrictionResult { public Variable newConstraint; List<Variable> restrictionList; public RestrictionResult(Variable newConstraint) { this.newConstraint = newConstraint; this.restrictionList = new ArrayList<>(); } public RestrictionResult(Variable newConstraint, Variable newRestriction) { this(newConstraint); this.restrictionList.add(newRestriction); } public RestrictionResult(Variable newConstraint, List<Variable> restrictionList) { this.newConstraint = newConstraint; this.restrictionList = restrictionList; } public static RestrictionResult restrictionInterval(RestrictionResult gt, RestrictionResult lt) { VariableInterval r = new VariableInterval((VariableGreater) gt.newConstraint ,(VariableLess) lt.newConstraint); List<Variable> rlst = new ArrayList<>(gt.restrictionList); rlst.addAll(lt.restrictionList); return new RestrictionResult(r,rlst); } public String toString() { return newConstraint.toString() + " & " + Arrays.toString(restrictionList.toArray()); } public String toACL2() { String res = newConstraint.toACL2() + "(and "; for (Variable v: restrictionList) { res += " " + v.toACL2(); } res += ")"; return "(and " + res + ")"; } }
1,536
26.446429
113
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableInequality.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.poly; abstract public class VariableInequality extends VariableRelation { protected VariableInequality(VariableID name, boolean cex, RelationType relation, AbstractPoly poly, FeatureType feature, TargetType target) { super(name,cex,relation,poly,feature,target); } abstract VariableInequality chooseBestCompliment(VariableInterval arg); @Override public boolean requiresRestriction() { return false; } @Override public RestrictionResult restriction() { throw new IllegalArgumentException(); } }
745
23.064516
143
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/OpType.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.poly; public class OpType { final String name; public static final OpType AND = new OpType("and"); public static final OpType OR = new OpType("or"); protected OpType(String name) { this.name = name; } public OpType not() { return ((this == AND) ? OR : AND); } public boolean op(boolean x, boolean y) { return (this == OR) ? x | y : x & y; } }
591
19.413793
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableList.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.poly; 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.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import fuzzm.lustre.SignalName; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.solver.SolverResults; import fuzzm.util.FuzzMInterval; import fuzzm.util.ID; import fuzzm.util.IntervalVector; import fuzzm.util.Rat; import fuzzm.util.RatSignal; import fuzzm.util.RatVect; import fuzzm.util.TypedName; import fuzzm.value.instance.RationalValue; import fuzzm.value.poly.GlobalState; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class VariableList extends LinkedList<Variable> { private static final long serialVersionUID = 7983100382771154597L; public VariableList() { super(); } public VariableList(VariableList arg) { super(arg); } public VariableList(Variable c) { super(); addLast(c); } // public VariableList not() { // VariableList res = new VariableList(); // for (Variable vc: this) { // res.addLast(vc.not()); // } // return res; // } @Override public boolean add(Variable b) { throw new IllegalArgumentException(); } public static void printAddFirst(String alt, Variable b, Variable first) { System.out.println("addFirst"+alt+"("+b.vid+":"+b.vid.level()+","+first.vid+":"+first.vid.level() + ",...)"); } public static void printAddLast(String alt, Variable last, Variable b) { System.out.println("addLast"+alt+"(...,"+last.vid+":"+last.vid.level()+","+b.vid+":"+b.vid.level()+")"); } @Override public void addFirst(Variable b) { // Maintain the ordering invariant .. if (! isEmpty()) { if (b.vid.compareTo(this.peekFirst().vid) >= 0) { printAddFirst("",b,this.peekFirst()); throw new IllegalArgumentException(); } } super.addFirst(b); } @Override public void addLast(Variable b) { // Maintain the ordering invariant .. if (! isEmpty()) { if (this.peekLast().vid.compareTo(b.vid) >= 0) { printAddLast("",this.peekLast(),b); throw new IllegalArgumentException(); } } super.addLast(b); } public void addFirstRev(Variable b) { // Maintain the ordering invariant .. if (! isEmpty()) { if (b.vid.compareTo(this.peekFirst().vid) <= 0) { printAddFirst("Rev",b,this.peekFirst()); throw new IllegalArgumentException(); } } super.addFirst(b); } public void addLastRev(Variable b) { // Maintain the ordering invariant .. if (! isEmpty()) { if (this.peekLast().vid.compareTo(b.vid) <= 0) { printAddLast("Rev",this.peekLast(),b); throw new IllegalArgumentException(); } } super.addLast(b); } public static VariableList andTF(VariableList x, VariableList y) { // andTF: Here T and F refer to the polarity of the associated // polyBool. y is, therefore, an implicitly negated 'or' // expression. We will be discarding all of x. if (x.isEmpty()) return y; if (y.isEmpty()) return y; VariableList res = new VariableList(); Iterator<Variable> xit = x.iterator(); Iterator<Variable> yit = y.iterator(); Variable xv = xit.next(); Variable yv = yit.next(); while (true) { int cmp = xv.vid.compareTo(yv.vid); if (cmp > 0) { res.addLast(yv); if (! yit.hasNext()) { res.addLast(new VariablePhantom(xv)); break; } yv = yit.next(); } else if (cmp < 0){ res.addLast(new VariablePhantom(xv)); if (! xit.hasNext()) { res.addLast(yv); break; } xv = xit.next(); } else { Variable z = Variable.target(yv,false,xv,true); res.addLast(z); if (! (xit.hasNext() && yit.hasNext())) break; xv = xit.next(); yv = yit.next(); } } while (yit.hasNext()) { res.addLast(yit.next()); } return res; } public static VariableList andFF(VariableList x, VariableList y) { // andFF: So we have the option of choosing one or the other // or of conjoining both. One might argue that, to keep the // solution space as large as possible, one should simply // discard one list or the other. However, when we consider // sampling, the false space gives us information about which // constraints to TARGET. if (x.isEmpty()) return y; if (y.isEmpty()) return x; VariableList res = new VariableList(); Iterator<Variable> xit = x.iterator(); Iterator<Variable> yit = y.iterator(); Variable xv = xit.next(); Variable yv = yit.next(); while (true) { int cmp = xv.vid.compareTo(yv.vid); if (cmp > 0) { res.addLast(yv); if (! yit.hasNext()) { res.addLast(xv); break; } yv = yit.next(); } else if (cmp < 0){ res.addLast(xv); if (! xit.hasNext()) { res.addLast(yv); break; } xv = xit.next(); } else { Variable z = Variable.minSet(xv,yv); res.addLast(z); if (! (xit.hasNext() && yit.hasNext())) break; xv = xit.next(); yv = yit.next(); } } while (xit.hasNext()) { res.addLast(xit.next()); } while (yit.hasNext()) { res.addLast(yit.next()); } return res; } public static VariableList andTT(VariableList x, VariableList y) { if (x.isEmpty()) return y; if (y.isEmpty()) return x; VariableList ctx = new VariableList(); Iterator<Variable> xit = x.iterator(); Iterator<Variable> yit = y.iterator(); Variable xv = xit.next(); Variable yv = yit.next(); //System.out.println("and() .."); while (true) { //System.out.println("xv:" + xv.vid + ":" + xv.vid.level()); //System.out.println("yv:" + yv.vid + ":" + yv.vid.level()); int cmp = xv.vid.compareTo(yv.vid); // Normal list is ordered from smallest to largest. if (cmp > 0) { // x is greater than y .. //if (Debug.isEnabled()) System.out.println(ID.location() + "(T and " + yv + ") = " + yv); ctx.addFirstRev(yv); if (! yit.hasNext()) { ctx.addFirstRev(xv); break; } yv = yit.next(); } else if (cmp < 0){ ctx.addFirstRev(xv); //if (Debug.isEnabled()) System.out.println(ID.location() + "(" + xv + " and T) = " + xv); if (! xit.hasNext()) { ctx.addFirstRev(yv); break; } xv = xit.next(); } else { RestrictionResult rr = Variable.andTrue(xv,yv); //if (Debug.isEnabled()) System.out.println(ID.location() + "(" + xv + " and " + yv + ") = " + rr.newConstraint); for (Variable r: rr.restrictionList) { ctx = restrict(r,ctx.iterator()); } ctx.addFirstRev(rr.newConstraint); if (! (xit.hasNext() && yit.hasNext())) break; xv = xit.next(); yv = yit.next(); } } while (xit.hasNext()) { ctx.addFirstRev(xit.next()); } while (yit.hasNext()) { ctx.addFirstRev(yit.next()); } Collections.reverse(ctx); //System.out.println("and()."); return ctx; } public static VariableList restrict(Variable c, Iterator<Variable> xit) { //System.out.println("Push " + c.vid + ":" + c.vid.level() + " .."); //if (Debug.isEnabled()) System.out.println(ID.location() + "Restriction : " + c); VariableList res = new VariableList(); while (xit.hasNext()) { // Reversed list is ordered from largest to smallest Variable xv = xit.next(); //System.out.println("Restriction : " + c.vid+":"+c.vid.level()); //System.out.println("Location : " + xv.vid+":"+xv.vid.level()); int cmp = xv.vid.compareTo(c.vid); if (cmp > 0) { res.addLastRev(xv); } else { if (cmp < 0) { res.addLastRev(c); c = xv; } else { RestrictionResult rr = Variable.andTrue(xv,c); //if (Debug.isEnabled()) System.out.println(ID.location() + "("+xv+" ^ "+c+") = " + rr.newConstraint); for (Variable vc: rr.restrictionList) { VariableList pres = restrict(vc,xit); xit = pres.iterator(); } c = rr.newConstraint; } while (xit.hasNext()) { res.addLastRev(c); c = xit.next(); } } } res.addLastRev(c); //System.out.println("Pop."); return res; } public VariableList applyRewrites() { Map<VariableID,AbstractPoly> rewrite = new HashMap<>(); VariableList res = new VariableList(); for (Variable v: this) { v = v.rewrite(rewrite); boolean keep = true; if (v instanceof VariableEquality) { VariableEquality veq = (VariableEquality) v; if (veq.relation == RelationType.INCLUSIVE) { rewrite.put(veq.vid, veq.poly); keep = (veq.vid.role != VariableRole.AUXILIARY); } } if (keep) res.addLast(v); } return res; } public VariableList normalize() { VariableList x = this.applyRewrites(); boolean changed; do { changed = false; x = new VariableList(x); Collections.reverse(x); VariableList res = new VariableList(); while (! x.isEmpty()) { //System.out.println(ID.location() + "Generalization size : " + x.size()); //System.out.println(ID.location() + x); Variable v = x.poll(); if (v instanceof VariablePhantom) { continue; } if (v.implicitEquality()) { //System.out.println(ID.location() + "Implicit Equality : " + v); v = v.toEquality(); changed = true; } if (v.slackIntegerBounds()) { //System.out.println(ID.location() + "Slack Bounds : " + v); v = v.tightenIntegerBounds(); changed = true; } if (v.reducableIntegerInterval()) { //System.out.println(ID.location() + "reducableIntegerInterval : " + v); RestrictionResult er = v.reducedInterval(); //System.out.println(ID.location() + "reducedInterval : " + er); v = er.newConstraint; for (Variable r: er.restrictionList) { x = restrict(r,x.iterator()); } changed = true; } if (v.requiresRestriction()) { RestrictionResult rr = v.restriction(); v = rr.newConstraint; for (Variable r: rr.restrictionList) { x = restrict(r,x.iterator()); } } res.addFirst(v); } x = res.applyRewrites(); } while (changed); return x; } // public VariableList chooseAndNegateOne() { // Variable one = null; // int max = 0; // for (Variable v : this) { // if (v.countFeatures() >= max) { // one = v; // max = v.countFeatures(); // } // } // assert(one != null); // return new VariableList(one.not()); // } public RatSignal randomVector(boolean biased, BigFraction Smin, BigFraction Smax, IntervalVector span, Map<VariableID,BigFraction> ctx) { //int tries = 100; @SuppressWarnings("unused") int bools = 0; while (true) { try { RatSignal res = new RatSignal(); for (Variable c: this) { RegionBounds r; try { r = c.constraintBounds(ctx); } catch (EmptyIntervalException e) { System.out.println(ID.location() + "Constraint : " + c); System.out.println(ID.location() + "Context : " + ctx); throw new IllegalArgumentException(); } VariableID vid = c.vid; SignalName sn = vid.name; TypedName name = sn.name; NamedType type = c.vid.name.name.type; FuzzMInterval bounds; try { bounds = span.containsKey(name) ? r.fuzzInterval(span.get(name)) : r.fuzzInterval(type, Smin, Smax); } catch (EmptyIntervalException e) { System.out.println(ID.location() + "Constraint : " + c); System.out.println(ID.location() + "Context : " + ctx); System.out.println(ID.location() + "RegionBounds : " + r); throw new IllegalArgumentException(); } BigFraction value; if (r.rangeType == RelationType.INCLUSIVE) { try { value = Rat.biasedRandom(type, biased, 0, bounds.min, bounds.max); } catch (EmptyIntervalException e) { System.out.println(ID.location() + "Constraint : " + c); System.out.println(ID.location() + "CEX String : " + c.cexString()); System.out.println(ID.location() + "Context : " + ctx); System.out.println(ID.location() + "RegionBounds : " + r); System.out.println(ID.location() + "FuzzMBounds : " + bounds); throw new IllegalArgumentException(); } } else { BigFraction upper = ((RationalValue) r.upper).value(); BigFraction lower = ((RationalValue) r.lower).value(); BigFraction one = type == NamedType.INT ? BigFraction.ONE : BigFraction.ZERO; BigFraction max = bounds.max.add(lower.subtract(bounds.min)).add(one); value = Rat.biasedRandom(type, biased, 0, upper, max); } if (sn.time >= 0) res.put(sn.time, sn.name, value); ctx.put(vid, value); if (! c.evalCEX(ctx)) { System.out.println(ID.location() + "Constraint : " + c); System.out.println(ID.location() + "Context : " + ctx); System.out.println(ID.location() + "RegionBounds : " + r); System.out.println(ID.location() + "FuzzMBounds : " + bounds); assert(false); } } // We should probably do this for all the variable types .. for (TypedName z : span.keySet()) { for (RatVect rv: res) { if (! rv.containsKey(z)) { if (z.type == NamedType.BOOL) { rv.put(z, GlobalState.oracle().nextBoolean() ? BigFraction.ONE : BigFraction.ZERO); } else { rv.put(z, Rat.biasedRandom(z.type, biased, 0, span.get(z).min, span.get(z).max)); } } } } //System.out.println(ID.location() + "Vector : "+ res); return res; } catch (EmptyIntervalException e) { throw new IllegalArgumentException(e); // tries--; // if (tries <= 0) throw e; // continue; } } } public Collection<VariableID> unboundVariables() { Set<VariableID> bound = new HashSet<>(); Set<VariableID> used = new HashSet<>(); for (Variable v: this) { bound.add(v.vid); } for (Variable v: this) { used = v.updateVariableSet(used); } used.removeAll(bound); return used; } public Map<VariableID,RegionBounds> intervalBounds() { Map<VariableID,RegionBounds> res = new HashMap<>(); for (Variable v: this) { RegionBounds b = v.intervalBounds(res); res.put(v.vid, b); } return res; } public SolverResults optimize(SolverResults sln, PolyFunctionMap fmap, RatSignal target) { RatSignal res = new RatSignal(sln.cex); RatVect tempVars = new RatVect(); VariableList z = new VariableList(this); // We need to do this top to bottom. Collections.reverse(z); while (! z.isEmpty()) { Variable v = z.poll(); RegionBounds interval; BigFraction value; if (v instanceof VariablePhantom) continue; if (v instanceof VariableBoolean) { value = v.vid.cex; int time = v.vid.name.time; TypedName tname = v.vid.name.name; if (time >= 0) { res.put(v.vid.name.time,v.vid.name.name,value); } else { tempVars.put(tname, value); } } else { try { interval = v.constraintBounds().fix(v.vid.name.name.type); } catch (EmptyIntervalException e) { System.out.println(ID.location() + "Interval Bound Violation on " + v); throw e; } int time = v.vid.name.time; TypedName tname = v.vid.name.name; NamedType type = v.vid.name.name.type; // TODO: Using only variable type I think we want to differentiate between // variables that map back into the model and those that do not. Here, // especially, we want to know the variables used in UF generalization. if (time >= 0) { value = interval.optimize(type,target.get(time).get(tname)); res.put(v.vid.name.time,v.vid.name.name,value); } else { // You could use a random value here .. because what we are doing is kinda silly. // Or just leave it unconstrained. value = interval.optimize(type, v.vid.getCex()); tempVars.put(tname, value); } // Now restrict the remaining constraints so that // they always at least contain "value" RestrictionResult rr = v.mustContain(new PolyBase(value)); v = rr.newConstraint; for (Variable r: rr.restrictionList) { z = restrict(r,z.iterator()); } } // assert(v.evalCEX(ctx)) : "Failure to preserve " + v + " with " + value + " under " + ctx; } fmap.updateFunctions(tempVars, sln.fns); return new SolverResults(sln.time,res,sln.fns); } public int[] gradiantToDirectionMatrix(AbstractPoly gradiant) { int direction[] = new int[this.size()]; Iterator<Variable> it = this.descendingIterator(); int index = this.size(); while (it.hasNext()) { index--; Variable v = it.next(); int sign = gradiant.getCoefficient(v.vid).signum(); direction[index] = sign; AbstractPoly bound = v.maxBound(sign); gradiant = gradiant.remove(v.vid); BigFraction N = gradiant.dot(bound); BigFraction D = bound.dot(bound); gradiant = gradiant.subtract(bound.divide(N.divide(D))); if (gradiant.isConstant()) break; } while (it.hasNext()) { index--; it.next(); direction[index] = 1; } assert(index == 0); return direction; } public Map<VariableID,BigFraction> maximize(int direction[]) { int index = 0; Map<VariableID,BigFraction> ctx = new HashMap<>(); for (Variable v: this) { BigFraction value = v.maxValue(direction[index], ctx); ctx.put(v.vid, value); index++; } return ctx; } public List<Variable> getTargets() { List<Variable> res = new ArrayList<>(); for (Variable v: this) { if (v instanceof VariableInterval) { VariableInterval vi = (VariableInterval) v; if (vi.gt.isTarget()) res.add(vi.gt); if (vi.lt.isTarget()) res.add(vi.lt); } else if (v.isTarget()) { res.add(v); } } return res; } public List<Variable> getArtifacts() { List<Variable> res = new ArrayList<>(); for (Variable v: this) { if (v instanceof VariableInterval) { VariableInterval vi = (VariableInterval) v; if (vi.gt.isArtifact()) res.add(vi.gt); if (vi.lt.isArtifact()) res.add(vi.lt); } else if (v.isArtifact()) { res.add(v); } } return res; } }
19,392
31.107616
138
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/TruePolyBool.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.poly; import java.util.List; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.solver.SolverResults; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.util.ProofWriter; import fuzzm.util.RatSignal; public class TruePolyBool extends PolyBool { protected TruePolyBool(boolean cex, VariableList body) { super(cex, body); assert(cex); } @Override public String toString() { String res = "(\n "; String delimit = ""; for (Variable vc: body) { res += delimit + vc; delimit = " &&\n "; } return res + "\n)"; } @Override public String toACL2() { String res = "(and\n"; for (Variable vc: body) { res += vc.toACL2() + "\n"; } return res + "\n)"; } public TruePolyBool(Variable c) { super(c); } @Override public boolean isNegated() { return false; } @Override public boolean isAlwaysFalse() { return false; } @Override public boolean isAlwaysTrue() { return (body.size() == 0); } @Override public PolyBool not() { return new FalsePolyBool(! cex,body); } @Override public PolyBool normalize() { VariableList x = body.normalize(); PolyBool res = new TruePolyBool(cex,x); // It would sure be nice to generate proofs here that we could check .. if (Debug.isEnabled()) { String s1 = this.toACL2(); String s2 = res.toACL2(); ProofWriter.printRefinement(ID.location(),"normalize", s1, s2); } return res; } @Override public SolverResults optimize(SolverResults cex, PolyFunctionMap fmap, RatSignal target) { //System.out.println(ID.location() + "Optimizing with :\n " + this); return body.optimize(cex,fmap,target); } @Override public List<Variable> getArtifacts() { return body.getArtifacts(); } @Override public List<Variable> getTargets() { return body.getTargets(); } }
2,063
19.435644
91
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/RegionBounds.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.poly; import java.math.BigInteger; import fuzzm.util.Debug; import fuzzm.util.FuzzMInterval; import fuzzm.util.ID; import fuzzm.util.Rat; import fuzzm.value.hierarchy.RationalType; import fuzzm.value.instance.BooleanValue; import fuzzm.value.instance.RationalInfinity; import fuzzm.value.instance.RationalValue; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class RegionBounds { public final RationalType lower; public final RelationType lowerType; public final RelationType rangeType; public final RationalType upper; public final RelationType upperType; public String toString() { return (rangeType == RelationType.INCLUSIVE ? "" : "!") + left(this.lowerType) + lower + "," + upper + right(this.upperType); } public RegionBounds(RationalType lower, RelationType lowerType, RelationType rangeType, RationalType upper, RelationType upperType) { this.lower = lower; this.lowerType = lowerType; this.upper = upper; this.upperType = upperType; this.rangeType = rangeType; if (rangeType == RelationType.INCLUSIVE) { BooleanValue res = (BooleanValue) this.lower.lessequal(this.upper); if (! res.isAlwaysTrue()) { throw new EmptyIntervalException("Empty Interval " + toString()); } } } public RegionBounds(RationalType lower, RelationType lowerType, RationalType upper, RelationType upperType) { this(lower,lowerType,RelationType.INCLUSIVE,upper,upperType); } public RegionBounds(RegionBounds lower, RelationType rangeType, RegionBounds upper) { boolean inclusive = rangeType == RelationType.INCLUSIVE; this.lower = inclusive ? lower.lower : lower.upper; this.lowerType = inclusive ? lower.lowerType : lower.upperType; this.upper = inclusive ? upper.upper : upper.lower; this.upperType = inclusive ? upper.upperType : upper.lowerType; this.rangeType = rangeType; if (inclusive) { BooleanValue res = (BooleanValue) this.lower.lessequal(this.upper); if (! res.isAlwaysTrue()) { throw new EmptyIntervalException("Empty Interval " + toString()); } } } public RegionBounds(RationalType lower, RationalType upper) { this(lower, RelationType.INCLUSIVE, RelationType.INCLUSIVE, upper, RelationType.INCLUSIVE); } public RegionBounds(RationalType value) { this(value,value); } public RegionBounds(BigFraction constant) { this(new RationalValue(constant)); } private BigFraction maxInterval(NamedType type, BigFraction oldMax) { BigFraction res = oldMax; if (upper.isFinite()) { res = upper.getValue(); if (type == NamedType.INT && upperType == RelationType.EXCLUSIVE) { res = res.subtract(BigFraction.ONE); } } return res; } private BigFraction minInterval(NamedType type, BigFraction oldMin) { BigFraction res = oldMin; if (lower.isFinite()) { res = lower.getValue(); if (type == NamedType.INT && lowerType == RelationType.EXCLUSIVE) { res = res.add(BigFraction.ONE); } } return res; } public FuzzMInterval updateInterval(FuzzMInterval oldInterval) { return new FuzzMInterval(oldInterval.type,minInterval(oldInterval.type,oldInterval.min),maxInterval(oldInterval.type,oldInterval.max)); } private static final RationalType ZERO = new RationalValue(BigFraction.ZERO); private static final RationalType ONE = new RationalValue(BigFraction.ONE); public static final RegionBounds EMPTY = new RegionBounds(RationalInfinity.NEGATIVE_INFINITY, RelationType.EXCLUSIVE, RelationType.EXCLUSIVE, RationalInfinity.POSITIVE_INFINITY, RelationType.EXCLUSIVE); RegionBounds multiply(BigFraction coefficient) { RationalValue value = new RationalValue(coefficient); int sign = coefficient.signum(); if (sign == 0) { return new RegionBounds(ZERO,RelationType.INCLUSIVE,ZERO,RelationType.INCLUSIVE); } if (sign < 0) { return new RegionBounds(upper.multiply(value),upperType,lower.multiply(value),lowerType); } return new RegionBounds(lower.multiply(value),lowerType,upper.multiply(value),upperType); } RegionBounds accumulate(RegionBounds res) { return new RegionBounds(lower.plus(res.lower),lowerType.inclusiveAND(res.lowerType),upper.plus(res.upper),upperType.inclusiveAND(res.upperType)); } public RegionBounds intersect(RegionBounds arg) { RationalType lower = this.lower.max(arg.lower); RationalType upper = this.upper.min(arg.upper); return new RegionBounds(lower,upper); } public RegionBounds union(RegionBounds arg) { RationalType lower = this.lower.min(arg.lower); RationalType upper = this.upper.max(arg.upper); return new RegionBounds(lower,upper); } private boolean fixed(NamedType type) { return (type == NamedType.INT) ? (upperType == RelationType.INCLUSIVE) && (lowerType == RelationType.INCLUSIVE) && (!upper.isFinite() || (upper.getValue().getDenominator().compareTo(BigInteger.ONE) == 0)) && (!lower.isFinite() || (lower.getValue().getDenominator().compareTo(BigInteger.ONE) == 0)) : true; } public BigFraction optimize(NamedType type, BigFraction target) { assert(fixed(type)); RationalValue tgt = new RationalValue(target); assert(rangeType == RelationType.INCLUSIVE); if (upper.less(tgt).isAlwaysTrue()) return upper.getValue(); if (lower.greater(tgt).isAlwaysTrue()) return lower.getValue(); return target; } static String left(RelationType rel) { return (rel == RelationType.INCLUSIVE) ? "[" : "("; } static String right(RelationType rel) { return (rel == RelationType.INCLUSIVE) ? "]" : ")"; } public RegionBounds fix(NamedType type) { RationalType lower; RationalType upper; if (type == NamedType.INT) { BigFraction value; if (rangeType == RelationType.INCLUSIVE) { if (this.lower.isFinite()) { value = this.lower.getValue(); if (value.getDenominator().compareTo(BigInteger.ONE) == 0) { if (this.lowerType == RelationType.INCLUSIVE) { lower = this.lower; } else { lower = this.lower.plus(ONE); } } else { lower = new RationalValue(Rat.roundUp(value)); } } else { lower = this.lower; } if (this.upper.isFinite()) { value = this.upper.getValue(); if (value.getDenominator().compareTo(BigInteger.ONE) == 0) { if (this.upperType == RelationType.INCLUSIVE) { upper = this.upper; } else { upper = (RationalType) this.upper.minus(ONE); } } else { upper = new RationalValue(Rat.roundDown(value)); } } else { upper = this.upper; } if (Debug.isEnabled()) System.out.println(ID.location() + "Fixing Interval "+ left(this.lowerType) + this.lower + "," + this.upper + right(this.upperType)); return new RegionBounds(lower,upper); } else { if (this.lower.isFinite()) { value = this.lower.getValue(); if (value.getDenominator().compareTo(BigInteger.ONE) == 0) { if (this.lowerType == RelationType.INCLUSIVE) { lower = this.lower; } else { lower = (RationalType) this.lower.minus(ONE); } } else { lower = new RationalValue(Rat.roundDown(value)); } } else { lower = this.lower; } if (this.upper.isFinite()) { value = this.upper.getValue(); if (value.getDenominator().compareTo(BigInteger.ONE) == 0) { if (this.upperType == RelationType.INCLUSIVE) { upper = this.upper; } else { upper = (RationalType) this.upper.plus(ONE); } } else { upper = new RationalValue(Rat.roundUp(value)); } } else { upper = this.upper; } return new RegionBounds(lower,RelationType.INCLUSIVE,RelationType.EXCLUSIVE,upper,RelationType.INCLUSIVE); } } return this; } public FuzzMInterval fuzzInterval(NamedType type, BigFraction smin, BigFraction smax) { BigFraction range = smax.subtract(smin); if (upper.isFinite()) { if (lower.isFinite()) { BigFraction min = lower.getValue(); BigFraction max = upper.getValue(); return new FuzzMInterval(type,min,max); } else { return new FuzzMInterval(type,upper.getValue().subtract(range),upper.getValue()); } } else { if (lower.isFinite()) { return new FuzzMInterval(type,lower.getValue(),lower.getValue().add(range)); } else { return new FuzzMInterval(type,smin,smax); } } } public FuzzMInterval fuzzInterval(FuzzMInterval interval) { if (upper.isFinite()) { if (lower.isFinite()) { BigFraction min = lower.getValue(); BigFraction max = upper.getValue(); return new FuzzMInterval(interval.type,min,max); } else { return new FuzzMInterval(interval.type,interval.min,upper.getValue()); } } else { if (lower.isFinite()) { return new FuzzMInterval(interval.type,lower.getValue(),interval.max); } else { return interval; } } } }
9,039
31.285714
160
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/TargetType.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.poly; public enum TargetType { /*** * This value tracks whether a given variable relation should * be a target for inversion when generating driving hypotheses. * * A target type can be imputed or inherited. * * Imputed: Given the conjunction (x[F] and y[T]), if condition * y implies !x (under cex), then x imputes target status to y. * For example: y = (a[2] = 2) and x = (a[2] < 0). It makes * sense to attempt to satisfy the negation of y because that * "frees" x. * * We need to decide which criteria is more relevant: * * 1) X Being True forces Y to be False [a] = 10, X:(a = 10) Y:not(a > 5) * 2) X being False allows Y to be True [a] = 10, X:(a > 9) Y:not(a = 10) * * cex X (T) Y(F) X.target * a[5] (a == 5) !(a == 5) Target <I think we always target True equalities> * a[5] (a == 5) !(a <= 7) Target * a[5] (a <= 7) !(a == 5) Chaff <False equalities never induce Targeting> * a[5] (a <= 7) !(a <= 9) Target X.ub < Y.ub * a[5] (a <= 7) !(a < 6) Chaff Y.ub < X.ub ;; andFF should choose most extreme bound * a[5] (a <= 7) !(a > 4) Chaff <any opposing comparison> * * * Inherited: Given the conjunction (x[T] and y[T]), if x * subsumes y, x should be a target if y was a target. For * example: x = (a[11] > 10) and y = (a[11] > 5). If y is * a target for inversion, x should be, too. * * Can target status ever be rescinded? */ TARGET, CHAFF; public TargetType inherit(TargetType subsumed) { return (this == TARGET) ? this : subsumed; } public TargetType impute(boolean YimpliesXbar) { return YimpliesXbar ? TARGET : this; } @Override public String toString() { return (this == TARGET) ? "@" : ""; } }
2,117
35.517241
96
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/PolyBase.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.poly; import java.math.BigInteger; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; import java.util.function.BiFunction; import java.util.function.Function; import fuzzm.value.instance.RationalInfinity; import jkind.util.BigFraction; import jkind.util.Util; public class PolyBase extends AbstractPoly { Map<VariableID,BigFraction> coefficients; BigFraction constant = BigFraction.ZERO; public PolyBase(){ this.coefficients = new HashMap<VariableID,BigFraction>(); } public PolyBase(VariableID x){ this.coefficients = new HashMap<VariableID,BigFraction>(); coefficients.put(x, BigFraction.ONE); } public PolyBase(BigFraction constant){ this.coefficients = new HashMap<VariableID,BigFraction>(); this.constant = constant; } public PolyBase(BigFraction coeff, VariableID x){ this.coefficients = new HashMap<VariableID,BigFraction>(); this.constant = BigFraction.ZERO; this.coefficients.put(x, coeff); } public PolyBase(Map<VariableID,BigFraction> coefficientsIn){ this.coefficients = normalizeCoefficients(coefficientsIn); } public PolyBase(Map<VariableID,BigFraction> coefficientsIn, BigFraction constant){ this.coefficients = normalizeCoefficients(coefficientsIn); this.constant = constant; } private static Map<VariableID,BigFraction> normalizeCoefficients(Map<VariableID,BigFraction> cIn){ Map<VariableID,BigFraction> res = new HashMap<VariableID,BigFraction>(cIn); cIn.forEach((key,val) -> { if(val.compareTo(BigFraction.ZERO) == 0){ res.remove(key); } }); return res; } @Override public Iterator<VariableID> iterator() { return coefficients.keySet().iterator(); } // solve(x) solves the poly for x by dividing // all other coefficients by the negation of the // coefficient of x and removing x; @Override public PolyBase solveFor(VariableID x) { //System.out.println(ID.location() + "solveFor(" + x + "," + this + ")"); if(!coefficients.containsKey(x)){ throw new IllegalArgumentException(); } BigFraction xCoef = coefficients.get(x); BigFraction xCoefNegated = xCoef.negate(); Map<VariableID,BigFraction> res = new HashMap<VariableID,BigFraction>(coefficients); res.remove(x); res.replaceAll((k,v) -> v.divide(xCoefNegated)); BigFraction newConstant = constant.divide(xCoefNegated); return new PolyBase(res,newConstant); } @Override public BigFraction getCoefficient(VariableID x) { if(coefficients.containsKey(x)){ return coefficients.get(x); } else{ return BigFraction.ZERO; } } @Override public PolyBase negate() { Function<BigFraction, BigFraction> neg = (lhs) -> lhs.negate(); return unaryOpGen(neg); } @Override public PolyBase add(AbstractPoly x) { BiFunction<BigFraction, BigFraction, BigFraction> add = (lhs,rhs) -> lhs.add(rhs); return binaryOpGen(add,x); } @Override public PolyBase add(BigFraction val) { Map<VariableID,BigFraction> newCoefs = new HashMap<VariableID,BigFraction>(coefficients); BigFraction newConstant = constant.add(val); return new PolyBase(newCoefs,newConstant); } @Override public PolyBase subtract(AbstractPoly x) { BiFunction<BigFraction, BigFraction, BigFraction> sub = (lhs,rhs) -> lhs.subtract(rhs); return binaryOpGen(sub,x); } @Override public PolyBase subtract(BigFraction val) { Map<VariableID,BigFraction> newCoefs = new HashMap<VariableID,BigFraction>(coefficients); BigFraction newConstant = constant.subtract(val); return new PolyBase(newCoefs,newConstant); } @Override public PolyBase multiply(BigFraction c) { Function<BigFraction, BigFraction> mul = (lhs) -> lhs.multiply(c); return unaryOpGen(mul); } @Override public PolyBase divide(BigFraction v) { Function<BigFraction, BigFraction> div = (lhs) -> lhs.divide(v); return unaryOpGen(div); } private PolyBase unaryOpGen (Function<BigFraction, BigFraction> f) { Map<VariableID,BigFraction> res = new HashMap<VariableID,BigFraction>(coefficients); res.replaceAll((k,v) -> f.apply(v)); BigFraction newConstant = f.apply(constant); return new PolyBase(res,newConstant); } private PolyBase binaryOpGen (BiFunction<BigFraction, BigFraction, BigFraction> f, AbstractPoly x){ Map<VariableID,BigFraction> res = new HashMap<VariableID,BigFraction>(coefficients); Map<VariableID,BigFraction> toAdd = ((PolyBase) x).coefficients; toAdd.forEach((var,val) -> { BigFraction myCoefficient = getCoefficient(var); res.put(var, f.apply(myCoefficient,val)); }); BigFraction newConstant = f.apply(constant, x.getConstant()); return new PolyBase(res,newConstant); } @Override public boolean isConstant() { return coefficients.keySet().isEmpty(); } @Override public BigFraction getConstant() { return constant; } @Override public VariableID leadingVariable() { if(isConstant()) { throw new IllegalArgumentException(); } VariableID res = null; for(VariableID var : coefficients.keySet()) { if ((res == null) || (var.compareTo(res) >= 0)) { res = var; } } assert(! (res == null)); return res; } @Override public VariableID trailingVariable() { if(isConstant()) { throw new IllegalArgumentException(); } VariableID res = null; for(VariableID var : coefficients.keySet()) { if ((res == null) || (var.compareTo(res) <= 0)) { res = var; } } assert(! (res == null)); return res; } private static BigFraction abs(BigFraction x){ boolean negative = x.signum() < 0; return negative ? x.negate() : x; } private static String spaceOp(boolean first, BigFraction coeff, String var){ // // s: sign, m: magnitude, v: variable // sm : poly is just the final constant // sm*v : magnitude of leadinv variable coeff != 1 // s*v : magnitude of leading variable coeff == 1 // s_m*v : subsequent variable with coeff != 1 // s_v : subsequent variable with coeff == 1 // s_m : final constant String res = ""; // Just the coefficient .. boolean validVar = (var != null); if (first && !validVar) return coeff.toString(); // Ignore value .. boolean zero = (coeff.signum() == 0); boolean no_value = ((! first) && zero); if (no_value) return res; // Include pre-space .. if (! first) { res += " "; } // Include sign .. boolean explicit_positive = (! first); String sign = (coeff.signum() < 0) ? "-" : (explicit_positive ? "+" : ""); res += sign; // Include sign space .. String sign_space = (! first) ? " " : ""; res += sign_space; // Include magnitude .. BigFraction mag = abs(coeff); boolean one = (mag.compareTo(BigFraction.ONE) == 0); boolean include_magnitude = !(validVar && one); if (include_magnitude) { res += mag.toString(); } // Include multiplication .. if (include_magnitude && validVar) { res += "*"; } // Include variable .. if (validVar) { res += var; } return res; } @Override public String toString() { String res = ""; res += "("; boolean first = true; TreeSet<VariableID> keys = new TreeSet<>(coefficients.keySet()); NavigableSet<VariableID> rkeys = keys.descendingSet(); for(VariableID var : rkeys) { BigFraction val = coefficients.get(var); res += spaceOp(first,val,var.toString()); first = false; } res += spaceOp(first,constant,null); res += ")"; return res; } @Override public String cexString() { String res = ""; res += "("; boolean first = true; for(VariableID var : this) { BigFraction val = coefficients.get(var); res += spaceOp(first,val,var.cex.toString()); first = false; } res += spaceOp(first,constant,null); res += ")"; return res; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (! (obj instanceof PolyBase)) return false; PolyBase other = (PolyBase) obj; if (!coefficients.equals(other.coefficients) || !constant.equals(other.constant)) return false; return true; } @Override public BigFraction evaluateCEX() { BigFraction res = constant; for(VariableID k : coefficients.keySet()) { BigFraction v = coefficients.get(k); BigFraction cex = k.cex; res = res.add(cex.multiply(v)); } return res; } @Override public RegionBounds polyBounds(Map<VariableID, RegionBounds> bounds) { RegionBounds res = new RegionBounds(constant); for (VariableID v: coefficients.keySet()) { if (bounds.containsKey(v)) { res = res.accumulate(bounds.get(v).multiply(coefficients.get(v))); } else if (coefficients.get(v).signum() != 0) { return new RegionBounds(RationalInfinity.NEGATIVE_INFINITY,RationalInfinity.POSITIVE_INFINITY); } } return res; } @Override public BigFraction evaluate(Map<VariableID, BigFraction> bounds) { BigFraction res = constant; for (VariableID v: coefficients.keySet()) { assert(bounds.containsKey(v)) : "Key " + v + " not bound in " + bounds.keySet(); res = res.add(bounds.get(v).multiply(coefficients.get(v))); } return res; } @Override public AbstractPoly div(BigInteger d) { assert(divisible(d)); Map<VariableID,BigFraction> Qcoeff = new HashMap<>(); BigFraction Qconstant = new BigFraction(Util.smtDivide(constant.getNumerator(),d)); for (VariableID v: coefficients.keySet()) { BigInteger c = coefficients.get(v).getNumerator(); Qcoeff.put(v, new BigFraction(Util.smtDivide(c,d))); } return new PolyBase(Qcoeff,Qconstant); } @Override public boolean divisible(BigInteger d) { if (constant.getDenominator().compareTo(BigInteger.ONE) != 0) return false; if (constant.getNumerator().mod(d).signum() != 0) return false; for (VariableID v: coefficients.keySet()) { BigFraction c = coefficients.get(v); if (c.getDenominator().compareTo(BigInteger.ONE) != 0) { return false; } if (c.getNumerator().mod(d).signum() != 0) { return false; } } return true; } public static PolyBase qpoly(BigInteger Q, VariableID k, VariableID m) { PolyBase Qk = new PolyBase(k).multiply(new BigFraction(Q)); PolyBase mp = new PolyBase(m); return Qk.add(mp); } @Override public AbstractPoly rewrite(Map<VariableID, AbstractPoly> rw) { AbstractPoly res = new PolyBase(constant); for (VariableID v: coefficients.keySet()) { BigFraction c = coefficients.get(v); AbstractPoly p = rw.get(v); if (p == null) { res = res.add(new PolyBase(c,v)); } else { res = res.add(p.multiply(c)); } } return res; } @Override public String toACL2() { String res = "(+ "; for(VariableID var : this) { res += "(* " + coefficients.get(var) + " " + var.toACL2() + ")"; } res += constant.toString(); res += ")"; return res; } @Override public Set<VariableID> updateVariableSet(Set<VariableID> in) { in.addAll(coefficients.keySet()); return in; } @Override public BigInteger leastCommonDenominator() { BigInteger q = constant.getDenominator(); for (VariableID v: this) { BigInteger d = coefficients.get(v).getDenominator(); BigInteger p = q.multiply(d); BigInteger g = q.gcd(d); q = p.divide(g); } return q; } @Override public BigInteger constantLCDContribution() { BigInteger q = BigInteger.ONE; for (VariableID v: this) { BigInteger d = coefficients.get(v).getDenominator(); BigInteger p = q.multiply(d); BigInteger g = q.gcd(d); q = p.divide(g); } BigInteger g = constant.getDenominator().gcd(q); return constant.getDenominator().divide(g); } @Override public AbstractPoly remove(VariableID x) { Map<VariableID,BigFraction> coefficients = new HashMap<>(); BigFraction constant = this.constant; for (VariableID v:this) { if (! v.equals(x)) { coefficients.put(v, this.coefficients.get(v)); } } return new PolyBase(coefficients,constant); } @Override public BigFraction dot(AbstractPoly arg) { BigFraction res = BigFraction.ZERO; for (VariableID v: this) { BigFraction prod = this.coefficients.get(v).multiply(arg.getCoefficient(v)); res = res.add(prod); } return res; } @Override public int compareTo(AbstractPoly arg) { // By convention, smaller variables are considered more significant. if (this.isConstant() && arg.isConstant()) { return this.getConstant().compareTo(arg.getConstant()); } Collection<VariableID> keys = ((PolyBase) arg).coefficients.keySet(); keys.addAll(this.coefficients.keySet()); while (! keys.isEmpty()) { VariableID minv = Collections.min(keys); BigFraction v = this.getCoefficient(minv); BigFraction w = arg.getCoefficient(minv); int cmp = v.compareTo(w); if (cmp != 0) return cmp; keys.remove(minv); } return 0; } @Override public AbstractPoly remove(AbstractPoly x) { Collection<VariableID> keys = ((PolyBase) x).coefficients.keySet(); Map<VariableID,BigFraction> coefficients = new HashMap<>(); BigFraction constant = this.constant; for (VariableID v:this) { if (! keys.contains(v)) { coefficients.put(v, this.coefficients.get(v)); } } return new PolyBase(coefficients,constant); } @Override public Set<VariableID> getVariables() { return coefficients.keySet(); } }
13,517
26.09018
100
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableBound.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.poly; import java.util.ArrayList; import java.util.List; import fuzzm.value.poly.GlobalState; import jkind.util.BigFraction; abstract public class VariableBound extends Variable { public VariableBound(VariableID vid, boolean cex) { super(vid,cex); } static RestrictionResult restrictInequalityGradient(AbstractPoly gradient, VariableInequality x, VariableInequality y) { BigFraction xg = gradient.dot(x.poly); BigFraction yg = gradient.dot(y.poly); int cmp = xg.compareTo(yg); if (cmp == 0) { cmp = x.poly.remove(gradient).compareTo(y.poly.remove(gradient)); } return restrictInequalityAux(cmp > 0,x,y); } // ACL2: (def::trueAnd restrictInequality (x y cex) static RestrictionResult restrictInequality(VariableInequality x, VariableInequality y) { int fcmp = x.countFeatures() - y.countFeatures(); boolean choosex = ((fcmp > 0) || ((fcmp == 0) && GlobalState.oracle().nextBoolean())); return restrictInequalityAux(choosex,x,y); } static RestrictionResult restrictInequalityAux(boolean prefx, VariableInequality x, VariableInequality y) { assert(x.cex && y.cex); assert(x.vid.equals(y.vid)); AbstractPoly diff = (x instanceof VariableGreater) ? y.poly.subtract(x.poly) : x.poly.subtract(y.poly); int cmp = diff.evaluateCEX().signum(); int xcmp = x.relation.compareWith(y.relation); boolean choosex = ((cmp < 0) || ((cmp == 0) && ((xcmp < 0) || ((xcmp == 0) && prefx)))); VariableInequality keep; TargetType newTarget = x.target.inherit(y.target); if (choosex) { keep = x; diff = diff.negate(); } else { keep = y; } if (diff.isConstant()) { return new RestrictionResult(keep.setTarget(newTarget)); } RelationType relation = RelationType.INCLUSIVE; if ((xcmp != 0) && (keep.relation == RelationType.INCLUSIVE)) { relation = RelationType.EXCLUSIVE; } return new RestrictionResult(keep,solvePolyGreater0(diff,relation,true,FeatureType.NONFEATURE,newTarget)); } static VariableEquality solvePolyEquality0(AbstractPoly arg, FeatureType feature, TargetType target) { assert(arg.evaluateCEX().signum() == 0); VariableID id = arg.leadingVariable(); AbstractPoly poly = arg.solveFor(id); return new VariableEquality(id,true,poly,feature, target); } static PolyBool normalizePolyEquality0(AbstractPoly arg, FeatureType feature, TargetType target) { VariableID id = arg.leadingVariable(); AbstractPoly poly = arg.solveFor(id); // x = -poly BigFraction diff = poly.evaluateCEX().subtract(id.cex); int cmp = diff.signum(); VariableBound res; if (cmp == 0) { return new TruePolyBool(new VariableEquality(id,true,poly,feature, target)); } else if (cmp < 0) { res = new VariableGreater(id,true,RelationType.EXCLUSIVE,poly,feature,target); } else { res = new VariableLess(id,true,RelationType.EXCLUSIVE,poly,feature,target); } return new TruePolyBool(res).not(); // else { // poly = poly.subtract(diff); // return new FalsePolyBool(new VariableEquality(id,true,poly,feature, target)); //} } static PolyBool normalizePolyGreater0(AbstractPoly arg, RelationType relation, FeatureType feature, TargetType target) { if (relation.gt(arg.evaluateCEX().signum())) { return new TruePolyBool(solvePolyGreater0(arg, relation, true, feature, target)); } return new TruePolyBool(solvePolyLess0(arg, relation.not(), true, feature, target)).not(); } static PolyBool normalizePolyLess0(AbstractPoly arg, RelationType relation, FeatureType feature, TargetType target) { if (relation.lt(arg.evaluateCEX().signum())) { return new TruePolyBool(solvePolyLess0(arg, relation, true, feature, target)); } return new TruePolyBool(solvePolyGreater0(arg, relation.not(), true, feature, target)).not(); } // ACL2 : (def::un solvePolyGreater0 (relation poly) static VariableInequality solvePolyGreater0(AbstractPoly poly, RelationType relation, boolean cex, FeatureType feature, TargetType target) { assert(cex && relation.gt(poly.evaluateCEX().signum())); // // Normalizes an expression of the form (<~ 0 poly) // VariableID name = poly.leadingVariable(); int sign = poly.getCoefficient(name).signum(); AbstractPoly sln = poly.solveFor(name); VariableInequality r = (sign < 0) ? new VariableLess(name,cex,relation,sln,feature,target) : new VariableGreater(name,cex,relation,sln,feature,target); //if (Debug.isEnabled()) System.out.println(ID.location() + "(< 0 " + poly + ") = " + r); return r; } // ACL2 : (def::un solvePolyLess0 (relation poly) static VariableInequality solvePolyLess0(AbstractPoly poly, RelationType relation, boolean cex, FeatureType feature, TargetType target) { return solvePolyGreater0(poly.negate(),relation,cex,feature,target); } // ACL2: (def::un restrictDisequality (xpoly ypoly relation cex) static List<Variable> restrictDisequality(AbstractPoly xpoly, AbstractPoly ypoly, RelationType relation, TargetType target) { // If you already know the relation and which variable bound to keep .. List<Variable> res = new ArrayList<>(); //if (Debug.isEnabled()) System.out.println(ID.location() + "restrictX: " + x + " & " + y); AbstractPoly diff = xpoly.subtract(ypoly); if (diff.isConstant()) { return res; } BigFraction z = diff.evaluateCEX(); int cmp = z.signum(); diff = (0 < cmp) ? diff : diff.negate(); if (! (diff.evaluateCEX().signum() >= 0)) assert(false); res.add(solvePolyGreater0(diff,relation,true,FeatureType.NONFEATURE,target)); return res; } }
6,030
38.940397
141
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/EmptyIntervalException.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.poly; public class EmptyIntervalException extends IllegalArgumentException { public EmptyIntervalException(String string) { super(string); } public EmptyIntervalException() { super(); } private static final long serialVersionUID = -4966015555719606305L; }
495
19.666667
70
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/polyBoolTest.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.poly; import java.math.BigDecimal; import fuzzm.util.Debug; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class polyBoolTest { static BigFraction valueOf(int value) { return BigFraction.valueOf(BigDecimal.valueOf(value)); } static PolyBase polyConst(int value) { return new PolyBase(valueOf(value)); } static PolyBase poly4(int cw, VariableID w, int cx, VariableID x, int cy, VariableID y, int cz, VariableID z, int c0) { PolyBase pw = new PolyBase(w).multiply(valueOf(cw)); PolyBase px = new PolyBase(x).multiply(valueOf(cx)); PolyBase py = new PolyBase(y).multiply(valueOf(cy)); PolyBase pz = new PolyBase(z).multiply(valueOf(cz)); PolyBase c = new PolyBase(valueOf(c0)); return pw.add(px).add(py).add(pz).add(c); } static PolyBase poly3(int cx, VariableID x, int cy, VariableID y, int cz, VariableID z, int c0) { PolyBase px = new PolyBase(x).multiply(valueOf(cx)); PolyBase py = new PolyBase(y).multiply(valueOf(cy)); PolyBase pz = new PolyBase(z).multiply(valueOf(cz)); PolyBase c = new PolyBase(valueOf(c0)); return px.add(py).add(pz).add(c); } static PolyBase poly2(int cx, VariableID x, int cy, VariableID y, int c0) { PolyBase px = new PolyBase(x).multiply(valueOf(cx)); PolyBase py = new PolyBase(y).multiply(valueOf(cy)); PolyBase c = new PolyBase(valueOf(c0)); return px.add(py).add(c); } static PolyBase poly1(int cx, VariableID x, int c0) { PolyBase px = new PolyBase(x).multiply(valueOf(cx)); PolyBase c = new PolyBase(valueOf(c0)); return px.add(c); } static PolyBool bound(VariableID x, PolyBase lo, PolyBase hi) { PolyBool xlo = PolyBool.less0(lo.subtract(new PolyBase(x))); PolyBool xhi = PolyBool.greater0(hi.subtract(new PolyBase(x))); return xlo.and(xhi); } // public static void error_6_26_16() { // PolyEvaluatableValue min0 = new IntegerPoly(new VariableID("min[0]")); // PolyEvaluatableValue in0 = new IntegerPoly(new VariableID("in[0]")); // PolyEvaluatableValue in1 = new IntegerPoly(new VariableID("in[1]")); // PolyEvaluatableValue in2 = new IntegerPoly(new VariableID("in[2]")); // PolyEvaluatableValue min2 = new IntegerPoly(new VariableID("min[2]")); // PolyEvaluatableValue min1 = new IntegerPoly(new VariableID("min[1]")); // PolyEvaluatableValue v128 = new IntegerPoly(new PolyBase(new BigFraction(BigInteger.valueOf(128)))); // // EvaluatableValue c1 = v128.negate().lessequal(min0).and(min0.lessequal(v128.negate())); // EvaluatableValue c2 = min0. lessequal(in0 ).and( in0.less(v128)); // EvaluatableValue c3 = in0. lessequal(in1 ).and( in1.less(v128)); // EvaluatableValue c4 = v128.negate().lessequal( in2).and( in2.less(v128)); // EvaluatableValue c5 = min2.equalop(min0); // EvaluatableValue c6 = min1.equalop(min2); // // EvaluatableValue r1 = c1.and(c2.and(c3.and(c4.and(c5.and(c6))))); // // } public static void main(String[] args) { Debug.setEnabled(true); VariableID w = VariableID.postAlloc("w",NamedType.REAL,BigFraction.ZERO); VariableID x = VariableID.postAlloc("xx",NamedType.REAL,BigFraction.ZERO); VariableID y = VariableID.postAlloc("y",NamedType.REAL,BigFraction.ZERO); VariableID z = VariableID.postAlloc("z",NamedType.REAL,BigFraction.ZERO); // Making sure that restriction does the right thing .. PolyBool f1 = PolyBool.greater0(poly2(3,x,-1,y,2)); PolyBool f2 = PolyBool.greater0(poly2(-5,x,-1,y,10)); PolyBool f3 = f1.and(f2); System.out.println("\nf3 : " + f3.toString()); // Restriction example from paper .. x.setCex(valueOf(4)); y.setCex(valueOf(1)); PolyBool e1 = PolyBool.greater0(poly2(1,x,-1,y,2)); PolyBool e2 = PolyBool.greater0(poly2(-1,x,-1,y,6)); PolyBool e3 = e1.and(e2); System.out.println("\ne3 : " + e3.toString()); // AND with restriction .. (quadratic) this looks good. x.setCex(valueOf(0)); y.setCex(valueOf(0)); z.setCex(valueOf(0)); PolyBool x1 = PolyBool.greater0(poly1(1,x,7)).and(PolyBool.greater0(poly1(-1,x,100))); PolyBool x2 = PolyBool.equal0(poly2(3,x,-1,y,7)).not(); PolyBool x3 = PolyBool.greater0(poly3(2,x,3,y,-1,z,5)); PolyBool x123 = x1.and(x2).and(x3); System.out.println("\nx123 : " + x123); PolyBool x4a = PolyBool.greater0(poly1(1,x,15)); PolyBool x4b = PolyBool.greater0(poly1(-1,x,90)); System.out.println("x4a : " + x4a); System.out.println("x4b : " + x4b); PolyBool x4 = x4a.or(x4b); System.out.println("or : " + x4); PolyBool x5 = PolyBool.greater0(poly2(4,x,-1,y,9)).and(PolyBool.greater0(poly2(-1,x,1,y,7))); PolyBool x6 = PolyBool.greater0(poly3(-3,x,5,y,-1,z,1)); PolyBool x456 = x4.and(x5).and(x6); System.out.println("\nx456 : " + x456); PolyBool x123456 = x123.and(x456); System.out.println("\nx123456 : " + x123456); // A more belabored version of our slide example .. x.setCex(valueOf(110)); y.setCex(valueOf(50)); z.setCex(valueOf(-50)); PolyBool xlo = PolyBool.less0(poly2(-1,x,0,y,100)); PolyBool xhi = PolyBool.greater0(poly2(-1,x,0,y,200)); PolyBool ylo = PolyBool.less0(poly2(3,x,-1,y,-290)); PolyBool yhi = PolyBool.greater0(poly2(-3,x,-1,y,970)); PolyBool zlo = PolyBool.less0(poly4(1,x,1,y,-1,z,0,z,-250)); PolyBool zhi = PolyBool.greater0(poly4(0,x,-1,y,-1,z,0,w,7)); PolyBool xbound = xlo.and(xhi); PolyBool ybound = xbound.and(ylo).and(yhi); PolyBool zbound = ybound.and(zlo).and(zhi); System.out.println("\nzbound : " + zbound.toString()); // This is our polyBool example from our slide deck .. xbound = bound(x,polyConst(100),polyConst(200)); ybound = bound(y,poly1(3,x,-290),poly1(-3,x,970)); zbound = bound(z,poly2(1,x,1,y,-250),poly1(-1,y,7)); PolyBool tz = xbound.and(ybound.and(zbound)); // The normalized expression cannot be System.out.println("\nNormalize : " + tz.toString()); tz = tz.normalize(); System.out.println("\nResult : " + tz.toString()); } }
6,139
40.486486
120
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableInterval.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.poly; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import fuzzm.util.ID; import fuzzm.util.Rat; import fuzzm.value.instance.RationalValue; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class VariableInterval extends VariableBound { VariableGreater gt; VariableLess lt; protected VariableInterval(VariableGreater gt, VariableLess lt) { super(gt.vid,gt.cex && lt.cex); assert(gt.vid.compareTo(lt.vid) == 0); this.gt = gt; this.lt = lt; } @Override public int countFeatures() { return gt.countFeatures() + lt.countFeatures(); } @Override public String toACL2() { return "(and " + gt.toACL2() + " " + lt.toACL2() + ")"; } @Override public String toACL2(String cex) { return "(and " + gt.toACL2(cex) + " " + lt.toACL2(cex) + ")"; } @Override public String toString() { return gt.statusString() + gt.polyString() + gt.opString(VariableLocation.RIGHT,gt.target.toString()) + vid + lt.opString(VariableLocation.LEFT,lt.target.toString()) + lt.polyString() + lt.statusString(); } @Override public String cexString() { return "(" + gt.cexString() + "&&" + lt.cexString() + ")"; } // @Override // protected VariableConstraint newConstraint() { // return new VariableRegion(gt,lt,op); // } @Override public RestrictionResult andTrue(Variable x) { assert(x.cex && this.cex); return ((VariableInterface) x).andTrue2(this); } @Override public RestrictionResult andTrue2(VariableEquality left) { return left.andTrue2(this); } // ACL2: (def::trueAnd andTrue-variableInterval-variableInterval (x y cex) @Override public RestrictionResult andTrue2(VariableInterval left) { VariableInterval right = this; RestrictionResult gt = restrictInequality(left.gt,right.gt); RestrictionResult lt = restrictInequality(left.lt,right.lt); return RestrictionResult.restrictionInterval(gt,lt); } // ACL2: (def::trueAnd andTrue-variableInterval-variableLess (x y cex) @Override public RestrictionResult andTrue2(VariableLess left) { RestrictionResult res = restrictInequality(left,lt); VariableLess less = (VariableLess) res.newConstraint; return new RestrictionResult(new VariableInterval(gt,less),res.restrictionList); } @Override // ACL2: (def::trueAnd andTrue-variableInterval-variableGreater (x y cex) public RestrictionResult andTrue2(VariableGreater left) { RestrictionResult res = restrictInequality(left,gt); VariableGreater greater = (VariableGreater) res.newConstraint; return new RestrictionResult(new VariableInterval(greater,lt),res.restrictionList); } @Override public boolean requiresRestriction() { AbstractPoly diff = lt.poly.subtract(gt.poly); return ! diff.isConstant(); } @Override public RestrictionResult restriction() { AbstractPoly diff = lt.poly.subtract(gt.poly); return new RestrictionResult(this,VariableBound.solvePolyGreater0(diff, RelationType.INCLUSIVE,true,FeatureType.NONFEATURE,lt.target.inherit(gt.target))); } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { RationalValue lower = new RationalValue(this.gt.poly.evaluate(ctx)); RationalValue upper = new RationalValue(this.lt.poly.evaluate(ctx)); return new RegionBounds(lower,this.gt.relation,upper,this.lt.relation); } @Override protected RegionBounds constraintBounds() { RationalValue lower = new RationalValue(this.gt.poly.evaluateCEX()); RationalValue upper = new RationalValue(this.lt.poly.evaluateCEX()); return new RegionBounds(lower,this.gt.relation,upper,this.lt.relation); } @Override protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx) { RegionBounds lower = this.gt.intervalBounds(ctx); RegionBounds upper = this.lt.intervalBounds(ctx); return lower.intersect(upper); } @Override public RestrictionResult andTrue2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public boolean implicitEquality() { AbstractPoly diff = lt.poly.subtract(gt.poly); if (diff.isConstant()) { BigFraction delta = diff.getConstant(); if (delta.signum() == 0) { return (gt.relation == RelationType.INCLUSIVE) && (lt.relation == RelationType.INCLUSIVE); } else if (vid.name.name.type == NamedType.INT) { if (delta.compareTo(BigFraction.ONE) < 0) { AbstractPoly base = gt.poly.subtract(gt.poly.getConstant()); BigInteger z = base.leastCommonDenominator(); if (z.compareTo(BigInteger.ONE) == 0) { return (delta.compareTo(BigFraction.ONE) < 0); } } } } return false; } @Override public Variable toEquality() { assert(implicitEquality()); AbstractPoly diff = lt.poly.subtract(gt.poly); BigFraction delta = diff.getConstant(); FeatureType newFeature = gt.feature == lt.feature ? gt.feature : FeatureType.NONFEATURE; TargetType newTarget = gt.target == lt.target ? gt.target : TargetType.TARGET; if (delta.signum() == 0) { return new VariableEquality(vid,cex,gt.poly,newFeature, newTarget); } else { BigFraction min = Rat.roundUp(gt.poly.getConstant()); BigFraction max = Rat.roundDown(lt.poly.getConstant()); if (min.compareTo(max) != 0) { System.out.println(ID.location() + this); System.out.println(ID.location() + gt.poly.getConstant() + " <= " + lt.poly.getConstant()); System.out.println(ID.location() + min + " <= " + max); System.exit(1); } AbstractPoly base = gt.poly.subtract(gt.poly.getConstant()).add(min); return new VariableEquality(vid,cex,base,newFeature,newTarget); } } @Override public Set<VariableID> updateVariableSet(Set<VariableID> in) { in = lt.updateVariableSet(in); in = gt.updateVariableSet(in); return in; } @Override public boolean slackIntegerBounds() { return lt.slackIntegerBounds() || gt.slackIntegerBounds(); } @Override public Variable tightenIntegerBounds() { VariableGreater gt = (VariableGreater) (this.gt.slackIntegerBounds() ? this.gt.tightenIntegerBounds() : this.gt); VariableLess lt = (VariableLess) (this.lt.slackIntegerBounds() ? this.lt.tightenIntegerBounds() : this.lt); return new VariableInterval(gt,lt); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { return gt.evalCEX(ctx) && lt.evalCEX(ctx); } @Override public boolean reducableIntegerInterval() { if (lt.relation == RelationType.EXCLUSIVE || gt.relation == RelationType.EXCLUSIVE) return false; boolean integerInterval = (vid.name.name.type == NamedType.INT) && !lt.poly.isConstant() && !gt.poly.isConstant(); if (! integerInterval) return false; VariableID LTvid = lt.poly.leadingVariable(); VariableID GTvid = gt.poly.leadingVariable(); int cmp = LTvid.compareTo(GTvid); if (cmp != 0) return false; boolean rationalBounds = lt.poly.leastCommonDenominator().compareTo(BigInteger.ONE) > 0 && gt.poly.leastCommonDenominator().compareTo(BigInteger.ONE) > 0; return rationalBounds; } private boolean useLT() { VariableID LTvid = lt.poly.leadingVariable(); VariableID GTvid = gt.poly.leadingVariable(); // LTvid == GTvid BigInteger LTA = lt.poly.leastCommonDenominator(); BigInteger GTA = gt.poly.leastCommonDenominator(); BigInteger C = lt.poly.getCoefficient(LTvid).multiply(LTA).getNumerator().abs(); BigInteger E = gt.poly.getCoefficient(GTvid).multiply(GTA).getNumerator().abs(); LTA = LTA.divide(LTA.gcd(C)); GTA = GTA.divide(GTA.gcd(E)); return (LTA.compareTo(GTA) <= 0); } @Override public RestrictionResult reducedInterval() { assert(reducableIntegerInterval()); if (useLT()) { // x <= lt.poly BigInteger N = lt.poly.leastCommonDenominator(); BigFraction diff = lt.poly.evaluateCEX().subtract(vid.cex); BigFraction delta0 = diff.multiply(N); assert(delta0.getDenominator().compareTo(BigInteger.ONE) == 0); // This still isn't right .. VariableID delta = lt.poly.leadingVariable().afterAlloc("delta", NamedType.INT, delta0); //System.out.println(ID.location() + delta + " allocated after " + lt.poly.leadingVariable()); //VariableID delta = VariableID.postAlloc("in", NamedType.INT, delta0); AbstractPoly eqpoly = lt.poly.subtract(new PolyBase(delta).divide(new BigFraction(N))); VariableGreater deltaBound = new VariableGreater(delta, true, RelationType.INCLUSIVE, new PolyBase(BigFraction.ZERO), lt.feature, lt.target); List<Variable> restrictions = new ArrayList<>(); eqpoly = VariableEquality.integerEqualityConstraint(eqpoly,TargetType.CHAFF,restrictions); assert(eqpoly.evaluateCEX().compareTo(vid.cex) == 0); VariableEquality newBound = new VariableEquality(vid,true,eqpoly,lt.feature,lt.target); // gt.poly <= xeq AbstractPoly gtpoly = gt.poly.subtract(eqpoly); VariableBound newGT = VariableBound.solvePolyLess0(gtpoly, RelationType.INCLUSIVE, true, gt.feature, gt.target); restrictions.add(newGT); restrictions.add(deltaBound); return new RestrictionResult(newBound,restrictions); } else { BigInteger N = gt.poly.leastCommonDenominator(); BigFraction diff = vid.cex.subtract(gt.poly.evaluateCEX()); BigFraction delta0 = diff.multiply(N); assert(delta0.getDenominator().compareTo(BigInteger.ONE) == 0); VariableID delta = gt.poly.leadingVariable().afterAlloc("delta", NamedType.INT, delta0); //System.out.println(ID.location() + delta + " allocated after " + gt.poly.leadingVariable()); //VariableID delta = VariableID.postAlloc("delta", NamedType.INT, delta0); AbstractPoly eqpoly = gt.poly.add(new PolyBase(delta).divide(new BigFraction(N))); VariableGreater deltaBound = new VariableGreater(delta, true, RelationType.INCLUSIVE, new PolyBase(BigFraction.ZERO), gt.feature, gt.target); List<Variable> restrictions = new ArrayList<>(); eqpoly = VariableEquality.integerEqualityConstraint(eqpoly,TargetType.CHAFF,restrictions); assert(eqpoly.evaluateCEX().compareTo(vid.cex) == 0); VariableEquality newBound = new VariableEquality(vid,true,eqpoly,gt.feature,gt.target); // xeq <= lt.poly AbstractPoly ltpoly = eqpoly.subtract(lt.poly); VariableBound newLT = VariableBound.solvePolyLess0(ltpoly, RelationType.INCLUSIVE, true, lt.feature, lt.target); restrictions.add(newLT); restrictions.add(deltaBound); return new RestrictionResult(newBound,restrictions); } } @Override public VariableInterval rewrite(Map<VariableID, AbstractPoly> rewrite) { return new VariableInterval(gt.rewrite(rewrite),lt.rewrite(rewrite)); } @Override public AbstractPoly maxBound(int sign) { if (sign > 0) { return lt.poly.negate(); } if (sign < 0) { return gt.poly; } return new PolyBase(BigFraction.ZERO); } @Override public BigFraction maxValue(int sign, Map<VariableID,BigFraction> ctx) { if (sign < 0) { return gt.poly.evaluate(ctx); } return lt.poly.evaluate(ctx); } @Override public RestrictionResult mustContain(AbstractPoly v) { List<Variable> restrictions = new ArrayList<>(); restrictions.addAll(gt.mustContain(v).restrictionList); restrictions.addAll(lt.mustContain(v).restrictionList); return new RestrictionResult(this,restrictions); } @Override public Variable target(boolean trueL, Variable right) { return right.target2(!trueL, this); } @Override public Variable target2(boolean trueL, VariableEquality left) { return new VariableInterval((VariableGreater) this.gt.target2(trueL,left),(VariableLess) this.lt.target2(trueL,left)); } @Override public Variable target2(boolean trueL, VariableInterval left) { if (trueL) { return new VariableInterval((VariableGreater) this.gt.target2(trueL,left.gt),(VariableLess) this.lt.target2(trueL,left.lt)); } else { return new VariableInterval((VariableGreater) this.gt.target2(trueL,left.lt),(VariableLess) this.lt.target2(trueL,left.gt)); } } @Override public Variable target2(boolean trueL, VariableLess left) { if (trueL) { return new VariableInterval(this.gt,(VariableLess) this.lt.target2(trueL,left)); } else { return new VariableInterval((VariableGreater) this.gt.target2(trueL,left),this.lt); } } @Override public Variable target2(boolean trueL, VariableGreater left) { if (trueL) { return new VariableInterval((VariableGreater) this.gt.target2(trueL,left),this.lt); } else { return new VariableInterval(this.gt,(VariableLess) this.lt.target2(trueL,left)); } } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable minSet(Variable right) { return right.minSet2(this); } @Override public Variable minSet2(VariableEquality left) { return left; } @Override public Variable minSet2(VariableInterval left) { return new VariableInterval((VariableGreater) this.gt.minSet2(left.gt),(VariableLess) this.lt.minSet2(left.lt)); } @Override public Variable minSet2(VariableLess left) { return new VariableInterval(this.gt,(VariableLess) this.lt.minSet2(left)); } @Override public Variable minSet2(VariableGreater left) { return new VariableInterval((VariableGreater) this.gt.minSet2(left),this.lt); } @Override public Variable minSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public boolean isTarget() { return lt.isTarget() || gt.isTarget(); } @Override public boolean isArtifact() { return lt.isArtifact() || gt.isArtifact(); } @Override public Variable maxSet(Variable right) { return right.maxSet2(this); } @Override public Variable maxSet2(VariableEquality left) { return this; } @Override public Variable maxSet2(VariableInterval left) { return new VariableInterval((VariableGreater) this.gt.maxSet2(left.gt),(VariableLess) this.lt.maxSet2(left.lt)); } @Override public Variable maxSet2(VariableLess left) { return new VariableInterval(this.gt,(VariableLess) this.lt.maxSet2(left)); } @Override public Variable maxSet2(VariableGreater left) { return new VariableInterval((VariableGreater) this.gt.maxSet2(left),this.lt); } @Override public Variable maxSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(Variable.target(this, true, left.v, false)); } @Override public Variable minSet2(VariablePhantom left) { return this; } @Override public Variable maxSet2(VariablePhantom left) { return this; } @Override public Variable target2(boolean trueL, VariablePhantom left) { return Variable.target(this, true, left.v, trueL); } }
15,429
31.621564
206
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableLess.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.poly; import java.math.BigInteger; import java.util.Map; import fuzzm.util.Rat; import fuzzm.value.instance.RationalInfinity; import fuzzm.value.instance.RationalValue; import jkind.lustre.BinaryOp; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class VariableLess extends VariableInequality { protected VariableLess(VariableID name, boolean cex, RelationType relation, AbstractPoly poly, FeatureType feature, TargetType target) { super(name,cex,relation,poly,feature,target); assert((relation == RelationType.EXCLUSIVE) ? cex == (name.cex.compareTo(poly.evaluateCEX()) < 0) : cex == (name.cex.compareTo(poly.evaluateCEX()) <= 0)); } protected VariableLess(VariableID name, AbstractPoly poly, boolean cex, TargetType target) { this(name,cex,RelationType.EXCLUSIVE,poly,FeatureType.FEATURE,target); } protected VariableLess(VariableID name, AbstractPoly poly, RelationType relation, boolean cex, TargetType target) { this(name,cex,relation,poly,FeatureType.FEATURE,target); } // // protected VariableLess(VariableID name, RelationType relation, AbstractPoly poly, FeatureType feature, boolean cex) { // this(name,OpType3.NEITHER,relation,poly,feature,cex,TerminalBool.ANY); // } // // protected VariableLess(VariableLess source, VariableID name, RelationType relation, AbstractPoly poly, boolean cex) { // this(name,source.listOp,relation,poly,FeatureType.NONFEATURE,cex,source.context); // } // // public VariableLess(VariableInequality source, boolean cex, RelationType relation) { // this(source.vid,cex,relation,source.poly,source.feature); // } // public VariableLess(VariableLess source, TargetType target) { this(source.vid,source.cex,source.relation,source.poly,source.feature,target); } // // conjoin() // @Override // public VariableConstraint newConstraint(VariableID name, RelationType relation, AbstractPoly poly, boolean cex) { // return new VariableLess(this,name,relation,poly,cex); // } // // cons() // @Override // protected VariableConstraint newConstraint(BooleanContext context) { // return new VariableLess(this,context); // } @Override public String toACL2() { return toACL2(vid.cex.toString()); } @Override public String toACL2(String cex) { return "(<" + ((relation == RelationType.INCLUSIVE) ? "= " : " ") + vid.toACL2(cex) + poly.toACL2() + ")"; } @Override public String toString() { return vid + opString(VariableLocation.LEFT,target.toString()) + poly + statusString(); } @Override public String cexString() { return vid.cex + opString(VariableLocation.LEFT,target.toString()) + poly.cexString(); } @Override protected String opString(VariableLocation location, String target) { String inclusive = ((relation == RelationType.INCLUSIVE) ? "=" : ""); return (location.equals(VariableLocation.LEFT) ? " " + target + "<" + inclusive + " " : " " + inclusive + ">" + target + " "); } @Override protected String polyString() { return poly.toString(); } @Override public RestrictionResult andTrue(Variable x) { assert(cex && x.cex); RestrictionResult res = ((VariableInterface) x).andTrue2(this); return res; } @Override public RestrictionResult andTrue2(VariableEquality left) { return left.andTrue2(this); } @Override public RestrictionResult andTrue2(VariableInterval left) { return left.andTrue2(this); } // ACL2: (def::trueAnd andTrue-variableLess-variableLess (x y cex) @Override public RestrictionResult andTrue2(VariableLess left) { VariableLess p1 = left; VariableLess p2 = this; return restrictInequality(p1,p2); } // ACL2: (def::trueAnd andTrue-variableGreater-variableLess (x y cex) @Override public RestrictionResult andTrue2(VariableGreater left) { return new RestrictionResult(new VariableInterval(left,this)); } // ACL2: (def::un chooseBestComplement-variabeLess-variableInterval (x y) @Override public VariableInequality chooseBestCompliment(VariableInterval arg) { if (arg.lt.countFeatures() > arg.gt.countFeatures()) { return arg.lt; } return arg.gt; } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { RationalValue bound = new RationalValue(poly.evaluate(ctx)); return new RegionBounds(RationalInfinity.NEGATIVE_INFINITY,RelationType.INCLUSIVE,bound,relation); } @Override protected RegionBounds constraintBounds() { RationalValue bound = new RationalValue(poly.evaluateCEX()); return new RegionBounds(RationalInfinity.NEGATIVE_INFINITY,RelationType.INCLUSIVE,bound,relation); } @Override protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx) { RegionBounds x = poly.polyBounds(ctx); return new RegionBounds(RationalInfinity.NEGATIVE_INFINITY,RelationType.INCLUSIVE,RelationType.INCLUSIVE,x.upper,x.upperType.inclusiveAND(this.relation)); } @Override public RestrictionResult andTrue2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public boolean slackIntegerBounds() { if (this.vid.name.name.type != NamedType.INT) return false; return ((this.relation == RelationType.EXCLUSIVE) || (this.poly.constantLCDContribution().compareTo(BigInteger.ONE) != 0)); } @Override public Variable tightenIntegerBounds() { assert(slackIntegerBounds()); BigInteger L = this.poly.leastCommonDenominator(); if ((this.relation == RelationType.EXCLUSIVE) && (this.poly.constantLCDContribution().compareTo(BigInteger.ONE) == 0)) { return new VariableLess(vid, this.poly.subtract(BigFraction.ONE.divide(L)), RelationType.INCLUSIVE, cex, target); } BigInteger G = this.poly.constantLCDContribution(); L = L.divide(G); BigFraction C = this.poly.getConstant(); AbstractPoly res = this.poly.subtract(C); C = Rat.roundDown(C.multiply(L)); res = res.add(C.divide(L)); return new VariableLess(vid,res,RelationType.INCLUSIVE,cex, target); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { BigFraction p = poly.evaluate(ctx); BigFraction x = ctx.get(this.vid); return (this.relation == RelationType.EXCLUSIVE) ? (x.compareTo(p) < 0) : (x.compareTo(p) <= 0); } @Override public VariableLess rewrite(Map<VariableID, AbstractPoly> rewrite) { return new VariableLess(vid, cex, relation, poly.rewrite(rewrite), feature, target); } @Override public AbstractPoly maxBound(int sign) { if (sign > 0) { return poly.negate(); } return new PolyBase(BigFraction.ZERO); } @Override public RestrictionResult mustContain(AbstractPoly v) { // v <~ poly // 0 <~ poly - v AbstractPoly diff = poly.subtract(v); assert(0 < diff.evaluateCEX().signum() || ((relation == RelationType.INCLUSIVE) && diff.evaluateCEX().signum() == 0)); if (diff.isConstant()) { return new RestrictionResult(this); } else { VariableBound res = VariableBound.solvePolyGreater0(diff, relation, cex, FeatureType.NONFEATURE, target); return new RestrictionResult(this,res); } } @Override public Variable target(boolean trueL, Variable right) { return right.target2(!trueL, this); } @Override public VariableLess target2(boolean trueL, VariableInterval left) { return (VariableLess) (trueL ? this.target2(trueL,left.lt) : Variable.target(this,true,left.gt,!trueL)); } @Override public VariableLess target2(boolean trueL, VariableEquality left) { if (trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp < 0) || ((cmp == 0) && (this.relation == RelationType.EXCLUSIVE)); return target ? new VariableLess(this,TargetType.TARGET) : this; } @Override public VariableLess target2(boolean trueL, VariableGreater left) { if (trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp < 0) || ((cmp == 0) && ((this.relation == RelationType.EXCLUSIVE) || (left.relation == RelationType.EXCLUSIVE))); return target ? new VariableLess(this,TargetType.TARGET) : this; } @Override public VariableLess target2(boolean trueL, VariableLess left) { if (! trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp < 0) || ((cmp == 0) && ((this.relation == RelationType.EXCLUSIVE) || (left.relation == RelationType.INCLUSIVE))); return target ? new VariableLess(this,TargetType.TARGET) : this; } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable minSet(Variable right) { return right.minSet2(this); } @Override public Variable minSet2(VariableEquality left) { return left; } @Override public Variable minSet2(VariableInterval left) { return new VariableInterval(left.gt,(VariableLess) this.minSet2(left.lt)); } @Override public Variable minSet2(VariableLess left) { int cmp = left.poly.evaluateCEX().compareTo(this.poly.evaluateCEX()); // Return the smallest bound .. if ((cmp < 0) || ((cmp == 0) && this.relation == RelationType.INCLUSIVE)) { return left; } return this; } @Override public Variable minSet2(VariableGreater left) { return new VariableInterval(left,this); } @Override public Variable minSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable maxSet(Variable right) { return right.maxSet2(this); } @Override public Variable maxSet2(VariableEquality left) { return this; } @Override public Variable maxSet2(VariableInterval left) { return new VariableInterval(left.gt,(VariableLess) this.maxSet2(left.lt)); } @Override public Variable maxSet2(VariableLess left) { int cmp = left.poly.evaluateCEX().compareTo(this.poly.evaluateCEX()); if ((cmp < 0) || ((cmp == 0) && this.relation == RelationType.INCLUSIVE)) { return this; } return left; } @Override public Variable maxSet2(VariableGreater left) { return new VariableInterval(left,this); } @Override public Variable maxSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(Variable.target(this, true, left.v, false)); } @Override public Variable minSet2(VariablePhantom left) { return this; } @Override public Variable maxSet2(VariablePhantom left) { return this; } @Override public Variable target2(boolean trueL, VariablePhantom left) { return Variable.target(this, true, left.v, trueL); } @Override public VariableRelation setTarget(TargetType target) { return (isTarget() || target == TargetType.CHAFF) ? this : new VariableLess(this,TargetType.TARGET); } @Override public BinaryOp binaryOp() { return (relation == RelationType.EXCLUSIVE) ? BinaryOp.LESS : BinaryOp.LESSEQUAL; } }
11,602
31.869688
156
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/FalsePolyBool.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.poly; import java.util.List; import fuzzm.lustre.evaluation.PolyFunctionMap; import fuzzm.solver.SolverResults; import fuzzm.util.RatSignal; public class FalsePolyBool extends PolyBool { protected FalsePolyBool(boolean cex, VariableList body) { super(cex, body); assert(! cex); } protected FalsePolyBool(Variable var) { this(! var.cex, new VariableList(var)); } @Override public String toString() { String res = "(not (\n "; String delimit = ""; for (Variable vc: body) { res += delimit + vc; delimit = " &\n "; } return res + "\n))"; } @Override public String toACL2() { String res = "(not (and\n"; for (Variable vc: body) { res += vc.toACL2() + "\n"; } return res + "))"; } @Override public boolean isNegated() { return true; } @Override public PolyBool not() { return new TruePolyBool(! cex,body); } @Override public boolean isAlwaysFalse() { return (body.size() == 0); } @Override public boolean isAlwaysTrue() { return false; } @Override public PolyBool normalize() { return this; } @Override public SolverResults optimize(SolverResults cex, PolyFunctionMap fmap, RatSignal target) { return cex; } @Override public List<Variable> getArtifacts() { throw new IllegalArgumentException(); } @Override public List<Variable> getTargets() { throw new IllegalArgumentException(); } }
1,652
17.573034
91
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariablePhantom.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.poly; import java.util.Map; import java.util.Set; import jkind.util.BigFraction; public class VariablePhantom extends VariableBound { // Phantom variables are created by andTF() when a True // variable constraint has no corresponding False constraint. // Phantom variables can be safely ignored during test generation. // Their only purpose in life is to help identify Target opportunities. // // DAG - it would be nice to have a tighter formal spec for phantom variables. // // DAG - I suspect that we will need to incorporate a negation bit to model // multiple level phantom variables .. we saw examples of that in the // dot arrow example after adding hyps. // Variable v; boolean polarity; public VariablePhantom(Variable v) { super(v.vid, v.cex); if (v instanceof VariablePhantom) { this.v = ((VariablePhantom) v).v; this.polarity = ! ((VariablePhantom) v).polarity; } else { this.v = v; this.polarity = false; } } @Override public RestrictionResult andTrue(Variable arg) { return arg.andTrue2(this); } @Override public RestrictionResult andTrue2(VariableEquality left) { Variable res = Variable.target(left, true, this.v, polarity); return new RestrictionResult(res); } @Override public RestrictionResult andTrue2(VariableInterval left) { Variable res = Variable.target(left, true, this.v, polarity); return new RestrictionResult(res); } @Override public RestrictionResult andTrue2(VariableLess left) { Variable res = Variable.target(left, true, this.v, polarity); return new RestrictionResult(res); } @Override public RestrictionResult andTrue2(VariableGreater left) { Variable res = Variable.target(left, true, this.v, polarity); return new RestrictionResult(res); } @Override public RestrictionResult andTrue2(VariableBoolean left) { Variable res = Variable.target(left, true, this.v, polarity); return new RestrictionResult(res); } @Override public Variable minSet(Variable right) { return right; } @Override public Variable minSet2(VariableEquality left) { return left; } @Override public Variable minSet2(VariableInterval left) { return left; } @Override public Variable minSet2(VariableLess left) { return left; } @Override public Variable minSet2(VariableGreater left) { return left; } @Override public Variable minSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable maxSet(Variable right) { return right; } @Override public Variable maxSet2(VariableEquality left) { return left; } @Override public Variable maxSet2(VariableInterval left) { return left; } @Override public Variable maxSet2(VariableLess left) { return left; } @Override public Variable maxSet2(VariableGreater left) { return left; } @Override public Variable maxSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable target(boolean trueL, Variable right) { return right.target2(! trueL, this); } @Override public Variable target2(boolean trueL, VariableEquality left) { // We need test cases for these .. I think v should be negated. return new VariablePhantom(Variable.target(v,polarity,left,!trueL)); } @Override public Variable target2(boolean trueL, VariableInterval left) { return new VariablePhantom(Variable.target(v,polarity,left,!trueL)); } @Override public Variable target2(boolean trueL, VariableLess left) { return new VariablePhantom(Variable.target(v,polarity,left,!trueL)); } @Override public Variable target2(boolean trueL, VariableGreater left) { return new VariablePhantom(Variable.target(v,polarity,left,!trueL)); } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public String toString() { return "PHI(" + v.toString() + ")"; } @Override public String toACL2() { return "#+joe" + v.toACL2(); } @Override public String toACL2(String cex) { return "#+joe" + v.toACL2(cex); } @Override public String cexString() { return ""; } @Override public int countFeatures() { return 0; } @Override public boolean implicitEquality() { return false; } @Override public Variable toEquality() { throw new IllegalArgumentException(); } @Override public boolean requiresRestriction() { return false; } @Override public RestrictionResult restriction() { throw new IllegalArgumentException(); } @Override public boolean slackIntegerBounds() { return false; } @Override public Variable tightenIntegerBounds() { throw new IllegalArgumentException(); } @Override public boolean reducableIntegerInterval() { return false; } @Override public RestrictionResult reducedInterval() { throw new IllegalArgumentException(); } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { throw new IllegalArgumentException(); } @Override protected RegionBounds constraintBounds() { throw new IllegalArgumentException(); } @Override protected RegionBounds intervalBounds(Map<VariableID, RegionBounds> ctx) { throw new IllegalArgumentException(); } @Override public Set<VariableID> updateVariableSet(Set<VariableID> in) { throw new IllegalArgumentException(); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { throw new IllegalArgumentException(); } @Override public Variable rewrite(Map<VariableID, AbstractPoly> rewrite) { return new VariablePhantom(v.rewrite(rewrite)); } @Override public AbstractPoly maxBound(int sign) { throw new IllegalArgumentException(); } @Override public BigFraction maxValue(int sign, Map<VariableID, BigFraction> ctx) { throw new IllegalArgumentException(); } @Override public RestrictionResult mustContain(AbstractPoly v) { throw new IllegalArgumentException(); } @Override public boolean isTarget() { return false; } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(new VariablePhantom(Variable.maxSet(v,left.v))); } @Override public Variable minSet2(VariablePhantom left) { return new VariablePhantom(Variable.minSet(v,left.v)); } @Override public Variable maxSet2(VariablePhantom left) { return new VariablePhantom(Variable.maxSet(v,left.v)); } @Override public Variable target2(boolean trueL, VariablePhantom left) { return new VariablePhantom(Variable.target(this.v, this.polarity, left.v, (!trueL) ^ left.polarity)); } @Override public boolean isArtifact() { return false; } }
7,729
28.06015
109
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableInterface.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.poly; public interface VariableInterface { public RestrictionResult andTrue(Variable right); public RestrictionResult andTrue2(VariableEquality left); public RestrictionResult andTrue2(VariableInterval left); public RestrictionResult andTrue2(VariableLess left); public RestrictionResult andTrue2(VariableGreater left); public RestrictionResult andTrue2(VariableBoolean left); public RestrictionResult andTrue2(VariablePhantom left); public Variable minSet(Variable right); public Variable minSet2(VariableEquality left); public Variable minSet2(VariableInterval left); public Variable minSet2(VariableLess left); public Variable minSet2(VariableGreater left); public Variable minSet2(VariableBoolean left); public Variable minSet2(VariablePhantom left); public Variable maxSet(Variable right); public Variable maxSet2(VariableEquality left); public Variable maxSet2(VariableInterval left); public Variable maxSet2(VariableLess left); public Variable maxSet2(VariableGreater left); public Variable maxSet2(VariableBoolean left); public Variable maxSet2(VariablePhantom left); public Variable target (boolean trueL, Variable right); public Variable target2(boolean trueL, VariableEquality left); public Variable target2(boolean trueL, VariableInterval left); public Variable target2(boolean trueL, VariableLess left); public Variable target2(boolean trueL, VariableGreater left); public Variable target2(boolean trueL, VariableBoolean left); public Variable target2(boolean trueL, VariablePhantom left); }
1,853
43.142857
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/FeatureType.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.poly; public enum FeatureType { FEATURE, NONFEATURE }
281
19.142857
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableEquality.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.poly; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Map; import fuzzm.util.BigIntegerEEA; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.value.instance.RationalValue; import jkind.lustre.BinaryOp; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class VariableEquality extends VariableRelation { protected VariableEquality(VariableID name, boolean cex, AbstractPoly poly, FeatureType feature, TargetType target) { super(name,cex,RelationType.INCLUSIVE,poly,feature,target); assert(cex == (name.cex.compareTo(poly.evaluateCEX()) == 0)); } protected VariableEquality(VariableID name, AbstractPoly poly, boolean cex, TargetType target) { this(name,cex,poly,FeatureType.FEATURE,target); } // // protected VariableEquality(VariableEquality source, VariableID name, boolean cex, RelationType relation, AbstractPoly poly) { // // Use only for non-features .. // this(name,cex,relation,poly,FeatureType.NONFEATURE); // } // protected VariableEquality(VariableEquality source, TargetType target) { this(source.vid,source.cex,source.poly,source.feature,target); } // protected VariableEquality(VariableEquality source) { // this(source.vid,context.listOp,source.relation,source.poly,source.feature,source.cex,context); // } // // @Override // public int direction() { // return 0; // } // // @Override // public VariableConstraint newConstraint(VariableID name, RelationType relation, AbstractPoly poly, boolean cex) { // return new VariableEquality(this,name,relation,poly,cex); // } // // @Override // protected VariableConstraint newConstraint(BooleanContext context) { // return new VariableEquality(this,context); // } @Override public String toACL2() { return toACL2(vid.cex.toString()); } @Override public String toACL2(String cex) { return "(" + "= " + vid.toACL2(cex) + poly.toACL2() + ")"; } @Override public String toString() { return vid + opString(VariableLocation.LEFT,target.toString()) + poly + statusString() ; } @Override public String cexString() { return vid.cex + "= " + poly.cexString(); } @Override protected String opString(VariableLocation location, String target) { return " " + target + "= "; } @Override protected String polyString() { return poly.toString(); } @Override public RestrictionResult andTrue(Variable x) { assert(cex && x.cex); return ((VariableInterface) x).andTrue2(this); } // // ACL2: (def::un linearizeTrue(x cex) // static VariableInequality linearizeTrue(VariableID v, VariableEquality eq) { // int sign = v.cex.compareTo(eq.poly.evaluateCEX()); // if (sign < 0) { // return new VariableLess(v,eq.poly,eq.relation,true); // } // if (sign > 0) { // return new VariableGreater(v,eq.poly,eq.relation,true); // } // // sign == 0 // return null; // } // ACL2: (def::un restrictEquality (x y) static RestrictionResult restrictEquality(VariableEquality x, VariableEquality y) { AbstractPoly diff = x.poly.subtract(y.poly); if (diff.isConstant()) return new RestrictionResult(x); VariableID vid = diff.leadingVariable(); AbstractPoly sln = diff.solveFor(vid); VariableEquality res = new VariableEquality(vid,true,sln,x.feature,x.target.inherit(y.target)); return new RestrictionResult(x,res); } // ACL2: (def::trueAnd andTrue-variableEquality-variableLess (x y cex) @Override public RestrictionResult andTrue2(VariableLess left) { RestrictionResult res = new RestrictionResult(this,VariableBound.restrictDisequality(this.poly, left.poly, left.relation, left.target.inherit(this.target))); return res; } // ACL2: (def::trueAnd andTrue-variableEquality-variableGreater (x y cex) @Override public RestrictionResult andTrue2(VariableGreater left) { RestrictionResult res = new RestrictionResult(this,VariableBound.restrictDisequality(left.poly, this.poly, left.relation, left.target.inherit(this.target))); return res; } // ACL2: (def::trueAnd andTrue-variableEquality-variableInterval (x y cex) @Override public RestrictionResult andTrue2(VariableInterval left) { List<Variable> list = VariableBound.restrictDisequality(this.poly,left.lt.poly,left.lt.relation, left.lt.target.inherit(this.target)); list.addAll( VariableBound.restrictDisequality(left.gt.poly,this.poly,left.gt.relation, left.gt.target.inherit(this.target))); RestrictionResult res = new RestrictionResult(this,list); return res; } // ACL2: (def::trueAnd andTrue-variableEquality-variableEquality (x y cex) @Override public RestrictionResult andTrue2(VariableEquality left) { VariableEquality x; VariableEquality y; if (left.countFeatures() < this.countFeatures()) { x = this; y = left; } else { x = left; y = this; } return restrictEquality(x,y); } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { RationalValue value = new RationalValue(poly.evaluate(ctx)); return new RegionBounds(value,RelationType.INCLUSIVE,relation,value,RelationType.INCLUSIVE); } @Override protected RegionBounds constraintBounds() { RationalValue value = new RationalValue(poly.evaluateCEX()); return new RegionBounds(value,RelationType.INCLUSIVE,relation,value,RelationType.INCLUSIVE); } @Override protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx) { return poly.polyBounds(ctx); } // static VariableBound linearizeFalse(VariableID v, VariableEquality eq) { // int sign = v.cex.compareTo(eq.poly.evaluateCEX()); // // System.out.println(ID.location() + v + "[" + v.cex + "] = " + eq.poly + "[" + eq.poly.evaluateCEX() + "]"); // if (sign > 0) { // return new VariableGreater(v,eq.poly,eq.relation,true); // } // if (sign < 0) { // return new VariableLess(v,eq.poly,eq.relation,true); // } // throw new IllegalArgumentException(); // } @Override public RestrictionResult andTrue2(VariableBoolean left) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } public static VariableEquality solveEquality(VariableID x, AbstractPoly poly, boolean cex, TargetType target) { AbstractPoly diff = poly.subtract(new PolyBase(x)); VariableID vid = diff.leadingVariable(); diff = diff.solveFor(vid); return new VariableEquality(vid,diff,cex,target); } public static AbstractPoly integerEqualityConstraint(AbstractPoly poly, TargetType target, List<Variable> res) { // gAx = gBy + Cz + D // gA(Bk) = gB(Ak) // gA(iA(Cz+d)/g) = gB(-iB(Cz + D)/g) + (Cz + D) // // gA(Bk + iA*(Cz + D)/g) = gB(Ak - iB(Cz + D)/g)) + (Cz + D) if (poly.isConstant()) return poly; BigInteger gA = poly.leastCommonDenominator(); if (gA.compareTo(BigInteger.ONE) == 0) return poly; // In some sense it feels like we are just doing this .. but I don't think that is quite true. // BigFraction cex = poly.evaluateCEX(); // // We really do depend on k being "smaller" than .. whatever the current var is. // VariableID k = VariableID.alloc("z", NamedType.INT, cex); // Variable eq = solveEquality(k, poly, true); // res.add(eq); // AbstractPoly kpoly = new PolyBase(k); // return kpoly; AbstractPoly ipoly = poly.multiply(new BigFraction(gA)); //System.out.println(ID.location() + "Constraining : " + gA + "(x) = " + ipoly); //System.out.println(ID.location() + "Constraining : " + A + "(x) = " + ipoly.cexString()); VariableID yid = ipoly.leadingVariable(); AbstractPoly reduced = ipoly.remove(yid); if (reduced.isConstant()) { BigFraction fgB = ipoly.getCoefficient(yid); // g *must* be equal to 1 .. right? assert(fgB.getDenominator().compareTo(BigInteger.ONE) == 0); VariableID k = yid.afterAlloc("eq", NamedType.INT, BigFraction.ZERO); //System.out.println(ID.location() + k + " allocated after " + yid); AbstractPoly y = new PolyBase(k).multiply(new BigFraction(gA)).add(yid.cex); //System.out.println(ID.location() + "Constraint : " + yid + " = " + y); Variable eq = solveEquality(yid, y, true,target); res.add(eq); reduced = reduced.add(y.multiply(fgB)); //System.out.println(ID.location() + "Updated Poly : " + gA + "(x) = " + reduced); reduced = reduced.divide(new BigFraction(gA)); assert(reduced.evaluateCEX().compareTo(poly.evaluateCEX()) == 0); return reduced; } else { BigFraction fgB = ipoly.getCoefficient(yid); assert(fgB.getDenominator().compareTo(BigInteger.ONE) == 0); BigInteger gB = fgB.getNumerator(); BigIntegerEEA eea = new BigIntegerEEA(gA,gB); BigInteger g = eea.gcd; BigInteger A = gA.divide(g); //BigInteger B = gB.divide(g); AbstractPoly inner = reduced.divide(new BigFraction(eea.gcd)); inner = integerEqualityConstraint(inner,target,res); AbstractPoly y = inner.multiply(new BigFraction(eea.iB.negate())); BigFraction fkcex = yid.cex.subtract(y.evaluateCEX()); assert(fkcex.getDenominator().compareTo(BigInteger.ONE) == 0); BigInteger kcex = fkcex.getNumerator(); assert(kcex.mod(A.abs()).compareTo(BigInteger.ZERO) == 0); kcex = kcex.divide(A); VariableID k = reduced.leadingVariable().afterAlloc("eq", NamedType.INT, new BigFraction(kcex)); //System.out.println(ID.location() + k + " allocated after " + reduced.leadingVariable()); y = y.add(new PolyBase(k).multiply(new BigFraction(A))); // System.out.println(ID.location()); // System.out.println("Poly : " + poly); // System.out.println("Poly : " + poly.cexString()); // System.out.println("gA : " + gA); // System.out.println("iPoly : " + ipoly); // System.out.println("iPoly : " + ipoly.cexString()); // System.out.println("yid : " + yid); // System.out.println("yid : " + yid.cex); // System.out.println("fgB : " + fgB); // System.out.println("A : " + A); // System.out.println("B : " + B); // System.out.println("inner : " + inner); // System.out.println("inner : " + inner.cexString()); // System.out.println("-iB : " + eea.iB.negate()); // System.out.println("y : " + y); // System.out.println("y : " + y.cexString()); // System.out.println("kcex : " + kcex); assert(y.evaluateCEX().compareTo(yid.cex) == 0); //System.out.println(ID.location() + "Constraint : " + yid + " = " + y); //System.out.println(ID.location() + "Constraint : " + yid.cex + " = " + y.cexString()); Variable eq = solveEquality(yid,y,true,target); res.add(eq); reduced = reduced.add(y.multiply(fgB)); //System.out.println(ID.location() + "Updated Poly : " + gA + "(x) = " + reduced); reduced = reduced.divide(new BigFraction(gA)); assert(reduced.evaluateCEX().compareTo(poly.evaluateCEX()) == 0); return reduced; } } @Override public boolean requiresRestriction() { return cex && (this.relation == RelationType.INCLUSIVE) && (vid.name.name.type == NamedType.INT); } @Override public RestrictionResult restriction() { assert(requiresRestriction()); List<Variable> res = new ArrayList<>(); AbstractPoly poly = integerEqualityConstraint(this.poly,target,res); if (Debug.isEnabled()) { System.out.println(ID.location() + "Initial Equality : " + this); System.out.println(ID.location() + "Initial Equality : " + this.cexString()); for (Variable v: res) { System.out.println(ID.location() + "Integer Contraint : " + v); System.out.println(ID.location() + "Integer Contraint : " + v.cexString()); } } //System.out.println(ID.location() + "Pre Final Equality : " + vid + " = " + poly); //System.out.println(ID.location() + "Pre Final Equality : " + vid.cex + " = " + poly.cexString()); VariableEquality ve = new VariableEquality(vid,poly,true,target); if (Debug.isEnabled()) { System.out.println(ID.location() + "Final Equality : " + ve); System.out.println(ID.location() + "Final Equality : " + ve.cexString()); } return new RestrictionResult(ve,res); } @Override public boolean slackIntegerBounds() { return false; } @Override public Variable tightenIntegerBounds() { throw new IllegalArgumentException(); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { BigFraction p = poly.evaluate(ctx); BigFraction x = ctx.get(this.vid); return (x.compareTo(p) == 0) ^ (this.relation == RelationType.EXCLUSIVE); } @Override public VariableEquality rewrite(Map<VariableID, AbstractPoly> rewrite) { return new VariableEquality(vid, cex, poly.rewrite(rewrite), feature,target); } @Override public AbstractPoly maxBound(int sign) { return new PolyBase(BigFraction.ZERO); } @Override public RestrictionResult mustContain(AbstractPoly v) { // v == poly // 0 == poly - v AbstractPoly diff = poly.subtract(v); assert(diff.evaluateCEX().signum() == 0); if (diff.isConstant()) { return new RestrictionResult(this); } else { VariableEquality res = VariableBound.solvePolyEquality0(diff, FeatureType.NONFEATURE, target); return new RestrictionResult(this,res); } } @Override public Variable target(boolean trueL, Variable right) { return right.target2(!trueL,this); } @Override public VariableEquality target2(boolean trueL, VariableInterval left) { VariableEquality z1 = (VariableEquality) this.target2(trueL,left.lt); if (z1.isTarget()) return z1; return this.target2(trueL,left.gt); } @Override public VariableEquality target2(boolean trueL, VariableEquality left) { int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); return ((cmp == 0) == trueL) ? new VariableEquality(this,TargetType.TARGET) : this; } @Override public VariableEquality target2(boolean trueL, VariableLess left) { int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); cmp = trueL ? cmp : (- cmp); RelationType rel = trueL ? left.relation : left.relation.not(); boolean target = (cmp < 0) || (cmp == 0) && (rel == RelationType.INCLUSIVE); return target ? new VariableEquality(this,TargetType.TARGET) : this; } @Override public VariableEquality target2(boolean trueL, VariableGreater left) { int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); cmp = trueL ? cmp : (- cmp); RelationType rel = trueL ? left.relation : left.relation.not(); boolean target = (cmp > 0) || (cmp == 0) && (rel == RelationType.INCLUSIVE); return target ? new VariableEquality(this,TargetType.TARGET) : this; } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable minSet(Variable right) { return this; } @Override public Variable minSet2(VariableEquality left) { return this; } @Override public Variable minSet2(VariableInterval left) { return this; } @Override public Variable minSet2(VariableLess left) { return this; } @Override public Variable minSet2(VariableGreater left) { return this; } @Override public Variable minSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable maxSet(Variable right) { return right; } @Override public Variable maxSet2(VariableEquality left) { return left; } @Override public Variable maxSet2(VariableInterval left) { return left; } @Override public Variable maxSet2(VariableLess left) { return left; } @Override public Variable maxSet2(VariableGreater left) { return left; } @Override public Variable maxSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(Variable.target(this, true, left.v, false)); } @Override public Variable minSet2(VariablePhantom left) { return this; } @Override public Variable maxSet2(VariablePhantom left) { return this; } @Override public Variable target2(boolean trueL, VariablePhantom left) { return Variable.target(this, true, left.v, trueL); } @Override public VariableRelation setTarget(TargetType target) { return (isTarget() || target == TargetType.CHAFF) ? this : new VariableEquality(this,TargetType.TARGET); } @Override public BinaryOp binaryOp() { return BinaryOp.EQUAL; } }
16,975
33.644898
162
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/AllocType.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.poly; public enum AllocType { EQ(0x8FFFFFFF,0x00000000), IN(0x8FFFFFFF,0x00000000), UF(0x9FFFFFFF,0x00000000), K(0xAFFFFFFF,0x00000000), M(0xBFFFFFFF,0x00000000); public final int andmask; public final int ormask; private AllocType(int andmask, int ormask) { this.andmask = andmask; this.ormask = ormask; } }
568
19.321429
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/AndType.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.poly; public enum AndType { TRUE, FALSE; }
270
18.357143
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/Variable.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.poly; import java.util.Map; import java.util.Set; import fuzzm.util.Debug; import fuzzm.util.ID; import fuzzm.util.ProofWriter; import fuzzm.value.poly.GlobalState; import jkind.util.BigFraction; abstract public class Variable implements VariableInterface { public final VariableID vid; public final boolean cex; public Variable(VariableID vid, boolean cex) { assert(cex); this.vid = vid; this.cex = cex; } abstract public String toACL2(); abstract public String toACL2(String vid); abstract public String cexString(); protected String statusString() { return "(" + ((countFeatures() > 0) ? "*" : "") + ")"; } abstract public int countFeatures(); abstract public RestrictionResult andTrue(Variable arg); //abstract public Variable not(); abstract public boolean implicitEquality(); abstract public Variable toEquality(); abstract public boolean requiresRestriction(); abstract public RestrictionResult restriction(); abstract public boolean slackIntegerBounds(); abstract public Variable tightenIntegerBounds(); abstract public boolean reducableIntegerInterval(); abstract public RestrictionResult reducedInterval(); abstract protected RegionBounds constraintBounds(Map<VariableID,BigFraction> ctx); abstract protected RegionBounds constraintBounds(); abstract protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx); // ACL2: (def::un better (x y) static Variable better(Variable c1, Variable c2) { if (c1.countFeatures() > c2.countFeatures()) return c1; if (c2.countFeatures() > c1.countFeatures()) return c2; if (GlobalState.oracle().nextBoolean()) { return c1; } else { return c2; } } static Variable secondOnlyIfBetter(Variable c1, Variable c2) { if (c2.countFeatures() > c1.countFeatures()) return c2; return c1; } abstract public Set<VariableID> updateVariableSet(Set<VariableID> in); abstract public boolean evalCEX(Map<VariableID, BigFraction> ctx); abstract public Variable rewrite(Map<VariableID, AbstractPoly> rewrite); abstract public AbstractPoly maxBound(int sign); abstract public BigFraction maxValue(int sign, Map<VariableID,BigFraction> ctx); abstract public RestrictionResult mustContain(AbstractPoly v); abstract public boolean isTarget(); abstract public boolean isArtifact(); static RestrictionResult andTrue(Variable x, Variable y) { RestrictionResult res = x.andTrue(y); if (Debug.isEnabled()) { String xacl2 = x.toACL2(); String yacl2 = y.toACL2(); String racl2 = res.toACL2(); ProofWriter.printRefinement(ID.location(), "andTrue", "(and "+xacl2+" "+yacl2+")", racl2); //ProofWriter.printAndTT(ID.location(),"andTrue",xacl2,yacl2, racl2); } Variable z = res.newConstraint; assert(!(z.isTarget() && y.isTarget()) || z.isTarget()); if ((x instanceof VariablePhantom) && (y instanceof VariablePhantom)) { assert(z instanceof VariablePhantom); } else if (x instanceof VariablePhantom) { } else if (y instanceof VariablePhantom) { } return res; } static Variable minSet(Variable x, Variable y) { Variable res = x.minSet(y); if (Debug.proof() && !(x instanceof VariablePhantom) && !(y instanceof VariablePhantom)) { String Xe = x.toACL2(",x"); String Ye = y.toACL2(",x"); String Ze = res.toACL2(",x"); String Ce = "(and "+Xe+" "+Ye+")"; //Debug.setEnabled(true); ProofWriter.printThm(ID.location(), "minSet", true, Ze, Ce); //Debug.setEnabled(false); } return res; } static Variable maxSet(Variable x, Variable y) { Variable res = x.maxSet(y); if (Debug.proof() && !(x instanceof VariablePhantom) && !(y instanceof VariablePhantom)) { String Xe = x.toACL2(",x"); String Ye = y.toACL2(",x"); String Ze = res.toACL2(",x"); String Ce = "(or "+Xe+" "+Ye+")"; //Debug.setEnabled(true); ProofWriter.printThm(ID.location(), "maxSet", true, Ce, Ze); //Debug.setEnabled(false); } return res; } static Variable target(Variable H, boolean trueH, Variable C, boolean trueC) { // We are keeping H. If H implies not C, we target H. if (H.isTarget()) return H; Variable res = trueH ? C.target(trueC, H) : C.target(! trueC, H); //Debug.setEnabled(true); if ((!(H instanceof VariablePhantom)) && Debug.proof()) { String He = H.toACL2(",x"); trueC = trueH ? trueC : ! trueC; if (C instanceof VariableInterval) { VariableInterval Ci = (VariableInterval) C; String Cl = Ci.lt.toACL2(",x"); Cl = trueC ? Cl : "(not "+Cl+")"; Cl = "(not "+Cl+")"; String Cg = Ci.gt.toACL2(",x"); Cg = trueC ? Cg : "(not "+Cg+")"; Cg = "(not "+Cg+")"; String Ce = res.isTarget() ? "(or " + Cl + " " + Cg + ")" : "(and " + Cl + " " + Cg + ")"; ProofWriter.printThm(ID.location(), "target", res.isTarget(), He, Ce); } else { String Ce = C.toACL2(",x"); Ce = trueC ? Ce : "(not "+Ce+")"; Ce = "(not "+Ce+")"; ProofWriter.printThm(ID.location(), "target", res.isTarget(), He, Ce); } //Debug.setEnabled(false); } return res; } }
5,905
32.556818
106
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableGreater.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.poly; import java.math.BigInteger; import java.util.Map; import fuzzm.util.ID; import fuzzm.util.Rat; import fuzzm.value.instance.RationalInfinity; import fuzzm.value.instance.RationalValue; import jkind.lustre.BinaryOp; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class VariableGreater extends VariableInequality { protected VariableGreater(VariableID name, boolean cex, RelationType relation, AbstractPoly poly, FeatureType feature, TargetType target) { super(name,cex,relation,poly,feature,target); if (! ((relation == RelationType.EXCLUSIVE) ? cex == (name.cex.compareTo(poly.evaluateCEX()) > 0) : cex == (name.cex.compareTo(poly.evaluateCEX()) >= 0))) { System.out.println(ID.location() + this.toString()); System.out.println(ID.location() + this.cexString()); assert(false); }; } protected VariableGreater(VariableID name, AbstractPoly poly, boolean cex, TargetType target) { this(name,cex,RelationType.EXCLUSIVE,poly,FeatureType.FEATURE,target); } protected VariableGreater(VariableID name, AbstractPoly poly, RelationType relation, boolean cex, TargetType target) { this(name,cex,relation,poly,FeatureType.FEATURE,target); } // // protected VariableGreater(VariableID name, RelationType relation, AbstractPoly poly, FeatureType feature, boolean cex) { // this(name,OpType3.NEITHER,relation,poly,feature,cex,TerminalBool.ANY); // } // // protected VariableGreater(VariableGreater source, VariableID name, RelationType relation, AbstractPoly poly, boolean cex) { // this(name,source.listOp,relation,poly,FeatureType.NONFEATURE,cex,source.context); // } // // public VariableGreater(VariableInequality source, boolean cex, RelationType relation) { // this(source.vid,cex,relation,source.poly,source.feature,source.target); // } // public VariableGreater(VariableGreater source, TargetType target) { this(source.vid,source.cex,source.relation,source.poly,source.feature,target); } // // @Override // public RationalType[] variableRange() { // RationalType range[] = polyRange(); // return new RationalType[]{range[0],RationalInfinity.POSITIVE_INFINITY}; // } // @Override // public VariableConstraint newConstraint(VariableID name, RelationType relation, AbstractPoly poly, boolean cex) { // return new VariableGreater(this,name,relation,poly,cex); // } // @Override public String toACL2() { return toACL2(vid.cex.toString()); } @Override public String toACL2(String cex) { return "(<" + ((relation == RelationType.INCLUSIVE) ? "= " : " ") + poly.toACL2() + vid.toACL2(cex) + ")"; } @Override public String toString() { return poly + opString(VariableLocation.RIGHT,target.toString()) + vid + statusString() ; } @Override public String cexString() { return poly.cexString() + opString(VariableLocation.RIGHT,target.toString()) + vid.cex; } @Override protected String opString(VariableLocation location, String target) { String inclusive = ((relation == RelationType.INCLUSIVE) ? "=" : ""); return (location.equals(VariableLocation.LEFT) ? " " + target + ">" + inclusive + " " : " " + "<" + inclusive + target + " "); } @Override protected String polyString() { return poly.toString(); } // @Override // protected VariableConstraint newConstraint(BooleanContext context) { // return new VariableGreater(this,context); // } @Override public RestrictionResult andTrue(Variable x) { assert(cex && x.cex); RestrictionResult res = ((VariableInterface) x).andTrue2(this); //if (Debug.enabled) System.out.println(ID.location() + "(" + this.toString1() + ") and ("+ x.toString1() + ") := (" + res + ")"); return res; } @Override public RestrictionResult andTrue2(VariableEquality left) { return left.andTrue2(this); } @Override public RestrictionResult andTrue2(VariableInterval left) { return left.andTrue2(this); } // ACL2: (def::trueAnd andTrue-variableGreater-variableLess (x y cex) @Override public RestrictionResult andTrue2(VariableLess left) { return new RestrictionResult(new VariableInterval(this,left)); } // ACL2: (def::trueAnd andTrue-variableGreater-variableGreater (x y cex) @Override public RestrictionResult andTrue2(VariableGreater left) { return restrictInequality(left,this); } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { RationalValue bound = new RationalValue(poly.evaluate(ctx)); return new RegionBounds(bound,relation,RationalInfinity.POSITIVE_INFINITY,RelationType.INCLUSIVE); } @Override protected RegionBounds constraintBounds() { RationalValue bound = new RationalValue(poly.evaluateCEX()); return new RegionBounds(bound,relation,RationalInfinity.POSITIVE_INFINITY,RelationType.INCLUSIVE); } @Override protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx) { RegionBounds x = poly.polyBounds(ctx); return new RegionBounds(x.lower,x.lowerType.inclusiveAND(this.relation),RelationType.INCLUSIVE,RationalInfinity.POSITIVE_INFINITY,RelationType.INCLUSIVE); } // ACL2: (def::un chooseBestComplement-variableGreater-variableInterval (x y) @Override public VariableInequality chooseBestCompliment(VariableInterval arg) { if (arg.gt.countFeatures() > arg.lt.countFeatures()) { return arg.gt; } return arg.lt; } @Override public RestrictionResult andTrue2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public boolean slackIntegerBounds() { if (this.vid.name.name.type != NamedType.INT) return false; return ((this.relation == RelationType.EXCLUSIVE) || (this.poly.constantLCDContribution().compareTo(BigInteger.ONE) != 0)); } @Override public Variable tightenIntegerBounds() { assert(slackIntegerBounds()); BigInteger L = this.poly.leastCommonDenominator(); if ((this.relation == RelationType.EXCLUSIVE) && (this.poly.constantLCDContribution().compareTo(BigInteger.ONE) == 0)) { return new VariableGreater(vid, this.poly.add(BigFraction.ONE.divide(L)), RelationType.INCLUSIVE, cex, this.target); } BigInteger G = this.poly.constantLCDContribution(); L = L.divide(G); BigFraction C = this.poly.getConstant(); AbstractPoly res = this.poly.subtract(C); C = Rat.roundUp(C.multiply(L)); res = res.add(C.divide(L)); return new VariableGreater(vid,res,RelationType.INCLUSIVE,cex,this.target); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { BigFraction p = poly.evaluate(ctx); BigFraction x = ctx.get(this.vid); return (this.relation == RelationType.EXCLUSIVE) ? (x.compareTo(p) > 0) : (x.compareTo(p) >= 0); } @Override public VariableGreater rewrite(Map<VariableID, AbstractPoly> rewrite) { return new VariableGreater(vid, cex, relation, poly.rewrite(rewrite), feature, target); } @Override public AbstractPoly maxBound(int sign) { if (sign < 0) { return poly; } return new PolyBase(BigFraction.ZERO); } @Override public RestrictionResult mustContain(AbstractPoly v) { // poly <~ v // poly - v <~ 0 AbstractPoly diff = poly.subtract(v); assert(diff.evaluateCEX().signum() < 0 || ((relation == RelationType.INCLUSIVE) && diff.evaluateCEX().signum() == 0)); if (diff.isConstant()) { return new RestrictionResult(this); } else { VariableBound res = VariableBound.solvePolyLess0(diff, relation, cex, FeatureType.NONFEATURE, target); return new RestrictionResult(this,res); } } @Override public Variable target(boolean trueL, Variable right) { return right.target2(!trueL, this); } @Override public VariableGreater target2(boolean trueL, VariableInterval left) { return (VariableGreater) (trueL ? this.target2(trueL,left.gt) : Variable.target(this,true,left.lt,!trueL)); } @Override public VariableGreater target2(boolean trueL, VariableEquality left) { if (trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp > 0) || ((cmp == 0) && (this.relation == RelationType.EXCLUSIVE)); return target ? new VariableGreater(this,TargetType.TARGET) : this; } @Override public VariableGreater target2(boolean trueL, VariableLess left) { if (trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp > 0) || ((cmp == 0) && ((this.relation == RelationType.EXCLUSIVE) || (left.relation == RelationType.EXCLUSIVE))); return target ? new VariableGreater(this,TargetType.TARGET) : this; } @Override public VariableGreater target2(boolean trueL, VariableGreater left) { if (! trueL) return this; int cmp = this.poly.evaluateCEX().compareTo(left.poly.evaluateCEX()); boolean target = (cmp > 0) || ((cmp == 0) && ((this.relation == RelationType.EXCLUSIVE) || (left.relation == RelationType.INCLUSIVE))); return target ? new VariableGreater(this,TargetType.TARGET) : this; } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable minSet(Variable right) { return right.minSet2(this); } @Override public Variable minSet2(VariableEquality left) { return left; } @Override public Variable minSet2(VariableInterval left) { return new VariableInterval((VariableGreater) this.minSet2(left.gt),left.lt); } @Override public Variable minSet2(VariableLess left) { return new VariableInterval(this,left); } @Override public Variable minSet2(VariableGreater left) { int cmp = left.poly.evaluateCEX().compareTo(this.poly.evaluateCEX()); // Return the greater bound .. if ((cmp > 0) || ((cmp == 0) && this.relation == RelationType.INCLUSIVE)) { return left; } return this; } @Override public Variable minSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable maxSet(Variable right) { return right.maxSet2(this); } @Override public Variable maxSet2(VariableEquality left) { return this; } @Override public Variable maxSet2(VariableInterval left) { return new VariableInterval((VariableGreater) this.maxSet2(left.gt),left.lt); } @Override public Variable maxSet2(VariableLess left) { return new VariableInterval(this,left); } @Override public Variable maxSet2(VariableGreater left) { int cmp = left.poly.evaluateCEX().compareTo(this.poly.evaluateCEX()); if ((cmp > 0) || ((cmp == 0) && this.relation == RelationType.INCLUSIVE)) { return this; } return left; } @Override public Variable maxSet2(VariableBoolean left) { throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(Variable.target(this, true, left.v, false)); } @Override public Variable minSet2(VariablePhantom left) { return this; } @Override public Variable maxSet2(VariablePhantom left) { return this; } @Override public Variable target2(boolean trueL, VariablePhantom left) { return Variable.target(this, true, left.v, trueL); } @Override public VariableRelation setTarget(TargetType target) { return (isTarget() || target == TargetType.CHAFF) ? this : new VariableGreater(this,TargetType.TARGET); } @Override public BinaryOp binaryOp() { return (relation == RelationType.EXCLUSIVE) ? BinaryOp.GREATER : BinaryOp.GREATEREQUAL; } }
12,080
32.372928
158
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableRelation.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.poly; import java.util.Map; import java.util.Set; import jkind.lustre.BinaryOp; import jkind.util.BigFraction; public abstract class VariableRelation extends VariableBound { public AbstractPoly poly; FeatureType feature; TargetType target; // The value for this variable that is consistent with the Counter Example RelationType relation; protected VariableRelation(VariableID name, boolean cex, RelationType relation, AbstractPoly poly, FeatureType feature, TargetType target) { super(name,cex); this.relation = relation; this.poly = poly; this.feature = feature; this.target = target; } @Override public int countFeatures() { return (feature == FeatureType.FEATURE) ? 1 : 0; } @Override public boolean isArtifact() { return (feature != FeatureType.FEATURE); } // abstract public VariableConstraint newConstraint(VariableID name, RelationType newInclusive, AbstractPoly poly, boolean cex); abstract protected String opString(VariableLocation location, String target); abstract protected String polyString(); @Override public boolean isTarget() { return target == TargetType.TARGET; } abstract public VariableRelation setTarget(TargetType target); @Override public boolean implicitEquality() { return false; } @Override public Variable toEquality() { throw new IllegalArgumentException(); } @Override public Set<VariableID> updateVariableSet(Set<VariableID> in) { return poly.updateVariableSet(in); } @Override public boolean reducableIntegerInterval() { return false; } @Override public RestrictionResult reducedInterval() { throw new IllegalArgumentException(); } public BigFraction maxValue(int sign, Map<VariableID,BigFraction> ctx) { return poly.evaluate(ctx); } abstract public BinaryOp binaryOp(); }
2,056
22.643678
141
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/PolyBaseTest.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.poly; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import org.junit.Test; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class PolyBaseTest { @Test public void testAdd() { //VariableID constant = new VariableID("",0); VariableID y = VariableID.principleAlloc("Y", NamedType.REAL,BigFraction.ONE); VariableID x = VariableID.principleAlloc("X",NamedType.REAL,BigFraction.ZERO); //VariableID z = VariableID.preAlloc("Z",NamedType.REAL,BigFraction.ZERO); // System.out.println(x.level); // System.out.println(y.level); // System.out.println(z.level); Map<VariableID,BigFraction> coefs = new HashMap<VariableID,BigFraction>(); //coefs.put(constant, BigFraction.ONE); coefs.put(x, BigFraction.valueOf(BigDecimal.valueOf(2))); PolyBase poly1 = new PolyBase(coefs,BigFraction.ONE); System.out.println("poly1: " + poly1); Map<VariableID,BigFraction> coefs2 = new HashMap<VariableID,BigFraction>(); //coefs2.put(constant, BigFraction.valueOf(BigDecimal.valueOf(40))); coefs2.put(x, BigFraction.valueOf(BigDecimal.valueOf(5))); coefs2.put(y, BigFraction.valueOf(BigDecimal.valueOf(4))); PolyBase poly2 = new PolyBase(coefs2,BigFraction.valueOf(BigDecimal.valueOf(40))); System.out.println("poly2: " + poly2); AbstractPoly polyadd = poly1.add(poly2); System.out.println("poly1 + poly2: " + polyadd); AbstractPoly polyaddsub = polyadd.subtract(poly2); System.out.println("poly1 + poly2 - poly2: " + polyaddsub); AbstractPoly polysub = poly1.subtract(poly1); System.out.println("poly1 - poly1: " + polysub); AbstractPoly polyaddneg = poly1.add(poly1.negate()); System.out.println("poly1 + (-poly1): " + polyaddneg); System.out.println("poly2 * 3: " + poly2.multiply(BigFraction.valueOf(BigDecimal.valueOf(3)))); PolyBase emptyPoly = new PolyBase(); Map<VariableID,BigFraction> zerocoefs = new HashMap<VariableID,BigFraction>(); //zerocoefs.put(constant, BigFraction.ZERO); PolyBase constZeroPoly = new PolyBase(zerocoefs,BigFraction.ZERO); Map<VariableID,BigFraction> constFourCoef = new HashMap<VariableID,BigFraction>(); //constFourCoef.put(constant, BigFraction.valueOf(BigDecimal.valueOf(4))); PolyBase constFourPoly = new PolyBase(constFourCoef,BigFraction.valueOf(BigDecimal.valueOf(4))); Map<VariableID,BigFraction> negHalfCoef = new HashMap<VariableID,BigFraction>(); BigFraction negHalf = new BigFraction(BigInteger.valueOf(-1),BigInteger.valueOf(2)); //negHalfCoef.put(constant, negHalf); PolyBase constNegHalfPoly = new PolyBase(negHalfCoef,negHalf); System.out.println("poly1 - constFour: " + poly1.subtract(constFourPoly)); System.out.println("poly1 solved for x: " + poly1.solveFor(x)); System.out.println("poly2 solved for x: " + poly2.solveFor(x)); System.out.println("poly2 solved for y: " + poly2.solveFor(y)); System.out.println("(poly1 - constFour) solved for x: " + poly1.subtract(constFourPoly).solveFor(x)); System.out.println("evaluate poly1(x is ZERO by default): " + poly1.evaluateCEX()); Map<VariableID,BigFraction> coefsCex1 = new HashMap<VariableID,BigFraction>(); coefsCex1.put(y, BigFraction.valueOf(BigDecimal.valueOf(2))); PolyBase poly1Cex1 = new PolyBase(coefsCex1,BigFraction.ONE); System.out.println("evaluate poly1Cex1: " + poly1Cex1.evaluateCEX()); x.setCex(new BigFraction(BigInteger.valueOf(2))); System.out.println("evaluate poly2: " + poly2.evaluateCEX()); //System.out.println(constZeroPoly); //System.out.println(emptyPoly); assertEquals(poly1,polyaddsub); assertEquals(emptyPoly,polysub); assertEquals(emptyPoly,polyaddneg); assertEquals(emptyPoly,constZeroPoly); assertEquals(constNegHalfPoly, poly1.solveFor(x)); } }
4,096
36.245455
103
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableBoolean.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.poly; import java.util.Map; import java.util.Set; import jkind.util.BigFraction; public class VariableBoolean extends Variable { // We support a limited form of boolean generalization. // If the boolean variable appears in the final generalization, // is is restricted. Otherwise it is unrestricted. This is // important from a test generation standpoint: if the variable // isn't bound, it is free. // We always create the variable "true" // Later on we may negate it. // // If the vid is bound to false, the variable must be negated. TargetType target; private static boolean isTrue(BigFraction f) { return (f.compareTo(BigFraction.ZERO) == 0) ? false : true; } public boolean isNegated() { return cex != isTrue(vid.cex); } private VariableBoolean(VariableID vid, boolean cex, TargetType target) { super(vid,cex); this.target = target; } public VariableBoolean(VariableID vid) { this(vid, true, TargetType.CHAFF); } public VariableBoolean(VariableBoolean src, TargetType target) { this(src.vid,src.cex,target); } @Override public RestrictionResult andTrue(Variable right) { return ((VariableInterface) right).andTrue2(this); } @Override public RestrictionResult andTrue2(VariableEquality left) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariableInterval left) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariableLess left) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariableGreater left) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public RestrictionResult andTrue2(VariableBoolean left) { assert(this.cex == left.cex); assert(this.vid == left.vid); return new RestrictionResult(this); } @Override public String toACL2() { return toACL2(isTrue(vid.cex) ? "t" : "nil"); } @Override public String toACL2(String cex) { // So .. the actual cex value is encoded in the negation. String name = vid.toACL2(cex); return isNegated() ? "(not " + name + ")" : name; } @Override public String toString() { String name = vid.toString(); return isNegated() ? "(! " + target.toString() + name + ")" : (target.toString() + name); } @Override public int countFeatures() { return 1; } @Override public boolean isArtifact() { return false; } @Override public boolean requiresRestriction() { return false; } @Override public RestrictionResult restriction() { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public boolean reducableIntegerInterval() { return false; } @Override public RestrictionResult reducedInterval() { throw new IllegalArgumentException(); } @Override protected RegionBounds constraintBounds(Map<VariableID, BigFraction> ctx) { return new RegionBounds(vid.cex); } @Override protected RegionBounds constraintBounds() { return new RegionBounds(vid.cex); } @Override protected RegionBounds intervalBounds(Map<VariableID,RegionBounds> ctx) { return new RegionBounds(vid.cex); } @Override public boolean implicitEquality() { return false; } @Override public Variable toEquality() { throw new IllegalArgumentException(); } @Override public Set<VariableID> updateVariableSet(Set<VariableID> in) { return in; } @Override public boolean slackIntegerBounds() { return false; } @Override public Variable tightenIntegerBounds() { throw new IllegalArgumentException(); } @Override public boolean evalCEX(Map<VariableID, BigFraction> ctx) { return isNegated() ^ isTrue(ctx.get(this.vid)); } @Override public String cexString() { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public Variable rewrite(Map<VariableID, AbstractPoly> rewrite) { return this; } @Override public AbstractPoly maxBound(int sign) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public BigFraction maxValue(int sign, Map<VariableID, BigFraction> ctx) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public RestrictionResult mustContain(AbstractPoly v) { // TODO Auto-generated method stub throw new IllegalArgumentException(); } @Override public Variable target(boolean trueL, Variable right) { // !right => (!trueL ^ this) when trueL = false return new VariableBoolean(this,(trueL == false) ? TargetType.TARGET : this.target); } @Override public Variable target2(boolean trueL, VariableEquality left) { throw new IllegalArgumentException(); } @Override public Variable target2(boolean trueL, VariableInterval left) { throw new IllegalArgumentException(); } @Override public Variable target2(boolean trueL, VariableLess left) { throw new IllegalArgumentException(); } @Override public Variable target2(boolean trueL, VariableGreater left) { throw new IllegalArgumentException(); } @Override public Variable target2(boolean trueL, VariableBoolean left) { throw new IllegalArgumentException(); } @Override public Variable minSet(Variable right) { return this; } @Override public Variable minSet2(VariableEquality left) { throw new IllegalArgumentException(); } @Override public Variable minSet2(VariableInterval left) { throw new IllegalArgumentException(); } @Override public Variable minSet2(VariableLess left) { throw new IllegalArgumentException(); } @Override public Variable minSet2(VariableGreater left) { throw new IllegalArgumentException(); } @Override public Variable minSet2(VariableBoolean left) { return this; } @Override public boolean isTarget() { return target == TargetType.TARGET; } @Override public Variable maxSet(Variable right) { return this; } @Override public Variable maxSet2(VariableEquality left) { throw new IllegalArgumentException(); } @Override public Variable maxSet2(VariableInterval left) { throw new IllegalArgumentException(); } @Override public Variable maxSet2(VariableLess left) { throw new IllegalArgumentException(); } @Override public Variable maxSet2(VariableGreater left) { throw new IllegalArgumentException(); } @Override public Variable maxSet2(VariableBoolean left) { return this; } @Override public RestrictionResult andTrue2(VariablePhantom left) { return new RestrictionResult(this); } @Override public Variable minSet2(VariablePhantom left) { return this; } @Override public Variable maxSet2(VariablePhantom left) { return this; } @Override public Variable target2(boolean trueL, VariablePhantom left) { return Variable.target(this, true, left.v, trueL); } }
7,666
22.375
97
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/RelationType.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.poly; public enum RelationType { INCLUSIVE, EXCLUSIVE; public RelationType inclusiveAND(RelationType arg) { return ((this == INCLUSIVE) && (arg == INCLUSIVE)) ? INCLUSIVE : EXCLUSIVE; } public RelationType inclusiveIFF(RelationType arg) { return (this == arg) ? INCLUSIVE : EXCLUSIVE; } public RelationType not() { return (this == INCLUSIVE) ? EXCLUSIVE : INCLUSIVE; } public boolean inclusiveEXCLUSIVE(RelationType arg) { return (this == INCLUSIVE) && (arg == EXCLUSIVE); } public int compareWith(RelationType arg) { // Compare the state space bounded by 'this' with that bounded by 'arg' .. which is bigger? if (this == arg) return 0; if (this == INCLUSIVE) return 1; return -1; } public boolean lt(int cmp) { return (cmp < 0) || ((this == INCLUSIVE) && (cmp == 0)); } public boolean gt(int cmp) { return (cmp > 0) || ((this == INCLUSIVE) && (cmp == 0)); } }
1,137
28.947368
93
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/AbstractPoly.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.poly; import java.math.BigInteger; import java.util.Map; import java.util.Set; import jkind.util.BigFraction; abstract public class AbstractPoly implements Iterable<VariableID>, Comparable<AbstractPoly> { // solve(x) solves the poly for x by dividing // all other coefficients by the negation of the // coefficient of x and removing x; public abstract AbstractPoly solveFor(VariableID x); public abstract AbstractPoly remove(VariableID x); public abstract AbstractPoly remove(AbstractPoly x); // The coefficient of variable x, otherwise 0. public abstract BigFraction getCoefficient(VariableID x); public abstract AbstractPoly negate(); public abstract AbstractPoly add(AbstractPoly x); public abstract AbstractPoly add(BigFraction x); public abstract AbstractPoly subtract(AbstractPoly x); public abstract AbstractPoly subtract(BigFraction x); // contains no variables public abstract boolean isConstant(); // The poly's constant value public abstract BigFraction getConstant(); // Returns the leading variable in this poly. // Throws an exception if this is constant. public abstract Set<VariableID> getVariables(); public abstract VariableID leadingVariable(); public abstract VariableID trailingVariable(); public abstract BigFraction evaluateCEX(); public abstract AbstractPoly multiply(BigFraction v); public abstract AbstractPoly divide(BigFraction v); public abstract AbstractPoly div(BigInteger d); public abstract boolean divisible(BigInteger d); public abstract RegionBounds polyBounds(Map<VariableID,RegionBounds> bounds); public abstract BigFraction evaluate(Map<VariableID,BigFraction> bounds); public abstract AbstractPoly rewrite(Map<VariableID,AbstractPoly> rw); public abstract String toACL2(); public abstract Set<VariableID> updateVariableSet(Set<VariableID> in); public abstract BigInteger leastCommonDenominator(); public abstract String cexString(); public abstract BigInteger constantLCDContribution(); public abstract BigFraction dot(AbstractPoly arg); }
2,245
39.836364
94
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/poly/VariableLocation.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.poly; public enum VariableLocation { LEFT, RIGHT; }
279
19
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/FuzzMInterval.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.BigInteger; import fuzzm.poly.EmptyIntervalException; import jkind.lustre.NamedType; import jkind.lustre.Type; import jkind.util.BigFraction; public class FuzzMInterval { public BigFraction min; public BigFraction max; public NamedType type; public FuzzMInterval(NamedType type, BigFraction min, BigFraction max) { if (! (min.compareTo(max) <= 0)) throw new EmptyIntervalException("Empty FuzzM Interval: [" + min + "," + max + "]"); if ((type == NamedType.BOOL) && (min.compareTo(max) != 0)) { // TODO: Look for a better solution here .. this.min = BigFraction.ZERO; this.max = BigFraction.ONE; } else { this.min = min; this.max = max; } this.type = type; } public FuzzMInterval(NamedType type, int min, int max){ this(type, new BigFraction (BigInteger.valueOf(min)), new BigFraction (BigInteger.valueOf(max))); } public FuzzMInterval(NamedType type) { this.type = type; this.min = defaultLow(type); this.max = defaultHigh(type); } public void setMin(BigFraction min) { this.min = min; } public void setMax(BigFraction max) { this.max = max; } public BigFraction uniformRandom() { return Rat.biasedRandom(type,false,0,min,max); } public double getMinVal (){ return min.doubleValue(); } public double getMaxVal (){ return max.doubleValue(); } public BigFraction getRange(){ return max.subtract(min); } public static FuzzMInterval defaultInterval(NamedType vType){ FuzzMInterval res = null; BigFraction lowVal = defaultLow(vType); BigFraction highVal = defaultHigh(vType); res = new FuzzMInterval(vType, lowVal, highVal); return res; } public static BigFraction defaultLow (Type vType){ if(vType == NamedType.INT || vType == NamedType.REAL) { return numericLow(); } else if (vType == NamedType.BOOL) { return BigFraction.ZERO; } else{ throw new IllegalArgumentException("Unsupported type: " + vType.getClass().getName()); } } public static BigFraction defaultHigh (Type vType){ if(vType == NamedType.INT || vType == NamedType.REAL) { return numericHigh(); } else if (vType == NamedType.BOOL) { return BigFraction.ONE; } else{ throw new IllegalArgumentException("Unsupported type: " + vType.getClass().getName()); } } private static BigFraction numericLow(){ double range = getNumericRange(); double low = -1 * (range / 2); return new BigFraction(BigInteger.valueOf((long)low)); } private static BigFraction numericHigh(){ double range = getNumericRange(); double high = (range / 2) - 1; return new BigFraction(BigInteger.valueOf((long)high)); } private static double getNumericRange(){ double power = 8; double range = Math.pow(2,power); return range; } @Override public String toString() { return "{min: " + this.min + ", max: " + this.max + ", type: " + this.type + "}"; } }
3,142
22.992366
119
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/FuzzmName.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; /** * FuzzMName enumerates the special variable names used * at various points by FuzzM. * */ public class FuzzmName { public static final IDString fuzzProperty = IDString.newID("fuzzProperty"); public static final IDString time = IDString.newID("time"); public static final IDString pivotDot = IDString.newID("pivotDot"); public static final String polyConstraint = "poly_constraint"; public static final String polyEval = "poly_eval"; public static final String polyTerm = "poly_term"; }
774
31.291667
78
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/EvaluatableVector.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.Collection; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import fuzzm.value.hierarchy.EvaluatableType; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.hierarchy.RationalType; import fuzzm.value.instance.RationalValue; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class EvaluatableVector extends Vector<EvaluatableValue> implements Copy<EvaluatableVector>{ private static final long serialVersionUID = 4232014853067213712L; public EvaluatableVector(EvaluatableVector arg) { super(arg); } public EvaluatableVector() { super(); } @Override public Vector<EvaluatableValue> add(Vector<EvaluatableValue> x) { EvaluatableVector res = new EvaluatableVector(this); Set<TypedName> keys = new HashSet<TypedName>(keySet()); keys.addAll(x.keySet()); for (TypedName key: keys) { res.put(key,get(key).plus(x.get(key))); } return res; } @Override public Vector<EvaluatableValue> sub(Vector<EvaluatableValue> x) { EvaluatableVector res = new EvaluatableVector(this); Set<TypedName> keys = new HashSet<TypedName>(keySet()); keys.addAll(x.keySet()); for (TypedName key: keys) { res.put(key,get(key).minus(x.get(key))); } return res; } @Override public Vector<EvaluatableValue> mul(BigFraction x) { EvaluatableVector res = new EvaluatableVector(this); RationalType M = new RationalValue(x); for (TypedName key: keySet()) { // This converts the whole vector to a real .. which we // are probably doing anyway if we are doing vector math. res.put(key,get(key).cast(NamedType.REAL).multiply(M)); } return res; } public EvaluatableValue get(TypedName key) { assert(key instanceof TypedName); if (containsKey(key)) { return super.get(key); } Collection<String> names = keySet().stream().map(TypedName::toString).collect(Collectors.toList()); System.out.println(key + " not among [" + String.join(",", names) + "]"); throw new IndexOutOfBoundsException(); } @Override public EvaluatableVector copy() { return new EvaluatableVector(this); } public RatVect ratVector() { RatVect res = new RatVect(); for (TypedName name: keySet()) { res.put(name, ((RationalValue) ((EvaluatableType<?>) get(name)).rationalType()).value()); } return res; } public void normalize(EvaluatableVector arg) { for (TypedName name : arg.keySet()) { if (! containsKey(name)) { put(name,arg.get(name)); } } } }
2,720
25.940594
101
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/RatSignal.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.List; import fuzzm.lustre.SignalName; import jkind.util.BigFraction; import jkind.util.StreamIndex; public class RatSignal extends Signal<RatVect> { private static final long serialVersionUID = 5365578259283718106L; public RatSignal() { super(); } public RatSignal(RatSignal x) { super(); for (RatVect v: x) { add(new RatVect(v)); } } public EvaluatableSignal evaluatableSignal() { EvaluatableSignal res = new EvaluatableSignal(); for (int time=0;time<size();time++) { res.add(get(time).evaluatableVector()); } return res; } public static RatSignal uniformRandom(int size, IntervalVector S) { RatSignal res = new RatSignal(); for (int i=0;i<size;i++) { res.add(RatVect.uniformRandom(S)); } return res; } @Override public RatVect get(int time) { if (time < size()) { return super.get(time); } return new RatVect(); } @Override public RatVect set(int time, RatVect value) { if (time < size()) { return super.set(time,value); } for (int i=size();i<time;i++) { add(new RatVect()); } add(value); return value; } public BigFraction maxAbs() { BigFraction max = BigFraction.ZERO; for (RatVect v: this) { BigFraction vmax = v.maxAbs(); max = max.compareTo(vmax) < 0 ? vmax : max; } return max; } public RatSignal round() { RatSignal res = new RatSignal(); for (RatVect v: this) { res.add(v.round()); } return res; } public void put(int time, TypedName key, BigFraction value) { RatVect vect = get(time); vect.put(key, value); set(time,vect); } public RatSignal mul(BigFraction M) { RatSignal res = new RatSignal(); for (RatVect v: this) { res.add(v.mul(M)); } return res; } public RatSignal add(RatSignal x) { RatSignal res = new RatSignal(); int size = Math.max(size(),x.size()); for (int i=0;i<size;i++) { res.add(get(i).add(x.get(i))); } return res; } public RatSignal sub(RatSignal x) { RatSignal res = new RatSignal(); int size = Math.max(size(),x.size()); for (int i=0;i<size;i++) { res.add(get(i).sub(x.get(i))); } return res; } public BigFraction dot(RatSignal x){ RatVect me = this.encode(); RatVect they = x.encode(); return me.dot(they); } public RatVect encode() { RatVect res = new RatVect(); for (int time=0;time<size();time++) { RatVect vect = get(time); for (TypedName key: vect.keySet()) { StreamIndex si = new StreamIndex(key.name,time); String keyString = si.getEncoded().str; res.put(new TypedName(keyString,key.type),vect.get(key)); } } return res; } // // public Map<String,EvaluatableValue>[] ratValues() { // int k = size(); // @SuppressWarnings("unchecked") // Map<String,EvaluatableValue> evaluatableValues[] = new HashMap[k]; // for (int time=0;time<k;time++) { // RatVect v = get(time); // evaluatableValues[time] = new HashMap<>(); // for (String key: v.keySet()) { // RatValue z = new RatValue(v.get(key)); // evaluatableValues[time].put(key,z); // } // } // return evaluatableValues; // } // // public Map<String,EvaluatableValue>[] intervalValues() { // int k = size(); // @SuppressWarnings("unchecked") // Map<String,EvaluatableValue> evaluatableValues[] = new HashMap[k]; // for (int time=0;time<k;time++) { // RatVect v = get(time); // evaluatableValues[time] = new HashMap<>(); // for (String key: v.keySet()) { // ValueInterval z = new ValueInterval(new UnboundFraction(v.get(key))); // evaluatableValues[time].put(key,z); // } // } // return evaluatableValues; // } // public List<SignalName> signalNames() { List<SignalName> res = new ArrayList<>(); for (int time=0;time<size();time++) { res.addAll(get(time).signalNames(time)); } return res; } @Override public String toString() { int time = 0; String res = "[\n"; for (RatVect v: this) { res += " time:" + time++ + " "; res += v.toString(); } return res + "]"; } public String toACL2() { int time = 0; String res = "`(\n"; for (RatVect v: this) { res += v.toACL2(time); time++; } return res + ")"; } }
4,434
21.39899
75
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/Signal.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; public abstract class Signal<V extends Copy<V>> extends ArrayList<V> { private static final long serialVersionUID = 1L; public Signal(Signal<V> x) { super(); for (V v: x) { add(v.copy()); } } public Signal() { super(); } public int bytes() { int res = 0; for (V v: this) { res += v.bytes(); } return res; } }
607
15.432432
70
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/ProofWriter.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.io.PrintWriter; public class ProofWriter { private static PrintWriter zed = null; private static void init() { try { zed = new PrintWriter("proof.lisp","UTF-8"); assert(zed != null); zed.println("(include-book \"misc/eval\" :dir :system)"); } catch (Throwable t) { System.exit(1); } } private static int thmCount = 0; public synchronized static void printAndTT(String loc, String thms, String prop, String pre, String post) { if (! Debug.proof()) return; if (zed == null) init(); String p1 = "(defthm inv1-" + thms + "_" + String.valueOf(thmCount) + " (evCex `(and " + prop + " " + pre + post + "))\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; String hyp = "(evAlt `" + post + " any)"; String con = "(evAlt `(and " + prop + " " + pre + ") any)"; String p2 = "(defthm inv2-" + thms + "_" + String.valueOf(thmCount) + " (implies " + hyp + " " + con + ")\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; zed.println(";; " + loc); zed.println(p1); zed.println(p2); zed.flush(); thmCount++; } public synchronized static void printAnd2(String loc, String thm, String x, String y, String res) { if (! Debug.proof()) return; if (zed == null) init(); String p1 = "(defthm inv1-" + thm + "_" + String.valueOf(thmCount) + " (iff (evCex `(and " + x + "\n" + y + ")) \n (evCex `" + res + "))\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; zed.println(";; " + loc); zed.println(p1); zed.flush(); thmCount++; } public synchronized static void printRefinement(String loc, String thms, String formula, String generalization) { if (! Debug.proof()) return; if (zed == null) init(); String formulaCex = "(evCex `" + formula + ")"; String generalizationCex = "(evCex `" + generalization + ")"; String inv1 = "(defthm inv1-" + thms + "_" + String.valueOf(thmCount) + "\n (iff " + generalizationCex + "\n " + formulaCex + ")\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; String formulaAny = "(evAlt `" + formula + " any)"; String generalizationAny = "(evAlt `" + generalization + " any)"; String hyp = "(iff " + formulaAny + " (not " + formulaCex + "))"; String con = "(iff " + generalizationAny + " " + formulaAny + ")"; String inv2 = "(defthm inv2-" + thms + "_" + String.valueOf(thmCount) + "\n (implies\n " + hyp + "\n " + con + ")\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; zed.println(";; " + loc); zed.println(inv1); zed.println(inv2); zed.flush(); thmCount++; } public synchronized static void printThm(String loc, String name, boolean target, String H, String C) { if (! Debug.proof()) return; if (zed == null) init(); String He = "(evCEX `" + H + ")"; String Ce = "(evCEX `" + C + ")"; String body = "(implies " + He + " " + Ce + ")"; String defthm = "(defthm " + name + "_" + String.valueOf(thmCount) + "\n" + body + "\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; String event = target ? defthm : "(must-fail\n" + defthm + ")"; zed.println(";; " + loc); zed.println(event); zed.flush(); thmCount++; } public synchronized static void printEval(String loc, String name, String zoid, String any) { if (! Debug.proof()) return; if (zed == null) init(); String body = "(evAlt `" + zoid + " " + any + ")"; String event = "(defthm " + name + "_" + String.valueOf(thmCount) + "\n" + body + "\n :hints ((\"Goal\" :do-not '(preprocess))) :rule-classes nil)"; zed.println(";; " + loc); zed.println(event); zed.flush(); thmCount++; } }
4,044
42.967391
209
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/BigIntegerEEA.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.BigInteger; public class BigIntegerEEA { public BigInteger iA, iB, gcd; public BigIntegerEEA(BigInteger A, BigInteger B) { BigInteger K = A; BigInteger M = B; BigInteger x = BigInteger.ZERO; BigInteger lastx = BigInteger.ONE; BigInteger y = BigInteger.ONE; BigInteger lasty = BigInteger.ZERO; while (!M.equals(BigInteger.ZERO)) { BigInteger[] quotientAndRemainder = K.divideAndRemainder(M); BigInteger quotient = quotientAndRemainder[0]; BigInteger temp = K; K = M; M = quotientAndRemainder[1]; temp = x; x = lastx.subtract(quotient.multiply(x)); lastx = temp; temp = y; y = lasty.subtract(quotient.multiply(y)); lasty = temp; } this.iA = lastx; this.iB = lasty; this.gcd = K; assert(A.multiply(iA).add(B.multiply(iB)).compareTo(gcd) == 0); } }
1,238
24.8125
71
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/RatVect.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.BigInteger; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import fuzzm.lustre.SignalName; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.instance.BooleanValue; import fuzzm.value.instance.IntegerValue; import fuzzm.value.instance.RationalValue; import jkind.lustre.NamedType; import jkind.lustre.Type; import jkind.util.BigFraction; public class RatVect extends Vector<BigFraction> implements Copy<RatVect> { private static final long serialVersionUID = -2872956873023967593L; public RatVect() { super(); } public RatVect(RatVect x) { super(x); } public BigFraction maxAbs() { BigFraction max = BigFraction.ZERO; for (TypedName key: keySet()) { BigFraction vmax = get(key); vmax = vmax.signum() < 0 ? vmax.negate() : vmax; max = max.compareTo(vmax) < 0 ? vmax : max; } return max; } public static RatVect uniformRandom(IntervalVector S) { RatVect res = new RatVect(); for (TypedName key: S.keySet()) { res.put(key,S.get(key).uniformRandom()); } return res; } public BigFraction dot(Vector<BigFraction> x) { BigFraction res = BigFraction.ZERO; for (TypedName key: keySet()) { res = res.add(get(key).multiply(x.get(key))); } return res; } private static final BigFraction HALF = new BigFraction(BigInteger.ONE,BigInteger.valueOf(2)); private static BigFraction round(BigFraction x) { int sign = x.signum(); BigFraction res = (sign < 0) ? x.negate() : x; BigInteger N = res.add(HALF).floor(); res = new BigFraction((sign < 0) ? N.negate() : N); return res; } public RatVect round() { RatVect res = new RatVect(); for (TypedName key: keySet()) { res.put(key,round(get(key))); } return res; } @Override public RatVect mul(BigFraction M) { RatVect res = new RatVect(); for (TypedName key: keySet()) { res.put(key,get(key).multiply(M)); } return res; } @Override public RatVect add(Vector<BigFraction> x) { RatVect res = new RatVect(); Set<TypedName> keys = new HashSet<TypedName>(keySet()); keys.addAll(x.keySet()); for (TypedName key: keys) { res.put(key,get(key).add(x.get(key))); } return res; } @Override public RatVect sub(Vector<BigFraction> x) { RatVect res = new RatVect(); Set<TypedName> keys = new HashSet<TypedName>(keySet()); keys.addAll(x.keySet()); for (TypedName key: keys) { res.put(key,get(key).subtract(x.get(key))); } return res; } @Override public BigFraction get(TypedName key) { if (containsKey(key)) { return super.get(key); } //System.out.println(key + " not among [" + String.join(",", keySet()) + "]"); //assert(false); return BigFraction.ZERO; } public List<SignalName> signalNames(int time) { List<SignalName> res = new ArrayList<>(); for (TypedName name: keySet()) { res.add(new SignalName(name,time)); } return res; } @Override public String toString() { String res = "(\n"; for (TypedName key: keySet()) { res += " " + key + ":" + get(key).toString() + "\n"; } return res + ")\n"; } @Override public RatVect copy() { return new RatVect(this); } private static EvaluatableValue evaluatableValue(Type type, BigFraction value) { if (type == NamedType.BOOL) { return (value.signum() != 0) ? BooleanValue.TRUE : BooleanValue.FALSE; } if (type == NamedType.INT) { return new IntegerValue(value.floor()); } if (type == NamedType.REAL) { return new RationalValue(value); } throw new IllegalArgumentException(); } public EvaluatableVector evaluatableVector() { EvaluatableVector res = new EvaluatableVector(); for (TypedName key: keySet()) { res.put(key,evaluatableValue(key.type,get(key))); } return res; } public String toACL2(int time) { String res = ""; for (TypedName key: keySet()) { BigFraction value = get(key); res += " (" + SignalName.toString(key.name, time) + " . " + ((key.type == NamedType.BOOL) ? (value.signum() == 0 ? "nil" : "t") : value.toString()) + ")\n"; } return res; } }
4,359
23.772727
170
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/ReversePartialOrder.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; /** * An extension of PartialOrder that iterates from largest to * smallest. * * @param <T> */ public class ReversePartialOrder<T> extends PartialOrder<T> { @Override public Iterator<T> iterator() { // This will iterate top down. return totalOrder().iterator(); } }
538
19.730769
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/StepExpr.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; import jkind.lustre.Expr; public class StepExpr { public int step; public Expr expr; public StepExpr(int step, Expr expr) { assert(step >= 0); this.step = step; this.expr = expr; } }
450
19.5
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/OrderedObject.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 fuzzm.poly.VariableID; public class OrderedObject { protected OrderedObject next; private int level; private final int id; protected static int count = 0; protected OrderedObject() { this.next = null; this.level = 0; this.id = count; count++; } public int level() { return level; } public int id() { return id; } public OrderedObject insertBefore(OrderedObject arg) { if (arg == null) { this.next = null; this.level = 0; } else { this.next = arg; this.level = arg.level+1; } return this; } public void insertAfter(OrderedObject arg) { //System.out.println(ID.location() + "Inserting " + this + " after " + arg); if (arg == null) { this.next = null; this.level = 0; } else { OrderedObject old_next = arg.next; arg.next = this; this.next = old_next; this.renumber(arg.level-1); } } private void renumber(int nextLevel) { //System.out.println(ID.location() + "Renumbering .."); OrderedObject curr = this; while (curr != null) { //System.out.println(ID.location() + curr + " from " + curr.level + " to " + nextLevel); curr.level = nextLevel; nextLevel--; curr = curr.next; } } protected boolean wellOrdered() { OrderedObject curr = this; while (curr.next != null) { assert(curr.level() == curr.next.level() + 1); curr = curr.next; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; //result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (! (obj instanceof VariableID)) return false; VariableID other = (VariableID) obj; if (id != other.id()) return false; return true; } }
2,087
19.271845
91
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/IntervalVector.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.List; import fuzzm.lustre.ExprSignal; import fuzzm.lustre.ExprVect; import fuzzm.lustre.SignalName; import jkind.util.BigFraction; public class IntervalVector extends Vector<FuzzMInterval> implements Copy<IntervalVector> { private static final long serialVersionUID = 1991897878162721964L; public IntervalVector() { super(); } public ExprVect getExprVector() { ExprVect res = new ExprVect(); for (TypedName name: keySet()) { res.put(name,Rat.cast(name.name,get(name).type)); } return res; } public ExprSignal getExprSignal(int k) { ExprVect v = getExprVector(); ExprSignal res = new ExprSignal(); for (int i=0;i<k;i++) { res.add(v); } return res; } public List<SignalName> elaborate(int k) { List<SignalName> res = new ArrayList<>(); for (int i=0;i<k;i++) { for (TypedName key: keySet()) { res.add(new SignalName(key,i)); } } return res; } public IntervalVector(IntervalVector x) { super(); for (TypedName key: x.keySet()) { put(key,x.get(key)); } } @Override public String toString() { String res = "(\n"; for (TypedName key: keySet()) { res += " " + key + ":" + get(key).toString() + "\n"; } return res + ")\n"; } @Override public IntervalVector copy() { return new IntervalVector(this); } @Override public Vector<FuzzMInterval> add(Vector<FuzzMInterval> x) { assert(false); return null; } @Override public Vector<FuzzMInterval> sub(Vector<FuzzMInterval> x) { assert(false); return null; } @Override public Vector<FuzzMInterval> mul(BigFraction x) { assert(false); return null; } }
1,887
19.085106
91
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/EvaluatableSignal.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.List; import fuzzm.lustre.SignalName; import fuzzm.value.hierarchy.EvaluatableValue; public class EvaluatableSignal extends Signal<EvaluatableVector> { public EvaluatableSignal(Signal<EvaluatableVector> x) { super(x); } public EvaluatableSignal() { super(); } private static final long serialVersionUID = -7514024314823844551L; public RatSignal ratSignal() { RatSignal res = new RatSignal(); for (int time=0;time<size();time++) { res.add(get(time).ratVector()); } return res; } @Override public EvaluatableVector get(int i) { if (i < size()) { return super.get(i); } return new EvaluatableVector(); } public EvaluatableValue get(TypedName name, int time) { EvaluatableVector slice = get(time); return slice.get(name); } public void set(TypedName name, int time, EvaluatableValue value) { EvaluatableVector curr = get(time); curr.put(name, value); if (time < size()) { super.set(time,curr); return; } for (int i=size();i<time;i++) { add(new EvaluatableVector()); } add(curr); } @Override public EvaluatableVector set(int time, EvaluatableVector value) { if (time < size()) { return super.set(time,value); } for (int i=size();i<time;i++) { add(new EvaluatableVector()); } add(value); return value; } public void normalize(EvaluatableSignal arg) { for (int time=0;time<arg.size();time++) { EvaluatableVector res = get(time); res.normalize(arg.get(time)); set(time,res); } } public List<SignalName> getSignalNames() { List<SignalName> res = new ArrayList<>(); for (int time=0;time<size();time++) { EvaluatableVector ev = get(time); for (TypedName name: ev.keySet()) { res.add(new SignalName(name, time)); } } return res; } }
2,040
20.484211
68
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/RatTest.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.io.BufferedWriter; import java.io.FileWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import jkind.lustre.NamedType; import jkind.util.BigFraction; public class RatTest { public static void main(String[] args) { testBias(); //testRandom(); //testRandomCoverage(); /* int res = doublePrecision(); System.out.println(res);*/ System.out.println("Done with RatTest main"); } // end main() /* Tests- Do we always produce min and max values for an INT range. Output- 1) and 2) activated by local boolean variables fileOutput and stdOutput, respectively: 1) Writes output values and their frequency to a file (value, freq). One value per line. 2) Prints missing integer values (integers with frequency 0) to StdOut. */ // TODO: fixed random seed to avoid non-determinism? @Test public void testRandomCoverage() { try { System.out.println("Testing random coverage" + "\n"); boolean stdOutput = true; boolean fileOutput = false; final int totalCount = 10000; final NamedType nt = NamedType.INT; final int minI = -128; final int maxI = 127; final BigFraction min = new BigFraction(BigInteger.valueOf(minI)); final BigFraction max = new BigFraction(BigInteger.valueOf(maxI)); ArrayList<Integer> bias = new ArrayList<Integer>(); bias.add(-1); bias.add(0); bias.add(1); int aBias; ArrayList<Integer> missing = new ArrayList<Integer>(); for(int bIndex = 0; bIndex < bias.size(); bIndex++){ aBias = bias.get(bIndex); if(stdOutput){ System.out.println("bias: " + aBias); } BufferedWriter myOut = null; if(fileOutput){ String myFileName = buildOutputFilename("random_freq_", aBias, totalCount); String rangeString = "_range_" + min + "--" + max; String typeString = "_type-" + nt.toString(); myFileName = myFileName.concat(rangeString).concat(typeString).concat(".txt"); myOut = new BufferedWriter(new FileWriter(myFileName)); System.out.println(myFileName + "\n"); } HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>(); for(int i = 0; i < totalCount; i += 1){ BigFraction resBF = Rat.biasedRandom(nt, true, aBias, min, max); double res = resBF.doubleValue(); if(hm.containsKey((int)res)){ Integer freq = hm.get((int)res); freq = freq + 1; hm.put((int)res, freq); } else { hm.put((int)res, 1); } } // end for totalCount // output frequencies to file, one value per line. format: value, frequency if(fileOutput){ for(int i = minI; i <= maxI; i++){ if(hm.containsKey(i)){ int freq = hm.get(i); myOut.write(i + ", " + freq + "\n"); } else myOut.write(i + ", " + 0 + "\n"); } } // end if stdOutput if(! (myOut==null)){ myOut.close(); } for(int i = minI; i <= maxI; i++){ if(! hm.containsKey(i)) missing.add(i); } if(stdOutput){ System.out.println("missing count: " + missing.size()); System.out.println("missing: \n" + missing + "\n"); } // test conditions: Ensure we always produce min and max values. Assert.assertFalse(missing.contains(minI)); Assert.assertFalse(missing.contains(maxI)); missing.clear(); } // end for bIndex } catch (Throwable e) { throw new Error(e); } } // end testRandomCoverage() public static void testRandom() { try { System.out.println("Testing random()" + "\n"); final int totalCount = 1000000; final NamedType nt = NamedType.REAL; final int minI = -128; final int maxI = 127; final BigFraction min = new BigFraction(BigInteger.valueOf(minI)); final BigFraction max = new BigFraction(BigInteger.valueOf(maxI)); int lowExtremeCount, highExtremeCount; final int [] bias = {-1, 0, 1}; int aBias; for(int bIndex = 0; bIndex < 3; bIndex++){ aBias = bias[bIndex]; String myFileName = buildOutputFilename("random_", aBias, totalCount); String rangeString = "_range_" + min + "--" + max; String typeString = "_type-" + nt.toString(); myFileName = myFileName.concat(rangeString).concat(typeString).concat(".txt"); BufferedWriter myOut = new BufferedWriter(new FileWriter(myFileName)); System.out.println("writing to: " + myFileName + "\n"); lowExtremeCount = highExtremeCount = 0; for(int i = 0; i < totalCount; i += 1){ BigFraction resBF = Rat.biasedRandom(nt, true, aBias, min, max); double res = resBF.doubleValue(); myOut.write(res + "\n"); double range = max.doubleValue() - min.doubleValue(); double lowCutoff = min.doubleValue() + (1.0/3.0)*range; double highCutoff = min.doubleValue() + (2.0/3.0)*range; if(res < lowCutoff) lowExtremeCount++; if(res > highCutoff) highExtremeCount++; } // end for count myOut.close(); System.out.println("bias: " + aBias); System.out.println("low: " + lowExtremeCount); System.out.println("high: " + highExtremeCount); System.out.println("extreme:" + (lowExtremeCount + highExtremeCount)); double hto = (double) ((double)highExtremeCount / (((double)totalCount)-(double)highExtremeCount)); double lto = (double) ((double)lowExtremeCount / (((double)totalCount)-(double)lowExtremeCount)); System.out.println("high-to-other:" + hto); System.out.println("low-to-other:" + lto); System.out.println(); } // end for bIndex } catch (Throwable e) { throw new Error(e); } } // end testRandom() public static void testBias() { try { System.out.println("Testing bias()" + "\n"); final double inc = 0.001; final int totalCount = (int)(1.0 / inc); final int [] bias = {-1, 0, 1}; int aBias; int lowExtremeCount, highExtremeCount; for(int bIndex = 0; bIndex < 3; bIndex++){ aBias = bias[bIndex]; String myFileName = buildOutputFilename("bias_", aBias, totalCount); myFileName.concat(".txt"); BufferedWriter myOut = new BufferedWriter(new FileWriter(myFileName)); System.out.println("wrote to: " + myFileName + "\n"); lowExtremeCount = highExtremeCount = 0; for(double i = 0; i < 1; i += inc){ double res = Rat.pubBias(i, aBias); myOut.write(res + "\n"); double highCutoff = (2.0/3.0); double lowCutoff = (1.0/3.0); if(res < lowCutoff) lowExtremeCount++; if(res > highCutoff) highExtremeCount++; } // end for inc myOut.close(); System.out.println("bias: " + aBias); System.out.println("low: " + lowExtremeCount); System.out.println("high: " + highExtremeCount); System.out.println("extreme:" + (highExtremeCount + lowExtremeCount)); double hto = (double) ((double)highExtremeCount / (((double)totalCount)-(double)highExtremeCount)); double lto = (double) ((double)lowExtremeCount / (((double)totalCount)-(double)lowExtremeCount)); System.out.println("high-to-other:" + hto); System.out.println("low-to-other:" + lto); System.out.println(); } } catch (Throwable e) { throw new Error(e); } // end for bIndex } // end testBias() private static String buildOutputFilename (String prefix, int bias, int step){ String biasString = ""; if(bias==-1) biasString = "minus1"; else if (bias==0) biasString = "zero"; else if (bias==1) biasString = "plus1"; String res = "/media/sf_mintBoxShared/" + prefix + biasString + "_step_" + step; // + ".txt"; return res; } // This method observes the LENGTH of a range of values. // Values within this range represent random double inputs that would cause our random() to output // the unlikeliest of integers (formulas assume a bias of 0, but a skewed bias would undoubtedly // make things worse). // If the observed range is 0.0, it means that Java's level of precision for double values makes it // IMPOSSIBLE to generate random double values that will trigger every integer output. // Returns the largest x such that it is possible to output all integers in the range of // [0, ((2^x) - 1)]. Invocation shows that the largest range of integers fully supported is // between 2^14 and 2^15 (i.e., it is impossible to output all 16 bit integer values, // regardless of the number of input samples). Maybe this is ok, since we don't care about outputs // towards the middle of the distribution. // TODO: Make formula correspond to the implementation (this method uses a hard-coded formula // derived by hand based on the current setup). public static int doublePrecision (){ double min = -1; //-129.0; int power = 9; double z = -1; while(z != 0.0){ power++; double max = Math.pow(2,power) + 1.0;//128.0; double range = max - min; double x = (Math.pow((1.0 / range), 4.0) / 2.0) + 0.5; double y = (Math.pow((3.0 / range), 4.0) / 2.0) + 0.5; /* double max = 257.0; double x = Math.pow( (((129.0/257.0) -0.5) / (0.5)), 4.0) * 0.5 + 0.5; System.out.println(x); double y = Math.pow(((130.0/257.0) -0.5) /(0.5), 4.0) * 0.5 + 0.5; System.out.println(y);*/ z = y - x; } // end while return (power-1); } // end doublePrecision } // end class RatTest
9,608
28.030211
103
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/Copy.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; public interface Copy<V> { V copy(); int bytes(); }
286
18.133333
66
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/StringMap.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.HashMap; import java.util.Map; public class StringMap<V> extends HashMap<String,V> { private static final long serialVersionUID = 2558872466324889478L; public StringMap(Map<String, V> arg) { super(arg); } public StringMap() { super(); } @Override public boolean containsKey(Object arg) { throw new IllegalArgumentException(); } public boolean containsKey(String arg) { return super.containsKey(arg); } @Override public V get(Object arg) { throw new IllegalArgumentException(); } public V get(String arg) { return super.get(arg); } }
823
17.311111
67
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/Debug.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; public class Debug { private static boolean enabled = false; private static boolean proof = false; public static boolean isEnabled() { return enabled; } public static boolean proof() { return proof; } public static void setEnabled(boolean enabled) { if ((! Debug.enabled) && enabled) System.out.println(ID.location(1) + "Enabling Debug .."); if (Debug.enabled && (! enabled)) System.out.println(ID.location(1) + "Disabling Debug."); Debug.enabled = enabled; } public static void setProof(boolean enabled) { if ((! Debug.proof) && enabled) System.out.println(ID.location(1) + "Enabling Logic .."); if (Debug.proof && (! enabled)) System.out.println(ID.location(1) + "Disabling Logic."); Debug.proof = enabled; } }
978
26.194444
93
java
FuzzM
FuzzM-master/fuzzm/fuzzm/src/main/java/fuzzm/util/Vector.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.HashMap; import jkind.util.BigFraction; public abstract class Vector<T> extends HashMap<TypedName,T> { private static final long serialVersionUID = 1L; public Vector() { super(); } public Vector(Vector<T> arg) { super(); for (TypedName key: arg.keySet()) { this.put(key,arg.get(key)); } } @Override public boolean containsKey(Object arg) { throw new IllegalArgumentException(); } public boolean containsKey(TypedName arg) { return super.containsKey(arg); } @Override public T get(Object key) { throw new IllegalArgumentException(); } public T get(TypedName key) { return super.get(key); } //abstract public ACExprCtx dot(Vector<T> x); abstract public Vector<T> add(Vector<T> x); abstract public Vector<T> sub(Vector<T> x); abstract public Vector<T> mul(BigFraction x); public int bytes() { return size(); } }
1,122
18.033898
66
java