repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
RevTerm-main/code/linear/part2/Main/src/LinearPredicate.java
import java.util.Vector; public class LinearPredicate { Vector<LinearCombination> exprs; LinearPredicate() { exprs=new Vector<>(); } void add(LinearCombination lc) { for(LinearCombination l:exprs) if(l!=null && l.equals(lc)) return; exprs.add(lc); } void add(LinearPredicate lp) { for(LinearCombination lc:lp.exprs) add(lc.deepCopy()); } public Vector<LinearPredicate> negate() { Vector<LinearPredicate> ret=new Vector<>(); for(LinearCombination lc:exprs) { LinearCombination l=lc.negate(); l.add("1",Rational.negate(Main.eps)); LinearPredicate lp=new LinearPredicate(); lp.add(l); ret.add(lp); } return ret; } public static Vector<LinearPredicate> negate(Vector<LinearPredicate> g) { Vector<LinearPredicate> ret=new Vector<>(); if(g.size()==1) ret=g.firstElement().negate(); else { Vector<LinearPredicate> notLast=g.lastElement().negate(); g.removeElementAt(g.size()-1); Vector<LinearPredicate> recurse=negate(g); for(LinearPredicate lp:notLast) for(LinearPredicate predicate:recurse) { LinearPredicate copy=predicate.deepCopy(); copy.add(lp); ret.add(copy); } } return ret; } public static Vector<LinearPredicate> conjunct(Vector<LinearPredicate> left,Vector<LinearPredicate> right) { Vector<LinearPredicate> ret=new Vector<>(); if(left.isEmpty()) { for(LinearPredicate lp:right) ret.add(lp.deepCopy()); return ret; } if(right.isEmpty()) { for(LinearPredicate lp:left) ret.add(lp.deepCopy()); return ret; } for(LinearPredicate lp1:left) for(LinearPredicate lp2:right) { LinearPredicate lp=new LinearPredicate(); lp.add(lp1); lp.add(lp2); ret.add(lp); } return ret; } public static Vector<LinearPredicate> disjunct(Vector<LinearPredicate> left,Vector<LinearPredicate> right) { Vector<LinearPredicate> ret=new Vector<>(); for(LinearPredicate lp:left) ret.add(lp.deepCopy()); for(LinearPredicate lp:right) ret.add(lp.deepCopy()); return ret; } void replaceVarWithLinear(String var,LinearCombination lc) { for(LinearCombination l:exprs) l.replaceVarWithLinear(var,lc); } public LinearPredicate deepCopy() { LinearPredicate ret=new LinearPredicate(); ret.add(this); return ret; } public boolean equalsLogic(LinearPredicate lp) { for(LinearCombination lc:exprs) if(!lp.contains(lc)) return false; for(LinearCombination lc:lp.exprs) if(!this.contains(lc)) return false; return true; } public boolean contains(LinearCombination lc) { for(LinearCombination l:exprs) if(l.equals(lc)) return true; return false; } public String toString() { String ret=""; for(int i=0;i<exprs.size();i++) { LinearCombination lc = exprs.elementAt(i); if (i==0) ret += lc.toNormalString() + ">=0"; else ret += " && " + lc.toNormalString() + ">=0"; } return ret; } }
3,778
24.193333
110
java
null
RevTerm-main/code/linear/part2/Main/src/Main.java
import java.util.Vector; public class Main { public static Rational eps=Rational.one; public static CFGNode startNode,cutPoint,termNode; public static String fileName="",solver="",workingdir="",solversDir="",cpaDir=""; public static int con=0,dis=0; public static void main(String[] args) throws Exception { con=Integer.parseInt(args[0]); dis=Integer.parseInt(args[1]); solver=args[2]; fileName=args[3]; workingdir=args[4]; solversDir=args[5]; cpaDir=args[6]; termNode=CFGNode.addNode(-2); startNode= CFGNode.addNode(-1); long startTime=System.currentTimeMillis(); Parser.readFile(fileName); Parser.parseProg(0,Parser.getTokenCount()-1); for(CFGNode n:CFGNode.allCFGNodes) { if(n.id==-1 || n.id==-2) continue; n.addTerminalTransitions(); } int curTotalCFGNodes=CFGNode.allCFGNodes.size(); for(int i=0;i<curTotalCFGNodes;i++) { CFGNode n=CFGNode.allCFGNodes.elementAt(i); if(n.id==-2 || n.id==-1) continue; n.addNecessaryNondet(); } //this is done after parsing because we need to have the list of all variables. for(Transition t:Transition.allTransitions) t.addNondetTemplate(); Vector<Transition> RevTransitions=new Vector<>(); for(Transition t:Transition.allTransitions) { Transition r=t.reverse(); RevTransitions.add(r); r.v.rout.add(r); } Vector<CFGNode> cutPoints=CFGUtil.findCutpoints(); fileName=fileName.replace("/","_"); // for(Transition t:Transition.allTransitions) // System.err.println(t); InvariantGeneration.MakeTemplate(1,1,startNode,0); // System.err.println("-----------------------Invariant---------------------"); // for(CFGNode n:CFGNode.allCFGNodes) // if(!n.inv.isEmpty()) // System.err.println(n.id+": "+n.inv.firstElement().toNormalString()); // System.err.println("-----------------------Invariant---------------------"); Vector <Farkas> InvFarkas=new Vector<>(); InvariantGeneration.generate(cutPoints,InvFarkas,0); //System.err.println("number of Farkas for CFG= "+InvFarkas.size()); InvariantGeneration.MakeTemplate(con,dis,termNode,1); termNode.preCondition=termNode.inv.firstElement(); // System.err.println("-----------------------Backward Invariant---------------------"); // for(CFGNode n:CFGNode.allCFGNodes) // for(QuadraticPredicate qp:n.inv) // System.err.println(n.id+": "+qp.toNormalString()); // System.err.println("-----------------------Backward Invariant---------------------"); InvariantGeneration.generate(cutPoints,InvFarkas,1); Vector<Farkas> inductiveness=new Vector<>(); int Dcount=Farkas.countD; InvariantGeneration.generate(cutPoints,inductiveness,0); Farkas.countD=Dcount; // for(Farkas farkas:InvFarkas) // System.err.println(farkas); boolean result=InvUtil.checkNonTermination(InvFarkas,inductiveness,startNode); if(result) //does not terminate System.out.println("Non-Terminating"); else System.out.println("Could Not Prove Non-Termination"); long endTime=System.currentTimeMillis(); System.out.println("total time used: "+ (endTime-startTime)); int val=(result) ? 3 : 0; System.exit(val); } }
3,654
33.481132
95
java
null
RevTerm-main/code/linear/part2/Main/src/Node.java
import java.util.Vector; public class Node { public static Vector<Node> allNodes=new Vector<>(); int id; Node par; int beginIndex,endIndex; String type; Vector<Node> children; String varName; LinearCombination expr; String nondetLow,nondetUp; Vector <LinearPredicate> guard; Node(Node par,int beginIndex,int endIndex,String type) { allNodes.add(this); id=allNodes.size()-1; this.par=par; this.beginIndex=beginIndex; this.endIndex=endIndex; this.type=type; this.expr=null; this.guard=new Vector<>(); children=new Vector<>(); if(par!=null) par.children.add(this); } public String toString() { String ret=""; ret+="Node #"+id+"\n"; if(par!=null) ret+="Par: "+par.id+"\n"; else ret+="Par: null\n"; ret+="beginIndex="+beginIndex+"\t"+"endIndex="+endIndex+"\n"; ret+="type: "+type+"\n"; ret+="guard:"; for(LinearPredicate lp:guard) ret+=lp.toString()+"\n"; return ret; } }
1,137
21.76
69
java
null
RevTerm-main/code/linear/part2/Main/src/Parser.java
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class Parser { public static Set<String> allVars = new HashSet<>(); public static Vector<String> tokens = new Vector<>(); public static int nondetCount = 0; static { allVars.add("1"); } public static Node parseProg(int beginIndex, int endIndex) throws Exception { if (!getToken(beginIndex).equals("START")) throw new Exception("program should start with START"); Node cur = new Node(null, beginIndex, endIndex, "prog"); CFGNode start = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 2))); Transition fromStart = new Transition(Main.startNode, start); fromStart.addToGraph(); if (getToken(beginIndex + 4).equals("CUTPOINT")) Main.cutPoint = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 6))); int lastFROM = -1; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("FROM")) { if (lastFROM != -1) throw new Exception(" \"TO: index\" expected before @" + i); lastFROM = i; } else if (getToken(i).equals("TO")) { parseTransition(cur, lastFROM, i + 3); lastFROM = -1; } return cur; } public static Node parseTransition(Node par, int beginIndex, int endIndex) throws Exception { if (!getToken(endIndex).equals(";")) throw new Exception("Transition must end with ; @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "Transition"); int vIndex = Integer.parseInt(getToken(beginIndex + 2)), uIndex = Integer.parseInt(getToken(endIndex - 1)); CFGNode vNode = CFGNode.addNode(vIndex); CFGNode uNode = CFGNode.addNode(uIndex); Vector<Transition> transitionVector = new Vector<>(); transitionVector.add(new Transition(vNode, uNode)); int lastColon = beginIndex + 3; for (int i = beginIndex + 4; i <= endIndex - 4; i++) { if (getToken(i).equals(";")) { Node ch = parseStmt(cur, lastColon + 1, i - 1); if (ch.type.equals("assume")) { if (ch.guard.size() == 1) for (Transition t : transitionVector) t.detGuard.add(ch.guard.elementAt(0)); else if (ch.guard.size() > 1) { Vector<Transition> tmp = new Vector<>(); for (int j = 0; j < ch.guard.size(); j++) { for (Transition t : transitionVector) { Transition tp = t.deepCopy(); tp.detGuard.add(ch.guard.elementAt(j)); tmp.add(tp); } } transitionVector = tmp; } } else { for (Transition t : transitionVector) { t.varName.add(ch.varName); t.update.add(ch.expr); // if (ch.expr.containsNondetVar()) // { // LinearCombination lowerBound = ch.expr.deepCopy(); // lowerBound.minus(new LinearCombination(ch.nondetLow, Rational.one)); //var - low >= 0 // t.nondetGuard.add(lowerBound); // // LinearCombination upperBound = new LinearCombination(ch.nondetUp, Rational.one); // upperBound.minus(ch.expr.deepCopy()); //up - var >= 0 // t.nondetGuard.add(upperBound); // // } } } lastColon = i; } } for (Transition t : transitionVector) t.addToGraph(); return cur; } public static Node parseStmt(Node par, int beginIndex, int endIndex) throws Exception { if (getToken(beginIndex).equals("assume")) { Node cur = new Node(par, beginIndex, endIndex, "assume"); Node ch = parseBexpr(cur, beginIndex + 2, endIndex - 1); cur.guard = ch.guard; return cur; } else { Node cur = new Node(par, beginIndex, endIndex, "assignment"); if (!getToken(beginIndex + 1).equals(":=")) throw new Exception("assignment without := @" + beginIndex + "-" + endIndex); int sgn = beginIndex + 1; String varName = getToken(beginIndex); allVars.add(varName); boolean isNondet = false; for (int i = sgn + 1; i <= endIndex; i++) if (getToken(i).equals("nondet")) isNondet = true; if (isNondet) { cur.varName = varName; cur.expr = new LinearCombination("_r_"+nondetCount); nondetCount++; } else { LinearCombination update = parseExpr(cur, sgn + 1, endIndex).expr; cur.varName = varName; cur.expr = update; } return cur; } } public static Node parseBexpr(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseBexpr: "+beginIndex+"---"+endIndex); Node cur = new Node(par, beginIndex, endIndex, "Bexpr"); for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("nondet")) return cur; Vector<Integer> ors = new Vector<>(); Vector<Integer> ands = new Vector<>(); ors.add(beginIndex - 1); ands.add(beginIndex - 1); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && getToken(i).equals("|") && getToken(i + 1).equals("|")) { ors.add(i + 1); i++; } else if (openPar == 0 && getToken(i).equals("&") && getToken(i + 1).equals("&")) { ands.add(i + 1); i++; } ors.add(endIndex + 2); ands.add(endIndex + 2); if (ors.size() > 2) { for (int i = 1; i < ors.size(); i++) { Node ch = parseBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 2); cur.guard = LinearPredicate.disjunct(cur.guard, ch.guard); } return cur; } if (ands.size() > 2) { for (int i = 1; i < ands.size(); i++) { Node ch = parseBexpr(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 2); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); } return cur; } boolean isCompletlyInsidePar = true; openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && i != endIndex) { isCompletlyInsidePar = false; break; } } if (isCompletlyInsidePar) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex - 1); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); return cur; } if (getToken(beginIndex).equals("!")) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex); cur.guard = LinearPredicate.negate(ch.guard); return cur; } Node ch = parseLiteral(cur, beginIndex, endIndex); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); return cur; } public static Node parseLiteral(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseLiteral:"+ beginIndex+"---"+endIndex); int sgn = -1, type = -1; //types: 0: "<=" 1: ">=" 2: ">" 3: "<" 4: "==" 5: "!=" for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("<=")) { sgn = i; type = 0; } else if (getToken(i).equals(">=")) { sgn = i; type = 1; } else if (getToken(i).equals(">")) { sgn = i; type = 2; } else if (getToken(i).equals("<")) { sgn = i; type = 3; } else if (getToken(i).equals("==")) { sgn = i; type = 4; } else if (getToken(i).equals("!=")) { sgn = i; type = 5; } if (sgn == beginIndex || sgn == endIndex) throw new Exception("literal starts or ends with sign @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "literal"); Node left = null; Node right=null; if (sgn == -1) { type = 5; left = parseExpr(cur, beginIndex, endIndex); right = new Node(cur, endIndex, endIndex, "0"); right.expr = new LinearCombination(Rational.zero); } else { left = parseExpr(cur, beginIndex, sgn - 1); right = parseExpr(cur, sgn + 1, endIndex); } if (type == 0) //left<=right --> right-left>=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 1) //left>=right --> left-right>=0 { LinearCombination lc = left.expr.deepCopy(); lc.minus(right.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 2) // left > right -> left -right >=eps -> left - right -eps >=0 { LinearCombination lc = left.expr.deepCopy(); lc.minus(right.expr); // left - right lc.minus(new LinearCombination(Main.eps)); // left - right - eps LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 3) //left < right --> right - left > eps --> right - left -eps >=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); // right - left lc.minus(new LinearCombination(Main.eps)); // right - left - eps LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 4) //left==right --> left-right>=0 and right-left>=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); LinearCombination lc2 = left.expr.deepCopy(); lc2.minus(right.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); lp.add(lc2); cur.guard.add(lp); } else { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); lc.minus(new LinearCombination(Main.eps)); LinearCombination lc2 = left.expr.deepCopy(); lc2.minus(right.expr); lc2.minus(new LinearCombination(Main.eps)); LinearPredicate lp1 = new LinearPredicate(), lp2 = new LinearPredicate(); lp1.add(lc); lp2.add(lc2); cur.guard.add(lp1); cur.guard.add(lp2); } return cur; } public static Node parseExpr(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseExpr: "+beginIndex+"----"+endIndex); Vector<Integer> signIndex = new Vector<>(); Vector<String> signType = new Vector<>(); if (!getToken(beginIndex).equals("-")) { signIndex.add(beginIndex - 1); signType.add("+"); } int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && (getToken(i).equals("+") || (getToken(i).equals("-") && (i - 1 < beginIndex || (i - 1 >= beginIndex && !getToken(i - 1).equals("*") && !getToken(i - 1).equals("+")))))) { signIndex.add(i); signType.add(getToken(i)); } } signIndex.add(endIndex + 1); signType.add("+"); Node cur = new Node(par, beginIndex, endIndex, "expr"); cur.expr = new LinearCombination(); for (int i = 0; i + 1 < signIndex.size(); i++) { Node ch = parseTerm(cur, signIndex.elementAt(i) + 1, signIndex.elementAt(i + 1) - 1); if (signType.elementAt(i).equals("+")) cur.expr.add(ch.expr); else cur.expr.minus(ch.expr); } return cur; } public static Node parseTerm(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseTerm: "+beginIndex+"---"+endIndex); if ((beginIndex == endIndex && isNumeric(getToken(beginIndex)))) //constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = Integer.parseInt(getToken(beginIndex)); cur.expr = new LinearCombination(); cur.expr.add("1", new Rational(val, 1)); return cur; } else if (beginIndex == endIndex - 1 && isNumeric(getToken(endIndex))) //negative constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = -Integer.parseInt(getToken(endIndex)); cur.expr = new LinearCombination(); cur.expr.add("1", new Rational(val, 1)); return cur; } else if (beginIndex == endIndex) //var { Node cur = new Node(par, beginIndex, endIndex, "var"); String var = getToken(beginIndex); allVars.add(var); if (Character.isDigit(var.charAt(0))) throw new Exception("Incorrect var name @" + beginIndex); cur.expr = new LinearCombination(); cur.expr.add(var, new Rational(1, 1)); return cur; } else // (...) or [] * [] { Node cur = new Node(par, beginIndex, endIndex, "term mul"); cur.expr = new LinearCombination(); Vector<Integer> sgnIndex = new Vector<>(); Vector<String> sgnType = new Vector<>(); sgnIndex.add(beginIndex - 1); sgnType.add("*"); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && (getToken(i).equals("*") || getToken(i).equals("/"))) { sgnIndex.add(i); sgnType.add(getToken(i)); } else if (getToken(i).equals("%")) { throw new Exception("% is not supported. @" + beginIndex + "-" + endIndex); } sgnIndex.add(endIndex + 1); sgnType.add("*"); if (sgnIndex.size() == 2) // (...) { Node ch = parseExpr(cur, beginIndex + 1, endIndex - 1); cur.expr = ch.expr; return cur; } else { cur.expr.add("1", Rational.one); for (int i = 1; i < sgnIndex.size(); i++) { Node ch = parseExpr(cur, sgnIndex.elementAt(i - 1) + 1, sgnIndex.elementAt(i) - 1); if (sgnType.elementAt(i - 1).equals("*")) cur.expr.multiplyByLin(ch.expr); else if (ch.expr.isConstant() && ch.expr.coef.containsKey("1")) cur.expr.multiplyByValue(Rational.inverse(ch.expr.coef.get("1"))); else throw new Exception("Divison by variable is not possible @" + beginIndex + "-" + endIndex); } return cur; } } } public static boolean isNumeric(String s) { for (int i = 0; i < s.length(); i++) if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != '.') return false; return true; } public static int getTokenCount() { return tokens.size(); } public static String getToken(int x) { return tokens.elementAt(x); } public static void readTokens(String program) throws Exception { String extraSpace = ""; for (int i = 0; i < program.length(); i++) { char c = program.charAt(i); if (c == '.' || Character.isAlphabetic(c) || Character.isDigit(c) || c == '_') extraSpace += c; else { extraSpace += " "; extraSpace += c; extraSpace += " "; } } Scanner scanner = new Scanner(extraSpace); while (scanner.hasNext()) { String s = scanner.next(); if (s.equals("=")) { if (tokens.size() == 0) throw new Exception("program cannot start with ="); String last = tokens.lastElement(); if (last.equals(":") || last.equals(">") || last.equals("<") || last.equals("=") || last.equals("!")) { tokens.removeElementAt(getTokenCount() - 1); last += s; tokens.add(last); } else tokens.add(s); } else tokens.add(s); } } public static void readFile(String fileName) throws Exception { File file = new File(fileName); Scanner in = new Scanner(file); String program = ""; while (in.hasNextLine()) { String s = in.nextLine(); if (s.contains("//")) s = s.substring(0, s.indexOf("//")); if (s.contains("AT(")) { int ind = s.indexOf("AT("); int openPar = 0, endOfAT = -1; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') openPar++; else if (s.charAt(i) == ')') { openPar--; if (openPar == 0) { endOfAT = i; break; } } } s = s.substring(0, ind) + s.substring(endOfAT + 1, s.length()); } program += s + " "; } readTokens(program); } }
20,210
34.457895
163
java
null
RevTerm-main/code/linear/part2/Main/src/QuadraticCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; public class QuadraticCombination { Map<String,LinearCombination> coef; public static final QuadraticCombination minus1=new QuadraticCombination("1",new LinearCombination("1",new Rational(-1,1))); QuadraticCombination() { coef=new HashMap<>(); } QuadraticCombination(String var,LinearCombination lc) { coef=new HashMap<>(); add(var,lc); } QuadraticCombination(Set<String> vars) { coef= new HashMap<>(); for(String var:vars) { add(var,new LinearCombination("c_"+InvariantGeneration.cCount)); InvariantGeneration.cCount++; } } public void add(String var,LinearCombination lc) { if(coef.containsKey(var)) coef.get(var).add(lc); else coef.put(var,lc); } public void add(QuadraticCombination qc) { for(String var:qc.coef.keySet()) add(var,qc.coef.get(var)); } public void add(LinearCombination lc) { for(String var:lc.coef.keySet()) { add(var,new LinearCombination(lc.coef.get(var))); } } public void add(Rational val) { add("1",new LinearCombination(val)); } public QuadraticCombination negate() { QuadraticCombination qc=new QuadraticCombination(); for(String var:coef.keySet()) qc.add(var,coef.get(var).negate()); return qc; } public LinearCombination getCoef(String var) { return coef.get(var); } public Rational getCoef(String var1,String var2) { if(coef.containsKey(var1) && coef.get(var1).coef.containsKey(var2)) return coef.get(var1).coef.get(var2); else if(coef.containsKey(var2) && coef.get(var2).coef.containsKey(var1)) return coef.get(var2).coef.get(var1); else return Rational.zero; } public QuadraticCombination primize() { QuadraticCombination ret=new QuadraticCombination(); for(String var:coef.keySet()) if(!var.equals("1")) ret.add(var+"_prime",coef.get(var)); else ret.add("1",coef.get(var)); return ret; } public QuadraticCombination deepCopy() { QuadraticCombination qc=new QuadraticCombination(); for(String var:coef.keySet()) qc.add(var,coef.get(var).deepCopy()); return qc; } public void replaceVarWithLinear(String var,LinearCombination lc) { if(!coef.containsKey(var)) return; LinearCombination l=coef.get(var); coef.remove(var); for(String v:lc.coef.keySet()) { LinearCombination tmp=l.deepCopy(); tmp.multiplyByValue(lc.coef.get(v)); add(v,tmp); } } public LinearCombination replaceVarsWithValue(Map<String,Integer> dict) throws Exception { LinearCombination ret=new LinearCombination(); for(String var:coef.keySet()) { Integer c=coef.get(var).replaceVarsWithValue(dict); ret.add(var,new Rational(c,1)); } return ret; } public String toNormalString() { String ret=""; for(String s:coef.keySet()) { if(ret.equals("")) ret+=s+"*("+coef.get(s).toNormalString()+")"; else ret+=" + "+s+"*("+coef.get(s).toNormalString()+")"; } return ret; } public String toString() { String ret=""; if(coef.keySet().size()>1) ret="(+ "; for(String var:coef.keySet()) { LinearCombination lc=coef.get(var); if(ret=="") ret="(* "+lc.toString()+" "+var+")"; else ret=ret+" (* "+lc.toString()+" "+var+")"; } if(coef.keySet().size()>1) ret+=")"; if(ret.equals("")) ret="0"; return ret; } }
4,165
23.946108
128
java
null
RevTerm-main/code/linear/part2/Main/src/QuadraticPredicate.java
import java.util.Map; import java.util.Vector; public class QuadraticPredicate { public static QuadraticPredicate TRUE=new QuadraticPredicate(new QuadraticCombination("1",new LinearCombination("1",Rational.one))); Vector<QuadraticCombination> exprs; QuadraticPredicate() //conjunctions { exprs =new Vector<>(); } QuadraticPredicate(QuadraticCombination qc) { exprs=new Vector<>(); exprs.add(qc); } void add(QuadraticCombination qc) { exprs.add(qc); } void add(QuadraticPredicate qp) { for(QuadraticCombination qc:qp.exprs) exprs.add(qc); } void replaceVarWithLinear(String var,LinearCombination update) { for(QuadraticCombination qc:exprs) qc.replaceVarWithLinear(var,update); } public static Vector<QuadraticPredicate> negate(Vector<QuadraticPredicate> vqp) { Vector<QuadraticPredicate> ret=new Vector<>(); for(QuadraticPredicate qp:vqp) { Vector<QuadraticCombination> vqc=qp.negate(); if(ret.isEmpty()) { for(QuadraticCombination qc:vqc) { QuadraticPredicate c=new QuadraticPredicate(); c.add(qc); ret.add(c); } continue; } Vector<QuadraticPredicate> tmp=new Vector<>(); for(QuadraticCombination cur:vqc) for(QuadraticPredicate q:ret) { QuadraticPredicate c=q.deepCopy(); c.add(cur); tmp.add(c); } ret.addAll(tmp); } return ret; } Vector<QuadraticCombination> negate() { Vector<QuadraticCombination> ret=new Vector<>(); for(QuadraticCombination qc:exprs) { QuadraticCombination q=qc.negate(); q.add("1",new LinearCombination(Rational.negate(Main.eps))); // 1*(-1) ret.add(q); } return ret; } QuadraticCombination getTerm(int ind) { return exprs.elementAt(ind); } public QuadraticPredicate deepCopy() { QuadraticPredicate qp=new QuadraticPredicate(); for(QuadraticCombination qc:exprs) qp.add(qc.deepCopy()); return qp; } public QuadraticPredicate primize() { QuadraticPredicate ret=new QuadraticPredicate(); for(QuadraticCombination qc:exprs) ret.add(qc.primize()); return ret; } public LinearPredicate replaceVarsWithValue(Map<String,Integer> dict) throws Exception { LinearPredicate ret=new LinearPredicate(); for(QuadraticCombination qc:exprs) ret.add(qc.replaceVarsWithValue(dict)); return ret; } public String toString() { String ret=""; for(QuadraticCombination qc: exprs) ret+="(>= "+qc.toString()+" 0) "; if(exprs.size()>1) ret="(and "+ret+") "; return ret; } public String toNormalString() { String ret=""; for(QuadraticCombination qc: exprs) ret+=qc.toNormalString()+">=0 and "; return ret; } }
3,307
25.464
136
java
null
RevTerm-main/code/linear/part2/Main/src/Rational.java
import java.util.EnumMap; public class Rational implements Comparable<Rational> { public static final Rational one=new Rational(1,1),zero=new Rational(0,1); int numerator,denominator; public int gcd(int a, int b) { if (b==0) return a; return gcd(b,a%b); } Rational(int numerator,int denominator) { if(numerator==0) { this.numerator=0; this.denominator=1; return; } if(denominator<0) { denominator*=-1; numerator*=-1; } int g=gcd(numerator,denominator); this.numerator=numerator/g; this.denominator=denominator/g; } public static Rational negate(Rational a) { return new Rational(-a.numerator,a.denominator); } public static Rational inverse(Rational a) throws Exception { if(a.numerator==0) throw new Exception("getting inverse of "+a+" which is not defined"); return new Rational(a.denominator,a.numerator); } public static Rational add(Rational a,Rational b) { return new Rational(a.numerator*b.denominator+b.numerator*a.denominator,a.denominator*b.denominator); } public static Rational minus(Rational a,Rational b) { return add(a,negate(b)); } public static Rational mul(Rational a,Rational b) { return new Rational(a.numerator*b.numerator,a.denominator*b.denominator); } public static Rational div(Rational a,Rational b) throws Exception { return mul(a,inverse(b)); } public boolean equals(Rational a) { return (a.numerator== numerator && a.denominator==denominator); } public boolean isNonNegative() { return (numerator>=0); } @Override public int compareTo(Rational a) { return numerator*a.denominator-a.numerator*denominator; } public String toNormalString() { if(denominator==1) return ""+numerator; return "("+numerator+"/"+denominator+")"; } public void normalize() { if(denominator<0) { numerator*=-1; denominator*=-1; } } public String toString() { normalize(); String num="",den=""+denominator; if(numerator<0) num="(- "+(-numerator)+")"; else num=""+numerator; if(denominator==1) return num; return "(/ "+num+" "+denominator+")"; } }
2,543
21.918919
109
java
null
RevTerm-main/code/linear/part2/Main/src/Transition.java
import java.util.Vector; public class Transition //from "v.first" to "v.second" with guard "g" and update "varName := update" { public static Vector<Transition> allTransitions=new Vector<>(); CFGNode v,u; LinearPredicate detGuard; QuadraticPredicate nondetGuard; Vector<String> varName; Vector<LinearCombination> update; //if update[i]=null then varName[i] is non-deterministicly assigned boolean hasGroup; Transition(CFGNode a,CFGNode b) { v = a; u = b; detGuard = new LinearPredicate(); nondetGuard = new QuadraticPredicate(); varName = new Vector<>(); update = new Vector<>(); hasGroup = false; } void addNondetTemplate() { for(LinearCombination lc:update) { if(lc.toString().contains("_r_")) // lc is a fresh nondet variable { // qc <= lc <= qc QuadraticCombination qc= new QuadraticCombination(Parser.allVars),qcc=qc.deepCopy(); qc.add(lc.negate()); //qc - lc <=0 nondetGuard.add(qc.negate()); qcc.add(lc.negate()); // qc - lc >=0 nondetGuard.add(qcc); } } } public void addToGraph() { allTransitions.add(this); v.out.add(this); } public Transition reverse() throws Exception { Transition ret=new Transition(u,v); for(LinearCombination lc: detGuard.exprs) ret.detGuard.add(lc.deepCopy()); for(QuadraticCombination qc: nondetGuard.exprs) ret.nondetGuard.add(qc.deepCopy()); for(int i=0;i<varName.size();i++) { LinearCombination lc=update.elementAt(i); String var=varName.elementAt(i); // System.err.println(var+" := "+lc.toNormalString()); if(lc.coef.containsKey(var) && lc.coef.get(var).numerator!=0) { Rational c=new Rational(lc.coef.get(var).numerator,lc.coef.get(var).denominator); LinearCombination upd=lc.deepCopy(); upd.coef.put(var,Rational.negate(Rational.one)); upd.multiplyByValue(Rational.inverse(Rational.negate(c))); ret.varName.add(var); ret.update.add(upd); } else //var is not in lc { LinearCombination g=lc.deepCopy(); g.minus(new LinearCombination(var)); //g==0 ret.detGuard.add(g); //g>=0 ret.detGuard.add(g.negate()); //-g>=0 ret.varName.add(var); ret.update.add(new LinearCombination("_r_"+Parser.nondetCount)); Parser.nondetCount++; } } return ret; } public Transition deepCopy() { Transition ret=new Transition(v,u); ret.detGuard = detGuard.deepCopy(); ret.nondetGuard=nondetGuard.deepCopy(); for(String var:varName) ret.varName.add(var.toString()); for(LinearCombination lc:update) if(lc!=null) ret.update.add(lc.deepCopy()); else ret.update.add(null); return ret; } public String toString() { String res=""; res+="from: "+v.id+"\nto: "+u.id+"\n"; if(detGuard !=null) res+="detGuard: "+ detGuard +"\n"; if(nondetGuard!=null) res+="nondetGuard: "+nondetGuard.toNormalString()+"\n"; for(int i=0;i<varName.size();i++) if(update.elementAt(i)!=null) res+=varName.elementAt(i)+" := "+update.elementAt(i).toNormalString()+"\n"; else res+=varName.elementAt(i)+" := nondet()\n"; return res; } }
3,821
30.073171
105
java
null
RevTerm-main/code/linear/part2/Main/src/safetyUtil.java
import java.io.File; import java.io.FileWriter; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class safetyUtil { public static boolean check(String fileName) throws Exception { Map<String,Integer> dict = getSMTResults(fileName); replaceAllVariables(dict); convertToC(fileName,dict); return hasPath(fileName); } public static Map<String,Integer> getSMTResults(String fileName) throws Exception { Map<String,Integer> res=new TreeMap<>(); File f=new File(fileName+".result"); Scanner in=new Scanner(f); in.nextLine(); //skip the "sat" while(in.hasNextLine()) { String s=in.nextLine(); s=takePars(s); //System.err.println("s = " + s); Scanner tmp=new Scanner(s); if(!tmp.hasNext()) continue; String var=tmp.next(); int val=1; String p=tmp.next(); if(p.equals("-")) { val *= -1; p=tmp.next(); } val*=Integer.parseInt(p); res.put(var,val); } // for(String var:res.keySet()) // System.err.println(var+" = "+res.get(var)); return res; } public static String takePars(String s) { //System.err.println(s); String ret=s.replace("("," "); ret=ret.replace(")"," "); return ret; } public static void replaceAllVariables(Map<String,Integer> dict) throws Exception { for(CFGNode n:CFGNode.allCFGNodes) { for(QuadraticPredicate qc:n.inv) { LinearPredicate lc=qc.replaceVarsWithValue(dict); //System.err.println(n.id+": "+lc); n.computedInv.add(lc); } } } public static void convertToC(String fileName, Map<String,Integer> dict) throws Exception { int nondetCnt=0; FileWriter fw=new FileWriter(fileName+".c"); fw.write("int main()\n{\n"); for(String var:Parser.allVars) if(!var.equals("1") && !var.startsWith("_a_") && !var.startsWith("_b_")) fw.write("int "+var+";\n"); fw.write("if("); boolean isFirst=true; for(String var:Parser.allVars) if(!var.equals("1") && !var.startsWith("_a_") && !var.startsWith("_b_")) { if(!isFirst) fw.write(" || "); else isFirst=false; fw.write(var + ">100000 || " + var + "<-100000 "); } fw.write(")\nreturn 0;\n"); fw.write("\ngoto START;\n"); for(CFGNode n:CFGNode.allCFGNodes) { fw.write(getlocName(n)+":\n"); //if(!BI) goto ERROR if(!n.computedInv.isEmpty()) { // System.err.println("computed: "); // for(LinearPredicate lp:n.computedInv) // System.err.println(lp.toString()); // System.err.println("actual: "); // for(QuadraticPredicate qp:n.inv) // System.err.println(qp.toNormalString()); fw.write("if(!("); for (int i = 0; i < n.computedInv.size(); i++) { LinearPredicate lp = n.computedInv.elementAt(i); if (i != 0) fw.write(" || "); fw.write("("+lp.toString()+")"); } fw.write("))\n"); fw.write("goto ERROR;\n"); } // for(Transition t:n.out) { if(t.detGuard.exprs.size()!=0) fw.write("if( "+t.detGuard+" )\n{\n"); for(int i=0;i<t.varName.size();i++) { String var=t.varName.elementAt(i); LinearCombination upd=t.update.elementAt(i); if(upd.toNormalString().contains("_r_")) { fw.write(var + " = nondet" + nondetCnt + "();\n"); nondetCnt++; } else fw.write(var+" = "+upd.toNormalString()+";\n"); } fw.write("goto "+getlocName(t.u)+";\n"); if(t.detGuard.exprs.size()!=0) fw.write("}\n"); } fw.write("return 0;\n"); } fw.write("ERROR:\nreturn (-1);\n"); fw.write("}"); fw.close(); } public static String getlocName(CFGNode n) throws Exception { if(n.id>=0) return "location"+n.id; else if(n.id==-1) return "START"; else if(n.id==-2) return "TERM"; else throw new Exception("node without known location id "+n.id); } public static boolean hasPath(String fileName) throws Exception { String []configurations={"predicateAnalysis.properties","bmc-incremental.properties","valueAnalysis-NoCegar.properties","valueAnalysis-Cegar.properties","kInduction-linear.properties"}; String config=configurations[4]; ProcessBuilder processBuilder = new ProcessBuilder("./"+Main.cpaDir+"/scripts/cpa.sh","-noout", "-config","cpachecker/config/"+config,fileName+".c") .redirectOutput(new File(fileName+"_cpa_out.txt")); Process process=processBuilder.start(); process.waitFor(); File output=new File(fileName+"_cpa_out.txt"); Scanner in=new Scanner(output); while(in.hasNextLine()) { String s=in.nextLine(); if (s.contains("FALSE.")) return true; } return false; } }
5,884
31.694444
193
java
null
RevTerm-main/code/polynomial/part1/Main/src/CFGNode.java
import java.util.Map; import java.util.TreeMap; import java.util.Vector; public class CFGNode { public static Vector<CFGNode> allCFGNodes = new Vector<>(); public static Map<Integer, CFGNode> idToNode = new TreeMap<>(); public static int greatestNodeIndex = 0; public Vector<Transition> out; int id; boolean visited; boolean isCutPoint; Vector<PolynomialPredicate> inv; CFGNode(int ind) { id = ind; idToNode.put(ind, this); out = new Vector<>(); allCFGNodes.add(this); inv = new Vector<>(); visited = isCutPoint =false; if (ind > greatestNodeIndex) greatestNodeIndex = ind; } void addNecessaryNondet() { Vector<Vector<Transition>> groups = new Vector<>(); for (Transition t : out) if (!t.hasGroup) { Vector<Transition> g = new Vector<>(); for (Transition tp : out) if (t.detGuard.equalsLogic(tp.detGuard)) { tp.hasGroup = true; g.add(tp); } if (g.size() == 1) t.hasGroup = false; else groups.add(g); } for (int i = 0; i < out.size(); i++) if (out.elementAt(i).hasGroup) { Transition.allTransitions.removeElement(out.elementAt(i)); out.removeElementAt(i); i--; } for (Vector<Transition> g : groups) { PolynomialPredicate commonGuard = g.firstElement().detGuard.deepCopy(); CFGNode n = new CFGNode(greatestNodeIndex + 1); String nontdetTmp = "_tmp_"; Parser.allVars.add("_tmp_"); for (int i = 0; i < g.size(); i++) { Transition t = new Transition(n, g.elementAt(i).u); t.varName = g.elementAt(i).varName; t.update = g.elementAt(i).update; t.nondetGuard = g.elementAt(i).nondetGuard; Polynomial lower = new Polynomial(nontdetTmp, Rational.one); lower.add(Monomial.one, new Rational(-i, 1)); // _tmp_ >= i Polynomial upper = new Polynomial(nontdetTmp, Rational.negate(Rational.one)); upper.add(Monomial.one, new Rational(i, 1)); // _tmp_ <= i if (i == 0) t.detGuard.add(upper); //t <= 0 else if (i == g.size() - 1) t.detGuard.add(lower); //t >= out.size()-1 else { t.detGuard.add(upper); // t >= i t.detGuard.add(lower); // t <= i } t.addToGraph(); } Transition t = new Transition(this, n); String nondetVar="_r_"+ Parser.nondetCount; t.detGuard.add(commonGuard); t.varName.add(nontdetTmp); t.update.add(new Polynomial(nondetVar)); t.addToGraph(); } } void addTerminalTransitions() { // if (out.size() > 0) // { // Vector<LinearPredicate> predicates = new Vector<>(); // boolean hasNondet=false; // for (Transition t : out) // { // LinearPredicate lp=t.detGuard.deepCopy(); // if(t.detGuard.isEmpty()) // hasNondet=true; // predicates.add(lp); // } // if (hasNondet) // return; // Vector<LinearPredicate> negation = LinearPredicate.negate(predicates); // CFGNode term = idToNode.get(-2); // for (LinearPredicate lp : negation) // { // Transition tau = new Transition(this, term); // tau.detGuard = lp; // tau.addToGraph(); // } // } // else if(out.size()==0) { CFGNode term = idToNode.get(-2); Transition tau = new Transition(this, term); tau.addToGraph(); } } public static CFGNode addNode(int x) { if (idToNode.containsKey(x)) return idToNode.get(x); return new CFGNode(x); } // public static CFGNode getCFGNode(int x) // { // return idToNode.get(x); // } }
4,452
29.292517
93
java
null
RevTerm-main/code/polynomial/part1/Main/src/CFGUtil.java
import java.util.Vector; public class CFGUtil { public static Vector<CFGNode> findCutpoints() { Vector<CFGNode> ret=new Vector<>(); ret.add(Main.startNode); Main.startNode.isCutPoint=true; ret.add(Main.termNode); Main.termNode.isCutPoint=true; dfs(Main.startNode,ret,new Vector<CFGNode>()); return ret; } private static void dfs(CFGNode v,Vector<CFGNode> res,Vector<CFGNode> currentBranch) { v.visited=true; currentBranch.add(v); for(Transition t:v.out) { if(!t.u.visited) dfs(t.u, res, currentBranch); else if(!res.contains(t.u) && currentBranch.contains(t.u)) { t.u.isCutPoint=true; res.add(t.u); } } currentBranch.removeElementAt(currentBranch.size()-1); } public static void weakestPreCondition(Vector<Transition> path, Putinar putinar) //NOTE: for C-Integer programs this is completely fine but for general T2 transition systems it might have problems { for(int i=path.size()-1;i>=0;i--) { Transition t=path.elementAt(i); for(int j=0;j<t.varName.size();j++) { String var=t.varName.elementAt(j); Polynomial upd=t.update.elementAt(j); putinar.replaceVarWithPoly(var,upd); } putinar.addPredicate(t.detGuard.deepCopy()); putinar.addPredicate(t.nondetGuard.deepCopy()); } } }
1,562
29.647059
201
java
null
RevTerm-main/code/polynomial/part1/Main/src/InvUtil.java
import java.io.BufferedReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.Vector; public class InvUtil { public static boolean checkNonTermination(Vector<Putinar> I, CFGNode startNode) throws Exception { Vector<Polynomial> equalities = new Vector<>(); for(Putinar putinar: I) equalities.addAll(putinar.generateEqualities()); String Template = "";//InvariantGeneration.cCount+" "+Farkas.countD+" "+Parser.allVars.size()+"\n"; Template += "(set-option :print-success false) \n"; if (Main.solver.equals("bclt")) { Template +="(set-option :produce-models true)\n"+ "(set-option :produce-assertions true)\n" + "(set-logic QF_NIA)\n"; } for (int i = 0; i < InvariantGeneration.cCount; i++) Template += "(declare-const c_" + i + " Int)\n"; Template+="(assert (< "+InvariantGeneration.negativeVar+" 0))\n"; //invariant at l_term // for (int i = 0; i < Putinar.countD; i++) // { // Template += "(declare-const d_" + i + " Int)\n"; // Template += "(assert (>= d_" + i + " 0))\n"; // d_i>=0 // } for(int i=0;i<InvariantGeneration.lCount;i++) Template += "(declare-const l_"+i + " Int)\n"; for(String lvar:InvariantGeneration.nonNegativeLvars) Template += "(assert (>= " + lvar + " 0))\n"; // lvar>=0 for(int i=0;i<InvariantGeneration.tCount;i++) Template += "(declare-const t_"+i+" Int)\n"; for (String var : Parser.allVars) if (!var.equals("1")) Template += "(declare-const " + var + " Int)\n"; for (Polynomial qc : startNode.inv.firstElement().exprs) Template += "(assert (>= " + qc.toString() + " 0))\n"; FileWriter fw = new FileWriter(Main.workingdir+"/"+Main.solver + Main.con+"-"+Main.dis+Main.fileName + ".smt2"); fw.write(Template); for (Polynomial e : equalities) { //System.err.println(qc.toNormalString()); fw.write("(assert (= 0 " + e.toString() + "))\n"); //System.err.println(qc.toNormalString()); } fw.write("(check-sat)\n"); fw.write("(get-value ("); for (int i = 0; i < InvariantGeneration.cCount; i++) fw.write("c_" + i + " "); for (String var : Parser.allVars) if (!var.equals("1")) fw.write(var + " "); fw.write("))"); fw.close(); return check(); } public static boolean check() throws Exception { // System.err.println("Solver Started"); String[] configs= {"bclt --file", "z3 -smt2", "mathsat "}; int solverInd = -1; if (Main.solver.equals("bclt")) solverInd = 0; else if(Main.solver.equals("z3")) solverInd=1; else if(Main.solver.equals("mathsat")) solverInd=2; Process process = Runtime.getRuntime().exec("./"+Main.solversDir+"/"+configs[solverInd] + " " + Main.workingdir+"/"+Main.solver + Main.con+"-"+Main.dis+Main.fileName+".smt2"); process.waitFor(); // if(!process.waitFor(10, TimeUnit.SECONDS)) // { // process.destroy(); // return false; // } BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while (bufferedReader.ready()) { String s = bufferedReader.readLine(); if (s.equals("sat")) { // System.err.println("SAT!"); return true; } else if (s.equals("unsat")) { // System.err.println("UNSAT!"); return false; } } return false; } }
3,910
34.554545
183
java
null
RevTerm-main/code/polynomial/part1/Main/src/InvariantGeneration.java
import java.util.*; public class InvariantGeneration { public static Map<String, String> nondetVarsC = new HashMap<>(); public static String negativeVar; public static int totalUnknownVars = 0; public static int cCount = 0,lCount=0,tCount=0; public static Vector<String> nonNegativeLvars=new Vector<>(); public static void MakeTemplate(int con,int dis)//conjunctions, disjunctions { for (CFGNode n : CFGNode.allCFGNodes) { if (n.id == Main.startNode.id) { PolynomialPredicate pp = new PolynomialPredicate(); for (String var : Parser.allVars) // var = c_j { Polynomial p = new Polynomial(); Rational minusOne = Rational.negate(Rational.one); p.add(new Monomial(var),minusOne); // p = -var p.add(new Monomial("c_"+cCount),Rational.one); // qc = -var + c_cCount nondetVarsC.put(var,"c_"+cCount); cCount++; pp.add(p); // p>=0 pp.add(p.deepCopy().negate()); // -p>=0 } n.inv.add(pp); } else if(n.id == Main.termNode.id) // -1 >=0 { PolynomialPredicate pp = new PolynomialPredicate(); Polynomial p = new Polynomial(); negativeVar="c_"+cCount; cCount++; p.add(new Monomial(negativeVar),Rational.one); pp.add(p); n.inv.add(pp); } else if(n.isCutPoint) { for(int k=0;k<dis;k++) { PolynomialPredicate pp = new PolynomialPredicate(); for (int j = 0; j < con; j++) { Polynomial p = new Polynomial(); // c_0 * 1 + c_1 * var_1 + c_2 * var2 .... + c_n * var_n >=0 Set<Monomial> allMonomials= Monomial.getAllMonomials(Parser.allVars,Main.degree); for (Monomial m : allMonomials) { m.addVar("c_"+cCount,1); p.add(m,Rational.one); // p+= var * c_cCount cCount++; } pp.add(p); // p>=0 } n.inv.add(pp); } } } } public static void generate(Vector<CFGNode> cutPoints,Vector<Putinar> putinarVector) { for(CFGNode v:cutPoints) processPaths(v,v,new Vector<Transition>(),putinarVector); } private static void processPaths(CFGNode st,CFGNode v,Vector<Transition> path,Vector<Putinar> putinarVector) { Vector<Transition> tran=v.out; for(Transition t:tran) { CFGNode u=t.u; path.add(t); if(u.isCutPoint) { PolynomialPredicate objPred = u.inv.lastElement(); Vector<PolynomialPredicate> tmp = new Vector<>(); for(PolynomialPredicate pp:u.inv) if(pp!=objPred) tmp.add(pp.deepCopy()); Vector<PolynomialPredicate> uinvNegate = PolynomialPredicate.negate(tmp,0); if(uinvNegate.isEmpty()) uinvNegate.add(PolynomialPredicate.TRUE); for(PolynomialPredicate vinv:st.inv) for(PolynomialPredicate uinv:uinvNegate) for(Polynomial obj:objPred.exprs) { //vinv & uinv & path => obj Putinar putinar=new Putinar(st.id,u.id); if(uinv!=PolynomialPredicate.TRUE) putinar.addPredicate(uinv.deepCopy()); putinar.setObjective(obj.deepCopy()); CFGUtil.weakestPreCondition(path,putinar); putinar.addPredicate(vinv); putinarVector.add(putinar); } } else processPaths(st,u,path,putinarVector); path.removeElementAt(path.size()-1); } } }
4,343
35.813559
117
java
null
RevTerm-main/code/polynomial/part1/Main/src/LinearCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class LinearCombination { Map<String, Rational> coef; public static final LinearCombination one = new LinearCombination(Rational.one); LinearCombination() { coef = new HashMap<>(); } LinearCombination(Rational c) { coef = new HashMap<>(); coef.put("1", c); } LinearCombination(String var) { coef = new HashMap<>(); coef.put(var, Rational.one); } LinearCombination(String var, Rational c) { coef = new HashMap<>(); coef.put(var, c); } public void add(String var, Rational c) { if (coef.containsKey(var)) coef.put(var, Rational.add(coef.get(var), c)); else coef.put(var, c); } public void add(LinearCombination lc) { for (String var : lc.coef.keySet()) add(var, lc.coef.get(var)); } public void minus(LinearCombination lc) { add(lc.negate()); } public void multiplyByValue(Rational val) { for (String var : coef.keySet()) coef.put(var, Rational.mul(coef.get(var), val)); } public LinearCombination negate() //does not negate "this". returns the negate of "this". { removeZeros(); LinearCombination lc = new LinearCombination(); for (String var : coef.keySet()) lc.coef.put(var, Rational.negate(coef.get(var))); return lc; } public boolean containsNondetVar() { for (String var : coef.keySet()) if (var.startsWith("_tmp_") || var.startsWith("_r_")) return true; return false; } public LinearCombination deepCopy() { removeZeros(); LinearCombination lc = new LinearCombination(); for (String var : coef.keySet()) { Rational c = coef.get(var); lc.add(var, c); } return lc; } // public QuadraticCombination mulByVar(String var) // { // QuadraticCombination ret = new QuadraticCombination(); // for (String s : coef.keySet()) // ret.add(s, new LinearCombination(var, coef.get(s))); // return ret; // } public void multiplyByLin(LinearCombination lc) throws Exception { if (!isConstant() && !lc.isConstant()) throw new Exception("multiplication of two linear Expressions is not linear"); if (isConstant()) { Rational x = coef.get("1"); if (x == null) x = Rational.zero; coef.clear(); for (String var : lc.coef.keySet()) coef.put(var, Rational.mul(lc.coef.get(var), x)); } else { Rational x = lc.coef.get("1"); multiplyByValue(x); } } void replaceVarWithLinear(String var,LinearCombination lc) { if(!coef.containsKey(var)) return; Rational r=coef.get(var); coef.put(var,Rational.zero); LinearCombination tmp=lc.deepCopy(); tmp.multiplyByValue(r); add(tmp); removeZeros(); } public boolean isConstant() { removeZeros(); return coef.size() <= 1 && (coef.size() != 1 || coef.containsKey("1")); } public void removeZeros() { Vector<String> allVars = new Vector<>(coef.keySet()); for (String s : allVars) if (coef.get(s).equals(Rational.zero)) coef.remove(s); } // public int replaceVarsWithValue(Map<String, Integer> dict) throws Exception // { // int ret = 0; // for (String var : coef.keySet()) // { // if (!dict.containsKey(var)) // throw new Exception("dictionary cannot support " + toNormalString()); // int varVal = dict.get(var); // ret += varVal * coef.get(var).numerator / coef.get(var).denominator; // } // return ret; // } public boolean equals(LinearCombination lc) { removeZeros(); lc.removeZeros(); for (String var : coef.keySet()) if (!lc.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; for (String var : lc.coef.keySet()) if (!this.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; return true; } public String toNormalString() { removeZeros(); if (coef.size() == 0) return "0"; String ret = ""; for (String s : coef.keySet()) { Rational c = coef.get(s); if (ret.equals("")) ret += c.toNormalString() + "*" + s; else if (coef.get(s).compareTo(Rational.zero) < 0) ret += " - " + (Rational.negate(c)).toNormalString() + "*" + s; else ret += " + " + c.toNormalString() + "*" + s; } return ret; } public String toString() { removeZeros(); String ret = ""; for (String s : coef.keySet()) { Rational c = coef.get(s); if (c.equals(Rational.one)) ret += " " + s; else if (s.equals("1")) { if (!c.isNonNegative()) ret += " (- " + Rational.negate(c) + ")"; else ret += " " + c + " "; } else if (c.isNonNegative()) ret += " (* " + (c) + " " + s + ")"; else ret += " (* (- " + Rational.negate(c) + ") " + s + ")"; } if (ret.equals("")) return "0"; if (coef.size() > 1) return "(+ " + ret + ")"; else return ret; } }
5,944
25.779279
94
java
null
RevTerm-main/code/polynomial/part1/Main/src/LinearPredicate.java
import java.util.Vector; public class LinearPredicate { Vector<LinearCombination> exprs; LinearPredicate() { exprs = new Vector<>(); } void add(LinearCombination lc) { for(LinearCombination l:exprs) if(l!=null && l.equals(lc)) return; exprs.add(lc); } void add(LinearPredicate lp) { for (LinearCombination lc : lp.exprs) add(lc.deepCopy()); } boolean isEmpty() { return exprs.isEmpty(); } void replaceVarWithLinear(String var,LinearCombination lc) { for(LinearCombination l:exprs) l.replaceVarWithLinear(var,lc); } public Vector<LinearPredicate> negate() { Vector<LinearPredicate> ret = new Vector<>(); for (LinearCombination lc : exprs) { LinearCombination l = lc.negate(); l.add("1", Rational.negate(Main.eps)); LinearPredicate lp = new LinearPredicate(); lp.add(l); ret.add(lp); } return ret; } public static Vector<LinearPredicate> negate(Vector<LinearPredicate> g) { Vector<LinearPredicate> ret = new Vector<>(); if (g.size() == 1) ret = g.firstElement().negate(); else { Vector<LinearPredicate> notLast = g.lastElement().negate(); g.removeElementAt(g.size() - 1); Vector<LinearPredicate> recurse = negate(g); for (LinearPredicate lp : notLast) for (LinearPredicate predicate : recurse) { LinearPredicate copy = predicate.deepCopy(); copy.add(lp); ret.add(copy); } } return ret; } public static Vector<LinearPredicate> conjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } if (right.isEmpty()) { for (LinearPredicate lp : left) ret.add(lp.deepCopy()); return ret; } for (LinearPredicate lp1 : left) for (LinearPredicate lp2 : right) { LinearPredicate lp = new LinearPredicate(); lp.add(lp1.deepCopy()); lp.add(lp2.deepCopy()); ret.add(lp); } return ret; } public static Vector<LinearPredicate> disjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); for (LinearPredicate lp : left) ret.add(lp.deepCopy()); for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } public LinearPredicate deepCopy() { LinearPredicate ret = new LinearPredicate(); ret.add(this); return ret; } public boolean equalsLogic(LinearPredicate lp) { for (LinearCombination lc : exprs) if (!lp.contains(lc)) return false; for (LinearCombination lc : lp.exprs) if (!this.contains(lc)) return false; return true; } public boolean contains(LinearCombination lc) { for (LinearCombination l : exprs) if (l.equals(lc)) return true; return false; } public String toString() { String ret = ""; for (int i = 0; i < exprs.size(); i++) { LinearCombination lc = exprs.elementAt(i); if (i == 0) ret += lc.toNormalString() + ">=0"; else ret += " && " + lc.toNormalString() + ">=0"; } return ret; } }
3,958
24.216561
111
java
null
RevTerm-main/code/polynomial/part1/Main/src/Main.java
import java.util.Vector; public class Main { public static Rational eps = Rational.one; public static CFGNode startNode, cutPoint, termNode; public static String fileName = "", solver = "",workingdir="",solversDir=""; public static int con = 0, dis = 0,degree=0,mu=0; //con = number of conjunctions, dis = number of disjunctions, degree = degree of invariants, mu = degree of SOS polynomials public static void main(String[] args) throws Exception { // Polynomial temp = new Polynomial("x",Rational.one); // temp.add(new Monomial("x",2),Rational.one); // System.err.println(temp.toString()); // System.exit(0); // Polynomial upd = temp.getCoef(new Monomial("x",2)); // System.err.println("coef: " + upd.toNormalString()); // //// temp.replaceVarWithPoly("x",upd); //// System.err.println(temp.toNormalString()); // System.exit(0); con = Integer.parseInt(args[0]); dis = Integer.parseInt(args[1]); degree = Integer.parseInt(args[2]); mu = Integer.parseInt(args[3]); solver = args[4]; fileName = args[5]; workingdir = args[6]; solversDir = args[7]; termNode = CFGNode.addNode(-2); startNode = CFGNode.addNode(-1); long startTime = System.currentTimeMillis(); Parser.readFile(fileName); Parser.parseProg(0, Parser.getTokenCount() - 1); for (CFGNode n : CFGNode.allCFGNodes) { if (n.id == -1 || n.id == -2) continue; n.addTerminalTransitions(); } int curTotalCFGNodes = CFGNode.allCFGNodes.size(); for (int i = 0; i < curTotalCFGNodes; i++) { CFGNode n = CFGNode.allCFGNodes.elementAt(i); if (n.id == -2 || n.id == -1) continue; n.addNecessaryNondet(); } //this is done after parsing because we need to have the list of all variables. for(Transition t:Transition.allTransitions) t.addNondetTemplate(); // System.err.println("Parsing Finished"); Vector<CFGNode> cutPoints=CFGUtil.findCutpoints(); // for(CFGNode x:cutPoints) // System.err.println("cutPoint: "+x.id); fileName=fileName.replace("/","_"); // for (Transition t : Transition.allTransitions) // System.err.println(t); /////////////////////////////OK////////////////////////////////// InvariantGeneration.MakeTemplate(con,dis); // for(CFGNode n:cutPoints) // for(int i=0;i<n.inv.size();i++) // System.err.println("id: "+n.id+" inv: "+n.inv.elementAt(i).toNormalString()); Vector<Putinar> invPutinar = new Vector<>(); InvariantGeneration.generate(cutPoints,invPutinar); // for(Putinar putinar:invPutinar) // System.err.println(putinar.toString()); boolean result = InvUtil.checkNonTermination(invPutinar, startNode); if(result) //does not terminate System.out.println("Non-Terminating"); else System.out.println("Could Not Prove Non-Termination"); long endTime = System.currentTimeMillis(); System.out.println("total time used: " + (endTime - startTime)); int val = (result) ? 3 : 0; System.exit(val); } }
3,380
32.475248
127
java
null
RevTerm-main/code/polynomial/part1/Main/src/Monomial.java
import java.util.*; public class Monomial implements Comparable<Monomial> { Map<String, Integer> vars; public static final Monomial one = new Monomial(); Monomial() { vars = new TreeMap<>(); } Monomial(String var) { vars=new TreeMap<>(); addVar(var,1); } Monomial(String var,int power) { vars= new TreeMap<>(); addVar(var,power); } void addVar(String varName, int power) { if (vars.containsKey(varName)) vars.put(varName, vars.get(varName) + power); else vars.put(varName, power); } Map<String, Integer> getVars() { return vars; } public static Monomial mul(Monomial a, Monomial b) { Monomial ret = new Monomial(); Map<String, Integer> avars = a.getVars(), bvars = b.getVars(); for (String varName : avars.keySet()) ret.addVar(varName, avars.get(varName)); for (String varName : bvars.keySet()) ret.addVar(varName, bvars.get(varName)); return ret; } Monomial deepCopy() { Monomial ret = new Monomial(); for (String varName : vars.keySet()) ret.addVar(varName, vars.get(varName)); return ret; } boolean containsVar(String var) { return vars.containsKey(var); } Monomial removeOneVar(String var) { Monomial ret = new Monomial(); for (String s : vars.keySet()) if (!s.equals(var)) ret.addVar(s, vars.get(s)); return ret; } int getPower(String var) { return vars.get(var); } public Monomial programVarsPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial unknownPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(var.startsWith("c_") || var.startsWith("t_") || var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial getProgramVarsPart() { Monomial ret=new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) ret.addVar(var,getPower(var)); return ret; } public static Set<Monomial> getAllMonomials(Set<String> vars, int degree) { Set<Monomial> ret=new TreeSet<>(); if(degree==0) ret.add(Monomial.one.deepCopy()); else { Set<Monomial> recurse = getAllMonomials(vars,degree-1); for(Monomial m:recurse) ret.add(m.deepCopy()); for(String var:vars) for(Monomial m:recurse) { if(m.degree()==degree-1) { Monomial tmp = m.deepCopy(); tmp.addVar(var, 1); ret.add(tmp); } } } return ret; } int degree() { int ret=0; for(String var:vars.keySet()) ret+=vars.get(var); return ret; } public int compareTo(Monomial m) { return (toNormalString().compareTo(m.toNormalString())); } void removeZeros() { Vector<String> allVars=new Vector<>(vars.keySet()); for(String var:allVars) if(getPower(var)==0) vars.remove(var); } public boolean equals(Monomial m) { removeZeros(); m.removeZeros(); for(String var:vars.keySet()) if(!m.containsVar(var) || m.getPower(var)!=getPower(var)) return false; for(String var:m.vars.keySet()) if(!this.containsVar(var)) return false; return true; } String toNormalString() { if (vars.isEmpty()) return "1"; String ret = ""; for (String varName : vars.keySet()) { if (!ret.equals("")) ret+=" * "; ret += varName; if(vars.get(varName)!=1) ret+="^"+vars.get(varName); } return ret; } public String toString() { if (vars.isEmpty()) return "1"; String ret = ""; for (String varName : vars.keySet()) { for (int i = 0; i < vars.get(varName); i++) ret += varName + " "; } // ret += ")"; return ret; } }
4,836
23.185
125
java
null
RevTerm-main/code/polynomial/part1/Main/src/Node.java
import java.util.Vector; public class Node { public static Vector<Node> allNodes = new Vector<>(); int id; Node par; int beginIndex, endIndex; String type; Vector<Node> children; String varName; Polynomial expr; QuadraticCombination nondetLow, nondetUp; Vector<PolynomialPredicate> guard; Node(Node par, int beginIndex, int endIndex, String type) { allNodes.add(this); id = allNodes.size() - 1; this.par = par; this.beginIndex = beginIndex; this.endIndex = endIndex; this.type = type; this.expr = null; this.guard = new Vector<>(); children = new Vector<>(); if (par != null) par.children.add(this); } public String toString() { String ret = ""; ret += "Node #" + id + "\n"; if (par != null) ret += "Par: " + par.id + "\n"; else ret += "Par: null\n"; ret += "beginIndex=" + beginIndex + "\t" + "endIndex=" + endIndex + "\n"; ret += "type: " + type + "\n"; ret += "guard:"; for (PolynomialPredicate lp : guard) ret += lp.toNormalString() + "\n"; return ret; } }
1,231
23.64
81
java
null
RevTerm-main/code/polynomial/part1/Main/src/Parser.java
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class Parser { public static Set<String> allVars = new HashSet<>(); public static Vector<String> tokens = new Vector<>(); public static int nondetCount = 0; static { // allVars.add("1"); } public static Node parseProg(int beginIndex, int endIndex) throws Exception { if (!getToken(beginIndex).equals("START")) throw new Exception("program should start with START"); Node cur = new Node(null, beginIndex, endIndex, "prog"); CFGNode start = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 2))); Transition fromStart = new Transition(Main.startNode, start); fromStart.addToGraph(); if (getToken(beginIndex + 4).equals("CUTPOINT")) Main.cutPoint = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 6))); int lastFROM = -1; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("FROM")) { if (lastFROM != -1) throw new Exception(" \"TO: index\" expected before @" + i); lastFROM = i; } else if (getToken(i).equals("TO")) { parseTransition(cur, lastFROM, i + 3); lastFROM = -1; } return cur; } public static Node parseTransition(Node par, int beginIndex, int endIndex) throws Exception { if (!getToken(endIndex).equals(";")) throw new Exception("Transition must end with ; @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "Transition"); int vIndex = Integer.parseInt(getToken(beginIndex + 2)), uIndex = Integer.parseInt(getToken(endIndex - 1)); CFGNode vNode = CFGNode.addNode(vIndex); CFGNode uNode = CFGNode.addNode(uIndex); Vector<Transition> transitionVector = new Vector<>(); transitionVector.add(new Transition(vNode, uNode)); int lastColon = beginIndex + 3; for (int i = beginIndex + 4; i <= endIndex - 4; i++) { if (getToken(i).equals(";")) { Node ch = parseStmt(cur, lastColon + 1, i - 1); if (ch.type.equals("assume")) { if (ch.guard.size() == 1) for (Transition t : transitionVector) t.detGuard.add(ch.guard.elementAt(0)); else if (ch.guard.size() > 1) { Vector<Transition> tmp = new Vector<>(); for (int j = 0; j < ch.guard.size(); j++) { for (Transition t : transitionVector) { Transition tp = t.deepCopy(); tp.detGuard.add(ch.guard.elementAt(j)); tmp.add(tp); } } transitionVector = tmp; } } else { for (Transition t : transitionVector) { t.varName.add(ch.varName); t.update.add(ch.expr); // if (ch.expr.containsNondetVar()) // { // LinearCombination lowerBound = ch.expr.deepCopy(); // lowerBound.minus(new LinearCombination(ch.nondetLow, Rational.one)); //var - low >= 0 // t.nondetGuard.add(lowerBound); // // LinearCombination upperBound = new LinearCombination(ch.nondetUp, Rational.one); // upperBound.minus(ch.expr.deepCopy()); //up - var >= 0 // t.nondetGuard.add(upperBound); // // } } } lastColon = i; } } for (Transition t : transitionVector) t.addToGraph(); return cur; } public static Node parseStmt(Node par, int beginIndex, int endIndex) throws Exception { if (getToken(beginIndex).equals("assume")) { Node cur = new Node(par, beginIndex, endIndex, "assume"); Node ch = parseBexpr(cur, beginIndex + 2, endIndex - 1); cur.guard = ch.guard; return cur; } else { Node cur = new Node(par, beginIndex, endIndex, "assignment"); if (!getToken(beginIndex + 1).equals(":=")) throw new Exception("assignment without := @" + beginIndex + "-" + endIndex); int sgn = beginIndex + 1; String varName = getToken(beginIndex); allVars.add(varName); boolean isNondet = false; for (int i = sgn + 1; i <= endIndex; i++) if (getToken(i).equals("nondet")) isNondet = true; if (isNondet) { cur.varName = varName; cur.expr = new Polynomial(new Monomial("_r_"+nondetCount)); nondetCount++; } else { Polynomial update = parseExpr(cur, sgn + 1, endIndex).expr; cur.varName = varName; cur.expr = update; } return cur; } } public static Node parseBexpr(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseBexpr: "+beginIndex+"---"+endIndex); Node cur = new Node(par, beginIndex, endIndex, "Bexpr"); for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("nondet")) return cur; Vector<Integer> ors = new Vector<>(); Vector<Integer> ands = new Vector<>(); ors.add(beginIndex - 1); ands.add(beginIndex - 1); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && getToken(i).equals("|") && getToken(i + 1).equals("|")) { ors.add(i + 1); i++; } else if (openPar == 0 && getToken(i).equals("&") && getToken(i + 1).equals("&")) { ands.add(i + 1); i++; } ors.add(endIndex + 2); ands.add(endIndex + 2); if (ors.size() > 2) { for (int i = 1; i < ors.size(); i++) { Node ch = parseBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 2); cur.guard = PolynomialPredicate.disjunct(cur.guard, ch.guard); } return cur; } if (ands.size() > 2) { for (int i = 1; i < ands.size(); i++) { Node ch = parseBexpr(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 2); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); } return cur; } boolean isCompletlyInsidePar = true; openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && i != endIndex) { isCompletlyInsidePar = false; break; } } if (isCompletlyInsidePar) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex - 1); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } if (getToken(beginIndex).equals("!")) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex); cur.guard = PolynomialPredicate.negate(ch.guard,0); return cur; } Node ch = parseLiteral(cur, beginIndex, endIndex); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } public static Node parseLiteral(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseLiteral:"+ beginIndex+"---"+endIndex); int sgn = -1, type = -1; //types: 0: "<=" 1: ">=" 2: ">" 3: "<" 4: "==" 5: "!=" for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("<=")) { sgn = i; type = 0; } else if (getToken(i).equals(">=")) { sgn = i; type = 1; } else if (getToken(i).equals(">")) { sgn = i; type = 2; } else if (getToken(i).equals("<")) { sgn = i; type = 3; } else if (getToken(i).equals("==")) { sgn = i; type = 4; } else if (getToken(i).equals("!=")) { sgn = i; type = 5; } if (sgn == beginIndex || sgn == endIndex) throw new Exception("literal starts or ends with sign @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "literal"); Node left = null; Node right=null; if (sgn == -1) { type = 5; left = parseExpr(cur, beginIndex, endIndex); right = new Node(cur, endIndex, endIndex, "0"); right.expr = new Polynomial(Rational.zero); } else { left = parseExpr(cur, beginIndex, sgn - 1); right = parseExpr(cur, sgn + 1, endIndex); } if (type == 0) //left<=right --> right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 1) //left>=right --> left-right>=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 2) // left > right -> left -right >=eps -> left - right -eps >=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); // left - right lc.minus(new Polynomial(Main.eps)); // left - right - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 3) //left < right --> right - left > eps --> right - left -eps >=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); // right - left lc.minus(new Polynomial(Main.eps)); // right - left - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 4) //left==right --> left-right>=0 and right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); lp.add(lc2); cur.guard.add(lp); } else { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); lc.minus(new Polynomial(Main.eps)); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); lc2.minus(new Polynomial(Main.eps)); PolynomialPredicate lp1 = new PolynomialPredicate(), lp2 = new PolynomialPredicate(); lp1.add(lc); lp2.add(lc2); cur.guard.add(lp1); cur.guard.add(lp2); } return cur; } public static Node parseExpr(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseExpr: "+beginIndex+"----"+endIndex); Vector<Integer> signIndex = new Vector<>(); Vector<String> signType = new Vector<>(); if (!getToken(beginIndex).equals("-")) { signIndex.add(beginIndex - 1); signType.add("+"); } int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && (getToken(i).equals("+") || (getToken(i).equals("-") && (i - 1 < beginIndex || (i - 1 >= beginIndex && !getToken(i - 1).equals("*") && !getToken(i - 1).equals("+")))))) { signIndex.add(i); signType.add(getToken(i)); } } signIndex.add(endIndex + 1); signType.add("+"); Node cur = new Node(par, beginIndex, endIndex, "expr"); cur.expr = new Polynomial(); for (int i = 0; i + 1 < signIndex.size(); i++) { Node ch = parseTerm(cur, signIndex.elementAt(i) + 1, signIndex.elementAt(i + 1) - 1); if (signType.elementAt(i).equals("+")) cur.expr.add(ch.expr); else cur.expr.minus(ch.expr); } return cur; } public static Node parseTerm(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseTerm: "+beginIndex+"---"+endIndex); if ((beginIndex == endIndex && isNumeric(getToken(beginIndex)))) //constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = Integer.parseInt(getToken(beginIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex - 1 && isNumeric(getToken(endIndex))) //negative constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = -Integer.parseInt(getToken(endIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex) //var { Node cur = new Node(par, beginIndex, endIndex, "var"); String var = getToken(beginIndex); allVars.add(var); if (Character.isDigit(var.charAt(0))) throw new Exception("Incorrect var name @" + beginIndex); cur.expr = new Polynomial(); cur.expr.add(new Monomial(var), new Rational(1, 1)); return cur; } else // (...) or [] * [] { Node cur = new Node(par, beginIndex, endIndex, "term mul"); cur.expr = new Polynomial(); Vector<Integer> sgnIndex = new Vector<>(); Vector<String> sgnType = new Vector<>(); sgnIndex.add(beginIndex - 1); sgnType.add("*"); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && (getToken(i).equals("*") || getToken(i).equals("/"))) { sgnIndex.add(i); sgnType.add(getToken(i)); } else if (getToken(i).equals("%")) { throw new Exception("% is not supported. @" + beginIndex + "-" + endIndex); } sgnIndex.add(endIndex + 1); sgnType.add("*"); if (sgnIndex.size() == 2) // (...) { Node ch = parseExpr(cur, beginIndex + 1, endIndex - 1); cur.expr = ch.expr; return cur; } else { cur.expr.add(Monomial.one, Rational.one); for (int i = 1; i < sgnIndex.size(); i++) { Node ch = parseExpr(cur, sgnIndex.elementAt(i - 1) + 1, sgnIndex.elementAt(i) - 1); if (sgnType.elementAt(i - 1).equals("*")) cur.expr.multiplyByPolynomial(ch.expr); else if (ch.expr.isConstant() && ch.expr.terms.containsKey(Monomial.one)) cur.expr.multiplyByValue(Rational.inverse(ch.expr.terms.get(Monomial.one))); else throw new Exception("Divison by variable is not possible @" + beginIndex + "-" + endIndex); } return cur; } } } public static boolean isNumeric(String s) { for (int i = 0; i < s.length(); i++) if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != '.') return false; return true; } public static int getTokenCount() { return tokens.size(); } public static String getToken(int x) { return tokens.elementAt(x); } public static void readTokens(String program) throws Exception { String extraSpace = ""; for (int i = 0; i < program.length(); i++) { char c = program.charAt(i); if (c == '.' || Character.isAlphabetic(c) || Character.isDigit(c) || c == '_') extraSpace += c; else { extraSpace += " "; extraSpace += c; extraSpace += " "; } } Scanner scanner = new Scanner(extraSpace); while (scanner.hasNext()) { String s = scanner.next(); if (s.equals("=")) { if (tokens.size() == 0) throw new Exception("program cannot start with ="); String last = tokens.lastElement(); if (last.equals(":") || last.equals(">") || last.equals("<") || last.equals("=") || last.equals("!")) { tokens.removeElementAt(getTokenCount() - 1); last += s; tokens.add(last); } else tokens.add(s); } else tokens.add(s); } // for(int i=0;i<tokens.size();i++) // System.err.println(i+":"+tokens.elementAt(i)); } public static void readFile(String fileName) throws Exception { File file = new File(fileName); Scanner in = new Scanner(file); String program = ""; while (in.hasNextLine()) { String s = in.nextLine(); if (s.contains("//")) s = s.substring(0, s.indexOf("//")); if (s.contains("AT(")) { int ind = s.indexOf("AT("); int openPar = 0, endOfAT = -1; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') openPar++; else if (s.charAt(i) == ')') { openPar--; if (openPar == 0) { endOfAT = i; break; } } } s = s.substring(0, ind) + s.substring(endOfAT + 1, s.length()); } program += s + " "; } readTokens(program); } }
20,331
34.607706
163
java
null
RevTerm-main/code/polynomial/part1/Main/src/Polynomial.java
import java.util.*; public class Polynomial { Map<Monomial, Rational> terms; Polynomial() { terms = new TreeMap<>(); } Polynomial(Rational c) { terms = new TreeMap<>(); terms.put(Monomial.one, c); } Polynomial(String var) { terms = new TreeMap<>(); terms.put(new Monomial(var), Rational.one); } Polynomial(String var, Rational c) { terms = new TreeMap<>(); terms.put(new Monomial(var), c); } Polynomial(Monomial m) { terms = new TreeMap<>(); terms.put(m, Rational.one); } Polynomial(Monomial m, Rational c) { terms = new TreeMap<>(); terms.put(m, c); } Polynomial(Set<String> vars) //generates the polynomial \sum c_i x_i { terms = new TreeMap<>(); for (String var : vars) { Monomial m = new Monomial(); m.addVar("c_" + InvariantGeneration.cCount, 1); InvariantGeneration.cCount++; m.addVar(var, 1); add(m, Rational.one); } } Polynomial(Set<String> vars, int degree) { terms = new TreeMap<>(); Set<Monomial> monomials = Monomial.getAllMonomials(vars, degree); for (Monomial m : monomials) { m.addVar("c_" + InvariantGeneration.cCount, 1); InvariantGeneration.cCount++; add(m, Rational.one); } } void add(Monomial m, Rational c) { if (terms.containsKey(m)) terms.put(m, Rational.add(terms.get(m), c)); else terms.put(m, c); } void add(Polynomial poly) { for (Monomial term : poly.terms.keySet()) add(term, poly.terms.get(term)); } void minus(Polynomial poly) { add(poly.negate()); } public void multiplyByValue(Rational val) { for (Monomial term : terms.keySet()) terms.put(term, Rational.mul(terms.get(term), val)); } public void multiplyByMonomial(Monomial m) { Map<Monomial, Rational> tmp = new HashMap<>(); for (Monomial term : terms.keySet()) tmp.put(Monomial.mul(term, m), terms.get(term)); terms = tmp; } public void multiplyByPolynomial(Polynomial poly) { Polynomial res = new Polynomial(); for (Monomial m : poly.terms.keySet()) for (Monomial n : this.terms.keySet()) res.add(Monomial.mul(m, n), Rational.mul(poly.terms.get(m), this.terms.get(n))); terms = res.terms; } boolean isConstant() { removeZeros(); return (terms.size() <= 1 && (terms.size() != 1 || terms.containsKey(Monomial.one))); } void removeZeros() { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (terms.get(term).equals(Rational.zero)) terms.remove(term); } Polynomial deepCopy() { removeZeros(); Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), terms.get(term)); return ret; } void replaceVarWithPoly(String var, Polynomial poly) { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (term.containsVar(var)) { Rational coef = terms.get(term); Monomial m = term.removeOneVar(var); Polynomial left = new Polynomial(m); Polynomial right = poly.deepCopy(); for (int i = 1; i < term.getPower(var); i++) right.multiplyByPolynomial(poly); left.multiplyByPolynomial(right); left.multiplyByValue(coef); terms.remove(term); add(left); } } public Set<Monomial> getProgramVariableMonomials() { Set<Monomial> ret= new TreeSet<>(); for(Monomial m:terms.keySet()) ret.add(m.getProgramVarsPart()); return ret; } public Polynomial getCoef(Monomial m) { Polynomial ret=new Polynomial(); for(Monomial monomial:terms.keySet()) { if(monomial.programVarsPart().equals(m)) ret.add(monomial.unknownPart(),terms.get(monomial)); } return ret; } public boolean equals(Polynomial poly) { for (Monomial m : terms.keySet()) if (!poly.terms.containsKey(m) || !poly.terms.get(m).equals(terms.get(m))) return false; return true; } Polynomial negate() { Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), Rational.negate(terms.get(term))); return ret; } public static Polynomial mul(Polynomial left,Polynomial right) { Polynomial ret=left.deepCopy(); ret.multiplyByPolynomial(right); return ret; } public String toString() { String ret = ""; if (terms.isEmpty()) return "0"; Vector<Monomial> monomials = new Vector<>(terms.keySet()); if (monomials.size() == 1) return "(* " + terms.get(monomials.firstElement()) +" "+ monomials.firstElement().toString()+")"; ret = "(+ "; for (Monomial m : monomials) ret += "(* "+ terms.get(m)+ " " +m.toString()+") "; ret += ")"; return ret; } public String toNormalString() { String ret = ""; if (terms.isEmpty()) return "0"; Vector<Monomial> monomials = new Vector<>(terms.keySet()); for (Monomial m : monomials) { if(!ret.equals("")) ret+=" + "; if(!terms.get(m).equals(Rational.one)) ret += terms.get(m).toNormalString()+" * "; ret += m.toNormalString(); } return ret; } }
6,071
25.285714
109
java
null
RevTerm-main/code/polynomial/part1/Main/src/PolynomialPredicate.java
import java.util.Vector; public class PolynomialPredicate { Vector<Polynomial> exprs; public static PolynomialPredicate TRUE = new PolynomialPredicate(new Polynomial(Monomial.one)); PolynomialPredicate() { exprs = new Vector<>(); } PolynomialPredicate(Polynomial poly) { exprs=new Vector<>(); add(poly); } void add(Polynomial poly) { for (Polynomial p : exprs) if (p.equals(poly)) return; exprs.add(poly); } void add(PolynomialPredicate pp) { for (Polynomial poly : pp.exprs) add(poly.deepCopy()); } void replaceVarWithPoly(String var, Polynomial poly) { for (Polynomial p : exprs) p.replaceVarWithPoly(var, poly); } public Vector<PolynomialPredicate> negate() { Vector<PolynomialPredicate> ret = new Vector<>(); for (Polynomial poly : exprs) { Polynomial p = poly.negate(); p.add(Monomial.one, Rational.negate(Main.eps)); PolynomialPredicate pp = new PolynomialPredicate(); pp.add(p); ret.add(pp); } return ret; } public static Vector<PolynomialPredicate> negate(Vector<PolynomialPredicate> g,int first) { if(first==g.size()) return new Vector<>(); else if (first== g.size()-1 ) return g.elementAt(first).negate(); else { // Vector<PolynomialPredicate> ret = new Vector<>(); Vector<PolynomialPredicate> notFirst = g.elementAt(first).negate(); Vector<PolynomialPredicate> recurse = negate(g,first+1); // for (PolynomialPredicate pp : notFirst) // for (PolynomialPredicate predicate : recurse) // { // PolynomialPredicate copy = predicate.deepCopy(); // copy.add(pp); // ret.add(copy); // } return conjunct(notFirst,recurse); } } public static Vector<PolynomialPredicate> conjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); } else if (right.isEmpty()) { for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); } else { for (PolynomialPredicate pp1 : left) for (PolynomialPredicate pp2 : right) { PolynomialPredicate pp = new PolynomialPredicate(); pp.add(pp1.deepCopy()); pp.add(pp2.deepCopy()); ret.add(pp); } } return ret; } public static Vector<PolynomialPredicate> disjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); return ret; } boolean equalsLogic(PolynomialPredicate pp) { for (Polynomial p : exprs) if (!pp.contains(p)) return false; for (Polynomial p : pp.exprs) if (!this.contains(p)) return false; return true; } boolean contains(Polynomial p) { for (Polynomial poly : exprs) if (p.equals(poly)) return true; return false; } PolynomialPredicate deepCopy() { PolynomialPredicate ret = new PolynomialPredicate(); ret.add(this); return ret; } public String toNormalString() { String ret = ""; for (int i = 0; i < exprs.size(); i++) { Polynomial p = exprs.elementAt(i); if (i == 0) ret += p.toNormalString() + ">=0"; else ret += " && " + p.toNormalString() + ">=0"; } return ret; } public String toString() { return toNormalString(); } }
4,321
26.705128
123
java
null
RevTerm-main/code/polynomial/part1/Main/src/Putinar.java
import java.util.Set; import java.util.TreeSet; import java.util.Vector; public class Putinar { public static int countD = 0; int startDIndex; int startNode, endNode; // private PolynomialPredicate nodeConstraint; //TODO: change name: constraints from start node private PolynomialPredicate constraints; //TODO: change name: constraints from transition private Polynomial objective; Putinar(int startNode, int endNode) { this.startNode = startNode; this.endNode = endNode; constraints = new PolynomialPredicate(); Polynomial lc = new Polynomial(); lc.add(Monomial.one, Rational.one); constraints.add(lc); // 1>=0 is always true // nodeConstraint = new PolynomialPredicate(); startDIndex = countD; countD++; // for 1>=0 } public Putinar deepCopy() { Putinar ret = new Putinar(startNode, endNode); countD--; // for 1>=0 which is added in new ret.startDIndex = startDIndex; // ret.nodeConstraint.exprs.addAll(nodeConstraint.exprs); //countD+=invConstraint.size(); ret.constraints = constraints.deepCopy(); //countD+=linearConstraints.exprs.size()-1; //-1 for 1>=0 which is already added ret.objective = objective.deepCopy(); return ret; } // public Farkas disabled() // { // Farkas ret=deepCopy(); //// LinearCombination lc=new LinearCombination("n_"+InvariantGeneration.nCount); //// QuadraticCombination obj=new QuadraticCombination("1",lc); // // InvariantGeneration.nCount++; // ret.objective=QuadraticCombination.minus1.deepCopy(); // return ret; // } // void addHypothesis(PolynomialPredicate inv) //TODO: remove // { // addHypothesis(inv); //// nodeConstraint.add(inv); //// countD += inv.exprs.size(); // } // void addHypothesis(PolynomialPredicate lp) //TODO: remove // { // addHypothesis(lp); //// transConstraints.add(lp); //// countD += lp.exprs.size(); // } void addPredicate(PolynomialPredicate pp) { constraints.add(pp); countD+=pp.exprs.size(); } void setObjective(Polynomial obj) { objective = obj.deepCopy(); } void replaceVarWithPoly(String var, Polynomial lc) { constraints.replaceVarWithPoly(var,lc); objective.replaceVarWithPoly(var,lc); // nodeConstraint.replaceVarWithPoly(var,lc); } public Vector<Polynomial> generateEqualities() { Vector<Polynomial> equalities = new Vector<>(); // poly = 0 Polynomial right = new Polynomial(); for(Polynomial poly:constraints.exprs) { Polynomial h = generateHPolynomial(Parser.allVars,Main.mu); Polynomial sos = generateSOSPolynomial(Parser.allVars,Main.mu); // System.err.println("h: "+h.toNormalString()); // System.err.println("sos: "+sos.toNormalString()); // System.err.println("-------------------------"); // System.exit(0); equalities.addAll(makeEqualities(h,sos)); h.multiplyByPolynomial(poly); right.add(h); } equalities.addAll(makeEqualities(objective,right)); return equalities; } private Polynomial generateHPolynomial(Set<String> vars,int degree) { Set<Monomial> monomials= Monomial.getAllMonomials(vars,degree); Polynomial h=new Polynomial(); for(Monomial m:monomials) { Monomial mp=m.deepCopy(); mp.addVar("t_"+InvariantGeneration.tCount,1); InvariantGeneration.tCount++; h.add(mp,Rational.one); } return h; } private Polynomial generateSOSPolynomial(Set<String> vars, int degree) // ret = y LL^T y^t { // if(degree==0) //NOTE: if not comment it will be Farkas when mu=0 // { // String var = "l_"+InvariantGeneration.lCount; // InvariantGeneration.lCount++; // InvariantGeneration.nonNegativeLvars.add(var); // return new Polynomial(var); // } Vector<Monomial> tmp = new Vector<>(Monomial.getAllMonomials(vars,degree/2)); Vector<Polynomial> y=new Vector<>(); int dim = tmp.size(); Polynomial[][] L = new Polynomial[dim][dim],Lt=new Polynomial[dim][dim],yt=new Polynomial[dim][1]; for(int i=0;i<dim;i++) { y.add(new Polynomial(tmp.elementAt(i))); yt[i][0]=new Polynomial(tmp.elementAt(i)); } for(int i=0;i<dim;i++) for (int j=0;j<dim;j++) { if (j <= i) { String var = "l_" + InvariantGeneration.lCount; InvariantGeneration.lCount++; L[i][j] = new Polynomial(var); Lt[j][i] = L[i][j].deepCopy(); if (i == j) InvariantGeneration.nonNegativeLvars.add(var); } else { L[i][j] = new Polynomial(); Lt[j][i] = L[i][j].deepCopy(); } } Vector<Polynomial> yL = mulVecMat(y,L); Vector<Polynomial> yLLt = mulVecMat(yL,Lt); Polynomial ret= new Polynomial(); for(int i=0;i<dim;i++) ret.add(Polynomial.mul(yLLt.elementAt(i), yt[i][0])); // System.err.println("SOS: "+ret.toNormalString()); return ret; } private Vector<Polynomial> mulVecMat(Vector<Polynomial> y,Polynomial[][] L) { Vector<Polynomial> ret= new Vector<>(); int sz=y.size(); for(int col=0;col<sz;col++) { Polynomial p=new Polynomial(); for(int i=0;i<sz;i++) p.add(Polynomial.mul(y.elementAt(i),L[i][col])); ret.add(p); } return ret; } Vector<Polynomial> makeEqualities(Polynomial left, Polynomial right) //TODO { Set<Monomial> allMonomials= new TreeSet<>(); allMonomials.addAll(left.getProgramVariableMonomials()); allMonomials.addAll(right.getProgramVariableMonomials()); Vector<Polynomial> ret=new Vector<>(); for(Monomial m:allMonomials) { Polynomial leftm=left.getCoef(m),rightm=right.getCoef(m); rightm.add(leftm.negate()); ret.add(rightm); } return ret; } public Set<Monomial> getAllVars() { Set<Monomial> ret=new TreeSet<>(); for(Polynomial lc: constraints.exprs) ret.addAll(lc.terms.keySet()); // for(Polynomial qc: nodeConstraint.exprs) // ret.addAll(qc.terms.keySet()); ret.addAll(objective.terms.keySet()); return ret; } // public QuadraticCombination makeEquality(String var) // { // QuadraticCombination qc = new QuadraticCombination(); // int dIndex = startDIndex; // if (!invConstraint.exprs.isEmpty()) // { // //for(int i=0;i<invConstraint.exprs.size();i++) // for (QuadraticCombination invc : invConstraint.exprs) // { // if (invc.coef.containsKey(var)) // { // String invMultiplier = "d_" + dIndex; // //InvariantGeneration.addUnknownVar("d_" + dIndex); // // // LinearCombination lc = invc.coef.get(var); // qc.add(invMultiplier, lc); // } // dIndex++; // } // } // // for (LinearCombination lp : linearConstraints.exprs) // lp>=0 // { // String multiplier = "d_" + dIndex; // if (lp.coef.containsKey(var)) // { // Rational coef = lp.coef.get(var); // qc.add(multiplier, new LinearCombination(coef)); // //InvariantGeneration.addUnknownVar("d_" + dIndex); // } // dIndex++; // } // // LinearCombination coef = objective.getCoef(var); // //qc=coef <=> qc-coef=0 // if (coef != null) // { // LinearCombination lc = coef.negate(); // qc.add(lc); // } //// System.err.println("var: "+var+" => "+qc.toNormalString()); // return qc; // } public String toString() { String ret = ""; ret += "\n---------------------------------------------\n"; ret += "from: " + startNode + " to: " + endNode + "\n"; int dIndex = startDIndex; // for (int i = 0; i < nodeConstraint.exprs.size(); i++) // { // ret += "d_" + dIndex + ": " + nodeConstraint.exprs.elementAt(i).toNormalString() + "\n"; // dIndex++; // } for (Polynomial lc : constraints.exprs) { ret += "\nd_" + dIndex + ": " + lc.toNormalString(); dIndex++; } ret += "\n---------------------------------------------\n"; ret += objective.toNormalString(); return ret; } }
9,139
31.29682
106
java
null
RevTerm-main/code/polynomial/part1/Main/src/QuadraticCombination.java
import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; public class QuadraticCombination { Map<String, LinearCombination> coef; QuadraticCombination() { coef = new HashMap<>(); } QuadraticCombination(String var, LinearCombination lc) { coef = new HashMap<>(); add(var, lc); } QuadraticCombination(Set<String> vars) { coef= new HashMap<>(); for(String var:vars) { add(var,new LinearCombination("c_"+InvariantGeneration.cCount)); InvariantGeneration.cCount++; } } public void add(String var, LinearCombination lc) { if (coef.containsKey(var)) coef.get(var).add(lc); else coef.put(var, lc); } public void add(QuadraticCombination qc) { for (String var : qc.coef.keySet()) add(var, qc.coef.get(var)); } public void add(LinearCombination lc) { for (String var : lc.coef.keySet()) { add(var, new LinearCombination(lc.coef.get(var))); } } public void add(Rational val) { add("1", new LinearCombination(val)); } public QuadraticCombination negate() { QuadraticCombination qc = new QuadraticCombination(); for (String var : coef.keySet()) qc.add(var, coef.get(var).negate()); return qc; } public LinearCombination getCoef(String var) { return coef.get(var); } public Rational getCoef(String var1, String var2) { if (coef.containsKey(var1) && coef.get(var1).coef.containsKey(var2)) return coef.get(var1).coef.get(var2); else if (coef.containsKey(var2) && coef.get(var2).coef.containsKey(var1)) return coef.get(var2).coef.get(var1); else return Rational.zero; } public QuadraticCombination deepCopy() { QuadraticCombination qc = new QuadraticCombination(); for (String var : coef.keySet()) qc.add(var, coef.get(var).deepCopy()); return qc; } public void replaceVarWithLinear(String var, LinearCombination lc) { if(!coef.containsKey(var)) return; LinearCombination l=coef.get(var); coef.remove(var); for(String v:lc.coef.keySet()) { LinearCombination tmp=l.deepCopy(); tmp.multiplyByValue(lc.coef.get(v)); add(v,tmp); } } public String toNormalString() { String ret = ""; for (String s : coef.keySet()) { if (ret.equals("")) ret += s + "*(" + coef.get(s).toNormalString() + ")"; else ret += " + " + s + "*(" + coef.get(s).toNormalString() + ")"; } return ret; } public String toString() { String ret = ""; if (coef.keySet().size() > 1) ret = "(+ "; for (String var : coef.keySet()) { LinearCombination lc = coef.get(var); if (ret == "") ret = "(* " + lc.toString() + " " + var + ")"; else ret = ret + " (* " + lc.toString() + " " + var + ")"; } if (coef.keySet().size() > 1) ret += ")"; if (ret.equals("")) ret = "0"; return ret; } }
3,438
23.390071
81
java
null
RevTerm-main/code/polynomial/part1/Main/src/QuadraticPredicate.java
import java.util.Vector; public class QuadraticPredicate { public static QuadraticPredicate TRUE=new QuadraticPredicate(new QuadraticCombination("1",new LinearCombination("1",Rational.one))); // 1>=0 Vector<QuadraticCombination> exprs; QuadraticPredicate() //conjunctions { exprs = new Vector<>(); } QuadraticPredicate(QuadraticCombination qc) { exprs=new Vector<>(); add(qc); } void add(QuadraticCombination qc) { exprs.add(qc); } void add(QuadraticPredicate qp) { exprs.addAll(qp.exprs); } void replaceVarWithLinear(String var,LinearCombination update) { for(QuadraticCombination qc:exprs) qc.replaceVarWithLinear(var,update); } public static Vector<QuadraticPredicate> negate(Vector<QuadraticPredicate> vqp) { Vector<QuadraticPredicate> ret = new Vector<>(); for (QuadraticPredicate qp : vqp) { Vector<QuadraticCombination> vqc = qp.negate(); if (ret.isEmpty()) { for (QuadraticCombination qc : vqc) { QuadraticPredicate c = new QuadraticPredicate(); c.add(qc); ret.add(c); } continue; } Vector<QuadraticPredicate> tmp = new Vector<>(); for (QuadraticCombination cur : vqc) for (QuadraticPredicate q : ret) { QuadraticPredicate c = q.deepCopy(); c.add(cur); tmp.add(c); } ret.addAll(tmp); } return ret; } Vector<QuadraticCombination> negate() { Vector<QuadraticCombination> ret = new Vector<>(); for (QuadraticCombination qc : exprs) { QuadraticCombination q = qc.negate(); q.add("1", new LinearCombination(Rational.negate(Main.eps))); // 1*(-1) ret.add(q); } return ret; } QuadraticCombination getTerm(int ind) { return exprs.elementAt(ind); } public QuadraticPredicate deepCopy() { QuadraticPredicate qp = new QuadraticPredicate(); for (QuadraticCombination qc : exprs) qp.add(qc.deepCopy()); return qp; } public String toString() { String ret = ""; for (QuadraticCombination qc : exprs) ret += "(>= " + qc.toString() + " 0) "; if (exprs.size() > 1) ret = "(and " + ret + ") "; return ret; } public String toNormalString() { String ret = ""; for (QuadraticCombination qc : exprs) ret += qc.toNormalString() + ">=0 and "; return ret; } }
2,833
25.240741
144
java
null
RevTerm-main/code/polynomial/part1/Main/src/Rational.java
import java.util.EnumMap; public class Rational implements Comparable<Rational> { public static final Rational one = new Rational(1, 1), zero = new Rational(0, 1); int numerator, denominator; public int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } Rational(int numerator, int denominator) { if (numerator == 0) { this.numerator = 0; this.denominator = 1; return; } if (denominator < 0) { denominator *= -1; numerator *= -1; } int g = gcd(numerator, denominator); this.numerator = numerator / g; this.denominator = denominator / g; } public static Rational negate(Rational a) { return new Rational(-a.numerator, a.denominator); } public static Rational inverse(Rational a) throws Exception { if (a.numerator == 0) throw new Exception("getting inverse of " + a + " which is not defined"); return new Rational(a.denominator, a.numerator); } public static Rational add(Rational a, Rational b) { return new Rational(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator); } public static Rational minus(Rational a, Rational b) { return add(a, negate(b)); } public static Rational mul(Rational a, Rational b) { return new Rational(a.numerator * b.numerator, a.denominator * b.denominator); } public static Rational div(Rational a, Rational b) throws Exception { return mul(a, inverse(b)); } public boolean equals(Rational a) { return (a.numerator == numerator && a.denominator == denominator); } public boolean isNonNegative() { return (numerator >= 0); } @Override public int compareTo(Rational a) { return numerator * a.denominator - a.numerator * denominator; } public String toNormalString() { if (denominator == 1) return "" + numerator; return "(" + numerator + "/" + denominator + ")"; } public void normalize() { if (denominator < 0) { numerator *= -1; denominator *= -1; } } public String toString() { normalize(); String num="", den = "" + denominator; if (numerator < 0) num = "(- " + (-numerator) + ")"; else num = "" + numerator; if (denominator == 1) return num; return "(/ " + num + " " + denominator + ")"; } }
2,675
22.892857
118
java
null
RevTerm-main/code/polynomial/part1/Main/src/Transition.java
import java.util.Vector; public class Transition //from "v.first" to "v.second" with guard "g" and update "varName := update" { public static Vector<Transition> allTransitions = new Vector<>(); CFGNode v, u; PolynomialPredicate detGuard; PolynomialPredicate nondetGuard; Vector<String> varName; Vector<Polynomial> update; boolean hasGroup; Transition(CFGNode a, CFGNode b) { v = a; u = b; detGuard = new PolynomialPredicate(); nondetGuard = new PolynomialPredicate(); varName = new Vector<>(); update = new Vector<>(); hasGroup = false; } void addNondetTemplate() { for(Polynomial lc:update) { if(lc.toString().contains("_r_")) // lc is a fresh nondet variable { // qc <= lc <= qc // gen: qc1<=qc2 Polynomial qc= new Polynomial(Parser.allVars),qcc=qc.deepCopy(); qc.add(lc.negate()); //qc - lc <=0 nondetGuard.add(qc.negate()); qcc.add(lc.negate()); // qc - lc >=0 nondetGuard.add(qcc); } } } public void addToGraph() { allTransitions.add(this); v.out.add(this); } public Transition deepCopy() { Transition ret = new Transition(v, u); ret.detGuard = detGuard.deepCopy(); ret.nondetGuard = nondetGuard.deepCopy(); for (String var : varName) ret.varName.add(var.toString()); for (Polynomial lc : update) if (lc != null) ret.update.add(lc.deepCopy()); else ret.update.add(null); return ret; } public String toString() { String res = ""; res += "from: " + v.id + "\nto: " + u.id + "\n"; if (detGuard != null) res += "detGuard: " + detGuard + "\n"; if (nondetGuard != null) res += "nondetGuard: " + nondetGuard.toNormalString() + "\n"; res+="updates:\n"; for (int i = 0; i < varName.size(); i++) if (update.elementAt(i) != null) res += varName.elementAt(i) + " := " + update.elementAt(i).toNormalString() + "\n"; else res += varName.elementAt(i) + " := nondet()\n"; return res; } }
2,377
26.976471
103
java
null
RevTerm-main/code/polynomial/part2/Main/src/CFGNode.java
import java.util.Map; import java.util.TreeMap; import java.util.Vector; public class CFGNode { public static Vector<CFGNode> allCFGNodes=new Vector<>(); public static Map<Integer,CFGNode> idToNode=new TreeMap<>(); public static int greaTestNodeIndex=0; public Vector<Transition> out; public Vector<Transition> rout; //outgoing transitions in BCFG int id; boolean isCutPoint,visited; Vector<PolynomialPredicate> inv; Vector<PolynomialPredicate> computedInv; PolynomialPredicate preCondition; CFGNode(int ind) { id = ind; idToNode.put(ind, this); isCutPoint=visited=false; out = new Vector<>(); rout = new Vector<>(); allCFGNodes.add(this); inv = new Vector<>(); computedInv = new Vector<>(); preCondition = null; if(ind>greaTestNodeIndex) greaTestNodeIndex=ind; } void addTransition(Transition t) { out.add(t); } void addNecessaryNondet() { boolean hasEqual=false; Vector <Vector<Transition>> groups= new Vector<>(); for (Transition t : out) if(!t.hasGroup) { Vector<Transition> g=new Vector<>(); for(Transition tp:out) if (t.detGuard.equalsLogic(tp.detGuard)) { tp.hasGroup=true; g.add(tp); } // for(Transition tmp:g) // System.err.println("from: "+id+" to "+tmp.u.id+" "+g.size()); if(g.size()==1) t.hasGroup = false; else groups.add(g); } for(int i=0;i<out.size();i++) if(out.elementAt(i).hasGroup) { Transition.allTransitions.removeElement(out.elementAt(i)); out.removeElementAt(i); i--; } for(Vector<Transition> g:groups) { // System.err.println("----------------"); // for(Transition tau:g) // System.err.println("transition from "+tau.v.id+" to: "+tau.u.id); // System.err.println("----------------"); PolynomialPredicate commonGuard=g.firstElement().detGuard.deepCopy(); CFGNode n=new CFGNode(greaTestNodeIndex+1); String nontdetTmp="_tmp_"; Parser.allVars.add("_tmp_"); for(int i=0;i<g.size();i++) { Transition t = new Transition(n,g.elementAt(i).u); t.varName=g.elementAt(i).varName; t.update=g.elementAt(i).update; t.nondetGuard=g.elementAt(i).nondetGuard; Polynomial lower = new Polynomial("_tmp_", Rational.one); lower.add(Monomial.one, new Rational(-i, 1)); // _tmp_ >= i Polynomial upper = new Polynomial("_tmp_", Rational.negate(Rational.one)); upper.add(Monomial.one, new Rational(i, 1)); // _tmp_ <= i if (i == 0) t.detGuard.add(upper); //t <= 0 else if (i == g.size() - 1) t.detGuard.add(lower); //t >= out.size()-1 else { t.detGuard.add(upper); // t >= i t.detGuard.add(lower); // t <= i } t.addToGraph(); } Transition t = new Transition(this, n); t.detGuard.add(commonGuard); String nondetr="_r_"+Parser.nondetCount; t.varName.add(nontdetTmp); t.update.add(new Polynomial(nondetr)); Parser.nondetCount++; t.addToGraph(); } } void addTerminalTransitions() { // if(out.size()>0) // { // Vector<LinearPredicate> predicates = new Vector<>(); // int cnt=0; // for (Transition t : out) // { // LinearPredicate lp=new LinearPredicate(); // for(LinearCombination lc:t.detGuard.exprs) // lp.add(lc.deepCopy()); // predicates.add(lp); // cnt+=lp.exprs.size(); // } // if(cnt==0) // return; // Vector<LinearPredicate> negation = LinearPredicate.negate(predicates); // CFGNode term=idToNode.get(-2); // for(LinearPredicate lp:negation) // { // Transition tau=new Transition(this,term); // tau.detGuard =lp; // tau.addToGraph(); // } // } // else if(out.size()==0) { CFGNode term=idToNode.get(-2); Transition tau=new Transition(this,term); tau.addToGraph(); } } public static CFGNode addNode(int x) { if(idToNode.containsKey(x)) return idToNode.get(x); CFGNode n=new CFGNode(x); return n; } public static CFGNode getCFGNode(int x) { return idToNode.get(x); } }
5,143
30.558282
90
java
null
RevTerm-main/code/polynomial/part2/Main/src/CFGUtil.java
import java.util.Vector; public class CFGUtil { public static Vector<CFGNode> findCutpoints() { Vector<CFGNode> ret=new Vector<>(); ret.add(Main.startNode); Main.startNode.isCutPoint=true; ret.add(Main.termNode); Main.termNode.isCutPoint=true; dfs(Main.startNode,ret,new Vector<CFGNode>()); return ret; } private static void dfs(CFGNode v,Vector<CFGNode> res,Vector<CFGNode> currentBranch) { v.visited=true; currentBranch.add(v); for(Transition t:v.out) { if(!t.u.visited) dfs(t.u, res, currentBranch); else if(!res.contains(t.u) && currentBranch.contains(t.u)) { t.u.isCutPoint=true; res.add(t.u); } } currentBranch.removeElementAt(currentBranch.size()-1); } public static void weakestPreCondition(Vector<Transition> path,Putinar putinar,int counter) //NOTE: for C-Integer programs this is completely fine but for general T2 transition systems it might have problems { for(int i=path.size()-1;i>=0;i--) { Transition t=path.elementAt(i); if(counter==0) { putinar.addPredicate(t.nondetGuard.deepCopy()); putinar.addPredicate(t.detGuard.deepCopy()); } for(int j=0;j<t.varName.size();j++) { String var=t.varName.elementAt(j); Polynomial upd=t.update.elementAt(j); putinar.replaceVarWithPoly(var,upd); } if(counter==1) { putinar.addPredicate(t.detGuard.deepCopy()); putinar.addPredicate(t.nondetGuard.deepCopy()); } } } }
1,822
27.046154
212
java
null
RevTerm-main/code/polynomial/part2/Main/src/InvUtil.java
import java.io.*; import java.nio.channels.FileLockInterruptionException; import java.util.Scanner; import java.util.Vector; //TODO: update checkNonTermination public class InvUtil { public static boolean checkNonTermination(Vector<Polynomial> I,Vector<Putinar> Inductive,CFGNode startNode) throws Exception { String Template="";//InvariantGeneration.cCount+" "+Farkas.countD+" "+Parser.allVars.size()+"\n"; Template+="(set-option :print-success false) \n" + "(set-option :produce-models true)\n" ; if(Main.solver.equals("bclt")) { Template+="(set-option :produce-assertions true)\n" + "(set-logic QF_NIA)\n"; } for(int i=0;i<InvariantGeneration.cCount;i++) Template+="(declare-const c_"+i+" Int)\n"; for(int i=0;i<InvariantGeneration.lCount;i++) Template+="(declare-const l_"+i+" Int)\n"; for(String lvar: InvariantGeneration.nonNegativeLvars) Template+="(assert (>= "+lvar+ " 0))\n"; for(int i=0;i<InvariantGeneration.tCount;i++) Template+="(declare-const t_"+i+" Int)\n"; for(String var: Parser.allVars) Template += "(declare-const " + var + " Int)\n"; for(int i=0;i<Parser.nondetCount;i++) Template+="(declare-const "+"_r_"+i+" Int)\n"; FileWriter fw = new FileWriter(Main.workingdir+"/"+Main.solver+Main.con+"-"+Main.dis+Main.fileName+".smt2"); fw.write(Template); //Inductive Backward Invariant: for(Polynomial f:I) fw.write("(assert (= 0 "+f.toString()+"))\n"); //Not Inductive Invariant: fw.write("(assert (or "); for(Putinar putinar: Inductive) { fw.write("(and "); for(Polynomial q:putinar.constraints.exprs) fw.write("(>= "+ q.toString()+" 0) "); fw.write("(< "+putinar.objective+" 0)"); fw.write(")\n"); } fw.write("))\n"); fw.write("(check-sat)\n"); fw.write("(get-value ("); for(int i=0;i<InvariantGeneration.cCount;i++) fw.write("c_"+i+" "); for(String var:Parser.allVars) if(!var.equals("1") && !var.startsWith("_a_") && !var.startsWith("_b_")) fw.write(var + " "); fw.write("))\n"); fw.close(); // System.exit(0); if(check()) return true; return false; } public static boolean check() throws Exception { String smtFile=Main.workingdir+"/"+Main.solver+Main.con+"-"+Main.dis+Main.fileName; String[] configs = {"bclt --file", "mathsat","z3 -smt2 "}; int solverInd = -1; if (Main.solver.equals("bclt")) solverInd = 0; else if(Main.solver.equals("mathsat")) solverInd=1; else if(Main.solver.equals("z3")) solverInd=2; // System.err.println(smtFile); // System.err.println("Solver Started"); Process process = Runtime.getRuntime().exec("./"+Main.solversDir+"/"+configs[solverInd] + " " + smtFile + ".smt2"); process.waitFor(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); FileWriter fw=new FileWriter(smtFile+".result"); boolean isSAT=false; while (bufferedReader.ready()) { String s = bufferedReader.readLine(); // System.err.println(s); fw.write(s+"\n"); if (s.equals("sat")) { // System.err.println("SAT!"); isSAT=true; } } fw.close(); // System.err.println("Solver Finished"); if(isSAT==false) return false; else return safetyUtil.check(smtFile); } }
3,872
32.973684
128
java
null
RevTerm-main/code/polynomial/part2/Main/src/InvariantGeneration.java
import java.util.*; public class InvariantGeneration { public static Map<String,String> nondetVarsC=new HashMap<>(); public static int totalUnknownVars=0; public static int cCount=0,tCount=0,lCount=0; public static Vector<String> nonNegativeLvars=new Vector<>(); public static void MakeTemplate(int con,int dis,CFGNode startNode,int counter)//conjunctions, disjunctions { Set<String> programVars=new TreeSet<>(); for(String var: Parser.allVars) if(!var.startsWith("_")) programVars.add(var); for(CFGNode n:CFGNode.allCFGNodes) { if(n.id==Main.termNode.id && counter==1) { //n.inv does not change. the previous computed invariant is used as the BI of the start location of BCFG. for(String var:Parser.allVars) if(var.startsWith("_a_") || var.startsWith("_b_")) { String cVar="c_"+cCount; cCount++; nondetVarsC.put(var,cVar); } } else if(n.id==Main.startNode.id && counter==0) { n.inv.add(PolynomialPredicate.TRUE.deepCopy()); } else if(n.isCutPoint) { n.inv.clear(); for(int i=0;i<dis;i++) { PolynomialPredicate qp = new PolynomialPredicate(); for (int j = 0; j < con; j++) { Polynomial qc = new Polynomial(programVars,Main.degree); qp.add(qc); } n.inv.add(qp); } } } } public static void generate(Vector<CFGNode> cutPoints,Vector<Putinar> putinarVector,int counter) { // if(counter==0) //for startNode // { // CFGNode u = Main.startNode; // PolynomialPredicate objPred=u.inv.lastElement(); // Vector<PolynomialPredicate> tmp = new Vector<>(); // for(PolynomialPredicate qc:u.inv) // if(qc!=objPred) // tmp.add(qc.deepCopy()); // Vector<QuadraticPredicate> uinvNegate=QuadraticPredicate.negate(tmp); // if(uinvNegate.isEmpty()) // uinvNegate.add(QuadraticPredicate.TRUE); // for(QuadraticCombination qc:objPred.exprs) // for(QuadraticPredicate qp:uinvNegate) // { // // Farkas farkas=new Farkas(-1,-1); // if(qp!=QuadraticPredicate.TRUE) // farkas.addInvConstraint(qp.deepCopy()); // farkas.setObjective(qc); // farkasVector.add(farkas); // } // } for(CFGNode v:cutPoints) processPaths(v,v,new Vector<Transition>(),putinarVector,counter); } private static void processPaths(CFGNode st,CFGNode v,Vector<Transition> path,Vector<Putinar> putinarVector,int counter) { //System.err.println("processPaths: st:"+st.id+" v:"+v.id+" v.out="+v.out.size()+" v.rout="+v.rout.size()+" counter="+counter); Vector<Transition> tran; if(counter==0) tran=v.out; else tran=v.rout; for(Transition t:tran) { CFGNode u=t.u; path.add(t); if(u.isCutPoint) { PolynomialPredicate objPred = u.inv.lastElement(); Vector<PolynomialPredicate> tmp = new Vector<>(); for(PolynomialPredicate pp:u.inv) if(pp!=objPred) tmp.add(pp.deepCopy()); Vector<PolynomialPredicate> uinvNegate = PolynomialPredicate.negate(tmp,0); if(uinvNegate.isEmpty()) uinvNegate.add(PolynomialPredicate.TRUE); for(PolynomialPredicate vinv:st.inv) for(PolynomialPredicate uinv:uinvNegate) for(Polynomial obj:objPred.exprs) { //vinv & uinv & path => obj Putinar putinar=new Putinar(st.id,u.id); if(uinv!=PolynomialPredicate.TRUE) putinar.addPredicate(uinv.deepCopy()); putinar.setObjective(obj.deepCopy()); CFGUtil.weakestPreCondition(path,putinar,counter); putinar.addPredicate(vinv); putinarVector.add(putinar); } } else processPaths(st,u,path,putinarVector,counter); path.removeElementAt(path.size()-1); } // for(Transition t:tran) // { // CFGNode u=t.u; // path.add(t); // if(u.isCutPoint) // { // QuadraticPredicate objPred=u.inv.lastElement(); // Vector<QuadraticPredicate> tmp = new Vector<>(); // for(QuadraticPredicate qc:u.inv) // if(qc!=objPred) // tmp.add(qc.deepCopy()); // // Vector<QuadraticPredicate> uinvNegate=QuadraticPredicate.negate(tmp); // if(uinvNegate.isEmpty()) // uinvNegate.add(QuadraticPredicate.TRUE); // // for(QuadraticPredicate vinv:st.inv) // for(QuadraticPredicate uinv:uinvNegate) // for(QuadraticCombination obj:objPred.exprs) // { // //vinv & uinv & path => obj // Farkas farkas=new Farkas(st.id,u.id); // if(uinv!=QuadraticPredicate.TRUE) // farkas.addInvConstraint(uinv.deepCopy()); // farkas.setObjective(obj.deepCopy()); // CFGUtil.weakestPreCondition(path,farkas,counter); // // farkas.addInvConstraint(vinv); // // farkasVector.add(farkas); // } // } // else // processPaths(st,u,path,farkasVector,counter); // path.removeElementAt(path.size()-1); // } } }
6,417
37.89697
135
java
null
RevTerm-main/code/polynomial/part2/Main/src/LinearCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class LinearCombination { Map<String,Rational> coef; public static LinearCombination one=new LinearCombination(Rational.one); LinearCombination() { coef=new HashMap<>(); } LinearCombination(Rational c) { coef=new HashMap<>(); coef.put("1",c); } LinearCombination(String var) { coef=new HashMap<>(); coef.put(var,Rational.one); } LinearCombination(String var,Rational c) { coef=new HashMap<>(); coef.put(var,c); } public void add(String var,Rational c) { if(coef.containsKey(var)) coef.put(var,Rational.add(coef.get(var),c)); else coef.put(var,c); } public void add(LinearCombination lc) { for(String var:lc.coef.keySet()) add(var,lc.coef.get(var)); } public void minus(LinearCombination lc) { add(lc.negate()); } public void multiplyByValue(Rational val) { for(String var:coef.keySet()) coef.put(var,Rational.mul(coef.get(var),val)); } public LinearCombination negate() //does not negate "this". returns the negate of "this". { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) lc.coef.put(var,Rational.negate(coef.get(var))); return lc; } public QuadraticCombination toQuadratic() { QuadraticCombination qc=new QuadraticCombination(); for(String var:coef.keySet()) qc.add(var,new LinearCombination(coef.get(var))); return qc; } public boolean containsNondetVar() { for(String var:coef.keySet()) if(var.startsWith("_a_") || var.startsWith("_b_") || var.startsWith("_tmp_")) return true; return false; } public LinearCombination deepCopy() { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) { Rational c=coef.get(var); lc.add(var, c); } return lc; } public QuadraticCombination mulByVar(String var) { QuadraticCombination ret=new QuadraticCombination(); for(String s:coef.keySet()) ret.add(s,new LinearCombination(var,coef.get(s))); return ret; } public void multiplyByLin(LinearCombination lc) throws Exception { if(!isConstant() && !lc.isConstant()) throw new Exception("multiplication of two linear Expressions is not linear"); if(isConstant()) { Rational x=coef.get("1"); if(x==null) x=Rational.zero; coef.clear(); for(String var:lc.coef.keySet()) coef.put(var,Rational.mul(lc.coef.get(var),x)); } else { Rational x=lc.coef.get("1"); multiplyByValue(x); } } public boolean isConstant() { if(coef.size()>1 || (coef.size()==1 && !coef.containsKey("1"))) return false; return true; } public void removeZeros() { Vector<String> allVars=new Vector<>(); allVars.addAll(coef.keySet()); for(String s:allVars) if(coef.get(s).equals(Rational.zero)) coef.remove(s); } public LinearCombination primize() { LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) { if(!var.equals("1")) { if(!var.contains("_prime")) lc.add(var + "_prime", coef.get(var)); } else lc.add(var,coef.get(var)); } return lc; } public LinearCombination unprime() { LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) { if(var.endsWith("_prime")) { String orig=var.substring(0, var.length()-6); lc.add(orig, coef.get(var)); } else lc.add(var,coef.get(var)); } return lc; } void replaceVarWithLinear(String var,LinearCombination lc) { if(!coef.containsKey(var)) return; Rational r=coef.get(var); coef.put(var,Rational.zero); LinearCombination tmp=lc.deepCopy(); tmp.multiplyByValue(r); add(tmp); removeZeros(); } public int replaceVarsWithValue(Map<String,Integer> dict) throws Exception { int ret=0; for(String var:coef.keySet()) { if(!dict.containsKey(var)) throw new Exception("dictionary cannot support "+toNormalString()); int varVal=dict.get(var); ret+=varVal*coef.get(var).numerator/coef.get(var).denominator; } return ret; } public boolean equals(LinearCombination lc) { lc.removeZeros(); removeZeros(); for(String var:coef.keySet()) if(!lc.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; for(String var:lc.coef.keySet()) if(!this.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; return true; } public String toNormalString() { removeZeros(); if(coef.size()==0) return "0"; String ret=""; for(String s:coef.keySet()) { Rational c=coef.get(s); if(ret.equals("")) ret+=c.toNormalString()+"*"+s; else if(coef.get(s).compareTo(Rational.zero)<0) ret+=" - "+(Rational.negate(c)).toNormalString()+"*"+s; else ret+=" + "+c.toNormalString()+"*"+s; } return ret; } public String toString() { removeZeros(); String ret=""; for(String s:coef.keySet()) { Rational c=coef.get(s); if(c.equals(Rational.one)) ret += " " + s; else if(s.equals("1")) { if (!c.isNonNegative()) ret += " (- " + Rational.negate(c) + ")"; else ret +=" "+c+" "; } else if(c.isNonNegative()) ret += " (* " + (c) + " " + s + ")"; else ret += " (* (- " + Rational.negate(c) + ") " + s + ")"; } if(ret.equals("")) return "0"; if(coef.size()>1) return "(+ "+ret+")"; else return ret; } }
6,870
25.125475
94
java
null
RevTerm-main/code/polynomial/part2/Main/src/LinearPredicate.java
import java.util.Vector; public class LinearPredicate { Vector<LinearCombination> exprs; LinearPredicate() { exprs=new Vector<>(); } void add(LinearCombination lc) { for(LinearCombination l:exprs) if(l!=null && l.equals(lc)) return; exprs.add(lc); } void add(LinearPredicate lp) { for(LinearCombination lc:lp.exprs) add(lc.deepCopy()); } public Vector<LinearPredicate> negate() { Vector<LinearPredicate> ret=new Vector<>(); for(LinearCombination lc:exprs) { LinearCombination l=lc.negate(); l.add("1",Rational.negate(Main.eps)); LinearPredicate lp=new LinearPredicate(); lp.add(l); ret.add(lp); } return ret; } public static Vector<LinearPredicate> negate(Vector<LinearPredicate> g) { Vector<LinearPredicate> ret=new Vector<>(); if(g.size()==1) ret=g.firstElement().negate(); else { Vector<LinearPredicate> notLast=g.lastElement().negate(); g.removeElementAt(g.size()-1); Vector<LinearPredicate> recurse=negate(g); for(LinearPredicate lp:notLast) for(LinearPredicate predicate:recurse) { LinearPredicate copy=predicate.deepCopy(); copy.add(lp); ret.add(copy); } } return ret; } public static Vector<LinearPredicate> conjunct(Vector<LinearPredicate> left,Vector<LinearPredicate> right) { Vector<LinearPredicate> ret=new Vector<>(); if(left.isEmpty()) { for(LinearPredicate lp:right) ret.add(lp.deepCopy()); return ret; } if(right.isEmpty()) { for(LinearPredicate lp:left) ret.add(lp.deepCopy()); return ret; } for(LinearPredicate lp1:left) for(LinearPredicate lp2:right) { LinearPredicate lp=new LinearPredicate(); lp.add(lp1); lp.add(lp2); ret.add(lp); } return ret; } public static Vector<LinearPredicate> disjunct(Vector<LinearPredicate> left,Vector<LinearPredicate> right) { Vector<LinearPredicate> ret=new Vector<>(); for(LinearPredicate lp:left) ret.add(lp.deepCopy()); for(LinearPredicate lp:right) ret.add(lp.deepCopy()); return ret; } void replaceVarWithLinear(String var,LinearCombination lc) { for(LinearCombination l:exprs) l.replaceVarWithLinear(var,lc); } public LinearPredicate deepCopy() { LinearPredicate ret=new LinearPredicate(); ret.add(this); return ret; } public boolean equalsLogic(LinearPredicate lp) { for(LinearCombination lc:exprs) if(!lp.contains(lc)) return false; for(LinearCombination lc:lp.exprs) if(!this.contains(lc)) return false; return true; } public boolean contains(LinearCombination lc) { for(LinearCombination l:exprs) if(l.equals(lc)) return true; return false; } public String toString() { String ret=""; for(int i=0;i<exprs.size();i++) { LinearCombination lc = exprs.elementAt(i); if (i==0) ret += lc.toNormalString() + ">=0"; else ret += " && " + lc.toNormalString() + ">=0"; } return ret; } }
3,778
24.193333
110
java
null
RevTerm-main/code/polynomial/part2/Main/src/Main.java
import java.util.Vector; public class Main { public static Rational eps=Rational.one; public static CFGNode startNode,cutPoint,termNode; public static String fileName="",solver="",workingdir="",solversDir="",cpaDir=""; public static int con=0,dis=0,degree=0,mu=0; public static void main(String[] args) throws Exception { con=Integer.parseInt(args[0]); dis=Integer.parseInt(args[1]); degree = Integer.parseInt(args[2]); mu = Integer.parseInt(args[3]); solver=args[4]; fileName=args[5]; workingdir=args[6]; solversDir=args[7]; cpaDir=args[8]; termNode=CFGNode.addNode(-2); startNode= CFGNode.addNode(-1); long startTime=System.currentTimeMillis(); Parser.readFile(fileName); Parser.parseProg(0,Parser.getTokenCount()-1); for(CFGNode n:CFGNode.allCFGNodes) { if(n.id==-1 || n.id==-2) continue; n.addTerminalTransitions(); } int curTotalCFGNodes=CFGNode.allCFGNodes.size(); for(int i=0;i<curTotalCFGNodes;i++) { CFGNode n=CFGNode.allCFGNodes.elementAt(i); if(n.id==-2 || n.id==-1) continue; n.addNecessaryNondet(); } //this is done after parsing because we need to have the list of all variables. for(Transition t:Transition.allTransitions) t.addNondetTemplate(); Vector<Transition> RevTransitions=new Vector<>(); for(Transition t:Transition.allTransitions) { Vector<Transition> r=t.reverse(); RevTransitions.addAll(r); for(Transition tau:r) tau.v.rout.add(tau); } Vector<CFGNode> cutPoints=CFGUtil.findCutpoints(); fileName=fileName.replace("/","_"); // for(Transition t:RevTransitions) // System.err.println(t); // System.exit(0); InvariantGeneration.MakeTemplate(1,1,startNode,0); // System.err.println("-----------------------Invariant---------------------"); // for(CFGNode n:CFGNode.allCFGNodes) // if(!n.inv.isEmpty()) // System.err.println(n.id+": "+n.inv.firstElement().toNormalString()); // System.err.println("-----------------------Invariant---------------------"); Vector <Putinar> InvPutinar=new Vector<>(); InvariantGeneration.generate(cutPoints,InvPutinar,0); InvariantGeneration.MakeTemplate(con,dis,termNode,1); termNode.preCondition=termNode.inv.firstElement(); // System.err.println("-----------------------Backward Invariant---------------------"); // for(CFGNode n:CFGNode.allCFGNodes) // for(PolynomialPredicate qp:n.inv) // System.err.println(n.id+": "+qp.toNormalString()); // System.err.println("-----------------------Backward Invariant---------------------"); InvariantGeneration.generate(cutPoints,InvPutinar,1); // for(Putinar p:InvPutinar) // System.err.println(p.toString()); Vector<Putinar> inductiveness=new Vector<>(); InvariantGeneration.generate(cutPoints,inductiveness,0); Vector<Polynomial> invEqualities=new Vector<>(); for(Putinar putinar: InvPutinar) invEqualities.addAll(putinar.generateEqualities()); boolean result=InvUtil.checkNonTermination(invEqualities,inductiveness,startNode); if(result) //does not terminate System.out.println("Non-Terminating"); else System.out.println("Could Not Prove Non-Termination"); long endTime=System.currentTimeMillis(); System.out.println("total time used: "+ (endTime-startTime)); int val=(result) ? 3 : 0; System.exit(val); } }
3,854
34.045455
95
java
null
RevTerm-main/code/polynomial/part2/Main/src/Monomial.java
import java.util.*; public class Monomial implements Comparable<Monomial> { Map<String, Integer> vars; public static final Monomial one = new Monomial(); Monomial() { vars = new TreeMap<>(); } Monomial(String var) { vars=new TreeMap<>(); addVar(var,1); } Monomial(String var,int power) { vars= new TreeMap<>(); addVar(var,power); } void addVar(String varName, int power) { if (vars.containsKey(varName)) vars.put(varName, vars.get(varName) + power); else vars.put(varName, power); } Map<String, Integer> getVars() { return vars; } public static Monomial mul(Monomial a, Monomial b) { Monomial ret = new Monomial(); Map<String, Integer> avars = a.getVars(), bvars = b.getVars(); for (String varName : avars.keySet()) ret.addVar(varName, avars.get(varName)); for (String varName : bvars.keySet()) ret.addVar(varName, bvars.get(varName)); return ret; } Monomial deepCopy() { Monomial ret = new Monomial(); for (String varName : vars.keySet()) ret.addVar(varName, vars.get(varName)); return ret; } boolean containsVar(String var) { return vars.containsKey(var); } Monomial removeOneVar(String var) { Monomial ret = new Monomial(); for (String s : vars.keySet()) if (!s.equals(var)) ret.addVar(s, vars.get(s)); return ret; } int getPower(String var) { return vars.get(var); } public Monomial programVarsPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial unknownPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(var.startsWith("c_") || var.startsWith("t_") || var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial getProgramVarsPart() { Monomial ret=new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) ret.addVar(var,getPower(var)); return ret; } public Polynomial replaceVarsWithValue(Map<String,Integer> dict) { Monomial p=new Monomial(); Rational coef=Rational.one.deepCopy(); for(String var:vars.keySet()) if(dict.containsKey(var)) coef.numerator*=dict.get(var); else p.addVar(var,vars.get(var)); return new Polynomial(p,coef); } public static Set<Monomial> getAllMonomials(Set<String> vars, int degree) { Set<Monomial> ret=new TreeSet<>(); if(degree==0) ret.add(Monomial.one.deepCopy()); else { Set<Monomial> recurse = getAllMonomials(vars,degree-1); for(Monomial m:recurse) ret.add(m.deepCopy()); for(String var:vars) for(Monomial m:recurse) { if(m.degree()==degree-1) { Monomial tmp = m.deepCopy(); tmp.addVar(var, 1); ret.add(tmp); } } } return ret; } int degree() { int ret=0; for(String var:vars.keySet()) ret+=vars.get(var); return ret; } public int compareTo(Monomial m) { return (toNormalString().compareTo(m.toNormalString())); } void removeZeros() { Vector<String> allVars=new Vector<>(vars.keySet()); for(String var:allVars) if(getPower(var)==0) vars.remove(var); } public boolean equals(Monomial m) { removeZeros(); m.removeZeros(); for(String var:vars.keySet()) if(!m.containsVar(var) || m.getPower(var)!=getPower(var)) return false; for(String var:m.vars.keySet()) if(!this.containsVar(var)) return false; return true; } String toNormalString() { if (vars.isEmpty()) return "1"; String ret = ""; for (String varName : vars.keySet()) { if (!ret.equals("")) ret+=" * "; ret += varName; if(vars.get(varName)!=1) ret+="^"+vars.get(varName); } return ret; } public String toString() { if (vars.isEmpty()) return "1"; String ret = ""; for (String varName : vars.keySet()) { for (int i = 0; i < vars.get(varName); i++) ret += varName + " "; } // ret += ")"; return ret; } }
5,226
23.425234
125
java
null
RevTerm-main/code/polynomial/part2/Main/src/Node.java
import java.util.Vector; public class Node { public static Vector<Node> allNodes=new Vector<>(); int id; Node par; int beginIndex,endIndex; String type; Vector<Node> children; String varName; Polynomial expr; String nondetLow,nondetUp; Vector <PolynomialPredicate> guard; Node(Node par,int beginIndex,int endIndex,String type) { allNodes.add(this); id=allNodes.size()-1; this.par=par; this.beginIndex=beginIndex; this.endIndex=endIndex; this.type=type; this.expr=null; this.guard=new Vector<>(); children=new Vector<>(); if(par!=null) par.children.add(this); } public String toString() { String ret=""; ret+="Node #"+id+"\n"; if(par!=null) ret+="Par: "+par.id+"\n"; else ret+="Par: null\n"; ret+="beginIndex="+beginIndex+"\t"+"endIndex="+endIndex+"\n"; ret+="type: "+type+"\n"; ret+="guard:"; for(PolynomialPredicate pp:guard) ret+=pp.toString()+"\n"; return ret; } }
1,138
21.78
69
java
null
RevTerm-main/code/polynomial/part2/Main/src/Parser.java
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class Parser { public static Set<String> allVars = new HashSet<>(); public static Vector<String> tokens = new Vector<>(); public static int nondetCount = 0; public static Node parseProg(int beginIndex, int endIndex) throws Exception { if (!getToken(beginIndex).equals("START")) throw new Exception("program should start with START"); Node cur = new Node(null, beginIndex, endIndex, "prog"); CFGNode start = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 2))); Transition fromStart = new Transition(Main.startNode, start); fromStart.addToGraph(); if (getToken(beginIndex + 4).equals("CUTPOINT")) Main.cutPoint = CFGNode.addNode(Integer.parseInt(getToken(beginIndex + 6))); int lastFROM = -1; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("FROM")) { if (lastFROM != -1) throw new Exception(" \"TO: index\" expected before @" + i); lastFROM = i; } else if (getToken(i).equals("TO")) { parseTransition(cur, lastFROM, i + 3); lastFROM = -1; } return cur; } public static Node parseTransition(Node par, int beginIndex, int endIndex) throws Exception { if (!getToken(endIndex).equals(";")) throw new Exception("Transition must end with ; @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "Transition"); int vIndex = Integer.parseInt(getToken(beginIndex + 2)), uIndex = Integer.parseInt(getToken(endIndex - 1)); CFGNode vNode = CFGNode.addNode(vIndex); CFGNode uNode = CFGNode.addNode(uIndex); Vector<Transition> transitionVector = new Vector<>(); transitionVector.add(new Transition(vNode, uNode)); int lastColon = beginIndex + 3; for (int i = beginIndex + 4; i <= endIndex - 4; i++) { if (getToken(i).equals(";")) { Node ch = parseStmt(cur, lastColon + 1, i - 1); if (ch.type.equals("assume")) { if (ch.guard.size() == 1) for (Transition t : transitionVector) t.detGuard.add(ch.guard.elementAt(0)); else if (ch.guard.size() > 1) { Vector<Transition> tmp = new Vector<>(); for (int j = 0; j < ch.guard.size(); j++) { for (Transition t : transitionVector) { Transition tp = t.deepCopy(); tp.detGuard.add(ch.guard.elementAt(j)); tmp.add(tp); } } transitionVector = tmp; } } else { for (Transition t : transitionVector) { t.varName.add(ch.varName); t.update.add(ch.expr); // if (ch.expr.containsNondetVar()) // { // LinearCombination lowerBound = ch.expr.deepCopy(); // lowerBound.minus(new LinearCombination(ch.nondetLow, Rational.one)); //var - low >= 0 // t.nondetGuard.add(lowerBound); // // LinearCombination upperBound = new LinearCombination(ch.nondetUp, Rational.one); // upperBound.minus(ch.expr.deepCopy()); //up - var >= 0 // t.nondetGuard.add(upperBound); // // } } } lastColon = i; } } for (Transition t : transitionVector) t.addToGraph(); return cur; } public static Node parseStmt(Node par, int beginIndex, int endIndex) throws Exception { if (getToken(beginIndex).equals("assume")) { Node cur = new Node(par, beginIndex, endIndex, "assume"); Node ch = parseBexpr(cur, beginIndex + 2, endIndex - 1); cur.guard = ch.guard; return cur; } else { Node cur = new Node(par, beginIndex, endIndex, "assignment"); if (!getToken(beginIndex + 1).equals(":=")) throw new Exception("assignment without := @" + beginIndex + "-" + endIndex); int sgn = beginIndex + 1; String varName = getToken(beginIndex); allVars.add(varName); boolean isNondet = false; for (int i = sgn + 1; i <= endIndex; i++) if (getToken(i).equals("nondet")) isNondet = true; if (isNondet) { cur.varName = varName; cur.expr = new Polynomial("_r_"+nondetCount); nondetCount++; } else { Polynomial update = parseExpr(cur, sgn + 1, endIndex).expr; cur.varName = varName; cur.expr = update; } return cur; } } public static Node parseBexpr(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseBexpr: "+beginIndex+"---"+endIndex); Node cur = new Node(par, beginIndex, endIndex, "Bexpr"); for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("nondet")) return cur; Vector<Integer> ors = new Vector<>(); Vector<Integer> ands = new Vector<>(); ors.add(beginIndex - 1); ands.add(beginIndex - 1); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && getToken(i).equals("|") && getToken(i + 1).equals("|")) { ors.add(i + 1); i++; } else if (openPar == 0 && getToken(i).equals("&") && getToken(i + 1).equals("&")) { ands.add(i + 1); i++; } ors.add(endIndex + 2); ands.add(endIndex + 2); if (ors.size() > 2) { for (int i = 1; i < ors.size(); i++) { Node ch = parseBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 2); cur.guard = PolynomialPredicate.disjunct(cur.guard, ch.guard); } return cur; } if (ands.size() > 2) { for (int i = 1; i < ands.size(); i++) { Node ch = parseBexpr(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 2); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); } return cur; } boolean isCompletlyInsidePar = true; openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && i != endIndex) { isCompletlyInsidePar = false; break; } } if (isCompletlyInsidePar) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex - 1); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } if (getToken(beginIndex).equals("!")) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex); cur.guard = PolynomialPredicate.negate(ch.guard,0); return cur; } Node ch = parseLiteral(cur, beginIndex, endIndex); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } public static Node parseLiteral(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseLiteral:"+ beginIndex+"---"+endIndex); int sgn = -1, type = -1; //types: 0: "<=" 1: ">=" 2: ">" 3: "<" 4: "==" 5: "!=" for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("<=")) { sgn = i; type = 0; } else if (getToken(i).equals(">=")) { sgn = i; type = 1; } else if (getToken(i).equals(">")) { sgn = i; type = 2; } else if (getToken(i).equals("<")) { sgn = i; type = 3; } else if (getToken(i).equals("==")) { sgn = i; type = 4; } else if (getToken(i).equals("!=")) { sgn = i; type = 5; } if (sgn == beginIndex || sgn == endIndex) throw new Exception("literal starts or ends with sign @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "literal"); Node left = null; Node right=null; if (sgn == -1) { type = 5; left = parseExpr(cur, beginIndex, endIndex); right = new Node(cur, endIndex, endIndex, "0"); right.expr = new Polynomial(); } else { left = parseExpr(cur, beginIndex, sgn - 1); right = parseExpr(cur, sgn + 1, endIndex); } if (type == 0) //left<=right --> right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 1) //left>=right --> left-right>=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 2) // left > right -> left -right >=eps -> left - right -eps >=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); // left - right lc.minus(new Polynomial(Main.eps)); // left - right - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 3) //left < right --> right - left > eps --> right - left -eps >=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); // right - left lc.minus(new Polynomial(Main.eps)); // right - left - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 4) //left==right --> left-right>=0 and right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); lp.add(lc2); cur.guard.add(lp); } else { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); lc.minus(new Polynomial(Main.eps)); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); lc2.minus(new Polynomial(Main.eps)); PolynomialPredicate lp1 = new PolynomialPredicate(), lp2 = new PolynomialPredicate(); lp1.add(lc); lp2.add(lc2); cur.guard.add(lp1); cur.guard.add(lp2); } return cur; } public static Node parseExpr(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseExpr: "+beginIndex+"----"+endIndex); Vector<Integer> signIndex = new Vector<>(); Vector<String> signType = new Vector<>(); if (!getToken(beginIndex).equals("-")) { signIndex.add(beginIndex - 1); signType.add("+"); } int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && (getToken(i).equals("+") || (getToken(i).equals("-") && (i - 1 < beginIndex || (i - 1 >= beginIndex && !getToken(i - 1).equals("*") && !getToken(i - 1).equals("+")))))) { signIndex.add(i); signType.add(getToken(i)); } } signIndex.add(endIndex + 1); signType.add("+"); Node cur = new Node(par, beginIndex, endIndex, "expr"); cur.expr = new Polynomial(); for (int i = 0; i + 1 < signIndex.size(); i++) { Node ch = parseTerm(cur, signIndex.elementAt(i) + 1, signIndex.elementAt(i + 1) - 1); if (signType.elementAt(i).equals("+")) cur.expr.add(ch.expr); else cur.expr.minus(ch.expr); } return cur; } public static Node parseTerm(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseTerm: "+beginIndex+"---"+endIndex); if ((beginIndex == endIndex && isNumeric(getToken(beginIndex)))) //constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = Integer.parseInt(getToken(beginIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex - 1 && isNumeric(getToken(endIndex))) //negative constant { Node cur = new Node(par, beginIndex, endIndex, "constant"); int val = -Integer.parseInt(getToken(endIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex) //var { Node cur = new Node(par, beginIndex, endIndex, "var"); String var = getToken(beginIndex); allVars.add(var); if (Character.isDigit(var.charAt(0))) throw new Exception("Incorrect var name @" + beginIndex); cur.expr = new Polynomial(); cur.expr.add(new Monomial(var), new Rational(1, 1)); return cur; } else // (...) or [] * [] { Node cur = new Node(par, beginIndex, endIndex, "term mul"); cur.expr = new Polynomial(); Vector<Integer> sgnIndex = new Vector<>(); Vector<String> sgnType = new Vector<>(); sgnIndex.add(beginIndex - 1); sgnType.add("*"); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && (getToken(i).equals("*") || getToken(i).equals("/"))) { sgnIndex.add(i); sgnType.add(getToken(i)); } else if (getToken(i).equals("%")) { throw new Exception("% is not supported. @" + beginIndex + "-" + endIndex); } sgnIndex.add(endIndex + 1); sgnType.add("*"); if (sgnIndex.size() == 2) // (...) { Node ch = parseExpr(cur, beginIndex + 1, endIndex - 1); cur.expr = ch.expr; return cur; } else { cur.expr.add(Monomial.one, Rational.one); for (int i = 1; i < sgnIndex.size(); i++) { Node ch = parseExpr(cur, sgnIndex.elementAt(i - 1) + 1, sgnIndex.elementAt(i) - 1); if (sgnType.elementAt(i - 1).equals("*")) cur.expr.multiplyByPolynomial(ch.expr); else if (ch.expr.isConstant() && ch.expr.terms.containsKey(Monomial.one)) cur.expr.multiplyByValue(Rational.inverse(ch.expr.terms.get(Monomial.one))); else throw new Exception("Divison by variable is not possible @" + beginIndex + "-" + endIndex); } return cur; } } } public static boolean isNumeric(String s) { for (int i = 0; i < s.length(); i++) if (!Character.isDigit(s.charAt(i)) && s.charAt(i) != '.') return false; return true; } public static int getTokenCount() { return tokens.size(); } public static String getToken(int x) { return tokens.elementAt(x); } public static void readTokens(String program) throws Exception { String extraSpace = ""; for (int i = 0; i < program.length(); i++) { char c = program.charAt(i); if (c == '.' || Character.isAlphabetic(c) || Character.isDigit(c) || c == '_') extraSpace += c; else { extraSpace += " "; extraSpace += c; extraSpace += " "; } } Scanner scanner = new Scanner(extraSpace); while (scanner.hasNext()) { String s = scanner.next(); if (s.equals("=")) { if (tokens.size() == 0) throw new Exception("program cannot start with ="); String last = tokens.lastElement(); if (last.equals(":") || last.equals(">") || last.equals("<") || last.equals("=") || last.equals("!")) { tokens.removeElementAt(getTokenCount() - 1); last += s; tokens.add(last); } else tokens.add(s); } else tokens.add(s); } } public static void readFile(String fileName) throws Exception { File file = new File(fileName); Scanner in = new Scanner(file); String program = ""; while (in.hasNextLine()) { String s = in.nextLine(); if (s.contains("//")) s = s.substring(0, s.indexOf("//")); if (s.contains("AT(")) { int ind = s.indexOf("AT("); int openPar = 0, endOfAT = -1; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') openPar++; else if (s.charAt(i) == ')') { openPar--; if (openPar == 0) { endOfAT = i; break; } } } s = s.substring(0, ind) + s.substring(endOfAT + 1, s.length()); } program += s + " "; } readTokens(program); } }
20,148
34.725177
163
java
null
RevTerm-main/code/polynomial/part2/Main/src/Polynomial.java
import java.util.*; public class Polynomial { Map<Monomial, Rational> terms; Polynomial() { terms = new TreeMap<>(); } Polynomial(Rational c) { terms = new TreeMap<>(); terms.put(Monomial.one, c); } Polynomial(String var) { terms = new TreeMap<>(); terms.put(new Monomial(var), Rational.one); } Polynomial(String var, Rational c) { terms = new TreeMap<>(); terms.put(new Monomial(var), c); } Polynomial(Monomial m) { terms = new TreeMap<>(); terms.put(m, Rational.one); } Polynomial(Monomial m, Rational c) { terms = new TreeMap<>(); terms.put(m, c); } Polynomial(Set<String> vars) //generates the polynomial \sum c_i x_i { terms = new TreeMap<>(); for (String var : vars) { Monomial m = new Monomial(); m.addVar("c_" + InvariantGeneration.cCount, 1); InvariantGeneration.cCount++; m.addVar(var, 1); add(m, Rational.one); } } Polynomial(Set<String> vars, int degree) { terms = new TreeMap<>(); Set<Monomial> monomials = Monomial.getAllMonomials(vars, degree); for (Monomial m : monomials) { m.addVar("c_" + InvariantGeneration.cCount, 1); InvariantGeneration.cCount++; add(m, Rational.one); } } boolean containsVar(String var) { for(Monomial m: terms.keySet()) if(m.containsVar(var) && terms.get(m).numerator!=0) return true; return false; } void add(Monomial m, Rational c) { if (terms.containsKey(m)) terms.put(m, Rational.add(terms.get(m), c)); else terms.put(m, c); } void add(Polynomial poly) { for (Monomial term : poly.terms.keySet()) add(term, poly.terms.get(term)); } void minus(Polynomial poly) { add(poly.negate()); } public void multiplyByValue(Rational val) { for (Monomial term : terms.keySet()) terms.put(term, Rational.mul(terms.get(term), val)); } public void multiplyByMonomial(Monomial m) { Map<Monomial, Rational> tmp = new HashMap<>(); for (Monomial term : terms.keySet()) tmp.put(Monomial.mul(term, m), terms.get(term)); terms = tmp; } public void multiplyByPolynomial(Polynomial poly) { Polynomial res = new Polynomial(); for (Monomial m : poly.terms.keySet()) for (Monomial n : this.terms.keySet()) res.add(Monomial.mul(m, n), Rational.mul(poly.terms.get(m), this.terms.get(n))); terms = res.terms; } boolean isConstant() { removeZeros(); return (terms.size() <= 1 && (terms.size() != 1 || terms.containsKey(Monomial.one))); } void removeZeros() { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (terms.get(term).equals(Rational.zero)) terms.remove(term); } Polynomial deepCopy() { removeZeros(); Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), terms.get(term)); return ret; } void replaceVarWithPoly(String var, Polynomial poly) { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (term.containsVar(var)) { Rational coef = terms.get(term); Monomial m = term.removeOneVar(var); Polynomial left = new Polynomial(m); Polynomial right = poly.deepCopy(); for (int i = 1; i < term.getPower(var); i++) right.multiplyByPolynomial(poly); left.multiplyByPolynomial(right); left.multiplyByValue(coef); terms.remove(term); add(left); } } public Set<Monomial> getProgramVariableMonomials() { Set<Monomial> ret= new TreeSet<>(); for(Monomial m:terms.keySet()) ret.add(m.getProgramVarsPart()); return ret; } public Polynomial getCoef(Monomial m) { Polynomial ret=new Polynomial(); for(Monomial monomial:terms.keySet()) { if(monomial.programVarsPart().equals(m)) ret.add(monomial.unknownPart(),terms.get(monomial)); } return ret; } public Polynomial replaceVarsWithValue(Map<String,Integer> dict) { Polynomial ret=new Polynomial(); for(Monomial m:terms.keySet()) { Polynomial r=m.replaceVarsWithValue(dict); r.multiplyByValue(terms.get(m)); ret.add(r); } return ret; } public boolean equals(Polynomial poly) { for (Monomial m : terms.keySet()) if (!poly.terms.containsKey(m) || !poly.terms.get(m).equals(terms.get(m))) return false; for(Monomial m: poly.terms.keySet()) if(!terms.containsKey(m)) return false; return true; } Polynomial negate() { Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), Rational.negate(terms.get(term))); return ret; } public static Polynomial mul(Polynomial left,Polynomial right) { Polynomial ret=left.deepCopy(); ret.multiplyByPolynomial(right); return ret; } public String toString() { String ret = ""; if (terms.isEmpty()) return "0"; Vector<Monomial> monomials = new Vector<>(terms.keySet()); if (monomials.size() == 1) return "(* " + terms.get(monomials.firstElement()) +" "+ monomials.firstElement().toString()+")"; ret = "(+ "; for (Monomial m : monomials) ret += "(* "+ terms.get(m)+ " " +m.toString()+") "; ret += ")"; return ret; } public String toNormalString() { String ret = ""; if (terms.isEmpty()) return "0"; Vector<Monomial> monomials = new Vector<>(terms.keySet()); for (Monomial m : monomials) { if(!ret.equals("")) ret+=" + "; if(!terms.get(m).equals(Rational.one)) ret += terms.get(m).toNormalString()+" * "; ret += m.toNormalString(); } return ret; } }
6,714
25.437008
109
java
null
RevTerm-main/code/polynomial/part2/Main/src/PolynomialPredicate.java
import java.util.Map; import java.util.Vector; public class PolynomialPredicate { Vector<Polynomial> exprs; public static PolynomialPredicate TRUE = new PolynomialPredicate(new Polynomial(Monomial.one)); PolynomialPredicate() { exprs = new Vector<>(); } PolynomialPredicate(Polynomial poly) { exprs=new Vector<>(); add(poly); } void add(Polynomial poly) { for (Polynomial p : exprs) if (p.equals(poly)) return; exprs.add(poly); } void add(PolynomialPredicate pp) { for (Polynomial poly : pp.exprs) add(poly.deepCopy()); } void replaceVarWithPoly(String var, Polynomial poly) { for (Polynomial p : exprs) p.replaceVarWithPoly(var, poly); } public Vector<PolynomialPredicate> negate() { Vector<PolynomialPredicate> ret = new Vector<>(); for (Polynomial poly : exprs) { Polynomial p = poly.negate(); p.add(Monomial.one, Rational.negate(Main.eps)); PolynomialPredicate pp = new PolynomialPredicate(); pp.add(p); ret.add(pp); } return ret; } public static Vector<PolynomialPredicate> negate(Vector<PolynomialPredicate> g,int first) { if(first==g.size()) return new Vector<>(); else if (first== g.size()-1 ) return g.elementAt(first).negate(); else { // Vector<PolynomialPredicate> ret = new Vector<>(); Vector<PolynomialPredicate> notFirst = g.elementAt(first).negate(); Vector<PolynomialPredicate> recurse = negate(g,first+1); // for (PolynomialPredicate pp : notFirst) // for (PolynomialPredicate predicate : recurse) // { // PolynomialPredicate copy = predicate.deepCopy(); // copy.add(pp); // ret.add(copy); // } return conjunct(notFirst,recurse); } } public static Vector<PolynomialPredicate> conjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); } else if (right.isEmpty()) { for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); } else { for (PolynomialPredicate pp1 : left) for (PolynomialPredicate pp2 : right) { PolynomialPredicate pp = new PolynomialPredicate(); pp.add(pp1.deepCopy()); pp.add(pp2.deepCopy()); ret.add(pp); } } return ret; } public static Vector<PolynomialPredicate> disjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); return ret; } public PolynomialPredicate replaceVarsWithValue(Map<String,Integer> dict) { PolynomialPredicate ret=new PolynomialPredicate(); for(Polynomial p:exprs) ret.add(p.replaceVarsWithValue(dict)); return ret; } boolean equalsLogic(PolynomialPredicate pp) { for (Polynomial p : exprs) if (!pp.contains(p)) return false; for (Polynomial p : pp.exprs) if (!this.contains(p)) return false; return true; } boolean contains(Polynomial p) { for (Polynomial poly : exprs) if (p.equals(poly)) return true; return false; } PolynomialPredicate deepCopy() { PolynomialPredicate ret = new PolynomialPredicate(); ret.add(this); return ret; } public String toNormalString() { String ret = ""; for (int i = 0; i < exprs.size(); i++) { Polynomial p = exprs.elementAt(i); if (i == 0) ret += p.toNormalString() + ">=0"; else ret += " && " + p.toNormalString() + ">=0"; } return ret; } public String toString() { return toNormalString(); } }
4,596
26.860606
123
java
null
RevTerm-main/code/polynomial/part2/Main/src/Putinar.java
import java.util.Set; import java.util.TreeSet; import java.util.Vector; public class Putinar { public static int countD = 0; int startDIndex; int startNode, endNode; public PolynomialPredicate constraints; public Polynomial objective; Putinar(int startNode, int endNode) { this.startNode = startNode; this.endNode = endNode; constraints = new PolynomialPredicate(); Polynomial lc = new Polynomial(); lc.add(Monomial.one, Rational.one); constraints.add(lc); // 1>=0 is always true // nodeConstraint = new PolynomialPredicate(); startDIndex = countD; countD++; // for 1>=0 } public Putinar deepCopy() { Putinar ret = new Putinar(startNode, endNode); countD--; // for 1>=0 which is added in new ret.startDIndex = startDIndex; // ret.nodeConstraint.exprs.addAll(nodeConstraint.exprs); //countD+=invConstraint.size(); ret.constraints = constraints.deepCopy(); //countD+=linearConstraints.exprs.size()-1; //-1 for 1>=0 which is already added ret.objective = objective.deepCopy(); return ret; } // public Farkas disabled() // { // Farkas ret=deepCopy(); //// LinearCombination lc=new LinearCombination("n_"+InvariantGeneration.nCount); //// QuadraticCombination obj=new QuadraticCombination("1",lc); // // InvariantGeneration.nCount++; // ret.objective=QuadraticCombination.minus1.deepCopy(); // return ret; // } void addPredicate(PolynomialPredicate pp) { constraints.add(pp); countD+=pp.exprs.size(); } void setObjective(Polynomial obj) { objective = obj.deepCopy(); } void replaceVarWithPoly(String var, Polynomial lc) { constraints.replaceVarWithPoly(var,lc); objective.replaceVarWithPoly(var,lc); // nodeConstraint.replaceVarWithPoly(var,lc); } public Vector<Polynomial> generateEqualities() { Vector<Polynomial> equalities = new Vector<>(); // poly = 0 Polynomial right = new Polynomial(); for(Polynomial poly:constraints.exprs) { Polynomial h = generateHPolynomial(Parser.allVars,Main.mu); Polynomial sos = generateSOSPolynomial(Parser.allVars,Main.mu); // System.err.println("h: "+h.toNormalString()); // System.err.println("sos: "+sos.toNormalString()); // System.err.println("-------------------------"); // System.exit(0); equalities.addAll(makeEqualities(h,sos)); h.multiplyByPolynomial(poly); right.add(h); } equalities.addAll(makeEqualities(objective,right)); return equalities; } private Polynomial generateHPolynomial(Set<String> vars,int degree) { Set<Monomial> monomials= Monomial.getAllMonomials(vars,degree); Polynomial h=new Polynomial(); for(Monomial m:monomials) { Monomial mp=m.deepCopy(); mp.addVar("t_"+InvariantGeneration.tCount,1); InvariantGeneration.tCount++; h.add(mp,Rational.one); } return h; } private Polynomial generateSOSPolynomial(Set<String> vars, int degree) // ret = y LL^T y^t { // if(degree==0) //NOTE: if not comment it will be Farkas when mu=0 // { // String var = "l_"+InvariantGeneration.lCount; // InvariantGeneration.lCount++; // InvariantGeneration.nonNegativeLvars.add(var); // return new Polynomial(var); // } Vector<Monomial> tmp = new Vector<>(Monomial.getAllMonomials(vars,degree/2)); Vector<Polynomial> y=new Vector<>(); int dim = tmp.size(); Polynomial[][] L = new Polynomial[dim][dim],Lt=new Polynomial[dim][dim],yt=new Polynomial[dim][1]; for(int i=0;i<dim;i++) { y.add(new Polynomial(tmp.elementAt(i))); yt[i][0]=new Polynomial(tmp.elementAt(i)); } for(int i=0;i<dim;i++) for (int j=0;j<dim;j++) { if (j <= i) { String var = "l_" + InvariantGeneration.lCount; InvariantGeneration.lCount++; L[i][j] = new Polynomial(var); Lt[j][i] = L[i][j].deepCopy(); if (i == j) InvariantGeneration.nonNegativeLvars.add(var); } else { L[i][j] = new Polynomial(); Lt[j][i] = L[i][j].deepCopy(); } } Vector<Polynomial> yL = mulVecMat(y,L); Vector<Polynomial> yLLt = mulVecMat(yL,Lt); Polynomial ret= new Polynomial(); for(int i=0;i<dim;i++) ret.add(Polynomial.mul(yLLt.elementAt(i), yt[i][0])); // System.err.println("SOS: "+ret.toNormalString()); return ret; } private Vector<Polynomial> mulVecMat(Vector<Polynomial> y,Polynomial[][] L) { Vector<Polynomial> ret= new Vector<>(); int sz=y.size(); for(int col=0;col<sz;col++) { Polynomial p=new Polynomial(); for(int i=0;i<sz;i++) p.add(Polynomial.mul(y.elementAt(i),L[i][col])); ret.add(p); } return ret; } Vector<Polynomial> makeEqualities(Polynomial left, Polynomial right) { Set<Monomial> allMonomials= new TreeSet<>(); allMonomials.addAll(left.getProgramVariableMonomials()); allMonomials.addAll(right.getProgramVariableMonomials()); Vector<Polynomial> ret=new Vector<>(); for(Monomial m:allMonomials) { Polynomial leftm=left.getCoef(m),rightm=right.getCoef(m); rightm.add(leftm.negate()); ret.add(rightm); } return ret; } public Set<Monomial> getAllVars() { Set<Monomial> ret=new TreeSet<>(); for(Polynomial lc: constraints.exprs) ret.addAll(lc.terms.keySet()); // for(Polynomial qc: nodeConstraint.exprs) // ret.addAll(qc.terms.keySet()); ret.addAll(objective.terms.keySet()); return ret; } // public QuadraticCombination makeEquality(String var) // { // QuadraticCombination qc = new QuadraticCombination(); // int dIndex = startDIndex; // if (!invConstraint.exprs.isEmpty()) // { // //for(int i=0;i<invConstraint.exprs.size();i++) // for (QuadraticCombination invc : invConstraint.exprs) // { // if (invc.coef.containsKey(var)) // { // String invMultiplier = "d_" + dIndex; // //InvariantGeneration.addUnknownVar("d_" + dIndex); // // // LinearCombination lc = invc.coef.get(var); // qc.add(invMultiplier, lc); // } // dIndex++; // } // } // // for (LinearCombination lp : linearConstraints.exprs) // lp>=0 // { // String multiplier = "d_" + dIndex; // if (lp.coef.containsKey(var)) // { // Rational coef = lp.coef.get(var); // qc.add(multiplier, new LinearCombination(coef)); // //InvariantGeneration.addUnknownVar("d_" + dIndex); // } // dIndex++; // } // // LinearCombination coef = objective.getCoef(var); // //qc=coef <=> qc-coef=0 // if (coef != null) // { // LinearCombination lc = coef.negate(); // qc.add(lc); // } //// System.err.println("var: "+var+" => "+qc.toNormalString()); // return qc; // } public String toString() { String ret = ""; ret += "\n---------------------------------------------\n"; ret += "from: " + startNode + " to: " + endNode + "\n"; int dIndex = startDIndex; // for (int i = 0; i < nodeConstraint.exprs.size(); i++) // { // ret += "d_" + dIndex + ": " + nodeConstraint.exprs.elementAt(i).toNormalString() + "\n"; // dIndex++; // } for (Polynomial lc : constraints.exprs) { ret += "\nd_" + dIndex + ": " + lc.toNormalString(); dIndex++; } ret += "\n---------------------------------------------\n"; ret += objective.toNormalString(); return ret; } }
8,607
30.881481
106
java
null
RevTerm-main/code/polynomial/part2/Main/src/QuadraticCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Vector; public class QuadraticCombination { Map<String,LinearCombination> coef; public static final QuadraticCombination minus1=new QuadraticCombination("1",new LinearCombination("1",new Rational(-1,1))); QuadraticCombination() { coef=new HashMap<>(); } QuadraticCombination(String var,LinearCombination lc) { coef=new HashMap<>(); add(var,lc); } QuadraticCombination(Set<String> vars) { coef= new HashMap<>(); for(String var:vars) { add(var,new LinearCombination("c_"+InvariantGeneration.cCount)); InvariantGeneration.cCount++; } } public void add(String var,LinearCombination lc) { if(coef.containsKey(var)) coef.get(var).add(lc); else coef.put(var,lc); } public void add(QuadraticCombination qc) { for(String var:qc.coef.keySet()) add(var,qc.coef.get(var)); } public void add(LinearCombination lc) { for(String var:lc.coef.keySet()) { add(var,new LinearCombination(lc.coef.get(var))); } } public void add(Rational val) { add("1",new LinearCombination(val)); } public QuadraticCombination negate() { QuadraticCombination qc=new QuadraticCombination(); for(String var:coef.keySet()) qc.add(var,coef.get(var).negate()); return qc; } public LinearCombination getCoef(String var) { return coef.get(var); } public Rational getCoef(String var1,String var2) { if(coef.containsKey(var1) && coef.get(var1).coef.containsKey(var2)) return coef.get(var1).coef.get(var2); else if(coef.containsKey(var2) && coef.get(var2).coef.containsKey(var1)) return coef.get(var2).coef.get(var1); else return Rational.zero; } public QuadraticCombination primize() { QuadraticCombination ret=new QuadraticCombination(); for(String var:coef.keySet()) if(!var.equals("1")) ret.add(var+"_prime",coef.get(var)); else ret.add("1",coef.get(var)); return ret; } public QuadraticCombination deepCopy() { QuadraticCombination qc=new QuadraticCombination(); for(String var:coef.keySet()) qc.add(var,coef.get(var).deepCopy()); return qc; } public void replaceVarWithLinear(String var,LinearCombination lc) { if(!coef.containsKey(var)) return; LinearCombination l=coef.get(var); coef.remove(var); for(String v:lc.coef.keySet()) { LinearCombination tmp=l.deepCopy(); tmp.multiplyByValue(lc.coef.get(v)); add(v,tmp); } } public LinearCombination replaceVarsWithValue(Map<String,Integer> dict) throws Exception { LinearCombination ret=new LinearCombination(); for(String var:coef.keySet()) { Integer c=coef.get(var).replaceVarsWithValue(dict); ret.add(var,new Rational(c,1)); } return ret; } public String toNormalString() { String ret=""; for(String s:coef.keySet()) { if(ret.equals("")) ret+=s+"*("+coef.get(s).toNormalString()+")"; else ret+=" + "+s+"*("+coef.get(s).toNormalString()+")"; } return ret; } public String toString() { String ret=""; if(coef.keySet().size()>1) ret="(+ "; for(String var:coef.keySet()) { LinearCombination lc=coef.get(var); if(ret=="") ret="(* "+lc.toString()+" "+var+")"; else ret=ret+" (* "+lc.toString()+" "+var+")"; } if(coef.keySet().size()>1) ret+=")"; if(ret.equals("")) ret="0"; return ret; } }
4,165
23.946108
128
java
null
RevTerm-main/code/polynomial/part2/Main/src/QuadraticPredicate.java
import java.util.Map; import java.util.Vector; public class QuadraticPredicate { public static QuadraticPredicate TRUE=new QuadraticPredicate(new QuadraticCombination("1",new LinearCombination("1",Rational.one))); Vector<QuadraticCombination> exprs; QuadraticPredicate() //conjunctions { exprs =new Vector<>(); } QuadraticPredicate(QuadraticCombination qc) { exprs=new Vector<>(); exprs.add(qc); } void add(QuadraticCombination qc) { exprs.add(qc); } void add(QuadraticPredicate qp) { for(QuadraticCombination qc:qp.exprs) exprs.add(qc); } void replaceVarWithLinear(String var,LinearCombination update) { for(QuadraticCombination qc:exprs) qc.replaceVarWithLinear(var,update); } public static Vector<QuadraticPredicate> negate(Vector<QuadraticPredicate> vqp) { Vector<QuadraticPredicate> ret=new Vector<>(); for(QuadraticPredicate qp:vqp) { Vector<QuadraticCombination> vqc=qp.negate(); if(ret.isEmpty()) { for(QuadraticCombination qc:vqc) { QuadraticPredicate c=new QuadraticPredicate(); c.add(qc); ret.add(c); } continue; } Vector<QuadraticPredicate> tmp=new Vector<>(); for(QuadraticCombination cur:vqc) for(QuadraticPredicate q:ret) { QuadraticPredicate c=q.deepCopy(); c.add(cur); tmp.add(c); } ret.addAll(tmp); } return ret; } Vector<QuadraticCombination> negate() { Vector<QuadraticCombination> ret=new Vector<>(); for(QuadraticCombination qc:exprs) { QuadraticCombination q=qc.negate(); q.add("1",new LinearCombination(Rational.negate(Main.eps))); // 1*(-1) ret.add(q); } return ret; } QuadraticCombination getTerm(int ind) { return exprs.elementAt(ind); } public QuadraticPredicate deepCopy() { QuadraticPredicate qp=new QuadraticPredicate(); for(QuadraticCombination qc:exprs) qp.add(qc.deepCopy()); return qp; } public QuadraticPredicate primize() { QuadraticPredicate ret=new QuadraticPredicate(); for(QuadraticCombination qc:exprs) ret.add(qc.primize()); return ret; } public LinearPredicate replaceVarsWithValue(Map<String,Integer> dict) throws Exception { LinearPredicate ret=new LinearPredicate(); for(QuadraticCombination qc:exprs) ret.add(qc.replaceVarsWithValue(dict)); return ret; } public String toString() { String ret=""; for(QuadraticCombination qc: exprs) ret+="(>= "+qc.toString()+" 0) "; if(exprs.size()>1) ret="(and "+ret+") "; return ret; } public String toNormalString() { String ret=""; for(QuadraticCombination qc: exprs) ret+=qc.toNormalString()+">=0 and "; return ret; } }
3,307
25.464
136
java
null
RevTerm-main/code/polynomial/part2/Main/src/Rational.java
import java.util.EnumMap; public class Rational implements Comparable<Rational> { public static final Rational one=new Rational(1,1),zero=new Rational(0,1); int numerator,denominator; public int gcd(int a, int b) { if (b==0) return a; return gcd(b,a%b); } Rational(int numerator,int denominator) { if(numerator==0) { this.numerator=0; this.denominator=1; return; } if(denominator<0) { denominator*=-1; numerator*=-1; } int g=gcd(numerator,denominator); this.numerator=numerator/g; this.denominator=denominator/g; } public static Rational negate(Rational a) { return new Rational(-a.numerator,a.denominator); } public static Rational inverse(Rational a) throws Exception { if(a.numerator==0) throw new Exception("getting inverse of "+a+" which is not defined"); return new Rational(a.denominator,a.numerator); } public static Rational add(Rational a,Rational b) { return new Rational(a.numerator*b.denominator+b.numerator*a.denominator,a.denominator*b.denominator); } public static Rational minus(Rational a,Rational b) { return add(a,negate(b)); } public static Rational mul(Rational a,Rational b) { return new Rational(a.numerator*b.numerator,a.denominator*b.denominator); } public static Rational div(Rational a,Rational b) throws Exception { return mul(a,inverse(b)); } public boolean equals(Rational a) { return (a.numerator== numerator && a.denominator==denominator); } public boolean isNonNegative() { return (numerator>=0); } @Override public int compareTo(Rational a) { return numerator*a.denominator-a.numerator*denominator; } public String toNormalString() { if(denominator==1) return ""+numerator; return "("+numerator+"/"+denominator+")"; } public Rational deepCopy() { Rational p= new Rational(numerator,denominator); return p; } public void normalize() { if(denominator<0) { numerator*=-1; denominator*=-1; } } public String toString() { normalize(); String num="",den=""+denominator; if(numerator<0) num="(- "+(-numerator)+")"; else num=""+numerator; if(denominator==1) return num; return "(/ "+num+" "+denominator+")"; } }
2,662
21.760684
109
java
null
RevTerm-main/code/polynomial/part2/Main/src/Transition.java
import java.util.Vector; public class Transition //from "v.first" to "v.second" with guard "g" and update "varName := update" { public static Vector<Transition> allTransitions=new Vector<>(); CFGNode v,u; PolynomialPredicate detGuard; PolynomialPredicate nondetGuard; Vector<String> varName; Vector<Polynomial> update; //if update[i]=null then varName[i] is non-deterministicly assigned boolean hasGroup; Transition(CFGNode a,CFGNode b) { v = a; u = b; detGuard = new PolynomialPredicate(); nondetGuard = new PolynomialPredicate(); varName = new Vector<>(); update = new Vector<>(); hasGroup = false; } void addNondetTemplate() { for(Polynomial p:update) { if(p.toString().contains("_r_")) // lc is a fresh nondet variable { // qc <= lc <= qc Polynomial poly= new Polynomial(Parser.allVars),poly2=poly.deepCopy(); poly.add(p.negate()); //poly - p <=0 nondetGuard.add(poly.negate()); poly2.add(p.negate()); // poly2 - p >=0 nondetGuard.add(poly2); } } } public void addToGraph() { allTransitions.add(this); v.out.add(this); } public Vector<Transition> reverse() throws Exception //NOTE: this is only for C-Integer Programs! { Transition res=new Transition(u,v); for(Polynomial lc: detGuard.exprs) res.detGuard.add(lc.deepCopy()); for(Polynomial qc: nondetGuard.exprs) res.nondetGuard.add(qc.deepCopy()); for(int i=0;i<varName.size();i++) { Polynomial lc=update.elementAt(i); String var=varName.elementAt(i); // System.err.println(var+" := "+lc.toNormalString()); if(lc.containsVar(var)) { CFGNode tmp = new CFGNode(CFGNode.greaTestNodeIndex+1); Transition utmp=new Transition(u,tmp),tmpv=new Transition(tmp,v); Polynomial g1 = new Polynomial(var); g1.add(new Monomial("_v_",1),Rational.negate(Rational.one)); utmp.detGuard.add(g1); utmp.detGuard.add(g1.negate()); // x- _v_ ==0 utmp.varName.add(var); utmp.update.add(new Polynomial("_r_"+Parser.nondetCount)); Parser.nondetCount++; Polynomial g2 = new Polynomial("_v_"); g2.add(lc.negate()); tmpv.detGuard.add(g2); tmpv.detGuard.add(g2.negate()); tmpv.varName.add("_v_"); tmpv.update.add(new Polynomial("_r_"+Parser.nondetCount)); Parser.nondetCount++; Vector<Transition> ret= new Vector<>(); ret.add(utmp); ret.add(tmpv); return ret; } else //var is not in lc { Polynomial g = new Polynomial(var); g.add(lc.negate()); res.detGuard.add(g); res.detGuard.add(g.negate()); //var - lc == 0 res.varName.add(var); res.update.add(new Polynomial("_r_"+Parser.nondetCount)); Parser.nondetCount++; } } Vector<Transition> ret=new Vector<>(); ret.add(res); return ret; } public Transition deepCopy() { Transition ret=new Transition(v,u); ret.detGuard = detGuard.deepCopy(); ret.nondetGuard=nondetGuard.deepCopy(); for(String var:varName) ret.varName.add(var.toString()); for(Polynomial lc:update) if(lc!=null) ret.update.add(lc.deepCopy()); else ret.update.add(null); return ret; } public String toString() { String res=""; res+="from: "+v.id+"\nto: "+u.id+"\n"; if(detGuard !=null) res+="detGuard: "+ detGuard +"\n"; if(nondetGuard!=null) res+="nondetGuard: "+nondetGuard.toNormalString()+"\n"; System.err.println("updates: "); for(int i=0;i<varName.size();i++) if(update.elementAt(i)!=null) res+=varName.elementAt(i)+" := "+update.elementAt(i).toNormalString()+"\n"; else res+=varName.elementAt(i)+" := nondet()\n"; return res; } }
4,512
30.78169
103
java
null
RevTerm-main/code/polynomial/part2/Main/src/safetyUtil.java
import java.io.File; import java.io.FileWriter; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class safetyUtil { public static boolean check(String fileName) throws Exception { Map<String,Integer> dict = getSMTResults(fileName); replaceAllVariables(dict); convertToC(fileName,dict); return hasPath(fileName); } public static Map<String,Integer> getSMTResults(String fileName) throws Exception { Map<String,Integer> res=new TreeMap<>(); File f=new File(fileName+".result"); Scanner in=new Scanner(f); in.nextLine(); //skip the "sat" while(in.hasNextLine()) { String s=in.nextLine(); s=takePars(s); //System.err.println("s = " + s); Scanner tmp=new Scanner(s); if(!tmp.hasNext()) continue; String var=tmp.next(); int val=1; String p=tmp.next(); if(p.equals("-")) { val *= -1; p=tmp.next(); } val*=Integer.parseInt(p); if(!Parser.allVars.contains(var)) res.put(var,val); } // for(String var:res.keySet()) // System.err.println(var+" = "+res.get(var)); return res; } public static String takePars(String s) { //System.err.println(s); String ret=s.replace("("," "); ret=ret.replace(")"," "); return ret; } public static void replaceAllVariables(Map<String,Integer> dict) throws Exception { for(CFGNode n:CFGNode.allCFGNodes) { for(PolynomialPredicate qc:n.inv) { PolynomialPredicate lc=qc.replaceVarsWithValue(dict); //System.err.println(n.id+": "+lc); n.computedInv.add(lc); } } } public static void convertToC(String fileName, Map<String,Integer> dict) throws Exception { int nondetCnt=0; FileWriter fw=new FileWriter(fileName+".c"); fw.write("int main()\n{\n"); for(String var:Parser.allVars) if(!var.equals("1") && !var.startsWith("_a_") && !var.startsWith("_b_")) fw.write("int "+var+";\n"); fw.write("if("); boolean isFirst=true; for(String var:Parser.allVars) if(!var.equals("1") && !var.startsWith("_a_") && !var.startsWith("_b_")) { if(!isFirst) fw.write(" || "); else isFirst=false; fw.write(var + ">100000 || " + var + "<-100000 "); } fw.write(")\nreturn 0;\n"); fw.write("\ngoto START;\n"); for(CFGNode n:CFGNode.allCFGNodes) { fw.write(getlocName(n)+":\n"); //if(!BI) goto ERROR if(!n.computedInv.isEmpty()) { // System.err.println("computed: "); // for(LinearPredicate lp:n.computedInv) // System.err.println(lp.toString()); // System.err.println("actual: "); // for(QuadraticPredicate qp:n.inv) // System.err.println(qp.toNormalString()); fw.write("if(!("); for (int i = 0; i < n.computedInv.size(); i++) { PolynomialPredicate lp = n.computedInv.elementAt(i); if (i != 0) fw.write(" || "); fw.write("("+lp.toString()+")"); } fw.write("))\n"); fw.write("goto ERROR;\n"); } // for(Transition t:n.out) { if(t.detGuard.exprs.size()!=0) fw.write("if( "+t.detGuard+" )\n{\n"); for(int i=0;i<t.varName.size();i++) { String var=t.varName.elementAt(i); Polynomial upd=t.update.elementAt(i); if(upd.toNormalString().contains("_r_")) { fw.write(var + " = nondet" + nondetCnt + "();\n"); nondetCnt++; } else fw.write(var+" = "+upd.toNormalString()+";\n"); } fw.write("goto "+getlocName(t.u)+";\n"); if(t.detGuard.exprs.size()!=0) fw.write("}\n"); } fw.write("return 0;\n"); } fw.write("ERROR:\nreturn (-1);\n"); fw.write("}"); fw.close(); } public static String getlocName(CFGNode n) throws Exception { if(n.id>=0) return "location"+n.id; else if(n.id==-1) return "START"; else if(n.id==-2) return "TERM"; else throw new Exception("node without known location id "+n.id); } public static boolean hasPath(String fileName) throws Exception { String []configurations={"predicateAnalysis.properties","bmc-incremental.properties","valueAnalysis-NoCegar.properties","valueAnalysis-Cegar.properties","kInduction-linear.properties"}; String config=configurations[4]; // System.err.println("Checker Started"); ProcessBuilder processBuilder = new ProcessBuilder("./"+Main.cpaDir+"/scripts/cpa.sh","-noout", "-config","cpachecker/config/"+config,fileName+".c") .redirectOutput(new File(fileName+"_cpa_out.txt")); Process process=processBuilder.start(); process.waitFor(); File output=new File(fileName+"_cpa_out.txt"); Scanner in=new Scanner(output); while(in.hasNextLine()) { String s=in.nextLine(); if (s.contains("FALSE.")) return true; } return false; } }
5,984
32.066298
193
java
null
RevTerm-main/code/prog_to_t2_linear/src/CFG.java
import java.util.Vector; public class CFG { public static Node startNode,endNode; public static Vector<Transition> edges=new Vector<>(); public static PairNode make(Node cur) throws Exception //makes the CFG of cur and returns the first and last statement. { if(cur.type.equals("stmtlist")) { Vector<PairNode> pairs=new Vector<>(); for(int i=0;i<cur.children.size();i++) { PairNode p= make(cur.children.elementAt(i)); pairs.add(p); } PairNode ret=new PairNode(pairs.firstElement().first,pairs.lastElement().second); boolean isStillFirst=false; for(int i=1;i<pairs.size();i++) { Transition t=getTransition(pairs.elementAt(i-1).second, pairs.elementAt(i).first,"consecution"); edges.add(t); } return ret; } else if(cur.type.equals("stmt")) { if(cur.rule.equals("if*")) { Node ifNode=cur; Node thenNode=cur.children.elementAt(0); Node elseNode=cur.children.elementAt(1); Node fiNode=cur.children.elementAt(2); PairNode p1= make(thenNode); PairNode p2= make(elseNode); Transition t1=getTransition(ifNode,p1.first,"if*-then"); Transition t2=getTransition(ifNode,p2.first,"if*-else"); Transition t3=getTransition(p1.second,fiNode,"then-fi*"); Transition t4=getTransition(p2.second,fiNode,"else-fi*"); edges.add(t1); edges.add(t2); edges.add(t3); edges.add(t4); return new PairNode(ifNode,fiNode); } else if(cur.rule.equals("affif")) { Node ifNode=cur; Node bexprNode=cur.children.elementAt(0); Node thenNode=cur.children.elementAt(1); Node elseNode=cur.children.elementAt(2); Node fiNode=cur.children.elementAt(3); PairNode p1= make(thenNode); PairNode p2= make(elseNode); Vector<LinearPredicate> guards=bexprNode.guard; for(LinearPredicate lp:guards) { Transition t = new Transition(ifNode, p1.first, "if-then",lp); edges.add(t); } Vector<LinearPredicate> notGuards=LinearPredicate.negate(guards); for(LinearPredicate lp:notGuards) { Transition t= new Transition(ifNode,p2.first,"if-else",lp); edges.add(t); } Transition t=getTransition(p1.second,fiNode,"then-fi"); edges.add(t); t=getTransition(p2.second,fiNode,"else-fi"); edges.add(t); return new PairNode(ifNode,fiNode); } else if(cur.rule.equals("while")) { Node whileNode=cur; Node bexprNode=cur.children.elementAt(0); Node doNode=cur.children.elementAt(1); Node odNode=cur.children.elementAt(2); PairNode p= make(doNode); Vector<LinearPredicate> guards=bexprNode.guard; for(LinearPredicate lp:guards) { Transition t = new Transition(whileNode, p.first, "while-do", lp); edges.add(t); } edges.add(getTransition(p.second,whileNode,"do-while")); Vector<LinearPredicate> notGuards=LinearPredicate.negate(guards); for(LinearPredicate lp:notGuards) { Transition t=new Transition(whileNode,odNode,"while-od",lp); edges.add(t); } return new PairNode(whileNode,odNode); } else return new PairNode(cur,cur); } else throw new Exception("requested CFG for node #"+cur.id+"which is of type:"+cur.type); } public static Transition getTransition(Node v,Node u,String type) { Transition t=new Transition(v,u,type); if(v.type.equals("stmt") && v.rule.equals("assignment")) { t.varName=v.varName; t.update=v.expr; } return t; } }
4,529
34.116279
126
java
null
RevTerm-main/code/prog_to_t2_linear/src/LinearCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class LinearCombination { Map<String,Rational> coef; public static LinearCombination one=new LinearCombination(Rational.one); LinearCombination() { coef=new HashMap<>(); } LinearCombination(Rational c) { coef=new HashMap<>(); coef.put("1",c); } LinearCombination(String var) { coef=new HashMap<>(); coef.put(var,Rational.one); } LinearCombination(String var,Rational c) { coef=new HashMap<>(); coef.put(var,c); } public void add(String var,Rational c) { if(coef.containsKey(var)) coef.put(var,Rational.add(coef.get(var),c)); else coef.put(var,c); } public void add(LinearCombination lc) { for(String var:lc.coef.keySet()) add(var,lc.coef.get(var)); } public void minus(LinearCombination lc) { add(lc.negate()); } public void multiplyByValue(Rational val) { for(String var:coef.keySet()) coef.put(var,Rational.mul(coef.get(var),val)); } public LinearCombination negate() //does not negate "this". returns the negate of "this". { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) lc.coef.put(var,Rational.negate(coef.get(var))); return lc; } public LinearCombination deepCopy() { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) { Rational c=coef.get(var); lc.add(var, c); } return lc; } public void multiplyByLin(LinearCombination lc) throws Exception { if (!isConstant() && !lc.isConstant()) throw new Exception("multiplication of two linear Expressions is not linear"); if (isConstant()) { Rational x = coef.get("1"); if (x == null) x = Rational.zero; coef.clear(); for (String var : lc.coef.keySet()) coef.put(var, Rational.mul(lc.coef.get(var), x)); } else { Rational x = lc.coef.get("1"); multiplyByValue(x); } } public boolean isConstant() { if (coef.size() > 1 || (coef.size() == 1 && !coef.containsKey("1"))) return false; return true; } public void removeZeros() { Vector<String> allVars=new Vector<>(); allVars.addAll(coef.keySet()); for(String s:allVars) if(coef.get(s).equals(Rational.zero)) coef.remove(s); } public boolean equals(LinearCombination lc) { removeZeros(); lc.removeZeros(); for (String var : coef.keySet()) if (!lc.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; for (String var : lc.coef.keySet()) if (!this.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; return true; } public String toString() { removeZeros(); if(coef.size()==0) return "0"; String ret=""; for(String s:coef.keySet()) { Rational c=coef.get(s); if(ret.equals("")) ret+=c.toString()+"*"+s; else if(coef.get(s).compareTo(Rational.zero)<0) ret+=" - "+(Rational.negate(c)).toString()+"*"+s; else ret+=" + "+c.toString()+"*"+s; } return ret; } }
3,789
23.451613
94
java
null
RevTerm-main/code/prog_to_t2_linear/src/LinearPredicate.java
import java.util.Vector; public class LinearPredicate { Vector<LinearCombination> exprs; LinearPredicate() { exprs=new Vector<>(); } void add(LinearCombination lc) { for(LinearCombination l:exprs) if(l!=null && l.equals(lc)) return; exprs.add(lc); } void add(LinearPredicate lp) { for(LinearCombination lc:lp.exprs) if(lc!=null) add(lc.deepCopy()); else exprs.add(null); } public Vector<LinearPredicate> negate() { Vector<LinearPredicate> ret=new Vector<>(); for(LinearCombination lc:exprs) { if(lc!=null) { LinearCombination l = lc.negate(); l.add("1", Rational.negate(prog_to_t2.eps)); LinearPredicate lp = new LinearPredicate(); lp.add(l); ret.add(lp); } else { LinearCombination l = null; LinearPredicate lp=new LinearPredicate(); lp.add(l); ret.add(lp); } } return ret; } public static Vector<LinearPredicate> negate(Vector<LinearPredicate> g) { Vector<LinearPredicate> ret=new Vector<>(); if(g.size()==1) ret = g.firstElement().negate(); else { Vector<LinearPredicate> notLast=g.lastElement().negate(); g.removeElementAt(g.size()-1); Vector<LinearPredicate> recurse=negate(g); for(LinearPredicate lp:notLast) for(LinearPredicate predicate:recurse) { LinearPredicate copy=predicate.deepCopy(); copy.add(lp); ret.add(copy); } } return ret; } public static Vector<LinearPredicate> conjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } if (right.isEmpty()) { for (LinearPredicate lp : left) ret.add(lp.deepCopy()); return ret; } for (LinearPredicate lp1 : left) for (LinearPredicate lp2 : right) { LinearPredicate lp = new LinearPredicate(); lp.add(lp1); lp.add(lp2); ret.add(lp); } return ret; } public static Vector<LinearPredicate> disjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); for (LinearPredicate lp : left) ret.add(lp.deepCopy()); for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } public LinearPredicate deepCopy() { LinearPredicate ret=new LinearPredicate(); ret.add(this); return ret; } public String toString() { String ret=""; for(LinearCombination lc:exprs) if(ret.equals("")) ret+=lc.toString()+">=0"; else ret+=" && "+lc.toString()+">=0"; return ret; } }
3,451
24.19708
111
java
null
RevTerm-main/code/prog_to_t2_linear/src/Node.java
import java.util.Vector; public class Node { public static Vector<Node> allNodes=new Vector<>(); int id; Node par; int beginIndex,endIndex; String type,rule; Vector<Node> children; String varName; LinearCombination expr; LinearPredicate preCondition; boolean inLoop; Vector<LinearPredicate> guard; Node(Node par,int beginIndex,int endIndex,String type,String rule,boolean inLoop) { allNodes.add(this); id=allNodes.size()-1; this.par=par; this.beginIndex=beginIndex; this.endIndex=endIndex; this.type=type; this.rule=rule; this.inLoop=inLoop; children=new Vector<>(); preCondition=null; if(par!=null) par.children.add(this); if(type.equals("bexpr") || type.equals("literal")) guard=new Vector<>(); else guard=null; varName=null; expr=null; } public String toString() { String ret=""; ret+="Node #"+id+"\n"; if(par!=null) ret+="Par: "+par.id+"\n"; else ret+="Par: null\n"; ret+="beginIndex="+beginIndex+"\t"+"endIndex="+endIndex+"\n"; ret+="type: "+type+"\n"; ret+="rule: "+rule+"\n"; ret+="inLoop: "+inLoop; if(type.equals("expr") || type.equals("term")) ret+="\nexpr: "+expr.toString(); if(type.equals("bexpr")) { ret+="\nguard: "; for (LinearPredicate lp : guard) ret += lp + " or "; } if(type.equals("stmt") && rule.equals("assignment")) { if(expr!=null) ret += "\nassignment: " + varName + ":=" + expr.toString(); else ret += "\nassignment: " + varName + ":= nondet()"; } if(preCondition!=null) ret+="\npre-condition:"+preCondition; return ret; } }
1,967
23.911392
85
java
null
RevTerm-main/code/prog_to_t2_linear/src/PairNode.java
public class PairNode { Node first; Node second; PairNode(Node a,Node b) { first=a; second=b; } }
135
10.333333
27
java
null
RevTerm-main/code/prog_to_t2_linear/src/Parser.java
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class Parser { public static Set<String> allVars=new HashSet<>(); public static Vector <String> tokens=new Vector<>(); static{ allVars.add("1"); } public static Node parseStmtList(Node p,int beginIndex,int endIndex,boolean inLoop) throws Exception { if(getToken(beginIndex).equals(";")) throw new Exception("stmtList cannot start with ; @"+beginIndex+"-"+endIndex); if(getToken(endIndex).equals(";")) throw new Exception("stmtList cannot end with ; @"+beginIndex+"-"+endIndex); Node cur=new Node(p,beginIndex,endIndex,"stmtlist","",inLoop); int afterPre=beginIndex-1; if(getToken(beginIndex).equals("#")) { for(int i=beginIndex+1;i<=endIndex;i++) if(getToken(i).equals("#")) afterPre=i; if(afterPre==beginIndex) throw new Exception("Pre-condition has no end"); Node pre=parseBexpr(null,beginIndex+1,afterPre-1); cur.preCondition=pre.guard.elementAt(0); } Vector<Integer> colons=new Vector<>(); colons.add(afterPre); int openIf=0,openWhile=0; for(int i=afterPre+1;i<=endIndex;i++) { if(getToken(i).equals("if")) openIf++; else if(getToken(i).equals("while")) openWhile++; else if(getToken(i).equals("fi")) openIf--; else if(getToken(i).equals("od")) openWhile--; else if(getToken(i).equals(";") && openIf==0 && openWhile==0) colons.add(i); if(openIf<0) throw new Exception("more fi's than if's @"+beginIndex+"-"+endIndex); if(openWhile<0) throw new Exception("more od's than while's @"+beginIndex+"-"+endIndex); } colons.add(endIndex+1); for(int i=1;i<colons.size();i++) parseStmt(cur,colons.elementAt(i-1)+1,colons.elementAt(i)-1,inLoop); return cur; } public static Node parseStmt(Node par,int beginIndex,int endIndex,boolean inLoop) throws Exception { // System.err.println(beginIndex+"---------"+endIndex); if(getToken(beginIndex).equals("skip")) { if(beginIndex!=endIndex) throw new Exception("skip node with beginIndex!=endIndex @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","skip",inLoop); return cur; } else if(getToken(beginIndex).equals("if")) //branching { if(!getToken(endIndex).equals("fi")) throw new Exception("if must end with fi @"+beginIndex+"-"+endIndex); // if(getToken(beginIndex+1).equals("*") || getToken(beginIndex+1).equals("_NONDET_")) //non-deterministic branching // { // int thenIndex=-1; // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("then")) // { // thenIndex=i; // break; // } // if(thenIndex==-1) // throw new Exception("if* without then @"+beginIndex+"-"+endIndex); // Node cur=new Node(par,beginIndex,endIndex,"stmt","if*",inLoop); // // int elseIndex=getElseOfIf(beginIndex+1,endIndex-1),fiIndex=endIndex; // Node thenNode=parseStmtList(cur,thenIndex+1,elseIndex-1,inLoop); // Node elseNode=parseStmtList(cur,elseIndex+1,fiIndex-1,inLoop); // Node fiNode=new Node(cur,fiIndex,fiIndex,"stmt","fi",inLoop); // // return cur; // } else //affine branching { int thenIndex=-1; for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("then")) { thenIndex=i; break; } if(thenIndex==-1) throw new Exception("if<bexpr> without then @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","affif",inLoop); int elseIndex=getElseOfIf(beginIndex+1,endIndex-1),fiIndex=endIndex,ifIndex=beginIndex; Node bexprNode= parseBexpr(cur,ifIndex+1,thenIndex-1); Node thenNode=parseStmtList(cur,thenIndex+1,elseIndex-1,inLoop); Node elseNode=parseStmtList(cur,elseIndex+1,fiIndex-1,inLoop); Node fiNode=new Node(cur,endIndex,endIndex,"stmt","fi",inLoop); return cur; } } else if(getToken(beginIndex).equals("while")) //while loop { if(!getToken(endIndex).equals("od")) throw new Exception("while does not end with od @"+beginIndex+"-"+endIndex); int whileIndex=beginIndex,doIndex=-1,odIndex=endIndex; for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("do")) { doIndex = i; break; } if(doIndex==-1) throw new Exception("while does not have do @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","while",true); Node bexprNode= parseBexpr(cur,whileIndex+1,doIndex-1); Node doNode=parseStmtList(cur,doIndex+1,odIndex-1,true); Node odNode=new Node(cur,endIndex,endIndex,"stmt","od",false); return cur; } else //assignment { int signIndex=beginIndex+1; if(!getToken(signIndex).equals(":=")) throw new Exception("assignment without ':=' @"+beginIndex+"-"+endIndex); String varName=getToken(beginIndex); allVars.add(varName); if(endIndex==beginIndex+2 && getToken(beginIndex+2).equals("_NONDET_")) { Node cur=new Node(par,beginIndex,endIndex,"stmt","assignment",inLoop); cur.expr=null; cur.varName=varName; return cur; } Node cur=new Node(par,beginIndex,endIndex,"stmt","assignment",inLoop); Node ch=parseExpr(cur,signIndex+1,endIndex); cur.expr=ch.expr; cur.varName=varName; return cur; } } public static Node parseBexpr(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseBexpr: "+beginIndex+"---"+endIndex); Node cur = new Node(par, beginIndex, endIndex, "Bexpr","Bexpr",false); if(cur.guard==null) cur.guard=new Vector<>(); Vector<Integer> ors = new Vector<>(); Vector<Integer> ands = new Vector<>(); ors.add(beginIndex - 1); ands.add(beginIndex - 1); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && getToken(i).equals("or")) { ors.add(i); } else if (openPar == 0 && getToken(i).equals("and")) { ands.add(i); } ors.add(endIndex + 1); ands.add(endIndex + 1); if (ors.size() > 2) { for (int i = 1; i < ors.size(); i++) { Node ch = parseBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 1); cur.guard = LinearPredicate.disjunct(cur.guard, ch.guard); } return cur; } if (ands.size() > 2) { for (int i = 1; i < ands.size(); i++) { Node ch = parseBexpr(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 1); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); } return cur; } boolean isCompletlyInsidePar = true; openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && i != endIndex) { isCompletlyInsidePar = false; break; } } if (isCompletlyInsidePar) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex - 1); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); return cur; } if (getToken(beginIndex).equals("!")) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex); cur.guard = LinearPredicate.negate(ch.guard); return cur; } Node ch = parseLiteral(cur, beginIndex, endIndex); cur.guard = LinearPredicate.conjunct(cur.guard, ch.guard); return cur; } public static Node parseLiteral(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseLiteral:"+ beginIndex+"---"+endIndex); int sgn = -1, type = -1; //types: 0: "<=" 1: ">=" 2: ">" 3: "<" 4: "==" 5: "!=" for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("<=")) { sgn = i; type = 0; } else if (getToken(i).equals(">=")) { sgn = i; type = 1; } else if (getToken(i).equals(">")) { sgn = i; type = 2; } else if (getToken(i).equals("<")) { sgn = i; type = 3; } else if (getToken(i).equals("==")) { sgn = i; type = 4; } else if (getToken(i).equals("!=")) { sgn = i; type = 5; } if (sgn == beginIndex || sgn == endIndex) throw new Exception("literal starts or ends with sign @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "literal","literal",false); for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("_NONDET_")) { LinearPredicate lp=new LinearPredicate(); lp.exprs.add(null); cur.guard.add(lp); return cur; } Node left = null; Node right = null; if (sgn == -1) { type = 5; left = parseExpr(cur, beginIndex, endIndex); right = new Node(cur, endIndex, endIndex, "0","0",false); right.expr = new LinearCombination(Rational.zero); } else { left = parseExpr(cur, beginIndex, sgn - 1); right = parseExpr(cur, sgn + 1, endIndex); } if (type == 0) //left<=right --> right-left>=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 1) //left>=right --> left-right>=0 { LinearCombination lc = left.expr.deepCopy(); lc.minus(right.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 2) // left > right -> left -right >=eps -> left - right -eps >=0 { LinearCombination lc = left.expr.deepCopy(); lc.minus(right.expr); // left - right lc.minus(new LinearCombination(prog_to_t2.eps)); // left - right - eps LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 3) //left < right --> right - left > eps --> right - left -eps >=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); // right - left lc.minus(new LinearCombination(prog_to_t2.eps)); // right - left - eps LinearPredicate lp = new LinearPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 4) //left==right --> left-right>=0 and right-left>=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); LinearCombination lc2 = left.expr.deepCopy(); lc2.minus(right.expr); LinearPredicate lp = new LinearPredicate(); lp.add(lc); lp.add(lc2); cur.guard.add(lp); } else if (type == 5) // left != right --> left - right -1 >=0 or right - left -1 >=0 { LinearCombination lc = right.expr.deepCopy(); lc.minus(left.expr); lc.minus(new LinearCombination(prog_to_t2.eps)); LinearCombination lc2 = left.expr.deepCopy(); lc2.minus(right.expr); lc2.minus(new LinearCombination(prog_to_t2.eps)); LinearPredicate lp1 = new LinearPredicate(), lp2 = new LinearPredicate(); lp1.add(lc); lp2.add(lc2); cur.guard.add(lp1); cur.guard.add(lp2); } return cur; } // public static Node parseOrBexpr(Node par, int beginIndex, int endIndex) throws Exception // { // // Vector<Integer> ors=new Vector<>(); // ors.add(beginIndex-1); // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("or")) // ors.add(i); // ors.add(endIndex+1); // // Node cur=new Node(par,beginIndex,endIndex,"bexpr","or",false); // for (int i = 1; i < ors.size(); i++) // { // Node ch=parseAndBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 1); // cur.guard.add(ch.guard.firstElement()); // } // // return cur; // } // public static Node parseAndBexpr(Node par, int beginIndex, int endIndex) throws Exception // { // Vector<Integer> ands=new Vector<>(); // ands.add(beginIndex-1); // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("and")) // ands.add(i); // ands.add(endIndex+1); // Node cur=new Node(par,beginIndex,endIndex,"bexpr","and",false); // LinearPredicate lp=new LinearPredicate(); // for(int i=1;i<ands.size();i++) // { // Node ch=parseLiteral(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 1); // lp.add(ch.guard.firstElement()); // } // cur.guard.add(lp); // return cur; // } // public static Node parseLiteral(Node par,int beginIndex,int endIndex) throws Exception // { // int sgn=-1,type=-1; //types: 0-> "<=" 1->">=" // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("<=")) // { // sgn=i; // type=0; // } // else if(getToken(i).equals(">=")) // { // sgn=i; // type=1; // } // else if(getToken(i).equals(">")) // { // sgn=i; // type=2; // } // else if(getToken(i).equals("<")) // { // sgn=i; // type=3; // } // else if(getToken(i).equals("==")) // { // sgn=i; // type=4; // } // else if(getToken(i).equals("!=")) // { // sgn=i; // type=5; // } // if(sgn==beginIndex || sgn==endIndex) // throw new Exception("literal starts or ends with sign @"+beginIndex+"-"+endIndex); // if(sgn==-1) // throw new Exception("no sign found for literal @"+beginIndex+"-"+endIndex); // Node cur=new Node(par,beginIndex,endIndex,"literal",getToken(sgn),false); // Node left=parseExpr(cur,beginIndex,sgn-1); // Node right=parseExpr(cur,sgn+1,endIndex); // if(type==0) //left<=right -> right-left>=0 // { // LinearCombination lc=right.expr.deepCopy(); // lc.minus(left.expr); // LinearPredicate lp=new LinearPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==1) //left>=right -> left-right>=0 // { // LinearCombination lc=left.expr.deepCopy(); // lc.minus(right.expr); // LinearPredicate lp=new LinearPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==2) // left > right -> left -right >=eps -> left - right -eps >=0 // { // LinearCombination lc=left.expr.deepCopy(); // lc.minus(right.expr); // left - right // lc.minus(new LinearCombination(prog_to_t2.eps)); // left - right - eps // LinearPredicate lp=new LinearPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==3) //left < right -> right - left > eps -> right - left -eps >=0 // { // LinearCombination lc=right.expr.deepCopy(); // lc.minus(left.expr); // right - left // lc.minus(new LinearCombination(prog_to_t2.eps)); // right - left - eps // LinearPredicate lp=new LinearPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==4) //left==right -> left-right>=0 and left - right <=0 // { // LinearCombination lc=left.expr.deepCopy(),lc2=right.expr.deepCopy(); // lc.minus(right.expr); // lc2.minus(left.expr); // LinearPredicate lp=new LinearPredicate(); // lp.add(lc); // lp.add(lc2); // cur.guard.add(lp); // } // else if(type==5) //left != right -> left > right || right > left -> left - right -eps >=0 || right - left - eps >=0 // { // LinearCombination lc=left.expr.deepCopy(),lc2=right.expr.deepCopy(); // lc.minus(right.expr); // lc2.minus(left.expr); // lc.minus(new LinearCombination(prog_to_t2.eps)); // lc2.minus(new LinearCombination(prog_to_t2.eps)); // LinearPredicate lp=new LinearPredicate(),lp2=new LinearPredicate(); // lp.add(lc); // lp2.add(lc2); // cur.guard.add(lp); // cur.guard.add(lp2); // } // return cur; // } public static Node parseExpr(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseExpr: "+beginIndex+"----"+endIndex); Vector<Integer> signIndex = new Vector<>(); Vector<String> signType = new Vector<>(); if (!getToken(beginIndex).equals("-")) { signIndex.add(beginIndex - 1); signType.add("+"); } int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && (getToken(i).equals("+") || (getToken(i).equals("-") && (i - 1 < beginIndex || (i - 1 >= beginIndex && !getToken(i - 1).equals("*") && !getToken(i - 1).equals("+")))))) { signIndex.add(i); signType.add(getToken(i)); } } signIndex.add(endIndex + 1); signType.add("+"); Node cur = new Node(par, beginIndex, endIndex, "expr","expr",false); cur.expr = new LinearCombination(); for (int i = 0; i + 1 < signIndex.size(); i++) { Node ch = parseTerm(cur, signIndex.elementAt(i) + 1, signIndex.elementAt(i + 1) - 1); if (signType.elementAt(i).equals("+")) cur.expr.add(ch.expr); else cur.expr.minus(ch.expr); } return cur; } public static Node parseTerm(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseTerm: "+beginIndex+"---"+endIndex); if ((beginIndex == endIndex && isNumeric(getToken(beginIndex)))) //constant { Node cur = new Node(par, beginIndex, endIndex, "term","constant",false); int val = Integer.parseInt(getToken(beginIndex)); cur.expr = new LinearCombination(); cur.expr.add("1", new Rational(val, 1)); return cur; } else if (beginIndex == endIndex - 1 && isNumeric(getToken(endIndex))) //negative constant { Node cur = new Node(par, beginIndex, endIndex,"term", "constant",false); int val = -Integer.parseInt(getToken(endIndex)); cur.expr = new LinearCombination(); cur.expr.add("1", new Rational(val, 1)); return cur; } else if (beginIndex == endIndex) //var { Node cur = new Node(par, beginIndex, endIndex,"term", "var",false); String var = getToken(beginIndex); allVars.add(var); if (Character.isDigit(var.charAt(0))) throw new Exception("Incorrect var name @" + beginIndex); cur.expr = new LinearCombination(); cur.expr.add(var, new Rational(1, 1)); return cur; } else // (...) or [] * [] { Node cur = new Node(par, beginIndex, endIndex,"term", "term mul",false); cur.expr = new LinearCombination(); Vector<Integer> sgnIndex = new Vector<>(); Vector<String> sgnType = new Vector<>(); sgnIndex.add(beginIndex - 1); sgnType.add("*"); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && (getToken(i).equals("*") || getToken(i).equals("/"))) { sgnIndex.add(i); sgnType.add(getToken(i)); } else if (getToken(i).equals("%")) { throw new Exception("% is not supported. @" + beginIndex + "-" + endIndex); } sgnIndex.add(endIndex + 1); sgnType.add("*"); if (sgnIndex.size() == 2) // (...) { Node ch = parseExpr(cur, beginIndex + 1, endIndex - 1); cur.expr = ch.expr; return cur; } else { cur.expr.add("1", Rational.one); for (int i = 1; i < sgnIndex.size(); i++) { Node ch = parseExpr(cur, sgnIndex.elementAt(i - 1) + 1, sgnIndex.elementAt(i) - 1); if (sgnType.elementAt(i - 1).equals("*")) cur.expr.multiplyByLin(ch.expr); else if (ch.expr.isConstant() && ch.expr.coef.containsKey("1")) cur.expr.multiplyByValue(Rational.inverse(ch.expr.coef.get("1"))); else throw new Exception("Divison by variable is not possible @" + beginIndex + "-" + endIndex); } return cur; } } } public static int getElseOfIf(int beginIndex,int endIndex) throws Exception { int openIf=0,openWhile=0; for(int i=beginIndex;i<=endIndex;i++) { if(getToken(i).equals("if")) openIf++; else if(getToken(i).equals("fi")) openIf--; else if(getToken(i).equals("while")) openWhile++; else if(getToken(i).equals("od")) openWhile--; else if(openIf==0 && openWhile==0 && getToken(i).equals("else")) return i; } throw new Exception("no else found for if @"+beginIndex+"-"+endIndex); } public static boolean isNumeric(String s) { for(int i=0;i<s.length();i++) if(!Character.isDigit(s.charAt(i)) && s.charAt(i)!='.') return false; return true; } public static int getTokenCount() { return tokens.size(); } public static String getToken(int x) { return tokens.elementAt(x); } public static void readTokens(String program) throws Exception { String extraSpace=""; for(int i=0;i<program.length();i++) { char c=program.charAt(i); if(c=='.' || Character.isAlphabetic(c) || Character.isDigit(c) || c=='_') extraSpace+=c; else { extraSpace+=" "; extraSpace+=c; extraSpace+=" "; } } Scanner scanner=new Scanner(extraSpace); while(scanner.hasNext()) { String s=scanner.next(); if(s.equals("=")) { if(tokens.size()==0) throw new Exception("program cannot start with ="); String last=tokens.lastElement(); if(last.equals(":") || last.equals(">") || last.equals("<") || last.equals("=") || last.equals("!")) { tokens.removeElementAt(getTokenCount() - 1); last += s; tokens.add(last); } else tokens.add(s); } else tokens.add(s); } } public static void readFile(String fileName) throws Exception { File file=new File(fileName); Scanner in=new Scanner(file); String program=""; boolean mainPartHasStarted=false; while(in.hasNextLine()) { String s=in.nextLine(); if(s.contains("if") || s.contains("while")) mainPartHasStarted=true; if(!mainPartHasStarted && s.contains("_NONDET_")) continue; program += s + " "; } readTokens(program); // System.err.println("tokens are:"); // for(int i=0;i<tokens.size();i++) // System.err.println(i+": "+getToken(i)); } }
27,053
35.708277
163
java
null
RevTerm-main/code/prog_to_t2_linear/src/Rational.java
import java.util.EnumMap; public class Rational implements Comparable<Rational> { public static final Rational one=new Rational(1,1),zero=new Rational(0,1); int numerator,denominator; public int gcd(int a, int b) { if (b==0) return a; return gcd(b,a%b); } Rational(int numerator,int denominator) { if(numerator==0) { this.numerator=0; this.denominator=1; return; } if(denominator<0) { denominator*=-1; numerator*=-1; } int g=gcd(numerator,denominator); this.numerator=numerator/g; this.denominator=denominator/g; } public static Rational negate(Rational a) { return new Rational(-a.numerator,a.denominator); } public static Rational inverse(Rational a) throws Exception { if(a.numerator==0) throw new Exception("getting inverse of "+a+" which is not defined"); return new Rational(a.denominator,a.numerator); } public static Rational add(Rational a,Rational b) { return new Rational(a.numerator*b.denominator+b.numerator*a.denominator,a.denominator*b.denominator); } public static Rational minus(Rational a,Rational b) { return add(a,negate(b)); } public static Rational mul(Rational a,Rational b) { return new Rational(a.numerator*b.numerator,a.denominator*b.denominator); } public static Rational div(Rational a,Rational b) throws Exception { return mul(a,inverse(b)); } public boolean equals(Rational a) { return (a.numerator== numerator && a.denominator==denominator); } public boolean isNonNegative() { return (numerator>=0); } @Override public int compareTo(Rational a) { return numerator*a.denominator-a.numerator*denominator; } public void normalize() { if(denominator<0) { numerator*=-1; denominator*=-1; } } public String toString() { if(denominator==1) return ""+numerator; return "("+numerator+"/"+denominator+")"; } }
2,231
21.09901
109
java
null
RevTerm-main/code/prog_to_t2_linear/src/Transition.java
public class Transition //from "v.first" to "v.second" with guard "g" and update "varName := update" { PairNode v; LinearPredicate guard; String varName; LinearCombination update; //when varName is not null but update is null then 'varName \in (-inf,inf)' is the assignment String type; Transition(Node a,Node b,String type) { v=new PairNode(a,b); this.type=type; guard=null; varName=null; update=null; } Transition(Node a,Node b,String type,LinearPredicate guard) { v=new PairNode(a,b); this.type=type; this.guard=guard; varName=null; update=null; } Transition(Node a,Node b,String type,String varName,LinearCombination update) { v=new PairNode(a,b); this.type=type; this.varName=varName; this.update=update; guard=null; } public String toString() { String res=""; res+="FROM: "+v.first.id+";"; if(guard!=null) { for(LinearCombination lc:guard.exprs) if(lc!=null) res += "\nassume(" + lc + ">=0);"; else res+="\nassume(nondet()!=0)"; } else if(type.equals("if*-then")) ; //it will be handled in T2 parser/cfg maker if(update!=null) res+="\n"+varName+" := "+update.toString()+";"; else if(varName!=null) res+="\n"+varName+" := nondet();"; res+="\nTO: "+v.second.id+";"; return res; } }
1,588
23.828125
124
java
null
RevTerm-main/code/prog_to_t2_linear/src/prog_to_t2.java
import java.io.FileWriter; public class prog_to_t2 { public static Rational eps=Rational.one; public static void main(String[] args) throws Exception { String input=args[0]; String output=args[1]; int con=1,dis=2; long startTime=System.currentTimeMillis(); //System.exit(0); Parser.readFile(input); //CFG.startNode=new Node(null,-1,-1,"startNode","",false); Node root=Parser.parseStmtList(null,0,Parser.getTokenCount()-1,false); //CFG.startNode.preCondition=root.preCondition; // for(Node n:Node.allNodes) // { // System.err.println("---------------------------"); // System.err.println(n.toString()); // System.err.println("---------------------------"); // } CFG.endNode=new Node(null,-1,-1,"endNode","",false); PairNode p=CFG.make(root); CFG.startNode=p.first; CFG.edges.add(CFG.getTransition(p.second,CFG.endNode,"to end")); FileWriter fw=new FileWriter(output); fw.write("START: "+CFG.startNode.id+";\n\n"); for(Transition t:CFG.edges) fw.write(t.toString()+"\n\n"); fw.close(); } }
1,216
27.302326
78
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/CFG.java
import java.util.Vector; public class CFG { public static Node startNode,endNode; public static Vector<Transition> edges=new Vector<>(); public static PairNode make(Node cur) throws Exception //makes the CFG of cur and returns the first and last statement. { if(cur.type.equals("stmtlist")) { Vector<PairNode> pairs=new Vector<>(); for(int i=0;i<cur.children.size();i++) { PairNode p= make(cur.children.elementAt(i)); pairs.add(p); } PairNode ret=new PairNode(pairs.firstElement().first,pairs.lastElement().second); boolean isStillFirst=false; for(int i=1;i<pairs.size();i++) { Transition t=getTransition(pairs.elementAt(i-1).second, pairs.elementAt(i).first,"consecution"); edges.add(t); } return ret; } else if(cur.type.equals("stmt")) { if(cur.rule.equals("if*")) { Node ifNode=cur; Node thenNode=cur.children.elementAt(0); Node elseNode=cur.children.elementAt(1); Node fiNode=cur.children.elementAt(2); PairNode p1= make(thenNode); PairNode p2= make(elseNode); Transition t1=getTransition(ifNode,p1.first,"if*-then"); Transition t2=getTransition(ifNode,p2.first,"if*-else"); Transition t3=getTransition(p1.second,fiNode,"then-fi*"); Transition t4=getTransition(p2.second,fiNode,"else-fi*"); edges.add(t1); edges.add(t2); edges.add(t3); edges.add(t4); return new PairNode(ifNode,fiNode); } else if(cur.rule.equals("affif")) { Node ifNode=cur; Node bexprNode=cur.children.elementAt(0); Node thenNode=cur.children.elementAt(1); Node elseNode=cur.children.elementAt(2); Node fiNode=cur.children.elementAt(3); PairNode p1= make(thenNode); PairNode p2= make(elseNode); Vector<PolynomialPredicate> guards=bexprNode.guard; for(PolynomialPredicate lp:guards) { Transition t = new Transition(ifNode, p1.first, "if-then",lp); edges.add(t); } Vector<PolynomialPredicate> notGuards=PolynomialPredicate.negate(guards,0); for(PolynomialPredicate lp:notGuards) { Transition t= new Transition(ifNode,p2.first,"if-else",lp); edges.add(t); } Transition t=getTransition(p1.second,fiNode,"then-fi"); edges.add(t); t=getTransition(p2.second,fiNode,"else-fi"); edges.add(t); return new PairNode(ifNode,fiNode); } else if(cur.rule.equals("while")) { Node whileNode=cur; Node bexprNode=cur.children.elementAt(0); Node doNode=cur.children.elementAt(1); Node odNode=cur.children.elementAt(2); PairNode p= make(doNode); Vector<PolynomialPredicate> guards=bexprNode.guard; for(PolynomialPredicate lp:guards) { Transition t = new Transition(whileNode, p.first, "while-do", lp); edges.add(t); } edges.add(getTransition(p.second,whileNode,"do-while")); Vector<PolynomialPredicate> notGuards=PolynomialPredicate.negate(guards,0); for(PolynomialPredicate lp:notGuards) { Transition t=new Transition(whileNode,odNode,"while-od",lp); edges.add(t); } return new PairNode(whileNode,odNode); } else return new PairNode(cur,cur); } else throw new Exception("requested CFG for node #"+cur.id+"which is of type:"+cur.type); } public static Transition getTransition(Node v,Node u,String type) { Transition t=new Transition(v,u,type); if(v.type.equals("stmt") && v.rule.equals("assignment")) { t.varName=v.varName; t.update=v.expr; } return t; } }
4,573
34.457364
126
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/LinearCombination.java
import java.text.DecimalFormat; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class LinearCombination { Map<String,Rational> coef; public static LinearCombination one=new LinearCombination(Rational.one); LinearCombination() { coef=new HashMap<>(); } LinearCombination(Rational c) { coef=new HashMap<>(); coef.put("1",c); } LinearCombination(String var) { coef=new HashMap<>(); coef.put(var,Rational.one); } LinearCombination(String var,Rational c) { coef=new HashMap<>(); coef.put(var,c); } public void add(String var,Rational c) { if(coef.containsKey(var)) coef.put(var,Rational.add(coef.get(var),c)); else coef.put(var,c); } public void add(LinearCombination lc) { for(String var:lc.coef.keySet()) add(var,lc.coef.get(var)); } public void minus(LinearCombination lc) { add(lc.negate()); } public void multiplyByValue(Rational val) { for(String var:coef.keySet()) coef.put(var,Rational.mul(coef.get(var),val)); } public LinearCombination negate() //does not negate "this". returns the negate of "this". { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) lc.coef.put(var,Rational.negate(coef.get(var))); return lc; } public LinearCombination deepCopy() { removeZeros(); LinearCombination lc=new LinearCombination(); for(String var:coef.keySet()) { Rational c=coef.get(var); lc.add(var, c); } return lc; } public void multiplyByLin(LinearCombination lc) throws Exception { if (!isConstant() && !lc.isConstant()) throw new Exception("multiplication of two linear Expressions is not linear"); if (isConstant()) { Rational x = coef.get("1"); if (x == null) x = Rational.zero; coef.clear(); for (String var : lc.coef.keySet()) coef.put(var, Rational.mul(lc.coef.get(var), x)); } else { Rational x = lc.coef.get("1"); multiplyByValue(x); } } public boolean isConstant() { if (coef.size() > 1 || (coef.size() == 1 && !coef.containsKey("1"))) return false; return true; } public void removeZeros() { Vector<String> allVars=new Vector<>(); allVars.addAll(coef.keySet()); for(String s:allVars) if(coef.get(s).equals(Rational.zero)) coef.remove(s); } public boolean equals(LinearCombination lc) { removeZeros(); lc.removeZeros(); for (String var : coef.keySet()) if (!lc.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; for (String var : lc.coef.keySet()) if (!this.coef.containsKey(var) || !lc.coef.get(var).equals(this.coef.get(var))) return false; return true; } public String toString() { removeZeros(); if(coef.size()==0) return "0"; String ret=""; for(String s:coef.keySet()) { Rational c=coef.get(s); if(ret.equals("")) ret+=c.toString()+"*"+s; else if(coef.get(s).compareTo(Rational.zero)<0) ret+=" - "+(Rational.negate(c)).toString()+"*"+s; else ret+=" + "+c.toString()+"*"+s; } return ret; } }
3,789
23.451613
94
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/LinearPredicate.java
import java.util.Vector; public class LinearPredicate { Vector<LinearCombination> exprs; LinearPredicate() { exprs=new Vector<>(); } void add(LinearCombination lc) { for(LinearCombination l:exprs) if(l!=null && l.equals(lc)) return; exprs.add(lc); } void add(LinearPredicate lp) { for(LinearCombination lc:lp.exprs) if(lc!=null) add(lc.deepCopy()); else exprs.add(null); } public Vector<LinearPredicate> negate() { Vector<LinearPredicate> ret=new Vector<>(); for(LinearCombination lc:exprs) { if(lc!=null) { LinearCombination l = lc.negate(); l.add("1", Rational.negate(prog_to_t2.eps)); LinearPredicate lp = new LinearPredicate(); lp.add(l); ret.add(lp); } else { LinearCombination l = null; LinearPredicate lp=new LinearPredicate(); lp.add(l); ret.add(lp); } } return ret; } public static Vector<LinearPredicate> negate(Vector<LinearPredicate> g) { Vector<LinearPredicate> ret=new Vector<>(); if(g.size()==1) ret = g.firstElement().negate(); else { Vector<LinearPredicate> notLast=g.lastElement().negate(); g.removeElementAt(g.size()-1); Vector<LinearPredicate> recurse=negate(g); for(LinearPredicate lp:notLast) for(LinearPredicate predicate:recurse) { LinearPredicate copy=predicate.deepCopy(); copy.add(lp); ret.add(copy); } } return ret; } public static Vector<LinearPredicate> conjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } if (right.isEmpty()) { for (LinearPredicate lp : left) ret.add(lp.deepCopy()); return ret; } for (LinearPredicate lp1 : left) for (LinearPredicate lp2 : right) { LinearPredicate lp = new LinearPredicate(); lp.add(lp1); lp.add(lp2); ret.add(lp); } return ret; } public static Vector<LinearPredicate> disjunct(Vector<LinearPredicate> left, Vector<LinearPredicate> right) { Vector<LinearPredicate> ret = new Vector<>(); for (LinearPredicate lp : left) ret.add(lp.deepCopy()); for (LinearPredicate lp : right) ret.add(lp.deepCopy()); return ret; } public LinearPredicate deepCopy() { LinearPredicate ret=new LinearPredicate(); ret.add(this); return ret; } public String toString() { String ret=""; for(LinearCombination lc:exprs) if(ret.equals("")) ret+=lc.toString()+">=0"; else ret+=" && "+lc.toString()+">=0"; return ret; } }
3,451
24.19708
111
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Monomial.java
import java.util.*; public class Monomial implements Comparable<Monomial> { Map<String, Integer> vars; public static final Monomial one = new Monomial(); Monomial() { vars = new TreeMap<>(); } Monomial(String var) { vars=new TreeMap<>(); addVar(var,1); } Monomial(String var,int power) { vars= new TreeMap<>(); addVar(var,power); } void addVar(String varName, int power) { if (vars.containsKey(varName)) vars.put(varName, vars.get(varName) + power); else vars.put(varName, power); } Map<String, Integer> getVars() { return vars; } public static Monomial mul(Monomial a, Monomial b) { Monomial ret = new Monomial(); Map<String, Integer> avars = a.getVars(), bvars = b.getVars(); for (String varName : avars.keySet()) ret.addVar(varName, avars.get(varName)); for (String varName : bvars.keySet()) ret.addVar(varName, bvars.get(varName)); return ret; } Monomial deepCopy() { Monomial ret = new Monomial(); for (String varName : vars.keySet()) ret.addVar(varName, vars.get(varName)); return ret; } boolean containsVar(String var) { return vars.containsKey(var); } Monomial removeOneVar(String var) { Monomial ret = new Monomial(); for (String s : vars.keySet()) if (!s.equals(var)) ret.addVar(s, vars.get(s)); return ret; } int getPower(String var) { return vars.get(var); } public Monomial programVarsPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial unknownPart() { Monomial ret = new Monomial(); for(String var:vars.keySet()) if(var.startsWith("c_") || var.startsWith("t_") || var.startsWith("l_")) //TODO: write a function for this if ret.addVar(var,getPower(var)); return ret; } public Monomial getProgramVarsPart() { Monomial ret=new Monomial(); for(String var:vars.keySet()) if(!var.startsWith("c_") && !var.startsWith("t_") && !var.startsWith("l_")) ret.addVar(var,getPower(var)); return ret; } public static Set<Monomial> getAllMonomials(Set<String> vars, int degree) { Set<Monomial> ret=new TreeSet<>(); if(degree==0) ret.add(Monomial.one.deepCopy()); else { Set<Monomial> recurse = getAllMonomials(vars,degree-1); for(Monomial m:recurse) ret.add(m.deepCopy()); for(String var:vars) for(Monomial m:recurse) { if(m.degree()==degree-1) { Monomial tmp = m.deepCopy(); tmp.addVar(var, 1); ret.add(tmp); } } } return ret; } int degree() { int ret=0; for(String var:vars.keySet()) ret+=vars.get(var); return ret; } public int compareTo(Monomial m) { return (toNormalString().compareTo(m.toNormalString())); } void removeZeros() { Vector<String> allVars=new Vector<>(vars.keySet()); for(String var:allVars) if(getPower(var)==0) vars.remove(var); } public boolean equals(Monomial m) { removeZeros(); m.removeZeros(); for(String var:vars.keySet()) if(!m.containsVar(var) || m.getPower(var)!=getPower(var)) return false; for(String var:m.vars.keySet()) if(!this.containsVar(var)) return false; return true; } String toNormalString() { if (vars.isEmpty()) return "1"; String ret = ""; for (String varName : vars.keySet()) { if (!ret.equals("")) ret+=" * "; int power=vars.get(varName); for(int i=0;i<power;i++) { ret += varName; if(i!=power-1) ret+="*"; } // if(vars.get(varName)!=1) // { // ret += "^" + vars.get(varName); // } } return ret; } public String toString() { return toNormalString(); // if (vars.isEmpty()) // return "1"; // // // String ret = ""; // for (String varName : vars.keySet()) // { // for (int i = 0; i < vars.get(varName); i++) // ret += varName + " "; // } //// ret += ")"; // return ret; } }
5,104
23.425837
125
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Node.java
import java.util.Vector; public class Node { public static Vector<Node> allNodes=new Vector<>(); int id; Node par; int beginIndex,endIndex; String type,rule; Vector<Node> children; String varName; Polynomial expr; PolynomialPredicate preCondition; boolean inLoop; Vector<PolynomialPredicate> guard; Node(Node par,int beginIndex,int endIndex,String type,String rule,boolean inLoop) { allNodes.add(this); id=allNodes.size()-1; this.par=par; this.beginIndex=beginIndex; this.endIndex=endIndex; this.type=type; this.rule=rule; this.inLoop=inLoop; children=new Vector<>(); preCondition=null; if(par!=null) par.children.add(this); if(type.equals("bexpr") || type.equals("literal")) guard=new Vector<>(); else guard=null; varName=null; expr=null; } public String toString() { String ret=""; ret+="Node #"+id+"\n"; if(par!=null) ret+="Par: "+par.id+"\n"; else ret+="Par: null\n"; ret+="beginIndex="+beginIndex+"\t"+"endIndex="+endIndex+"\n"; ret+="type: "+type+"\n"; ret+="rule: "+rule+"\n"; ret+="inLoop: "+inLoop; if(type.equals("expr") || type.equals("term")) ret+="\nexpr: "+expr.toString(); if(type.equals("bexpr")) { ret+="\nguard: "; for (PolynomialPredicate lp : guard) ret += lp + " or "; } if(type.equals("stmt") && rule.equals("assignment")) { if(expr!=null) ret += "\nassignment: " + varName + ":=" + expr.toString(); else ret += "\nassignment: " + varName + ":= nondet()"; } if(preCondition!=null) ret+="\npre-condition:"+preCondition; return ret; } }
1,972
23.974684
85
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/PairNode.java
public class PairNode { Node first; Node second; PairNode(Node a,Node b) { first=a; second=b; } }
135
10.333333
27
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Parser.java
import java.io.File; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class Parser { public static Set<String> allVars=new HashSet<>(); public static Vector <String> tokens=new Vector<>(); static{ allVars.add("1"); } public static Node parseStmtList(Node p,int beginIndex,int endIndex,boolean inLoop) throws Exception { if(getToken(beginIndex).equals(";")) throw new Exception("stmtList cannot start with ; @"+beginIndex+"-"+endIndex); if(getToken(endIndex).equals(";")) throw new Exception("stmtList cannot end with ; @"+beginIndex+"-"+endIndex); Node cur=new Node(p,beginIndex,endIndex,"stmtlist","",inLoop); int afterPre=beginIndex-1; if(getToken(beginIndex).equals("#")) { for(int i=beginIndex+1;i<=endIndex;i++) if(getToken(i).equals("#")) afterPre=i; if(afterPre==beginIndex) throw new Exception("Pre-condition has no end"); Node pre=parseBexpr(null,beginIndex+1,afterPre-1); cur.preCondition=pre.guard.elementAt(0); } Vector<Integer> colons=new Vector<>(); colons.add(afterPre); int openIf=0,openWhile=0; for(int i=afterPre+1;i<=endIndex;i++) { if(getToken(i).equals("if")) openIf++; else if(getToken(i).equals("while")) openWhile++; else if(getToken(i).equals("fi")) openIf--; else if(getToken(i).equals("od")) openWhile--; else if(getToken(i).equals(";") && openIf==0 && openWhile==0) colons.add(i); if(openIf<0) throw new Exception("more fi's than if's @"+beginIndex+"-"+endIndex); if(openWhile<0) throw new Exception("more od's than while's @"+beginIndex+"-"+endIndex); } colons.add(endIndex+1); for(int i=1;i<colons.size();i++) parseStmt(cur,colons.elementAt(i-1)+1,colons.elementAt(i)-1,inLoop); return cur; } public static Node parseStmt(Node par,int beginIndex,int endIndex,boolean inLoop) throws Exception { // System.err.println(beginIndex+"---------"+endIndex); if(getToken(beginIndex).equals("skip")) { if(beginIndex!=endIndex) throw new Exception("skip node with beginIndex!=endIndex @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","skip",inLoop); return cur; } else if(getToken(beginIndex).equals("if")) //branching { if(!getToken(endIndex).equals("fi")) throw new Exception("if must end with fi @"+beginIndex+"-"+endIndex); // if(getToken(beginIndex+1).equals("*") || getToken(beginIndex+1).equals("_NONDET_")) //non-deterministic branching // { // int thenIndex=-1; // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("then")) // { // thenIndex=i; // break; // } // if(thenIndex==-1) // throw new Exception("if* without then @"+beginIndex+"-"+endIndex); // Node cur=new Node(par,beginIndex,endIndex,"stmt","if*",inLoop); // // int elseIndex=getElseOfIf(beginIndex+1,endIndex-1),fiIndex=endIndex; // Node thenNode=parseStmtList(cur,thenIndex+1,elseIndex-1,inLoop); // Node elseNode=parseStmtList(cur,elseIndex+1,fiIndex-1,inLoop); // Node fiNode=new Node(cur,fiIndex,fiIndex,"stmt","fi",inLoop); // // return cur; // } else //affine branching { int thenIndex=-1; for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("then")) { thenIndex=i; break; } if(thenIndex==-1) throw new Exception("if<bexpr> without then @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","affif",inLoop); int elseIndex=getElseOfIf(beginIndex+1,endIndex-1),fiIndex=endIndex,ifIndex=beginIndex; Node bexprNode= parseBexpr(cur,ifIndex+1,thenIndex-1); Node thenNode=parseStmtList(cur,thenIndex+1,elseIndex-1,inLoop); Node elseNode=parseStmtList(cur,elseIndex+1,fiIndex-1,inLoop); Node fiNode=new Node(cur,endIndex,endIndex,"stmt","fi",inLoop); return cur; } } else if(getToken(beginIndex).equals("while")) //while loop { if(!getToken(endIndex).equals("od")) throw new Exception("while does not end with od @"+beginIndex+"-"+endIndex); int whileIndex=beginIndex,doIndex=-1,odIndex=endIndex; for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("do")) { doIndex = i; break; } if(doIndex==-1) throw new Exception("while does not have do @"+beginIndex+"-"+endIndex); Node cur=new Node(par,beginIndex,endIndex,"stmt","while",true); Node bexprNode= parseBexpr(cur,whileIndex+1,doIndex-1); Node doNode=parseStmtList(cur,doIndex+1,odIndex-1,true); Node odNode=new Node(cur,endIndex,endIndex,"stmt","od",false); return cur; } else //assignment { int signIndex=beginIndex+1; if(!getToken(signIndex).equals(":=")) throw new Exception("assignment without ':=' @"+beginIndex+"-"+endIndex); String varName=getToken(beginIndex); allVars.add(varName); if(endIndex==beginIndex+2 && getToken(beginIndex+2).equals("_NONDET_")) { Node cur=new Node(par,beginIndex,endIndex,"stmt","assignment",inLoop); cur.expr=null; cur.varName=varName; return cur; } Node cur=new Node(par,beginIndex,endIndex,"stmt","assignment",inLoop); Node ch=parseExpr(cur,signIndex+1,endIndex); cur.expr=ch.expr; cur.varName=varName; return cur; } } public static Node parseBexpr(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseBexpr: "+beginIndex+"---"+endIndex); Node cur = new Node(par, beginIndex, endIndex, "Bexpr","Bexpr",false); if(cur.guard==null) cur.guard=new Vector<>(); Vector<Integer> ors = new Vector<>(); Vector<Integer> ands = new Vector<>(); ors.add(beginIndex - 1); ands.add(beginIndex - 1); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && getToken(i).equals("or")) { ors.add(i); } else if (openPar == 0 && getToken(i).equals("and")) { ands.add(i); } ors.add(endIndex + 1); ands.add(endIndex + 1); if (ors.size() > 2) { for (int i = 1; i < ors.size(); i++) { Node ch = parseBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 1); cur.guard = PolynomialPredicate.disjunct(cur.guard, ch.guard); } return cur; } if (ands.size() > 2) { for (int i = 1; i < ands.size(); i++) { Node ch = parseBexpr(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 1); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); } return cur; } boolean isCompletlyInsidePar = true; openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && i != endIndex) { isCompletlyInsidePar = false; break; } } if (isCompletlyInsidePar) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex - 1); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } if (getToken(beginIndex).equals("!")) { Node ch = parseBexpr(cur, beginIndex + 1, endIndex); cur.guard = PolynomialPredicate.negate(ch.guard,0); return cur; } Node ch = parseLiteral(cur, beginIndex, endIndex); // System.err.println("-----------------------"); // System.err.println(ch); // System.err.println("-----------------------"); cur.guard = PolynomialPredicate.conjunct(cur.guard, ch.guard); return cur; } public static Node parseLiteral(Node par, int beginIndex, int endIndex) throws Exception { // System.err.println("parseLiteral:"+ beginIndex+"---"+endIndex); int sgn = -1, type = -1; //types: 0: "<=" 1: ">=" 2: ">" 3: "<" 4: "==" 5: "!=" for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("<=")) { sgn = i; type = 0; } else if (getToken(i).equals(">=")) { sgn = i; type = 1; } else if (getToken(i).equals(">")) { sgn = i; type = 2; } else if (getToken(i).equals("<")) { sgn = i; type = 3; } else if (getToken(i).equals("==")) { sgn = i; type = 4; } else if (getToken(i).equals("!=")) { sgn = i; type = 5; } if (sgn == beginIndex || sgn == endIndex) throw new Exception("literal starts or ends with sign @" + beginIndex + "-" + endIndex); Node cur = new Node(par, beginIndex, endIndex, "literal","literal",false); for(int i=beginIndex;i<=endIndex;i++) if(getToken(i).equals("_NONDET_")) { PolynomialPredicate lp=new PolynomialPredicate(); lp.exprs.add(null); cur.guard.add(lp); return cur; } Node left = null; Node right = null; if (sgn == -1) { type = 5; left = parseExpr(cur, beginIndex, endIndex); right = new Node(cur, endIndex, endIndex, "0","0",false); right.expr = new Polynomial(Rational.zero); } else { left = parseExpr(cur, beginIndex, sgn - 1); right = parseExpr(cur, sgn + 1, endIndex); } if (type == 0) //left<=right --> right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 1) //left>=right --> left-right>=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 2) // left > right -> left -right >=eps -> left - right -eps >=0 { Polynomial lc = left.expr.deepCopy(); lc.minus(right.expr); // left - right lc.minus(new Polynomial(prog_to_t2.eps)); // left - right - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 3) //left < right --> right - left > eps --> right - left -eps >=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); // right - left lc.minus(new Polynomial(prog_to_t2.eps)); // right - left - eps PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); cur.guard.add(lp); } else if (type == 4) //left==right --> left-right>=0 and right-left>=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); PolynomialPredicate lp = new PolynomialPredicate(); lp.add(lc); lp.add(lc2); cur.guard.add(lp); } else if (type == 5) // left != right --> left - right -1 >=0 or right - left -1 >=0 { Polynomial lc = right.expr.deepCopy(); lc.minus(left.expr); lc.minus(new Polynomial(prog_to_t2.eps)); Polynomial lc2 = left.expr.deepCopy(); lc2.minus(right.expr); lc2.minus(new Polynomial(prog_to_t2.eps)); PolynomialPredicate lp1 = new PolynomialPredicate(), lp2 = new PolynomialPredicate(); lp1.add(lc); lp2.add(lc2); cur.guard.add(lp1); cur.guard.add(lp2); } return cur; } // public static Node parseOrBexpr(Node par, int beginIndex, int endIndex) throws Exception // { // // Vector<Integer> ors=new Vector<>(); // ors.add(beginIndex-1); // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("or")) // ors.add(i); // ors.add(endIndex+1); // // Node cur=new Node(par,beginIndex,endIndex,"bexpr","or",false); // for (int i = 1; i < ors.size(); i++) // { // Node ch=parseAndBexpr(cur, ors.elementAt(i - 1) + 1, ors.elementAt(i) - 1); // cur.guard.add(ch.guard.firstElement()); // } // // return cur; // } // public static Node parseAndBexpr(Node par, int beginIndex, int endIndex) throws Exception // { // Vector<Integer> ands=new Vector<>(); // ands.add(beginIndex-1); // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("and")) // ands.add(i); // ands.add(endIndex+1); // Node cur=new Node(par,beginIndex,endIndex,"bexpr","and",false); // PolynomialPredicate lp=new PolynomialPredicate(); // for(int i=1;i<ands.size();i++) // { // Node ch=parseLiteral(cur, ands.elementAt(i - 1) + 1, ands.elementAt(i) - 1); // lp.add(ch.guard.firstElement()); // } // cur.guard.add(lp); // return cur; // } // public static Node parseLiteral(Node par,int beginIndex,int endIndex) throws Exception // { // int sgn=-1,type=-1; //types: 0-> "<=" 1->">=" // for(int i=beginIndex;i<=endIndex;i++) // if(getToken(i).equals("<=")) // { // sgn=i; // type=0; // } // else if(getToken(i).equals(">=")) // { // sgn=i; // type=1; // } // else if(getToken(i).equals(">")) // { // sgn=i; // type=2; // } // else if(getToken(i).equals("<")) // { // sgn=i; // type=3; // } // else if(getToken(i).equals("==")) // { // sgn=i; // type=4; // } // else if(getToken(i).equals("!=")) // { // sgn=i; // type=5; // } // if(sgn==beginIndex || sgn==endIndex) // throw new Exception("literal starts or ends with sign @"+beginIndex+"-"+endIndex); // if(sgn==-1) // throw new Exception("no sign found for literal @"+beginIndex+"-"+endIndex); // Node cur=new Node(par,beginIndex,endIndex,"literal",getToken(sgn),false); // Node left=parseExpr(cur,beginIndex,sgn-1); // Node right=parseExpr(cur,sgn+1,endIndex); // if(type==0) //left<=right -> right-left>=0 // { // Polynomial lc=right.expr.deepCopy(); // lc.minus(left.expr); // PolynomialPredicate lp=new PolynomialPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==1) //left>=right -> left-right>=0 // { // Polynomial lc=left.expr.deepCopy(); // lc.minus(right.expr); // PolynomialPredicate lp=new PolynomialPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==2) // left > right -> left -right >=eps -> left - right -eps >=0 // { // Polynomial lc=left.expr.deepCopy(); // lc.minus(right.expr); // left - right // lc.minus(new Polynomial(prog_to_t2.eps)); // left - right - eps // PolynomialPredicate lp=new PolynomialPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==3) //left < right -> right - left > eps -> right - left -eps >=0 // { // Polynomial lc=right.expr.deepCopy(); // lc.minus(left.expr); // right - left // lc.minus(new Polynomial(prog_to_t2.eps)); // right - left - eps // PolynomialPredicate lp=new PolynomialPredicate(); // lp.add(lc); // cur.guard.add(lp); // } // else if(type==4) //left==right -> left-right>=0 and left - right <=0 // { // Polynomial lc=left.expr.deepCopy(),lc2=right.expr.deepCopy(); // lc.minus(right.expr); // lc2.minus(left.expr); // PolynomialPredicate lp=new PolynomialPredicate(); // lp.add(lc); // lp.add(lc2); // cur.guard.add(lp); // } // else if(type==5) //left != right -> left > right || right > left -> left - right -eps >=0 || right - left - eps >=0 // { // Polynomial lc=left.expr.deepCopy(),lc2=right.expr.deepCopy(); // lc.minus(right.expr); // lc2.minus(left.expr); // lc.minus(new Polynomial(prog_to_t2.eps)); // lc2.minus(new Polynomial(prog_to_t2.eps)); // PolynomialPredicate lp=new PolynomialPredicate(),lp2=new PolynomialPredicate(); // lp.add(lc); // lp2.add(lc2); // cur.guard.add(lp); // cur.guard.add(lp2); // } // return cur; // } public static Node parseExpr(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseExpr: "+beginIndex+"----"+endIndex); Vector<Integer> signIndex = new Vector<>(); Vector<String> signType = new Vector<>(); if (!getToken(beginIndex).equals("-")) { signIndex.add(beginIndex - 1); signType.add("+"); } int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) { if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; if (openPar == 0 && (getToken(i).equals("+") || (getToken(i).equals("-") && (i - 1 < beginIndex || (i - 1 >= beginIndex && !getToken(i - 1).equals("*") && !getToken(i - 1).equals("+")))))) { signIndex.add(i); signType.add(getToken(i)); } } signIndex.add(endIndex + 1); signType.add("+"); Node cur = new Node(par, beginIndex, endIndex, "expr","expr",false); cur.expr = new Polynomial(); for (int i = 0; i + 1 < signIndex.size(); i++) { Node ch = parseTerm(cur, signIndex.elementAt(i) + 1, signIndex.elementAt(i + 1) - 1); if (signType.elementAt(i).equals("+")) cur.expr.add(ch.expr); else cur.expr.minus(ch.expr); } return cur; } public static Node parseTerm(Node par, int beginIndex, int endIndex) throws Exception { //System.err.println("parseTerm: "+beginIndex+"---"+endIndex); if ((beginIndex == endIndex && isNumeric(getToken(beginIndex)))) //constant { Node cur = new Node(par, beginIndex, endIndex, "term","constant",false); int val = Integer.parseInt(getToken(beginIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex - 1 && isNumeric(getToken(endIndex))) //negative constant { Node cur = new Node(par, beginIndex, endIndex,"term", "constant",false); int val = -Integer.parseInt(getToken(endIndex)); cur.expr = new Polynomial(); cur.expr.add(Monomial.one, new Rational(val, 1)); return cur; } else if (beginIndex == endIndex) //var { Node cur = new Node(par, beginIndex, endIndex,"term", "var",false); String var = getToken(beginIndex); allVars.add(var); if (Character.isDigit(var.charAt(0))) throw new Exception("Incorrect var name @" + beginIndex); cur.expr = new Polynomial(); cur.expr.add(new Monomial(var), new Rational(1, 1)); return cur; } else // (...) or [] * [] { Node cur = new Node(par, beginIndex, endIndex,"term", "term mul",false); cur.expr = new Polynomial(); Vector<Integer> sgnIndex = new Vector<>(); Vector<String> sgnType = new Vector<>(); sgnIndex.add(beginIndex - 1); sgnType.add("*"); int openPar = 0; for (int i = beginIndex; i <= endIndex; i++) if (getToken(i).equals("(")) openPar++; else if (getToken(i).equals(")")) openPar--; else if (openPar == 0 && (getToken(i).equals("*") || getToken(i).equals("/"))) { sgnIndex.add(i); sgnType.add(getToken(i)); } else if (getToken(i).equals("%")) { throw new Exception("% is not supported. @" + beginIndex + "-" + endIndex); } sgnIndex.add(endIndex + 1); sgnType.add("*"); if (sgnIndex.size() == 2) // (...) { Node ch = parseExpr(cur, beginIndex + 1, endIndex - 1); cur.expr = ch.expr; return cur; } else { cur.expr.add(Monomial.one, Rational.one); for (int i = 1; i < sgnIndex.size(); i++) { Node ch = parseExpr(cur, sgnIndex.elementAt(i - 1) + 1, sgnIndex.elementAt(i) - 1); if (sgnType.elementAt(i - 1).equals("*")) cur.expr.multiplyByPolynomial(ch.expr); else throw new Exception("Divison by variable is not possible @" + beginIndex + "-" + endIndex); } return cur; } } } public static int getElseOfIf(int beginIndex,int endIndex) throws Exception { int openIf=0,openWhile=0; for(int i=beginIndex;i<=endIndex;i++) { if(getToken(i).equals("if")) openIf++; else if(getToken(i).equals("fi")) openIf--; else if(getToken(i).equals("while")) openWhile++; else if(getToken(i).equals("od")) openWhile--; else if(openIf==0 && openWhile==0 && getToken(i).equals("else")) return i; } throw new Exception("no else found for if @"+beginIndex+"-"+endIndex); } public static boolean isNumeric(String s) { for(int i=0;i<s.length();i++) if(!Character.isDigit(s.charAt(i)) && s.charAt(i)!='.') return false; return true; } public static int getTokenCount() { return tokens.size(); } public static String getToken(int x) { return tokens.elementAt(x); } public static void readTokens(String program) throws Exception { String extraSpace=""; for(int i=0;i<program.length();i++) { char c=program.charAt(i); if(c=='.' || Character.isAlphabetic(c) || Character.isDigit(c) || c=='_') extraSpace+=c; else { extraSpace+=" "; extraSpace+=c; extraSpace+=" "; } } Scanner scanner=new Scanner(extraSpace); while(scanner.hasNext()) { String s=scanner.next(); if(s.equals("=")) { if(tokens.size()==0) throw new Exception("program cannot start with ="); String last=tokens.lastElement(); if(last.equals(":") || last.equals(">") || last.equals("<") || last.equals("=") || last.equals("!")) { tokens.removeElementAt(getTokenCount() - 1); last += s; tokens.add(last); } else tokens.add(s); } else tokens.add(s); } } public static void readFile(String fileName) throws Exception { File file=new File(fileName); Scanner in=new Scanner(file); String program=""; boolean mainPartHasStarted=false; while(in.hasNextLine()) { String s=in.nextLine(); if(s.contains("if") || s.contains("while")) mainPartHasStarted=true; if(!mainPartHasStarted && s.contains("_NONDET_")) continue; program += s + " "; } readTokens(program); // System.err.println("tokens are:"); // for(int i=0;i<tokens.size();i++) // System.err.println(i+": "+getToken(i)); } }
27,019
35.662144
163
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Polynomial.java
import java.util.*; public class Polynomial { Map<Monomial, Rational> terms; Polynomial() { terms = new TreeMap<>(); } Polynomial(Rational c) { terms = new TreeMap<>(); terms.put(Monomial.one, c); } Polynomial(String var) { terms = new TreeMap<>(); terms.put(new Monomial(var), Rational.one); } Polynomial(String var, Rational c) { terms = new TreeMap<>(); terms.put(new Monomial(var), c); } Polynomial(Monomial m) { terms = new TreeMap<>(); terms.put(m, Rational.one); } Polynomial(Monomial m, Rational c) { terms = new TreeMap<>(); terms.put(m, c); } void add(Monomial m, Rational c) { if (terms.containsKey(m)) terms.put(m, Rational.add(terms.get(m), c)); else terms.put(m, c); } void add(Polynomial poly) { for (Monomial term : poly.terms.keySet()) add(term, poly.terms.get(term)); } void minus(Polynomial poly) { add(poly.negate()); } public void multiplyByValue(Rational val) { for (Monomial term : terms.keySet()) terms.put(term, Rational.mul(terms.get(term), val)); } public void multiplyByMonomial(Monomial m) { Map<Monomial, Rational> tmp = new HashMap<>(); for (Monomial term : terms.keySet()) tmp.put(Monomial.mul(term, m), terms.get(term)); terms = tmp; } public void multiplyByPolynomial(Polynomial poly) { Polynomial res = new Polynomial(); for (Monomial m : poly.terms.keySet()) for (Monomial n : this.terms.keySet()) res.add(Monomial.mul(m, n), Rational.mul(poly.terms.get(m), this.terms.get(n))); terms = res.terms; } boolean isConstant() { removeZeros(); return (terms.size() <= 1 && (terms.size() != 1 || terms.containsKey(Monomial.one))); } void removeZeros() { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (terms.get(term).equals(Rational.zero)) terms.remove(term); } Polynomial deepCopy() { removeZeros(); Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), terms.get(term)); return ret; } void replaceVarWithPoly(String var, Polynomial poly) { Vector<Monomial> allTerms = new Vector<>(terms.keySet()); for (Monomial term : allTerms) if (term.containsVar(var)) { Rational coef = terms.get(term); Monomial m = term.removeOneVar(var); Polynomial left = new Polynomial(m); Polynomial right = poly.deepCopy(); for (int i = 1; i < term.getPower(var); i++) right.multiplyByPolynomial(poly); left.multiplyByPolynomial(right); left.multiplyByValue(coef); terms.remove(term); add(left); } } public Set<Monomial> getProgramVariableMonomials() { Set<Monomial> ret= new TreeSet<>(); for(Monomial m:terms.keySet()) ret.add(m.getProgramVarsPart()); return ret; } public Polynomial getCoef(Monomial m) { Polynomial ret=new Polynomial(); for(Monomial monomial:terms.keySet()) { if(monomial.programVarsPart().equals(m)) ret.add(monomial.unknownPart(),terms.get(monomial)); } return ret; } public boolean equals(Polynomial poly) { for (Monomial m : terms.keySet()) if (!poly.terms.containsKey(m) || !poly.terms.get(m).equals(terms.get(m))) return false; return true; } Polynomial negate() { Polynomial ret = new Polynomial(); for (Monomial term : terms.keySet()) ret.add(term.deepCopy(), Rational.negate(terms.get(term))); return ret; } public static Polynomial mul(Polynomial left,Polynomial right) { Polynomial ret=left.deepCopy(); ret.multiplyByPolynomial(right); return ret; } public String toString() { return toNormalString(); // String ret = ""; // if (terms.isEmpty()) // return "0"; // Vector<Monomial> monomials = new Vector<>(terms.keySet()); // if (monomials.size() == 1) // return "(* " + terms.get(monomials.firstElement()) +" "+ monomials.firstElement().toString()+")"; // ret = "(+ "; // for (Monomial m : monomials) // ret += "(* "+ terms.get(m)+ " " +m.toString()+") "; // ret += ")"; // return ret; } public String toNormalString() { String ret = ""; if (terms.isEmpty()) return "0"; Vector<Monomial> monomials = new Vector<>(terms.keySet()); for (Monomial m : monomials) { if(!ret.equals("")) ret+=" + "; if(!terms.get(m).equals(Rational.one)) ret += terms.get(m).toString()+" * "; ret += m.toNormalString(); } return ret; } }
5,386
24.652381
111
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/PolynomialPredicate.java
import java.util.Vector; public class PolynomialPredicate { Vector<Polynomial> exprs; public static PolynomialPredicate TRUE = new PolynomialPredicate(new Polynomial(Monomial.one)); PolynomialPredicate() { exprs = new Vector<>(); } PolynomialPredicate(Polynomial poly) { exprs=new Vector<>(); add(poly); } void add(Polynomial poly) { for (Polynomial p : exprs) if (p!=null && p.equals(poly)) return; exprs.add(poly); } void add(PolynomialPredicate pp) { for (Polynomial poly : pp.exprs) if(poly!=null) add(poly.deepCopy()); else exprs.add(null); } void replaceVarWithPoly(String var, Polynomial poly) { for (Polynomial p : exprs) p.replaceVarWithPoly(var, poly); } public Vector<PolynomialPredicate> negate() { Vector<PolynomialPredicate> ret = new Vector<>(); for (Polynomial poly : exprs) { // Polynomial p = poly.negate(); Polynomial p = null; if(poly!=null) { p = poly.negate(); p.add(Monomial.one, Rational.negate(prog_to_t2.eps)); } PolynomialPredicate pp = new PolynomialPredicate(); pp.add(p); ret.add(pp); } return ret; } public static Vector<PolynomialPredicate> negate(Vector<PolynomialPredicate> g,int first) { if(first==g.size()) return new Vector<>(); else if (first== g.size()-1 ) { return g.elementAt(first).negate(); } else { // Vector<PolynomialPredicate> ret = new Vector<>(); Vector<PolynomialPredicate> notFirst = g.elementAt(first).negate(); Vector<PolynomialPredicate> recurse = negate(g,first+1); // for (PolynomialPredicate pp : notFirst) // for (PolynomialPredicate predicate : recurse) // { // PolynomialPredicate copy = predicate.deepCopy(); // copy.add(pp); // ret.add(copy); // } return conjunct(notFirst,recurse); } } public static Vector<PolynomialPredicate> conjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); if (left.isEmpty()) { for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); } else if (right.isEmpty()) { for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); } else { for (PolynomialPredicate pp1 : left) for (PolynomialPredicate pp2 : right) { PolynomialPredicate pp = new PolynomialPredicate(); pp.add(pp1.deepCopy()); pp.add(pp2.deepCopy()); ret.add(pp); } } return ret; } public static Vector<PolynomialPredicate> disjunct(Vector<PolynomialPredicate> left, Vector<PolynomialPredicate> right) { Vector<PolynomialPredicate> ret = new Vector<>(); for (PolynomialPredicate pp : left) ret.add(pp.deepCopy()); for (PolynomialPredicate pp : right) ret.add(pp.deepCopy()); return ret; } boolean equalsLogic(PolynomialPredicate pp) { for (Polynomial p : exprs) if (!pp.contains(p)) return false; for (Polynomial p : pp.exprs) if (!this.contains(p)) return false; return true; } boolean contains(Polynomial p) { for (Polynomial poly : exprs) if (p.equals(poly)) return true; return false; } PolynomialPredicate deepCopy() { PolynomialPredicate ret = new PolynomialPredicate(); ret.add(this); return ret; } public String toNormalString() { String ret = ""; for (int i = 0; i < exprs.size(); i++) { Polynomial p = exprs.elementAt(i); if (i == 0) ret += p.toNormalString() + ">=0"; else ret += " && " + p.toNormalString() + ">=0"; } return ret; } public String toString() { return toNormalString(); } }
4,568
26.524096
123
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Rational.java
import java.util.EnumMap; public class Rational implements Comparable<Rational> { public static final Rational one=new Rational(1,1),zero=new Rational(0,1); int numerator,denominator; public int gcd(int a, int b) { if (b==0) return a; return gcd(b,a%b); } Rational(int numerator,int denominator) { if(numerator==0) { this.numerator=0; this.denominator=1; return; } if(denominator<0) { denominator*=-1; numerator*=-1; } int g=gcd(numerator,denominator); this.numerator=numerator/g; this.denominator=denominator/g; } public static Rational negate(Rational a) { return new Rational(-a.numerator,a.denominator); } public static Rational inverse(Rational a) throws Exception { if(a.numerator==0) throw new Exception("getting inverse of "+a+" which is not defined"); return new Rational(a.denominator,a.numerator); } public static Rational add(Rational a,Rational b) { return new Rational(a.numerator*b.denominator+b.numerator*a.denominator,a.denominator*b.denominator); } public static Rational minus(Rational a,Rational b) { return add(a,negate(b)); } public static Rational mul(Rational a,Rational b) { return new Rational(a.numerator*b.numerator,a.denominator*b.denominator); } public static Rational div(Rational a,Rational b) throws Exception { return mul(a,inverse(b)); } public boolean equals(Rational a) { return (a.numerator== numerator && a.denominator==denominator); } public boolean isNonNegative() { return (numerator>=0); } @Override public int compareTo(Rational a) { return numerator*a.denominator-a.numerator*denominator; } public void normalize() { if(denominator<0) { numerator*=-1; denominator*=-1; } } public String toString() { if(denominator==1) return ""+numerator; return "("+numerator+"/"+denominator+")"; } }
2,231
21.09901
109
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/Transition.java
public class Transition //from "v.first" to "v.second" with guard "g" and update "varName := update" { PairNode v; PolynomialPredicate guard; String varName; Polynomial update; //when varName is not null but update is null then 'varName \in (-inf,inf)' is the assignment String type; Transition(Node a,Node b,String type) { v=new PairNode(a,b); this.type=type; guard=null; varName=null; update=null; } Transition(Node a,Node b,String type,PolynomialPredicate guard) { v=new PairNode(a,b); this.type=type; this.guard=guard; varName=null; update=null; } Transition(Node a,Node b,String type,String varName,Polynomial update) { v=new PairNode(a,b); this.type=type; this.varName=varName; this.update=update; guard=null; } public String toString() { String res=""; res+="FROM: "+v.first.id+";"; if(guard!=null) { for(Polynomial lc:guard.exprs) if(lc!=null) res += "\nassume(" + lc + ">=0);"; else res+="\nassume(nondet()!=0)"; } else if(type.equals("if*-then")) ; //it will be handled in T2 parser/cfg maker if(update!=null) res+="\n"+varName+" := "+update.toString()+";"; else if(varName!=null) res+="\n"+varName+" := nondet();"; res+="\nTO: "+v.second.id+";"; return res; } }
1,575
23.625
117
java
null
RevTerm-main/code/prog_to_t2_polynomial/src/prog_to_t2.java
import java.io.FileWriter; public class prog_to_t2 { public static Rational eps=Rational.one; public static void main(String[] args) throws Exception { String input=args[0]; String output=args[1]; int con=1,dis=2; long startTime=System.currentTimeMillis(); //System.exit(0); Parser.readFile(input); //CFG.startNode=new Node(null,-1,-1,"startNode","",false); Node root=Parser.parseStmtList(null,0,Parser.getTokenCount()-1,false); //CFG.startNode.preCondition=root.preCondition; // for(Node n:Node.allNodes) // { // System.err.println("---------------------------"); // System.err.println(n.toString()); // System.err.println("---------------------------"); // } CFG.endNode=new Node(null,-1,-1,"endNode","",false); PairNode p=CFG.make(root); CFG.startNode=p.first; CFG.edges.add(CFG.getTransition(p.second,CFG.endNode,"to end")); FileWriter fw=new FileWriter(output); fw.write("START: "+CFG.startNode.id+";\n\n"); for(Transition t:CFG.edges) fw.write(t.toString()+"\n\n"); fw.close(); } }
1,216
27.302326
78
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Element.java
package it.unisa.dia.gas.jpbc; import java.math.BigInteger; /** * Elements of groups, rings and fields are accessible using the <code>Element</code> * interface. You can obtain an instance of an Element starting from an algebraic structure, such as a particular * finite field or elliptic curve group, represented by the <code>Field</code> interface. * * @author Angelo De Caro (jpbclib@gmail.com) * @see Field * @since 1.0.0 */ public interface Element extends ElementPow { /** * Returns the field to which this element lie. * * @return the field to which this element lie. * @since 1.0.0 */ Field getField(); /** * Returns the length in bytes necessary to represent this element. * * @return the length in bytes necessary to represent this element. * @see it.unisa.dia.gas.jpbc.Field#getLengthInBytes() * @since 1.0.0 */ int getLengthInBytes(); /** * Returns <tt>true</tt> if this element is immutable, <tt>false</tt> otherwise. * * @return <tt>true</tt> if this element is immutable, <tt>false</tt> otherwise. * @see #getImmutable() */ boolean isImmutable(); /** * Returns an immutable copy of this element if the * element is not already immutable. * <br/> * For immutable elements the internal value cannot be modified after it is created, * any method designed to modify the internal state of the element will return * a new element whose internal value represents the computation executed. * * @return an immutable copy of this element if the * element is not already immutable. * @see #isImmutable() */ Element getImmutable(); /** * Returns a copy of this element. If this element * is immutable then the copy is mutable. * * @return a copy of this element. * @since 1.0.0 */ Element duplicate(); /** * Sets this element to value. * * @param value the new value of this element. * @return this element set to value. * @since 1.0.0 */ Element set(Element value); /** * Sets this element to value. * * @param value the new value of this element. * @return this element set to value. * @since 1.0.0 */ Element set(int value); /** * Sets this element to value. * * @param value the new value of this element. * @return this element set to value. * @since 1.0.0 */ Element set(BigInteger value); /** * Converts this to a BigInteger if such operation makes sense. * * @return a BigInteger which represents this element. * @since 1.0.0 */ BigInteger toBigInteger(); /** * If this element lies in a finite algebraic structure, assigns a uniformly random element to it. * * @return this. * @since 1.0.0 */ Element setToRandom(); /** * Sets this element deterministically from the length bytes stored in the source parameter starting from the passed offset. * * @param source the buffer data. * @param offset the starting offset. * @param length the number of bytes to be used. * @return this element modified. * @since 1.0.0 */ Element setFromHash(byte[] source, int offset, int length); /** * Reads this element from the buffer source. * * @param source the source of bytes. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytes(byte[] source); /** * Reads this element from the buffer source starting from offset. * * @param source the source of bytes. * @param offset the starting offset. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytes(byte[] source, int offset); /** * Converts this element to bytes. The number of bytes it will * write can be determined calling getLengthInBytes(). * * @return the bytes written. * @since 1.0.0 */ byte[] toBytes(); /** * Returns the canonical representation of this element. * In most of the cases the output of this method * is the same as that of the #toBytes method. * * @return the canonical representation of this element. * @since 2.0.0 */ byte[] toCanonicalRepresentation(); /** * Sets this element to zero. * * @return this element set to zero. * @since 1.0.0 */ Element setToZero(); /** * Returns true if n is zero, false otherwise. * * @return true if n is zero, false otherwise. * @since 1.0.0 */ boolean isZero(); /** * Sets this element to one. * * @return this element set to one. * @since 1.0.0 */ Element setToOne(); /** * Returns <tt>true</tt> if this and value have the same value, <tt>false</tt> otherwise. * * @param value the element to be compared. * @return <tt>true</tt> if this and value have the same value, <tt>false</tt> otherwise. */ boolean isEqual(Element value); /** * Returns true if n is one, false otherwise. * * @return true if n is one, false otherwise. * @since 1.0.0 */ boolean isOne(); /** * Sets this = this + this. * * @return this + this. * @since 1.0.0 */ Element twice(); /** * Se this = this^2. * * @return this^2. * @since 1.0.0 */ Element square(); /** * Sets this to the inverse of itself. * * @return the inverse of itself. * @since 1.0.0 */ Element invert(); /** * Sets this = this / 2. * * @return this / 2. * @since 1.0.0 */ Element halve(); /** * Set this = -this. * * @return -this. * @since 1.0.0 */ Element negate(); /** * Sets this = this + element. * * @param element the value to be added. * @return this + element. * @since 1.0.0 */ Element add(Element element); /** * Sets this = this - element. * * @param element the value to be subtracted. * @return this - element. * @since 1.0.0 */ Element sub(Element element); /** * Sets this = this * element. * * @param element the value to be multiplied * @return this * element. * @since 1.0.0 */ Element mul(Element element); /** * Sets this = this * z, that is this + this + ... + this where there are z this's. * * @param z the value to be multiplied * @return this * z * @since 1.0.0 */ Element mul(int z); /** * Sets this = this * n, that is this + this + ... + this where there are n this's. * * @param n the value to be multiplied * @return this * n * @since 1.0.0 */ Element mul(BigInteger n); /** * Sets this = this * z, that is this + this + … + this where there are z this's and * z is an element of a ring Z_N for some N. * * @param z the value to be multiplied * @return this * z * @since 1.0.0 */ Element mulZn(Element z); /** * Sets this = this / element * * @param element is the divisor. * @return this / element * @since 1.0.0 */ Element div(Element element); /** * Sets this = this^n. * * @param n the exponent of the power. * @return this^n. * @since 1.0.0 */ Element pow(BigInteger n); /** * Sets this = this^n, where n is an element of a ring Z_N for some N * (typically the order of the algebraic structure n lies in). * * @param n the exponent of the power. * @return this^n * @since 1.0.0 */ Element powZn(Element n); /** * Prepare to exponentiate this element and returns pre-processing information. * * @return the pre-processing information used to execute the exponentation of this element. * @see it.unisa.dia.gas.jpbc.ElementPowPreProcessing */ ElementPowPreProcessing getElementPowPreProcessing(); /** * Sets this = sqrt(this). * * @return the square radix of this element. * @since 1.0.0 */ Element sqrt(); /** * Returns true if this element is a perfect square (quadratic residue), false otherwise. * * @return true if this element is a perfect square (quadratic residue), false otherwise. * @since 1.0.0 */ boolean isSqr(); /** * If this element is zero, returns 0. For a non zero value the behaviour depends on the algebraic structure. * * @return 0 is this element is zero, otherwise the behaviour depends on the algebraic structure. * @since 1.0.0 */ int sign(); }
8,847
24.207977
128
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/ElementPow.java
package it.unisa.dia.gas.jpbc; import java.math.BigInteger; /** * Common interface for the exponentiation. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.2.0 */ public interface ElementPow { /** * Compute the power to n. * * @param n the exponent of the power. * @return the computed power. * @since 1.2.0 */ Element pow(BigInteger n); /** * Compute the power to n, where n is an element of a ring Z_N for some N. * * @param n the exponent of the power. * @return the computed power. * @since 1.2.0 */ Element powZn(Element n); }
627
18.625
78
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/ElementPowPreProcessing.java
package it.unisa.dia.gas.jpbc; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface ElementPowPreProcessing extends ElementPow, PreProcessing { /** * Returns the field the pre-processed element belongs to. * * @return Returns the field the pre-processed element belongs to. * @since 1.2.0 */ Field getField(); /** * Compute the power to n using the pre-processed information. * * @param n the exponent of the power. * @return a new element whose value is the computed power. * @since 1.0.0 */ Element pow(BigInteger n); /** * Compute the power to n, where n is an element of a ring Z_N for some N, * using the pre-processed information, * * @param n the exponent of the power. * @return a new element whose value is the computed power. * @since 1.0.0 */ Element powZn(Element n); }
966
23.794872
78
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Field.java
package it.unisa.dia.gas.jpbc; import java.math.BigInteger; /** * Represents an algebraic structure. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface Field<E extends Element> { /** * Returns a new element which lies in this field. * * @return a new element which lies in this field. * @since 1.0.0 */ E newElement(); /** * Returns a new element whose value is passed as parameter. * * @param value the value of the new element. * @return a new element whose value is passed as parameter. * @see Element#set(int) * @since 1.0.0 */ E newElement(int value); /** * Returns a new element whose value is passed as parameter. * * @param value the value of the new element. * @return a new element whose value is passed as parameter. * @see Element#set(java.math.BigInteger) * @since 1.0.0 */ E newElement(BigInteger value); /** * Returns a new element whose value is copied from the passed element. * * @param e the element whose value is copied. * @return a new element whose value is copied from the passed element. * @since 2.0.0 */ E newElement(E e); /** * Returns a new element whose value is set deterministically from the length bytes stored * in the source parameter starting from the passed offset. * * @param source the buffer data. * @param offset the starting offset. * @param length the number of bytes to be used. * @return this element modified. * @since 2.0.0 */ E newElementFromHash(byte[] source, int offset, int length); /** * Returns a new element whose value is set from the buffer source. * * @param source the source of bytes. * @return the number of bytes read. * @since 2.0.0 */ E newElementFromBytes(byte[] source); /** * Returns a new element whose value is set from the buffer source starting from offset. * * @param source the source of bytes. * @param offset the starting offset. * @return the number of bytes read. * @since 2.0.0 */ E newElementFromBytes(byte[] source, int offset); /** * Returns a new element whose value is zero. * * @return a new element whose value is zero. * @since 1.0.0 */ E newZeroElement(); /** * Returns a new element whose value is one. * * @return a new element whose value is one. * @since 1.0.0 */ E newOneElement(); /** * Returns a new random element. * * @return a new random element. * @since 1.0.0 */ E newRandomElement(); /** * Returns the order of this field. * * @return the order of this field. Returns 0 for infinite order. * @since 1.0.0 */ BigInteger getOrder(); /** * Returns <tt>true></tt> if the order is odd, * false otherwise. * * @return <tt>true></tt> if the order is odd, * false otherwise. * @since 1.2.0 */ boolean isOrderOdd(); /** * Returns a quadratic non-residue in this field. It returns always the same element. * * @return a quadratic non-residue in this field. * @since 1.0.0 */ E getNqr(); /** * Returns the length in bytes needed to represent an element of this Field. * * @return the length in bytes needed to represent an element of this Field. * @since 1.0.0 */ int getLengthInBytes(); /** * Returns the length in bytes needed to represent an element of this Field. * * @return the length in bytes needed to represent an element of this Field. * @since 1.0.0 */ int getLengthInBytes(Element e); /** * Returns the length in bytes needed to canonical represent an element of this Field. * * @return the length in bytes needed to canonical represent an element of this Field. * @since 2.0.0 */ int getCanonicalRepresentationLengthInBytes(); /** * Computes the component-wise twice. * * @param elements the vector of elements to be twiced. * @return elements twiced. * @since 1.1.0 */ Element[] twice(Element[] elements); /** * Computes the component-wise addition between a and b. * * @param a an array of elements of the field * @param b another array of elements of the field to be added to a * @return the vector a modified by adding b. * @since 1.1.0 */ Element[] add(Element[] a, Element[] b); /** * Reads an ElementPowPreProcessing from the buffer source. * * @param source the source of bytes. * @return the ElementPowPreProcessing instance. * @since 1.2.0 */ ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source); /** * Reads an ElementPowPreProcessing from the buffer source starting from offset. * * @param source the source of bytes. * @param offset the starting offset. * @return the ElementPowPreProcessing instance. * @since 1.2.0 */ ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source, int offset); }
5,266
26.290155
94
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/FieldOver.java
package it.unisa.dia.gas.jpbc; /** * This interface represents an algebraic structure defined * over another. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 * @see Field */ public interface FieldOver<F extends Field, E extends Element> extends Field<E> { /** * Returns the target field. * * @return the target field. * @since 1.0.0 */ F getTargetField(); }
415
17.909091
81
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Pairing.java
package it.unisa.dia.gas.jpbc; /** * This interface gives access to the pairing functions. * Pairings involve three groups of prime order r called G1, G2, and GT. * The pairing is a bilinear map that takes two elements as input, one from G1 and one from G2, and outputs an element of GT. * Sometimes G1 and G2 are the same group (i.e. the pairing is symmetric) so their elements can be mixed freely. * In this case the #isSymmetric() function returns true. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface Pairing { /** * Returns true if this pairing is symmetric, false otherwise. * * @return true if this pairing is symmetric, false otherwise. * @since 1.0.0 */ boolean isSymmetric(); /** * Returns the degree of the pairing. * For bilinear maps, this value is 2. * For multilinear maps, this value represents * the degree of linearity supported. * * @return the degree of the pairing. * @since 2.0.0 */ int getDegree(); /** * Return the G1 group. * * @return the G1 group. * @since 1.0.0 */ Field getG1(); /** * Return the G2 group. * * @return the G2 group. * @since 1.0.0 */ Field getG2(); /** * Return the GT group which is the group of rth roots of unity. * * @return the GT group. * @since 1.0.0 */ Field getGT(); /** * Return the Zr group. * * @return the Zr group. * @since 1.0.0 */ Field getZr(); /** * Returns the field at level <tt>index</tt>. * For bilinear maps, Zr has index 0, G1 has index 1, * G2 has index 2 and GT has index 3. * * @return Returns the field at level <tt>index</tt> * @since 2.0.0 */ Field getFieldAt(int index); /** * Returns the index of the field if it belongs * to this pairing, otherwise it returns -1. * * @param field the field whose index has to be determine. * @return the index of the field if it belongs * to this pairing, otherwise it returns Unknown. * @see #getFieldAt(int) * @since 2.0.0 */ int getFieldIndex(Field field); /** * Applies the bilinear map. It returns e(in1, in2). g1 must be in the group G1, g2 must be in the group G2. * * @param in1 an element from G1. * @param in2 an element from G2. * @return an element from GT whose value is assigned by this map applied to in1 and in2. * @since 1.0.0 */ Element pairing(Element in1, Element in2); /** * Returns <tt>true</tt> if optimized * product of pairing is supported, * <tt>false</tt> otherwise. * * If optimized product of pairing is supported then * invoking the #pairing(Element[], Element[]) method should * guarantee better performance. * * @return <tt>true</tt> if optimized * product of pairing is supported, * <tt>false</tt> otherwise. * @since 2.0.0 * @see #pairing(Element[], Element[]) */ boolean isProductPairingSupported(); /** * Computes the product of pairings, that is * 'e'('in1'[0], 'in2'[0]) ... 'e'('in1'[n-1], 'in2'[n-1]). * * @param in1 must have at least 'n' elements belonging to the groups G1 * @param in2 must have at least 'n' elements belonging to the groups G2 * @return the product of pairings, that is 'e'('in1'[0], 'in2'[0]) ... 'e'('in1'[n-1], 'in2'[n-1]). * @since 1.1.0 */ Element pairing(Element[] in1, Element[] in2); /** * Returns the length in bytes needed to represent a PairingPreProcessing structure. * * @return the length in bytes needed to represent a PairingPreProcessing structure. * @since 1.2.0 * @see #getPairingPreProcessingFromBytes(byte[]) * @see #getPairingPreProcessingFromElement(Element) * @see PairingPreProcessing */ int getPairingPreProcessingLengthInBytes(); /** * Get ready to perform a pairing whose first input is in1, returns the results of time-saving pre-computation. * * @param in1 the first input of a pairing execution, used to pre-compute the pairing. * @return the results of time-saving pre-computation. * @since 1.0.0 */ PairingPreProcessing getPairingPreProcessingFromElement(Element in1); /** * Reads a PairingPreProcessing from the buffer source. * * @param source the source of bytes. * @return the PairingPreProcessing instance. * @since 1.2.0 */ PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source); /** * Reads a PairingPreProcessing from the buffer source starting from offset. * * @param source the source of bytes. * @param offset the starting offset. * @return the PairingPreProcessing instance. * @since 1.2.0 */ PairingPreProcessing getPairingPreProcessingFromBytes(byte[] source, int offset); }
5,015
29.216867
125
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/PairingParameters.java
package it.unisa.dia.gas.jpbc; import java.io.Serializable; import java.math.BigInteger; /** * Represents the set of parameters describing a pairing. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 2.0.0 */ public interface PairingParameters extends Serializable { /** * Returns <tt>true</tt> if a mapping for the specified * key exists. * * @param key key whose presence is to be tested * @return <tt>true</tt> if a mapping for the specified key exists. * @since 2.0.0 */ boolean containsKey(String key); /** * Returns the value as a string to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as a string to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ String getString(String key); /** * Returns the value as a string to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * * @param key the key whose associated value is to be returned * @return the value as a string to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * @since 2.0.0 */ String getString(String key, String defaultValue); /** * Returns the value as an int to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as an int to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ int getInt(String key); /** * Returns the value as an int to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * * @param key the key whose associated value is to be returned * @return the value as an int to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * @since 2.0.0 */ int getInt(String key, int defaultValue); /** * Returns the value as a BigInteger to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as a BigInteger to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ BigInteger getBigInteger(String key); /** * Returns the BigInteger to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * * @param key the key whose associated value is to be returned * @return the BigInteger to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * @since 2.0.0 */ BigInteger getBigInteger(String key, BigInteger defaultValue); /** * Returns the BigInteger at the specified index in the array to which * the specified key is mapped. * * @param key the key whose associated array is to be used * @param index the index relative to the array. * @return the BigInteger at the specified index in the array to which * the specified key is mapped. * @since 2.0.0 */ BigInteger getBigIntegerAt(String key, int index); /** * Returns the value as a long to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as a long to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ long getLong(String key); /** * Returns the value as a long to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * * @param key the key whose associated value is to be returned * @return the value as a long to which the specified key is mapped. * If the mapping does not exist the passed defaultValue is returned. * @since 2.0.0 */ long getLong(String key, long defaultValue); /** * Returns the value as an array of bytes to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as an array of bytes to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ byte[] getBytes(String key); /** * Returns the value as an array of bytes to which the specified key is mapped. * * @param key the key whose associated value is to be returned * @return the value as an array of bytes to which the specified key is mapped. * @throws IllegalArgumentException if the specified key does not exists. * @since 2.0.0 */ byte[] getBytes(String key, byte[] defaultValue); /** * Returns a string representation of the parameters * using the specified key/value separator. * * @param separator key/value separator separator to be used . * @return a string representation of the parameters. * @since 2.0.0 */ String toString(String separator); /** * Returns the object to which the specified key is mapped. * * @param key the key whose associated object is to be returned * @since 2.0.0 */ Object getObject(String key); }
5,649
34.759494
83
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/PairingParametersGenerator.java
package it.unisa.dia.gas.jpbc; /** * This interface lets the user to generate all the necessary parameters * to initialize a pairing. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 2.0.0 */ public interface PairingParametersGenerator<P extends PairingParameters> { /** * Generates the parameters. * * @return a map with all the necessary parameters. * @since 2.0.0 */ P generate(); }
435
19.761905
74
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/PairingPreProcessing.java
package it.unisa.dia.gas.jpbc; /** * This interface is used to compute the pairing function when pre-processed information has * been compute before on the first input which is so fixed for each instance of this interface. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface PairingPreProcessing extends PreProcessing { /** * Compute the pairing where the second argument is in2. The pre-processed information * are used for a fast computation * * @param in2 the second pairing function argument. * @return an element from GT whose value is assigned by this map applied to in1 and in2. * @since 1.0.0 */ Element pairing(Element in2); }
718
30.26087
96
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Point.java
package it.unisa.dia.gas.jpbc; /** * This interface represents an element with two coordinates. * (A point over an elliptic curve). * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface Point<E extends Element> extends Element, Vector<E> { /** * Returns the x-coordinate. * * @return the x-coordinate. * @since 1.0.0 */ E getX(); /** * Returns the y-coordinate. * * @return the y-coordinate. * @since 1.0.0 */ E getY(); /** * Returns the length in bytes needed to represent this element in a compressed way. * * @return the length in bytes needed to represent this element in a compressed way. */ int getLengthInBytesCompressed(); /** * Converts this element to bytes. The number of bytes it will write can be determined calling getLengthInBytesCompressed(). * * @return the bytes written. * @since 1.0.0 */ byte[] toBytesCompressed(); /** * Reads this element from the buffer source. staring from the passed offset. * * @param source the source of bytes. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytesCompressed(byte[] source); /** * Reads the x-coordinate from the buffer source staring from the passed offset. The y-coordinate is then recomputed. * Pay attention. the y-coordinate could be different from the element which originates the buffer source. * * @param source the source of bytes. * @param offset the starting offset. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytesCompressed(byte[] source, int offset); /** * Returns the length in bytes needed to represent the x coordinate of this element. * * @return the length in bytes needed to represent the x coordinate of this element. * @since 1.0.0 */ int getLengthInBytesX(); /** * Converts the x-coordinate to bytes. The number of bytes it will write can be determined calling getLengthInBytesX(). * * @return the bytes written. * @since 1.0.0 */ byte[] toBytesX(); /** * Reads the x-coordinate from the buffer source. The y-coordinate is then recomputed. * Pay attention. the y-coordinate could be different from the element which originates the buffer source. * * @param source the source of bytes. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytesX(byte[] source); /** * Reads the x-coordinate from the buffer source staring from the passed offset. The y-coordinate is then recomputed. * Pay attention. the y-coordinate could be different from the element which originates the buffer source. * * @param source the source of bytes. * @param offset the starting offset. * @return the number of bytes read. * @since 1.0.0 */ int setFromBytesX(byte[] source, int offset); }
3,031
29.019802
128
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Polynomial.java
package it.unisa.dia.gas.jpbc; import java.util.List; /** * This element represents a polynomial through its coefficients. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface Polynomial<E extends Element> extends Element, Vector { /** * Returns the degree of this polynomial. * * @return the degree of this polynomial. * @since 1.0.0 */ int getDegree(); /** * Returns the list of coefficients representing * this polynomial. * * @return the list of coefficients representing * this polynomial. * @since 1.0.0 */ List<E> getCoefficients(); /** * Returns the coefficient at a specified position. * * @param index the position of the requested coefficient. * @return the coefficient at a specified position. * @since 1.0.0 */ E getCoefficient(int index); }
909
21.195122
72
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/PreProcessing.java
package it.unisa.dia.gas.jpbc; /** * Common interface for all pre-processing interfaces. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.0.0 */ public interface PreProcessing { /** * Converts the object to bytes. * * @return the bytes written. * @since 1.2.0 */ byte[] toBytes(); }
333
15.7
54
java
CP-ABE
CP-ABE-master/src/jpbc-api/src/main/java/it/unisa/dia/gas/jpbc/Vector.java
package it.unisa.dia.gas.jpbc; /** * This element represents a vector through its coordinates. * * @author Angelo De Caro (jpbclib@gmail.com) * @since 1.2.0 */ public interface Vector<E extends Element> extends Element { /** * Returns the size of this vector. * * @return the size of this vector. * @since 1.2.0 */ int getSize(); /** * Returns the element at the specified coordinate. * * @param index the index of the requested coordinate. * @return the element at the specified coordinate. * @since 1.2.0 */ E getAt(int index); }
612
20.137931
60
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractElement.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.ElementPowPreProcessing; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractElement<F extends AbstractField> implements Element { protected F field; protected boolean immutable = false; public AbstractElement(F field) { this.field = field; } public F getField() { return field; } public boolean isImmutable() { return immutable; } public Element getImmutable() { throw new IllegalStateException("Not Implemented yet!"); } public int getLengthInBytes() { return field.getLengthInBytes(); } public int setFromBytes(byte[] source) { return setFromBytes(source, 0); } public int setFromBytes(byte[] source, int offset) { throw new IllegalStateException("Not Implemented yet!"); } public Element pow(BigInteger n) { if (BigInteger.ZERO.equals(n)) { setToOne(); return this; } elementPowWind(n); return this; } public Element powZn(Element n) { return pow(n.toBigInteger()); } public ElementPowPreProcessing getElementPowPreProcessing() { return new AbstractElementPowPreProcessing(this, AbstractElementPowPreProcessing.DEFAULT_K); } public Element halve() { return mul(field.newElement().set(2).invert()); } public Element sub(Element element) { add(element.duplicate().negate()); return this; } public Element div(Element element) { return mul(element.duplicate().invert()); } public Element mul(int z) { mul(field.newElement().set(z)); return this; } public Element sqrt() { throw new IllegalStateException("Not Implemented yet!"); } public byte[] toBytes() { throw new IllegalStateException("Not Implemented yet!"); } public byte[] toCanonicalRepresentation() { return toBytes(); } public Element mulZn(Element z) { return mul(z.toBigInteger()); } public Element square() { return mul(this); } public Element twice() { return add(this); } @Override public boolean equals(Object obj) { return obj instanceof Element && isEqual((Element) obj); } protected int optimalPowWindowSize(BigInteger n) { int expBits; expBits = n.bitLength(); /* try to minimize 2^k + n/(k+1). */ if (expBits > 9065) return 8; if (expBits > 3529) return 7; if (expBits > 1324) return 6; if (expBits > 474) return 5; if (expBits > 157) return 4; if (expBits > 47) return 3; return 2; } /** * Builds k-bit lookup window for base a * * @param k * @return */ protected List<Element> buildPowWindow(int k) { int s; int lookupSize; List<Element> lookup; if (k < 1) { /* no window */ return null; } /* build 2^k lookup table. lookup[i] = x^i. */ /* TODO(-): a more careful word-finding algorithm would allow * us to avoid calculating even lookup entries > 2 */ lookupSize = 1 << k; lookup = new ArrayList<Element>(lookupSize); lookup.add(field.newOneElement()); for (s = 1; s < lookupSize; s++) { lookup.add(lookup.get(s - 1).duplicate().mul(this)); } return lookup; } /** * left-to-right exponentiation with k-bit window. * NB. must have k >= 1. * * @param n */ protected void elementPowWind(BigInteger n) { /* early abort if raising to power 0 */ if (n.signum() == 0) { setToOne(); return; } int word = 0; /* the word to look up. 0<word<base */ int wbits = 0; /* # of bits so far in word. wbits<=k. */ int k = optimalPowWindowSize(n); List<Element> lookup = buildPowWindow(k); Element result = field.newElement().setToOne(); for (int inword = 0, s = n.bitLength() - 1; s >= 0; s--) { result.square(); int bit = n.testBit(s) ? 1 : 0; if (inword == 0 && bit == 0) continue; /* keep scanning. note continue. */ if (inword == 0) { /* was scanning, just found word */ inword = 1; /* so, start new word */ word = 1; wbits = 1; } else { word = (word << 1) + bit; wbits++; /* continue word */ } if (wbits == k || s == 0) { result.mul(lookup.get(word)); inword = 0; } } set(result); } protected String[] tokenize(String value) { StringTokenizer tokenizer = new StringTokenizer(value,","); int n = tokenizer.countTokens(); String[] tokens = new String[n]; for (int i = 0; i < n; i++) { tokens[i] = tokenizer.nextToken(); } return tokens; } }
5,485
23.491071
100
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractElementPowPreProcessing.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.ElementPowPreProcessing; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.plaf.jpbc.util.io.FieldStreamReader; import it.unisa.dia.gas.plaf.jpbc.util.io.PairingStreamWriter; import java.io.IOException; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class AbstractElementPowPreProcessing implements ElementPowPreProcessing { public static final int DEFAULT_K = 5; protected Field field; protected int k; protected int bits; protected int numLookups; protected Element table[][]; public AbstractElementPowPreProcessing(Element g, int k) { this.field = g.getField(); this.bits = field.getOrder().bitLength(); this.k = k; initTable(g); } public AbstractElementPowPreProcessing(Field field, int k, byte[] source, int offset) { this.field = field; this.bits = field.getOrder().bitLength(); this.k = k; initTableFromBytes(source, offset); } public Field getField() { return field; } public Element pow(BigInteger n) { return powBaseTable(n); } public Element powZn(Element n) { return pow(n.toBigInteger()); } public byte[] toBytes() { try { PairingStreamWriter out = new PairingStreamWriter(field.getLengthInBytes() * table.length * table[0].length); for (Element[] row : table) for (Element element : row) out.write(element); return out.toBytes(); } catch (IOException e) { throw new RuntimeException(e); } } protected void initTableFromBytes(byte[] source, int offset) { int lookupSize = 1 << k; numLookups = bits / k + 1; table = new Element[numLookups][lookupSize]; FieldStreamReader in = new FieldStreamReader(field, source, offset); for (int i = 0; i < numLookups; i++) for (int j = 0; j < lookupSize; j++) table[i][j] = in.readElement(); } /** * build k-bit base table for n-bit exponentiation w/ base a * * @param g an element */ protected void initTable(Element g) { int lookupSize = 1 << k; numLookups = bits / k + 1; table = new Element[numLookups][lookupSize]; Element multiplier = g.duplicate(); for (int i = 0; i < numLookups; i++) { table[i][0] = field.newOneElement(); for (int j = 1; j < lookupSize; j++) { table[i][j] = multiplier.duplicate().mul(table[i][j - 1]); } multiplier.mul(table[i][lookupSize - 1]); } } protected Element powBaseTable(BigInteger n) { /* early abort if raising to power 0 */ if (n.signum() == 0) { return field.newOneElement(); } if (n.compareTo(field.getOrder()) > 0) n = n.mod(field.getOrder()); Element result = field.newOneElement(); int numLookups = n.bitLength() / k + 1; for (int row = 0; row < numLookups; row++) { int word = 0; for (int s = 0; s < k; s++) { word |= (n.testBit(k * row + s) ? 1 : 0) << s; } if (word > 0) { result.mul(table[row][word]); } } return result; } }
3,506
26.186047
121
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractField.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.ElementPowPreProcessing; import it.unisa.dia.gas.jpbc.Field; import java.math.BigInteger; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractField<E extends Element> implements Field<E> { protected boolean orderIsOdd = false; protected SecureRandom random; protected AbstractField(SecureRandom random) { this.random = random; } public E newElement(int value) { E e = newElement(); e.set(value); return e; } public E newElement(BigInteger value) { E e = newElement(); e.set(value); return e; } public E newElement(E e) { E newElement = newElement(); newElement.set(e); return newElement; } public E newElementFromHash(byte[] source, int offset, int length) { E e = newElement(); e.setFromHash(source, offset, length); return e; } public E newElementFromBytes(byte[] source) { E e = newElement(); e.setFromBytes(source); return e; } public E newElementFromBytes(byte[] source, int offset) { E e = newElement(); e.setFromBytes(source, offset); return e; } public E newZeroElement() { E e = newElement(); e.setToZero(); return e; } public E newOneElement() { E e = newElement(); e.setToOne(); return e; } public E newRandomElement() { E e = newElement(); e.setToRandom(); return e; } public boolean isOrderOdd() { return orderIsOdd; } public int getLengthInBytes(Element e) { return getLengthInBytes(); } public int getCanonicalRepresentationLengthInBytes() { return getLengthInBytes(); } public Element[] twice(Element[] elements) { for (Element element : elements) { element.twice(); } return elements; } public Element[] add(Element[] a, Element[] b) { for (int i = 0; i < a.length; i++) { a[i].add(b[i]); } return a; } public ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source) { return new AbstractElementPowPreProcessing(this, AbstractElementPowPreProcessing.DEFAULT_K, source, 0); } public ElementPowPreProcessing getElementPowPreProcessingFromBytes(byte[] source, int offset) { return new AbstractElementPowPreProcessing(this, AbstractElementPowPreProcessing.DEFAULT_K, source, offset); } public SecureRandom getRandom() { return random; } }
2,782
20.913386
116
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractFieldOver.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.jpbc.FieldOver; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractFieldOver<F extends Field, E extends Element> extends AbstractField<E> implements FieldOver<F, E> { protected F targetField; protected AbstractFieldOver(SecureRandom random, F targetField) { super(random); this.targetField = targetField; } public F getTargetField() { return targetField; } }
624
22.148148
129
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractPointElement.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Point; import it.unisa.dia.gas.jpbc.Vector; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractPointElement<E extends Element, F extends AbstractFieldOver> extends AbstractElement<F> implements Point<E>, Vector<E> { protected E x, y; protected AbstractPointElement(F field) { super(field); } public int getSize() { return 2; } public E getAt(int index) { return (index == 0) ? x : y; } public E getX() { return x; } public E getY() { return y; } public int getLengthInBytesCompressed() { throw new IllegalStateException("Not Implemented yet!"); } public byte[] toBytesCompressed() { throw new IllegalStateException("Not Implemented yet!"); } public int setFromBytesCompressed(byte[] source) { throw new IllegalStateException("Not Implemented yet!"); } public int setFromBytesCompressed(byte[] source, int offset) { throw new IllegalStateException("Not Implemented yet!"); } public int getLengthInBytesX() { throw new IllegalStateException("Not Implemented yet!"); } public byte[] toBytesX() { throw new IllegalStateException("Not Implemented yet!"); } public int setFromBytesX(byte[] source) { throw new IllegalStateException("Not Implemented yet!"); } public int setFromBytesX(byte[] source, int offset) { throw new IllegalStateException("Not Implemented yet!"); } }
1,648
22.557143
150
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/base/AbstractVectorElement.java
package it.unisa.dia.gas.plaf.jpbc.field.base; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Vector; import java.util.ArrayList; import java.util.List; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractVectorElement<E extends Element, F extends AbstractFieldOver> extends AbstractElement<F> implements Vector<E> { protected List<E> coeff; protected AbstractVectorElement(F field) { super(field); this.coeff = new ArrayList<E>(); } public E getAt(int index) { return coeff.get(index); } public int getSize() { return coeff.size(); } }
658
20.258065
141
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/curve/CurveElement.java
package it.unisa.dia.gas.plaf.jpbc.field.curve; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractPointElement; import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class CurveElement<E extends Element, F extends CurveField> extends AbstractPointElement<E, F> { protected int infFlag; public CurveElement(F field) { super(field); this.x = (E) field.getTargetField().newElement(); this.y = (E) field.getTargetField().newElement(); this.infFlag = 1; } public CurveElement(CurveElement<E, F> curveElement) { super(curveElement.getField()); this.x = (E) curveElement.x.duplicate(); this.y = (E) curveElement.y.duplicate(); this.infFlag = curveElement.infFlag; } public E getX() { return x; } public E getY() { return y; } public F getField() { return field; } public Element getImmutable() { return new ImmutableCurveElement<E, F>(this); } public CurveElement<E,F> duplicate() { return new CurveElement<E,F>(this); } public CurveElement set(Element e) { CurveElement element = (CurveElement) e; if (element.infFlag != 0) { infFlag = 1; return this; } this.x.set(element.x); this.y.set(element.y); this.infFlag = 0; return this; } public CurveElement set(int value) { if (value == 0 || value == 1) setToZero(); else throw new IllegalStateException("Value not supported."); return this; } public CurveElement set(BigInteger value) { if (BigInteger.ZERO.equals(value) || BigInteger.ONE.equals(value)) setToZero(); else throw new IllegalStateException("Value not supported."); return this; } public boolean isZero() { return infFlag == 1; } public boolean isOne() { return infFlag == 1; } public CurveElement twice() { if (infFlag != 0) return this; if (y.isZero()) { infFlag = 1; return this; } else { twiceInternal(); return this; } } public CurveElement setToZero() { infFlag = 1; return this; } public CurveElement setToOne() { infFlag = 1; return this; } public CurveElement setToRandom() { set(getField().getGenPow().pow(BigIntegerUtils.getRandom(field.getTargetField().getOrder(), field.getRandom()))); return this; } public int setFromBytes(byte[] source, int offset) { int len; infFlag = 0; len = x.setFromBytes(source, offset); len += y.setFromBytes(source, offset + len); //if point does not lie on curve, set it to O if (!isValid()) setToZero(); return len; } public CurveElement square() { if (infFlag != 0) { infFlag = 1; return this; } if (y.isZero()) { infFlag = 1; return this; } twiceInternal(); return this; } public CurveElement invert() { if (infFlag != 0) { infFlag = 1; return this; } infFlag = 0; y.negate(); return this; } public CurveElement negate() { return invert(); } public CurveElement add(Element e) { mul(e); return this; } public CurveElement mul(Element e) { // counter++; // Apply the Chord-Tangent Law of Composition // Consider P1 = this = (x1, y1); // P2 = e = (x2, y2); if (infFlag != 0) { set(e); return this; } CurveElement element = (CurveElement) e; if (element.infFlag != 0) return this; if (x.isEqual(element.x)) { if (y.isEqual(element.y)) { if (y.isZero()) { infFlag = 1; return this; } else { twiceInternal(); return this; } } infFlag = 1; return this; } else { // P1 != P2, so the slope of the line L through P1 and P2 is // lambda = (y2-y1)/(x2-x1) Element lambda = element.y.duplicate().sub(y).mul(element.x.duplicate().sub(x).invert()); // x3 = lambda^2 - x1 - x2 Element x3 = lambda.duplicate().square().sub(x).sub(element.x); //y3 = (x1-x3)lambda - y1 Element y3 = x.duplicate().sub(x3).mul(lambda).sub(y); x.set(x3); y.set(y3); infFlag = 0; } return this; } public CurveElement mul(BigInteger n) { return (CurveElement) pow(n); } public CurveElement mulZn(Element e) { return powZn(e); } public boolean isSqr() { return BigIntegerUtils.isOdd(field.getOrder()) || duplicate().pow(field.getOrder().subtract(BigInteger.ONE).divide(BigIntegerUtils.TWO)).isOne(); } public boolean isEqual(Element e) { if (e == this) return true; if (!(e instanceof CurveElement)) return false; CurveElement element = (CurveElement) e; if (field.quotientCmp != null) { // If we're working with a quotient group we must account for different // representatives of the same coset. return this.duplicate().div(element).pow(field.quotientCmp).isOne(); } return isEqual(element); } public CurveElement powZn(Element e) { pow(e.toBigInteger()); return this; } public BigInteger toBigInteger() { if (isOne()) return BigInteger.ZERO; else throw new IllegalStateException("Cannot convert to BigInteger."); } public byte[] toBytes() { byte[] xBytes = x.toBytes(); byte[] yBytes = y.toBytes(); byte[] result = new byte[xBytes.length + yBytes.length]; System.arraycopy(xBytes, 0, result, 0, xBytes.length); System.arraycopy(yBytes, 0, result, xBytes.length, yBytes.length); return result; } public CurveElement setFromHash(byte[] source, int offset, int length) { infFlag = 0; x.setFromHash(source, offset, length); Element t = field.getTargetField().newElement(); for (; ;) { t.set(x).square().add(field.a).mul(x).add(field.b); if (t.isSqr()) break; x.square().add(t.setToOne()); } y.set(t).sqrt(); if (y.sign() < 0) y.negate(); if (field.cofac != null) mul(field.cofac); return this; } public int sign() { if (infFlag != 0) return 0; return y.sign(); } public String toString() { return String.format("%s,%s,%d", x, y, infFlag); } public int getLengthInBytesCompressed() { return x.getLengthInBytes() + 1; } public byte[] toBytesCompressed() { byte[] xBytes = x.toBytes(); byte[] result = new byte[getLengthInBytesCompressed()]; System.arraycopy(xBytes, 0, result, 0, xBytes.length); if (y.sign() > 0) result[xBytes.length] = 1; else result[xBytes.length] = 0; return result; } public int setFromBytesCompressed(byte[] source) { return setFromBytesCompressed(source, 0); } public int setFromBytesCompressed(byte[] source, int offset) { int len = x.setFromBytes(source, offset); setPointFromX(); if (source[offset + len] == 1) { if (y.sign() < 0) y.negate(); } else if (y.sign() > 0) y.negate(); return len + 1; } public int getLengthInBytesX() { return x.getLengthInBytes(); } public byte[] toBytesX() { return x.toBytes(); } public int setFromBytesX(byte[] source) { return setFromBytesX(source, 0); } public int setFromBytesX(byte[] source, int offset) { int len = x.setFromBytes(source, offset); setPointFromX(); return len; } public boolean isValid() { Element t0, t1; if (infFlag != 0) return true; t0 = field.getTargetField().newElement(); t1 = field.getTargetField().newElement(); t0.set(x).square().add(getField().getA()).mul(x).add(getField().getB()); t1.set(y).square(); return t0.isEqual(t1); } protected void twiceInternal() { // We have P1 = P2 so the tangent line T at P1 ha slope //lambda = (3x^2 + a) / 2y Element lambda = x.duplicate().square().mul(3).add(getField().a).mul(y.duplicate().twice().invert()); // x3 = lambda^2 - 2x Element x3 = lambda.duplicate().square().sub(x.duplicate().twice()); // y3 = (x - x3) lambda - y Element y3 = x.duplicate().sub(x3).mul(lambda).sub(y); x.set(x3); y.set(y3); infFlag = 0; } protected void setPointFromX() { infFlag = 0; y.set(x.duplicate().square().add(field.a).mul(x).add(field.b).sqrt()); } protected boolean isEqual(CurveElement element) { if (this.infFlag != 0 || element.infFlag != 0) { return (this.infFlag != 0 && element.infFlag != 0); } return x.isEqual(element.x) && y.isEqual(element.y); } public void setX(E x) { this.x = x; } public void setY(E y) { this.y = y; } }
9,952
22.697619
153
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/curve/CurveField.java
package it.unisa.dia.gas.plaf.jpbc.field.curve; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.ElementPow; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver; import java.math.BigInteger; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class CurveField<F extends Field> extends AbstractFieldOver<F, CurveElement> { public static <F extends Field> CurveField<F> newCurveFieldJ(SecureRandom random, Element j, BigInteger order, BigInteger cofac) { // Assumes j != 0, 1728 Element a, b; a = j.getField().newElement(); b = j.getField().newElement(); a.set(1728).sub(j).invert().mul(j); //b = 2 j / (1728 - j) b.set(a).add(a); //a = 3 j / (1728 - j) a.add(b); return new CurveField<F>(random, a, b, order, cofac); } protected Element a, b; protected Element gen, genNoCofac; protected ElementPow genPow; protected BigInteger order, cofac; // A non-NULL quotientCmp means we are working with the quotient group of // order #E / quotientCmp, and the points are actually coset // representatives. Thus for a comparison, we must multiply by quotientCmp // before comparing. protected BigInteger quotientCmp = null; public CurveField(SecureRandom random, Element a, Element b, BigInteger order) { this(random, a, b, order, (BigInteger) null); } public CurveField(SecureRandom random, Element a, Element b, BigInteger order, byte[] gen) { super(random, (F) a.getField()); this.a = a; this.b = b; this.order = order; this.gen = newElementFromBytes(gen); } public CurveField(SecureRandom random, Element a, Element b, BigInteger order, BigInteger cofac) { super(random, (F) a.getField()); this.a = a; this.b = b; this.order = order; this.cofac = cofac; initGen(); } public CurveField(SecureRandom random, Element a, Element b, BigInteger order, BigInteger cofac, byte[] genNoCofac) { super(random, (F) a.getField()); this.random = random; this.a = a; this.b = b; this.order = order; this.cofac = cofac; initGen(genNoCofac); } public CurveField(SecureRandom random, Element b, BigInteger order, BigInteger cofac) { this(random, b.getField().newZeroElement(), b, order, cofac); } public CurveElement newElement() { return new CurveElement(this); } public BigInteger getOrder() { return order; } public CurveElement getNqr() { throw new IllegalStateException("Not Implemented yet!"); } public int getLengthInBytes() { return getTargetField().getLengthInBytes() * 2; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CurveField)) return false; CurveField that = (CurveField) o; if (!a.equals(that.a)) return false; if (!b.equals(that.b)) return false; if (cofac != null ? !cofac.equals(that.cofac) : that.cofac != null) return false; if (!order.equals(that.order)) return false; return true; } public int hashCode() { int result = a.hashCode(); result = 31 * result + b.hashCode(); result = 31 * result + order.hashCode(); result = 31 * result + (cofac != null ? cofac.hashCode() : 0); return result; } public Element getA() { return a; } public Element getB() { return b; } public BigInteger getQuotientCmp() { return quotientCmp; } public void setQuotientCmp(BigInteger quotientCmp) { this.quotientCmp = quotientCmp; } /** * Existing points are invalidated as this mangles c. * Consider the curve E′ given by Y^2 = X^3 + a v^2 X + v^3 b, which * we call the (quadratic) twist of the curve E, where * v is a quadratic nonresidue in Fq * * @return the twisted curve. */ public CurveField twist() { Element nqr = getTargetField().getNqr(); a.mul(nqr).mul(nqr); b.mul(nqr).mul(nqr).mul(nqr); initGen(); return this; } public Element getGenNoCofac() { return genNoCofac; } public Element getGen() { return gen; } protected void initGen() { genNoCofac = getCurveRandomNoCofacSolvefory(); if (cofac != null) { gen = genNoCofac.duplicate().mul(cofac); } else { gen = genNoCofac.duplicate(); } } protected void initGen(byte[] genNoCofac) { if (genNoCofac == null) { this.genNoCofac = getCurveRandomNoCofacSolvefory(); } else { this.genNoCofac = newElementFromBytes(genNoCofac); } if (cofac != null) { gen = this.genNoCofac.duplicate().mul(cofac); } else { gen = this.genNoCofac.duplicate(); } } protected CurveElement getCurveRandomNoCofacSolvefory() { //TODO(-): with 0.5 probability negate y-coord CurveElement element = new CurveElement(this); element.infFlag = 0; Element t = targetField.newElement(); do { t.set(element.getX().setToRandom()).square().add(a).mul(element.getX()).add(b); } while (!t.isSqr()); element.getY().set(t.sqrt()); return element; } public Element[] twice(Element[] elements) { int i; int n = elements.length; Element[] table = new Element[n]; //a big problem? Element e0, e1, e2; CurveElement q, r; q = (CurveElement) elements[0]; e0 = q.getX().getField().newElement(); e1 = e0.duplicate(); e2 = e0.duplicate(); for (i = 0; i < n; i++) { q = (CurveElement) elements[i]; table[i] = q.getY().getField().newElement(); if (q.infFlag != 0) { q.infFlag = 1; continue; } if (q.getY().isZero()) { q.infFlag = 1; continue; } } //to compute 1/2y multi. see Cohen's GTM139 Algorithm 10.3.4 for (i = 0; i < n; i++) { q = (CurveElement) elements[i]; table[i].set(q.getY()).twice(); if (i > 0) table[i].mul(table[i - 1]); } e2.set(table[n - 1]).invert(); for (i = n - 1; i > 0; i--) { q = (CurveElement) elements[i]; table[i].set(table[i - 1]).mul(e2); e2.mul(q.getY()).twice(); //e2=e2*2y_j } table[0].set(e2); //e2 no longer used. for (i = 0; i < n; i++) { q = (CurveElement) elements[i]; if (q.infFlag != 0) continue; //e2=lambda = (3x^2 + a) / 2y e2.set(q.getX()).square().mul(3).add(a).mul(table[i]); //Recall that table[i]=1/2y_i //x1 = lambda^2 - 2x e1.set(q.getX()).twice(); e0.set(e2).square().sub(e1); //y1 = (x - x1)lambda - y e1.set(q.getX()).sub(e0).mul(e2).sub(q.getY()); q.getX().set(e0); q.getY().set(e1); q.infFlag = 0; } return elements; } public Element[] add(Element[] a, Element[] b) { int n = a.length; Element[] table = new Element[n]; CurveElement p, q, r; Element e0, e1, e2; p = (CurveElement) a[0]; q = (CurveElement) b[0]; e0 = p.getX().getField().newElement(); e1 = e0.duplicate(); e2 = e0.duplicate(); table[0] = q.getX().duplicate().sub(p.getX()); for (int i = 1; i < n; i++) { p = (CurveElement) a[i]; q = (CurveElement) b[i]; table[i] = q.getX().duplicate().sub(p.getX()).mul(table[i-1]); } e2.set(table[n-1]).invert(); for (int i = n - 1; i > 0; i--) { p = (CurveElement) a[i]; q = (CurveElement) b[i]; table[i].set(table[i-1]).mul(e2); e1.set(q.getX()).sub(p.getX()); e2.mul(e1); //e2=e2*(x2_j-x1_j) } table[0].set(e2); //e2 no longer used. for (int i = 0; i < n; i++) { p = (CurveElement) a[i]; q = (CurveElement) b[i]; if (p.infFlag != 0) { a[i].set(b[i]); continue; } if (q.infFlag != 0) { continue; } if (p.getX().isEqual(q.getX())) { //a[i]=b[i] if (p.getY().isEqual(q.getY())) { if (p.getY().isZero()) { p.infFlag = 1; continue; } else { p.twice(); continue; } } //points are inverses of each other p.infFlag = 1; continue; } else { //lambda = (y2-y1)/(x2-x1) e2.set(q.getY()).sub(p.getY()).mul(table[i]); //x3 = lambda^2 - x1 - x2 e0.set(e2).square().sub(p.getX()).sub(q.getX()); //y3 = (x1-x3)lambda - y1 e1.set(p.getX()).sub(e0).mul(e2).sub(p.getY()); p.getX().set(e0); p.getY().set(e1); p.infFlag = 0; } } return a; } public ElementPow getGenPow() { if (genPow == null) genPow = gen.getElementPowPreProcessing(); return genPow; } }
9,830
26.537815
134
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/curve/ImmutableCurveElement.java
package it.unisa.dia.gas.plaf.jpbc.field.curve; import it.unisa.dia.gas.jpbc.Element; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class ImmutableCurveElement<E extends Element, F extends CurveField> extends CurveElement<E, F> { public ImmutableCurveElement(CurveElement<E,F> curveElement) { super(curveElement); this.x = (E) curveElement.getX().getImmutable(); this.y = (E) curveElement.getY().getImmutable(); this.immutable = true; } @Override public CurveElement duplicate() { return super.duplicate(); } public Element getImmutable() { return this; } @Override public CurveElement set(Element e) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement set(int value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement set(BigInteger value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement twice() { return (CurveElement) super.duplicate().twice().getImmutable(); } @Override public CurveElement setToZero() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement setToOne() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement setToRandom() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public CurveElement square() { return (CurveElement) super.duplicate().square().getImmutable(); } @Override public CurveElement invert() { return (CurveElement) super.duplicate().invert().getImmutable(); } @Override public CurveElement negate() { return (CurveElement) super.duplicate().negate().getImmutable(); } @Override public CurveElement add(Element e) { return (CurveElement) super.duplicate().add(e).getImmutable(); } @Override public CurveElement mul(Element e) { return (CurveElement) super.duplicate().mul(e).getImmutable(); } @Override public CurveElement mul(BigInteger n) { return (CurveElement) super.duplicate().mul(n).getImmutable(); } @Override public CurveElement mulZn(Element e) { return (CurveElement) super.duplicate().mulZn(e).getImmutable(); } @Override public CurveElement powZn(Element e) { return (CurveElement) super.duplicate().powZn(e).getImmutable(); } @Override public CurveElement setFromHash(byte[] source, int offset, int length) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesCompressed(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesCompressed(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesX(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesX(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public Element pow(BigInteger n) { return (CurveElement) super.duplicate().pow(n).getImmutable(); } @Override public Element halve() { return (CurveElement) super.duplicate().halve().getImmutable(); } @Override public Element sub(Element element) { return (CurveElement) super.duplicate().sub(element).getImmutable(); } @Override public Element div(Element element) { return (CurveElement) super.duplicate().div(element).getImmutable(); } @Override public Element mul(int z) { return (CurveElement) super.duplicate().mul(z).getImmutable(); } @Override public Element sqrt() { return (CurveElement) super.duplicate().sqrt().getImmutable(); } }
4,629
26.235294
104
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/gt/GTFiniteElement.java
package it.unisa.dia.gas.plaf.jpbc.field.gt; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractElement; import it.unisa.dia.gas.plaf.jpbc.pairing.map.PairingMap; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class GTFiniteElement extends AbstractElement { protected PairingMap pairing; protected Element value; public GTFiniteElement(PairingMap pairing, GTFiniteField field) { super(field); this.pairing = pairing; this.value = field.getTargetField().newElement().setToOne(); } public GTFiniteElement(PairingMap pairing, GTFiniteField field, Element value) { super(field); this.pairing = pairing; this.value = value; } public GTFiniteElement(GTFiniteElement element) { super(element.field); this.pairing = element.pairing; this.value = element.value; } public GTFiniteElement getImmutable() { if (isImmutable()) return this; return new ImmutableGTFiniteElement(this); } public GTFiniteElement duplicate() { return new GTFiniteElement(pairing, (GTFiniteField) field, value.duplicate()); } public GTFiniteElement set(Element value) { this.value.set(((GTFiniteElement) value).value); return this; } public GTFiniteElement set(int value) { this.value.set(value); return this; } public GTFiniteElement set(BigInteger value) { this.value.set(value); return this; } public boolean isZero() { return isOne(); } public boolean isOne() { return value.isOne(); } public GTFiniteField getField() { return (GTFiniteField) field; } public GTFiniteElement setToZero() { value.setToOne(); return this; } public GTFiniteElement setToOne() { value.setToOne(); return this; } public GTFiniteElement setToRandom() { value.setToRandom(); pairing.finalPow(value); return this; } public GTFiniteElement setFromHash(byte[] source, int offset, int length) { value.setFromHash(source, offset, length); pairing.finalPow(value); return this; } public int setFromBytes(byte[] source) { return value.setFromBytes(source); } public int setFromBytes(byte[] source, int offset) { return value.setFromBytes(source, offset); } public GTFiniteElement invert() { value.invert(); return this; } public GTFiniteElement negate() { return invert(); } public GTFiniteElement add(Element element) { return mul(element); } public GTFiniteElement sub(Element element) { return div(element); } public GTFiniteElement div(Element element) { value.div(((GTFiniteElement) element).value); return this; } public GTFiniteElement mul(Element element) { value.mul(((GTFiniteElement) element).value); return this; } public GTFiniteElement mul(BigInteger n) { return pow(n); } public boolean isSqr() { throw new IllegalStateException("Not Implemented yet!"); } public GTFiniteElement pow(BigInteger n) { this.value.pow(n); return this; } public boolean isEqual(Element element) { return this == element || (element instanceof GTFiniteElement && value.isEqual(((GTFiniteElement) element).value)); } public GTFiniteElement powZn(Element n) { this.value.powZn(n); return this; } public BigInteger toBigInteger() { return value.toBigInteger(); } @Override public byte[] toBytes() { return value.toBytes(); } public int sign() { throw new IllegalStateException("Not implemented yet!!!"); } public String toString() { return value.toString(); } }
4,050
20.663102
123
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/gt/GTFiniteField.java
package it.unisa.dia.gas.plaf.jpbc.field.gt; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver; import it.unisa.dia.gas.plaf.jpbc.pairing.map.PairingMap; import java.math.BigInteger; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class GTFiniteField<F extends Field> extends AbstractFieldOver<F, GTFiniteElement> { protected PairingMap pairing; protected BigInteger order; public GTFiniteField(SecureRandom random, BigInteger order, PairingMap pairing, F targetField) { super(random, targetField); this.order = order; this.pairing = pairing; } public GTFiniteElement newElement() { return new GTFiniteElement(pairing, this); } public BigInteger getOrder() { return order; } public GTFiniteElement getNqr() { throw new IllegalStateException("Not Implemented yet!"); } public int getLengthInBytes() { return getTargetField().getLengthInBytes(); } }
1,065
23.790698
100
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/gt/ImmutableGTFiniteElement.java
package it.unisa.dia.gas.plaf.jpbc.field.gt; import it.unisa.dia.gas.jpbc.Element; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class ImmutableGTFiniteElement extends GTFiniteElement { public ImmutableGTFiniteElement(GTFiniteElement gtFiniteElement) { super(gtFiniteElement); this.value = gtFiniteElement.value.getImmutable(); this.immutable = true; } @Override public GTFiniteElement duplicate() { return super.duplicate(); } @Override public GTFiniteElement getImmutable() { return this; } @Override public GTFiniteElement set(Element value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement set(int value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement set(BigInteger value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement twice() { return (GTFiniteElement) duplicate().twice().getImmutable(); } @Override public GTFiniteElement mul(int z) { return (GTFiniteElement) duplicate().mul(z).getImmutable(); } @Override public GTFiniteElement setToZero() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement setToOne() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement setToRandom() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement setFromHash(byte[] source, int offset, int length) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public GTFiniteElement square() { return (GTFiniteElement) duplicate().square().getImmutable(); } @Override public GTFiniteElement invert() { return duplicate().invert().getImmutable(); } @Override public GTFiniteElement halve() { return (GTFiniteElement) duplicate().halve().getImmutable(); } @Override public GTFiniteElement negate() { return duplicate().negate().getImmutable(); } @Override public GTFiniteElement add(Element element) { return duplicate().add(element).getImmutable(); } @Override public GTFiniteElement sub(Element element) { return duplicate().sub(element).getImmutable(); } @Override public GTFiniteElement div(Element element) { return duplicate().div(element).getImmutable(); } @Override public GTFiniteElement mul(Element element) { return duplicate().mul(element).getImmutable(); } @Override public GTFiniteElement mul(BigInteger n) { return duplicate().mul(n).getImmutable(); } @Override public GTFiniteElement mulZn(Element z) { return (GTFiniteElement) duplicate().mulZn(z).getImmutable(); } @Override public GTFiniteElement sqrt() { return (GTFiniteElement) duplicate().sqrt().getImmutable(); } @Override public GTFiniteElement pow(BigInteger n) { return duplicate().pow(n).getImmutable(); } @Override public GTFiniteElement powZn(Element n) { return duplicate().powZn(n).getImmutable(); } }
3,844
24.805369
80
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/AbstractPolyElement.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Polynomial; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractElement; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver; import java.util.ArrayList; import java.util.List; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public abstract class AbstractPolyElement<E extends Element, F extends AbstractFieldOver> extends AbstractElement<F> implements Polynomial<E> { protected List<E> coefficients; protected AbstractPolyElement(F field) { super(field); this.coefficients = new ArrayList<E>(); } public int getSize() { return coefficients.size(); } public E getAt(int index) { return coefficients.get(index); } public List<E> getCoefficients() { return coefficients; } public E getCoefficient(int index) { return coefficients.get(index); } public int getDegree() { return coefficients.size(); } }
1,060
21.574468
89
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/ImmutablePolyModElement.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class ImmutablePolyModElement<E extends Element> extends PolyModElement<E> { public ImmutablePolyModElement(PolyModElement<E> element) { super(element.getField()); coefficients.clear(); for (int i = 0; i < field.n; i++) { coefficients.add((E) element.getCoefficient(i).getImmutable()); } this.immutable = true; } @Override public PolyModElement<E> duplicate() { return super.duplicate(); } @Override public Element getImmutable() { return this; } @Override public PolyModElement<E> set(Element e) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> set(int value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> set(BigInteger value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> setToRandom() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> setFromHash(byte[] source, int offset, int length) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> setToZero() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> setToOne() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> map(Element e) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public PolyModElement<E> twice() { return (PolyModElement<E>) super.duplicate().twice().getImmutable(); } @Override public PolyModElement<E> square() { return (PolyModElement<E>) super.duplicate().square().getImmutable(); } @Override public PolyModElement<E> invert() { return (PolyModElement<E>) super.duplicate().invert().getImmutable(); } @Override public PolyModElement<E> negate() { return (PolyModElement<E>) super.duplicate().negate().getImmutable(); } @Override public PolyModElement<E> add(Element e) { return (PolyModElement<E>) super.duplicate().add(e).getImmutable(); } @Override public PolyModElement<E> sub(Element e) { return (PolyModElement<E>) super.duplicate().sub(e).getImmutable(); } @Override public PolyModElement<E> mul(Element e) { return (PolyModElement<E>) super.duplicate().mul(e).getImmutable(); } @Override public PolyModElement<E> mul(int z) { return (PolyModElement<E>) super.duplicate().mul(z).getImmutable(); } @Override public PolyModElement<E> mul(BigInteger n) { return (PolyModElement<E>) super.duplicate().mul(n).getImmutable(); } @Override public Element pow(BigInteger n) { return (PolyModElement<E>) super.duplicate().pow(n).getImmutable(); } @Override public PolyModElement<E> powZn(Element e) { return (PolyModElement<E>) super.duplicate().powZn(e).getImmutable(); } @Override public PolyModElement<E> sqrt() { return (PolyModElement<E>) super.duplicate().sqrt().getImmutable(); } @Override public int setFromBytes(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public Element halve() { return (PolyModElement<E>) super.duplicate().halve().getImmutable(); } @Override public Element div(Element element) { return (PolyModElement<E>) super.duplicate().div(element).getImmutable(); } @Override public Element mulZn(Element z) { return (PolyModElement<E>) super.duplicate().mulZn(z).getImmutable(); } }
4,405
26.886076
84
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyElement.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.jpbc.Polynomial; import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class PolyElement<E extends Element> extends AbstractPolyElement<E, PolyField> { public PolyElement(PolyField<Field> field) { super(field); } public PolyField getField() { return field; } public PolyElement<E> duplicate() { PolyElement copy = new PolyElement((PolyField<Field>) field); for (Element e : coefficients) { copy.coefficients.add(e.duplicate()); } return copy; } public PolyElement<E> set(Element e) { PolyElement<E> element = (PolyElement<E>) e; ensureSize(element.coefficients.size()); for (int i = 0; i < coefficients.size(); i++) { coefficients.get(i).set(element.coefficients.get(i)); } return this; } public PolyElement<E> set(int value) { ensureSize(1); coefficients.get(0).set(value); removeLeadingZeroes(); return this; } public PolyElement<E> set(BigInteger value) { ensureSize(1); coefficients.get(0).set(value); removeLeadingZeroes(); return this; } public PolyElement<E> setToRandom() { throw new IllegalStateException("Not Implemented yet!"); } public PolyElement<E> setFromHash(byte[] source, int offset, int length) { throw new IllegalStateException("Not Implemented yet!"); } public PolyElement<E> setToZero() { ensureSize(0); return this; } public boolean isZero() { return coefficients.size() == 0; } public PolyElement<E> setToOne() { ensureSize(1); coefficients.get(0).setToOne(); return this; } public boolean isOne() { return coefficients.size() == 1 && coefficients.get(0).isOne(); } public PolyElement<E> twice() { for (int i = 0, size = coefficients.size(); i < size; i++) { coefficients.get(i).twice(); } return this; } public PolyElement<E> invert() { throw new IllegalStateException("Not Implemented yet!"); } public PolyElement<E> negate() { for (int i = 0, size = coefficients.size(); i < size; i++) { coefficients.get(i).negate(); } return this; } public PolyElement<E> add(Element e) { PolyElement<E> element = (PolyElement<E>) e; int i, n, n1; PolyElement<E> big; n = coefficients.size(); n1 = element.coefficients.size(); if (n > n1) { big = this; n = n1; n1 = coefficients.size(); } else { big = element; } ensureSize(n1); for (i = 0; i < n; i++) { coefficients.get(i).add(element.coefficients.get(i)); } for (; i < n1; i++) { coefficients.get(i).set(big.coefficients.get(i)); } removeLeadingZeroes(); return this; } public PolyElement<E> sub(Element e) { PolyElement<E> element = (PolyElement<E>) e; int i, n, n1; PolyElement<E> big; n = coefficients.size(); n1 = element.coefficients.size(); if (n > n1) { big = this; n = n1; n1 = coefficients.size(); } else { big = element; } ensureSize(n1); for (i = 0; i < n; i++) { coefficients.get(i).sub(element.coefficients.get(i)); } for (; i < n1; i++) { if (big == this) { coefficients.get(i).set(big.coefficients.get(i)); // coefficients.add((E) big.coefficients.get(i).duplicate()); } else { coefficients.get(i).set(big.coefficients.get(i)).negate(); // coefficients.add((E) big.coefficients.get(i).duplicate().negate()); } } removeLeadingZeroes(); return this; } public PolyElement<E> div(Element e) { throw new IllegalStateException("Not Implemented yet!"); } public PolyElement<E> mul(Element e) { PolyElement<E> element = (PolyElement<E>) e; int fcount = coefficients.size(); int gcount = element.coefficients.size(); int i, j, n; PolyElement prod; Element e0; if (fcount == 0 || gcount == 0) { setToZero(); return this; } prod = (PolyElement) field.newElement(); n = fcount + gcount - 1; prod.ensureSize(n); e0 = field.getTargetField().newElement(); for (i = 0; i < n; i++) { Element x = prod.getCoefficient(i); x.setToZero(); for (j = 0; j <= i; j++) { if (j < fcount && i - j < gcount) { e0.set(coefficients.get(j)).mul(element.coefficients.get(i - j)); x.add(e0); } } } prod.removeLeadingZeroes(); set(prod); return this; } public PolyElement<E> mul(int z) { for (int i = 0, size = coefficients.size(); i < size; i++) { coefficients.get(i).mul(z); } return this; } public PolyElement<E> mul(BigInteger n) { for (int i = 0, size = coefficients.size(); i < size; i++) { coefficients.get(i).mul(n); } return this; } public PolyElement<E> sqrt() { throw new IllegalStateException("Not Implemented yet!"); } public boolean isSqr() { throw new IllegalStateException("Not Implemented yet!"); } public int sign() { int res = 0; for (int i = 0, size = coefficients.size(); i < size; i++) { res = coefficients.get(i).sign(); if (res != 0) break; } return res; } public boolean isEqual(Element e) { if (e == this) return true; if (!(e instanceof PolyElement)) return false; PolyElement<E> element = (PolyElement<E>) e; int n = this.coefficients.size(); int n1 = element.coefficients.size(); if (n != n1) return false; for (int i = 0; i < n; i++) { if (!coefficients.get(i).isEqual(element.coefficients.get(i))) return false; } return true; } public byte[] toBytes() { int count = coefficients.size(); int targetLB = field.getTargetField().getLengthInBytes(); byte[] buffer = new byte[2 + (count * targetLB)]; buffer[0] = (byte) ((count >>> 8) & 0xFF); buffer[1] = (byte) ((count >>> 0) & 0xFF); for (int len = 2, i = 0; i < count; i++, len += targetLB) { byte[] temp = coefficients.get(i).toBytes(); System.arraycopy(temp, 0, buffer, len, targetLB); } return buffer; } public int setFromBytes(byte[] source) { return setFromBytes(source, 0); } @Override public int setFromBytes(byte[] source, int offset) { int len = offset; int count = ((source[len] << 8) + (source[len+1] << 0)); ensureSize(count); len += 2; for (int i = 0; i < count; i++) { len += coefficients.get(i).setFromBytes(source, len); } return len - offset; } public BigInteger toBigInteger() { throw new IllegalStateException("Not Implemented yet!"); } public int getDegree() { return coefficients.size() - 1; } public String toString() { StringBuffer buffer = new StringBuffer("["); for (Element e : coefficients) { buffer.append(e).append(" "); } buffer.append("]"); return buffer.toString(); } public void ensureSize(int size) { int k = coefficients.size(); while (k < size) { coefficients.add((E) field.getTargetField().newElement()); k++; } while (k > size) { k--; coefficients.remove(coefficients.size() - 1); } } public void setCoefficient1(int n) { if (this.coefficients.size() < n + 1) { ensureSize(n + 1); } this.coefficients.get(n).setToOne(); } public void removeLeadingZeroes() { int n = coefficients.size() - 1; while (n >= 0) { Element e0 = coefficients.get(n); if (!e0.isZero()) return; coefficients.remove(n); n--; } } public PolyElement<E> setFromPolyMod(PolyModElement polyModElement) { int i, n = polyModElement.getField().getN(); ensureSize(n); for (i = 0; i < n; i++) { coefficients.get(i).set(polyModElement.getCoefficient(i)); } removeLeadingZeroes(); return this; } public PolyElement<E> setToRandomMonic(int degree) { ensureSize(degree + 1); int i; for (i = 0; i < degree; i++) { coefficients.get(i).setToRandom(); } coefficients.get(i).setToOne(); return this; } public PolyElement<E> setFromCoefficientMonic(BigInteger[] coefficients) { setCoefficient1(coefficients.length - 1); for (int i = 0; i < coefficients.length; i++) { this.coefficients.get(i).set(coefficients[i]); } return this; } public PolyElement<E> makeMonic() { int n = this.coefficients.size(); if (n == 0) return this; Element e0 = coefficients.get(n - 1); e0.invert(); for (int i = 0; i < n - 1; i++) { coefficients.get(i).mul(e0); } e0.setToOne(); return this; } /** * Returns <tt>true</tt> if polynomial is irreducible, <tt>false</tt> otherwise. * <p/> * A polynomial f(x) is irreducible in F_q[x] if and only if: * (1) f(x) | x^{q^n} - x, and * (2) gcd(f(x), x^{q^{n/d}} - x) = 1 for all primes d | n. * (Recall GF(p) is the splitting field for x^p - x.) * * @return */ public boolean isIrriducible() { // 0, units are not irreducibles. // Assume coefficients are from a field. if (getDegree() <= 0) return false; // Degree 1 polynomials are always irreducible. if (getDegree() == 1) return true; PolyModField rxmod = new PolyModField(field.getRandom(), this); final PolyModElement xpow = rxmod.newElement(); // The degree fits in an unsigned int but I'm lazy and want to use my // mpz trial division code. final PolyElement g = getField().newElement(); final PolyModElement x = rxmod.newElement(); x.getCoefficient(1).setToOne(); final BigInteger deg = BigInteger.valueOf(getDegree()); BigIntegerUtils.TrialDivide trialDivide = new BigIntegerUtils.TrialDivide(null) { protected int fun(BigInteger factor, int multiplicity) { BigInteger z = deg.divide(factor); z = getField().getTargetField().getOrder().pow(z.intValue()); xpow.set(x).pow(z).sub(x); if (xpow.isZero()) return 1; g.setFromPolyMod(xpow); g.gcd(PolyElement.this); return g.getDegree() != 0 ? 1 : 0; } }; if (trialDivide.trialDivide(deg) == 0) { // By now condition (2) has been satisfied. Check (1). BigInteger z = getField().getTargetField().getOrder().pow(this.getDegree()); xpow.set(x).pow(z).sub(x); return xpow.isZero(); } return false; } public PolyElement<E> gcd(PolyElement g) { PolyElement a = this.duplicate(); PolyElement b = g.duplicate(); Element r = field.newElement(); while (true) { PolyUtils.reminder(r, a, b); if (r.isZero()) break; a.set(b); b.set(r); } set(b); return this; } /** * Returns 0 if a root exists and sets root to one of the roots * otherwise return value is nonzero * * @return */ public E findRoot() { // Compute gcd(x^q - x, poly) PolyModField<Field> fpxmod = new PolyModField<Field>(field.getRandom(), this); PolyModElement p = fpxmod.newElement(); Polynomial x = fpxmod.newElement(); BigInteger q = field.getTargetField().getOrder(); PolyElement g = (PolyElement) field.newElement(); x.getCoefficient(1).setToOne(); p.set(x).pow(q).sub(x); g.setFromPolyMod(p).gcd(this).makeMonic(); if (g.getDegree() == 0) { return null; } // Use Cantor-Zassenhaus to find a root PolyElement fac = (PolyElement) field.newElement(); PolyElement r = (PolyElement) field.newElement(); x = (PolyElement) field.newElement(1); q = q.subtract(BigInteger.ONE); q = q.divide(BigIntegerUtils.TWO); while (true) { if (g.getDegree() == 1) { // found a root! break; } while (true) { r.setToRandomMonic(1); // TODO(-): evaluate at g instead of bothering with gcd fac.set(r).gcd(g); if (fac.getDegree() > 0) { g.set(fac).makeMonic(); break; } else { fpxmod = new PolyModField<Field>(field.getRandom(), g, null); p = fpxmod.newElement(); p.setFromPolyTruncate(r); p.pow(q); r.setFromPolyMod(p); r.add(x); fac.set(r).gcd(g); int n = fac.getDegree(); if (n > 0 && n < g.getDegree()) { g.set(fac).makeMonic(); break; } } } } return (E) g.getCoefficient(0).negate(); } }
14,552
25.080645
89
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyField.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver; import java.math.BigInteger; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class PolyField<F extends Field> extends AbstractFieldOver<F, PolyElement> { public PolyField(SecureRandom random, F targetField) { super(random, targetField); } public PolyField(F targetField) { super(new SecureRandom(), targetField); } public PolyElement newElement() { return new PolyElement(this); } public BigInteger getOrder() { throw new IllegalStateException("Not Implemented yet!"); } public PolyElement getNqr() { throw new IllegalStateException("Not Implemented yet!"); } public int getLengthInBytes() { throw new IllegalStateException("Not Implemented yet!"); } }
956
22.341463
83
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyModElement.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.jpbc.Polynomial; import it.unisa.dia.gas.plaf.jpbc.util.math.BigIntegerUtils; import java.math.BigInteger; import java.util.List; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class PolyModElement<E extends Element> extends AbstractPolyElement<E, PolyModField> { public PolyModElement(PolyModField field) { super(field); for (int i = 0; i < field.n; i++) coefficients.add((E) field.getTargetField().newElement()); } public PolyModElement(PolyModElement<E> source) { super(source.getField()); for (int i = 0, n = source.getSize(); i < n; i++) coefficients.add((E) source.getCoefficient(i).duplicate()); } @Override public Element getImmutable() { return new ImmutablePolyModElement<E>(this); } public PolyModField getField() { return field; } public PolyModElement<E> duplicate() { return new PolyModElement<E>(this); } public PolyModElement<E> set(Element e) { PolyModElement<E> element = (PolyModElement<E>) e; for (int i = 0; i < coefficients.size(); i++) { coefficients.get(i).set(element.coefficients.get(i)); } return this; } public PolyModElement<E> set(int value) { coefficients.get(0).set(value); for (int i = 1; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public PolyModElement<E> set(BigInteger value) { coefficients.get(0).set(value); for (int i = 1; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public PolyModElement<E> setToRandom() { for (int i = 0; i < field.n; i++) { coefficients.get(i).setToRandom(); } return this; } public PolyModElement<E> setFromHash(byte[] source, int offset, int length) { for (int i = 0; i < field.n; i++) { coefficients.get(i).setFromHash(source, offset, length); } return this; } public PolyModElement<E> setToZero() { for (int i = 0; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public boolean isZero() { for (int i = 0; i < field.n; i++) { if (!coefficients.get(i).isZero()) return false; } return true; } public PolyModElement<E> setToOne() { coefficients.get(0).setToOne(); for (int i = 1; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public boolean isOne() { if (!coefficients.get(0).isOne()) return false; for (int i = 1; i < field.n; i++) { if (!coefficients.get(i).isZero()) return false; } return true; } public PolyModElement<E> map(Element e) { coefficients.get(0).set(e); for (int i = 1; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public PolyModElement<E> twice() { for (int i = 0; i < field.n; i++) { coefficients.get(i).twice(); } return this; } public PolyModElement<E> square() { switch (field.n) { case 3: PolyModElement<E> p0 = field.newElement(); Element c0 = field.getTargetField().newElement(); Element c2 = field.getTargetField().newElement(); Element c3 = p0.coefficients.get(0); Element c1 = p0.coefficients.get(1); c3.set(coefficients.get(0)).mul(coefficients.get(1)); c1.set(coefficients.get(0)).mul(coefficients.get(2)); coefficients.get(0).square(); c2.set(coefficients.get(1)).mul(coefficients.get(2)); c0.set(coefficients.get(2)).square(); coefficients.get(2).set(coefficients.get(1)).square(); coefficients.get(1).set(c3).add(c3); c1.add(c1); coefficients.get(2).add(c1); p0.set(field.xpwr[1]); p0.polymodConstMul(c0); add(p0); c2.add(c2); p0.set(field.xpwr[0]); p0.polymodConstMul(c2); add(p0); return this; default: squareInternal(); } return this; } public PolyModElement<E> invert() { setFromPolyTruncate(polyInvert(field.irreduciblePoly.getField().newElement().setFromPolyMod(this))); return this; } public PolyModElement<E> negate() { for (Element e : coefficients) { e.negate(); } return this; } public PolyModElement<E> add(Element e) { PolyModElement<E> element = (PolyModElement<E>) e; for (int i = 0; i < field.n; i++) { coefficients.get(i).add(element.coefficients.get(i)); } return this; } public PolyModElement<E> sub(Element e) { PolyModElement<E> element = (PolyModElement<E>) e; for (int i = 0; i < field.n; i++) { coefficients.get(i).sub(element.coefficients.get(i)); } return this; } public PolyModElement<E> mul(Element e) { Polynomial<E> element = (Polynomial<E>) e; switch (field.n) { case 3: PolyModElement<E> p0 = field.newElement(); Element c3 = field.getTargetField().newElement(); Element c4 = field.getTargetField().newElement(); kar_poly_2(coefficients, c3, c4, coefficients, element.getCoefficients(), p0.coefficients); p0.set(field.xpwr[0]).polymodConstMul(c3); add(p0); p0.set(field.xpwr[1]).polymodConstMul(c4); add(p0); return this; // case 6: // TODO: port the PBC code // throw new IllegalStateException("Not Implemented yet!"); /* mfptr p = res->field->data; element_t *dst = res->data, *s0, *s1 = e->data, *s2 = f->data; element_t *a0, *a1, *b0, *b1; element_t p0, p1, p2, p3; a0 = s1; a1 = &s1[3]; b0 = s2; b1 = &s2[3]; element_init(p0, res->field); element_init(p1, res->field); element_init(p2, res->field); element_init(p3, res->field); s0 = p0->data; s1 = p1->data; s2 = p2->data; element_add(s0[0], a0[0], a1[0]); element_add(s0[1], a0[1], a1[1]); element_add(s0[2], a0[2], a1[2]); element_add(s1[0], b0[0], b1[0]); element_add(s1[1], b0[1], b1[1]); element_add(s1[2], b0[2], b1[2]); kar_poly_2(s2, s2[3], s2[4], s0, s1, p3->data); kar_poly_2(s0, s0[3], s0[4], a0, b0, p3->data); kar_poly_2(s1, s1[3], s1[4], a1, b1, p3->data); element_set(dst[0], s0[0]); element_set(dst[1], s0[1]); element_set(dst[2], s0[2]); element_sub(dst[3], s0[3], s0[0]); element_sub(dst[3], dst[3], s1[0]); element_add(dst[3], dst[3], s2[0]); element_sub(dst[4], s0[4], s0[1]); element_sub(dst[4], dst[4], s1[1]); element_add(dst[4], dst[4], s2[1]); element_sub(dst[5], s2[2], s0[2]); element_sub(dst[5], dst[5], s1[2]); // Start reusing part of s0 as scratch space(!) element_sub(s0[0], s2[3], s0[3]); element_sub(s0[0], s0[0], s1[3]); element_add(s0[0], s0[0], s1[0]); element_sub(s0[1], s2[4], s0[4]); element_sub(s0[1], s0[1], s1[4]); element_add(s0[1], s0[1], s1[1]); polymod_const_mul(p3, s0[0], p->xpwr[0]); element_add(res, res, p3); polymod_const_mul(p3, s0[1], p->xpwr[1]); element_add(res, res, p3); polymod_const_mul(p3, s1[2], p->xpwr[2]); element_add(res, res, p3); polymod_const_mul(p3, s1[3], p->xpwr[3]); element_add(res, res, p3); polymod_const_mul(p3, s1[4], p->xpwr[4]); element_add(res, res, p3); element_clear(p0); element_clear(p1); element_clear(p2); element_clear(p3); */ default: Element[] high = new Element[field.n - 1]; for (int i = 0, size = field.n - 1; i < size; i++) { high[i] = field.getTargetField().newElement().setToZero(); } PolyModElement<E> prod = field.newElement(); p0 = field.newElement(); Element c0 = field.getTargetField().newElement(); for (int i = 0; i < field.n; i++) { int ni = field.n - i; int j = 0; for (; j < ni; j++) { c0.set(coefficients.get(i)).mul(element.getCoefficient(j)); prod.coefficients.get(i + j).add(c0); } for (; j < field.n; j++) { c0.set(coefficients.get(i)).mul(element.getCoefficient(j)); high[j - ni].add(c0); } } for (int i = 0, size = field.n - 1; i < size; i++) { p0.set(field.xpwr[i]).polymodConstMul(high[i]); prod.add(p0); } set(prod); return this; } } public PolyModElement<E> mul(int z) { for (int i = 0; i < field.n; i++) { coefficients.get(i).mul(z); } return this; } public PolyModElement<E> mul(BigInteger n) { for (int i = 0; i < field.n; i++) { coefficients.get(i).mul(n); } return this; } public PolyModElement<E> powZn(Element e) { // TODO: port the PBC code return (PolyModElement<E>) pow(e.toBigInteger()); } public PolyModElement<E> sqrt() { PolyField polyField = new PolyField(field.getRandom(), field); PolyElement f = polyField.newElement(); PolyElement r = polyField.newElement(); PolyElement s = polyField.newElement(); Element e0 = field.newElement(); f.ensureSize(3); f.getCoefficient(2).setToOne(); f.getCoefficient(0).set(this).negate(); BigInteger z = field.getOrder().subtract(BigInteger.ONE).divide(BigIntegerUtils.TWO); while (true) { int i; Element x; Element e1, e2; r.ensureSize(2); r.getCoefficient(1).setToOne(); x = r.getCoefficient(0); x.setToRandom(); e0.set(x).mul(x); if (e0.isEqual(this)) { set(x); break; } s.setToOne(); for (i = z.bitLength() - 1; i >= 0; i--) { s.mul(s); if (s.getDegree() == 2) { e1 = s.getCoefficient(0); e2 = s.getCoefficient(2); e0.set(e2).mul(this); e1.add(e0); s.ensureSize(2); s.removeLeadingZeroes(); } if (z.testBit(i)) { s.mul(r); if (s.getDegree() == 2) { e1 = s.getCoefficient(0); e2 = s.getCoefficient(2); e0.set(e2).mul(this); e1.add(e0); s.ensureSize(2); s.removeLeadingZeroes(); } } } if (s.getDegree() < 1) continue; e0.setToOne(); e1 = s.getCoefficient(0); e2 = s.getCoefficient(1); e1.add(e0); e0.set(e2).invert(); e0.mul(e1); e2.set(e0).mul(e0); if (e2.isEqual(this)) { set(e0); break; } } return this; } public boolean isSqr() { BigInteger z = field.getOrder().subtract(BigInteger.ONE).divide(BigIntegerUtils.TWO); return field.newElement().set(this).pow(z).isOne(); } public int sign() { int res = 0; for (int i = 0, size = coefficients.size(); i < size; i++) { res = coefficients.get(i).sign(); if (res != 0) break; } return res; } public boolean isEqual(Element e) { if (e == this) return true; if (!(e instanceof PolyModElement)) return false; PolyModElement<E> element = (PolyModElement<E>) e; for (int i = 0; i < field.n; i++) { if (!coefficients.get(i).isEqual(element.coefficients.get(i))) return false; } return true; } public int setFromBytes(byte[] source) { return setFromBytes(source, 0); } public int setFromBytes(byte[] source, int offset) { int len = offset; for (int i = 0, size = coefficients.size(); i < size; i++) { len += coefficients.get(i).setFromBytes(source, len); } return len - offset; } public byte[] toBytes() { byte[] buffer = new byte[field.getLengthInBytes()]; int targetLB = field.getTargetField().getLengthInBytes(); for (int len = 0, i = 0, size = coefficients.size(); i < size; i++, len += targetLB) { byte[] temp = coefficients.get(i).toBytes(); System.arraycopy(temp, 0, buffer, len, targetLB); } return buffer; } public BigInteger toBigInteger() { return coefficients.get(0).toBigInteger(); } public String toString() { StringBuilder buffer = new StringBuilder("["); for (Element e : coefficients) { buffer.append(e).append(", "); } buffer.append("]"); return buffer.toString(); } public PolyModElement<E> setFromPolyTruncate(PolyElement<E> element) { int n = element.getCoefficients().size(); if (n > field.n) n = field.n; int i = 0; for (; i < n; i++) { coefficients.get(i).set(element.getCoefficients().get(i)); } for (; i < field.n; i++) { coefficients.get(i).setToZero(); } return this; } public PolyModElement<E> polymodConstMul(Element e) { //a lies in R, e in R[x] for (int i = 0, n = coefficients.size(); i < n; i++) { coefficients.get(i).mul(e); } return this; } protected void squareInternal() { List<E> dst; List<E> src = coefficients; int n = field.n; PolyModElement<E> prod, p0; Element c0; int i, j; Element high[] = new Element[n - 1]; for (i = 0; i < n - 1; i++) { high[i] = field.getTargetField().newElement().setToZero(); } prod = field.newElement(); dst = prod.coefficients; p0 = field.newElement(); c0 = field.getTargetField().newElement(); for (i = 0; i < n; i++) { int twicei = 2 * i; c0.set(src.get(i)).square(); if (twicei < n) { dst.get(twicei).add(c0); } else { high[twicei - n].add(c0); } for (j = i + 1; j < n - i; j++) { c0.set(src.get(i)).mul(src.get(j)); c0.add(c0); dst.get(i + j).add(c0); } for (; j < n; j++) { c0.set(src.get(i)).mul(src.get(j)); c0.add(c0); high[i + j - n].add(c0); } } for (i = 0; i < n - 1; i++) { p0.set(field.xpwr[i]).polymodConstMul(high[i]); prod.add(p0); } set(prod); } /** * Karatsuba for degree 2 polynomials * * @param dst * @param c3 * @param c4 * @param s1 * @param s2 * @param scratch */ protected void kar_poly_2(List<E> dst, Element c3, Element c4, List<E> s1, List<E> s2, List<E> scratch) { Element c01, c02, c12; c12 = scratch.get(0); c02 = scratch.get(1); c01 = scratch.get(2); c3.set(s1.get(0)).add(s1.get(1)); c4.set(s2.get(0)).add(s2.get(1)); c01.set(c3).mul(c4); c3.set(s1.get(0)).add(s1.get(2)); c4.set(s2.get(0)).add(s2.get(2)); c02.set(c3).mul(c4); c3.set(s1.get(1)).add(s1.get(2)); c4.set(s2.get(1)).add(s2.get(2)); c12.set(c3).mul(c4); dst.get(1).set(s1.get(1)).mul(s2.get(1)); //constant term dst.get(0).set(s1.get(0)).mul(s2.get(0)); //coefficient of x^4 c4.set(s1.get(2)).mul(s2.get(2)); //coefficient of x^3 c3.set(dst.get(1)).add(c4); c3.set(c12.duplicate().sub(c3)); //coefficient of x^2 dst.get(2).set(c4).add(dst.get(0)); c02.sub(dst.get(2)); dst.get(2).set(dst.get(1)).add(c02); //coefficient of x c01.sub(dst.get(0)); dst.set(1, (E) c01.duplicate().sub(dst.get(1))); } protected PolyElement polyInvert(PolyElement f) { PolyField<Field> polyField = f.getField(); PolyElement q = polyField.newElement(); PolyElement b0 = polyField.newZeroElement(); PolyElement b1 = polyField.newOneElement(); PolyElement b2 = polyField.newElement(); PolyElement r0 = field.irreduciblePoly.duplicate(); PolyElement r1 = f.duplicate(); PolyElement r2 = polyField.newElement(); Element inv = f.getField().getTargetField().newElement(); while (true) { PolyUtils.div(q, r2, r0, r1); if (r2.isZero()) break; b2.set(b1).mul(q); b2.set(b0.duplicate().sub(b2)); b0.set(b1); b1.set(b2); r0.set(r1); r1.set(r2); } inv.set(r1.getCoefficient(0)).invert(); return PolyUtils.constMul(inv, b1); } }
18,754
26.826409
109
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyModField.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; import it.unisa.dia.gas.jpbc.Field; import it.unisa.dia.gas.plaf.jpbc.field.base.AbstractFieldOver; import java.math.BigInteger; import java.security.SecureRandom; import java.util.List; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class PolyModField<F extends Field> extends AbstractFieldOver<F, PolyModElement> { protected PolyElement irreduciblePoly; protected PolyModElement nqr; protected BigInteger order; protected int n; protected int fixedLengthInBytes; protected PolyModElement[] xpwr; public PolyModField(SecureRandom random, F targetField, int cyclotomicPolyDegree) { super(random, targetField); PolyField polyField = new PolyField(random, targetField); irreduciblePoly = polyField.newElement(); List<Element> coefficients = irreduciblePoly.getCoefficients(); coefficients.add(polyField.getTargetField().newElement().setToOne()); for (int i = 1; i < cyclotomicPolyDegree; i++) { coefficients.add(polyField.getTargetField().newZeroElement()); } coefficients.add(polyField.getTargetField().newElement().setToOne()); init(null); } public PolyModField(SecureRandom random, PolyElement irreduciblePoly) { this(random, irreduciblePoly, null); } public PolyModField(SecureRandom random, PolyElement irreduciblePoly, BigInteger nqr) { super(random, (F) irreduciblePoly.getField().getTargetField()); this.irreduciblePoly = irreduciblePoly; init(nqr); } protected void init(BigInteger nqr) { this.n = irreduciblePoly.getDegree(); this.order = targetField.getOrder().pow(irreduciblePoly.getDegree()); if (nqr != null) { this.nqr = newElement(); this.nqr.getCoefficient(0).set(nqr); } // if (order.compareTo(BigInteger.ZERO) != 0) computeXPowers(); if (targetField.getLengthInBytes() < 0) { //f->length_in_bytes = fq_length_in_bytes; fixedLengthInBytes = -1; } else { fixedLengthInBytes = targetField.getLengthInBytes() * n; } } public PolyModElement newElement() { return new PolyModElement(this); } public BigInteger getOrder() { return order; } public PolyModElement getNqr() { return nqr; } public int getLengthInBytes() { return fixedLengthInBytes; } public int getN() { return n; } /** * compute x^n,...,x^{2n-2} mod poly */ protected void computeXPowers() { xpwr = new PolyModElement[n]; for (int i = 0; i < n; i++) { xpwr[i] = newElement(); } xpwr[0].setFromPolyTruncate(irreduciblePoly).negate(); PolyModElement p0 = newElement(); for (int i = 1; i < n; i++) { List<Element> coeff = xpwr[i - 1].getCoefficients(); List<Element> coeff1 = xpwr[i].getCoefficients(); coeff1.get(0).setToZero(); for (int j = 1; j < n; j++) { coeff1.get(j).set(coeff.get(j - 1)); } p0.set(xpwr[0]).polymodConstMul(coeff.get(n - 1)); xpwr[i].add(p0); } // for (PolyModElement polyModElement : xpwr) { // System.out.println("xprw = " + polyModElement); // } /* polymod_field_data_ptr p = field - > data; element_t p0; element_ptr pwrn; element_t * coefficients,*coeff1; int i, j; int n = p - > n; element_t * xpwr; xpwr = p - > xpwr; element_init(p0, field); for (i = 0; i < n; i++) { element_init(xpwr[i], field); } pwrn = xpwr[0]; element_poly_to_polymod_truncate(pwrn, poly); element_neg(pwrn, pwrn); for (i = 1; i < n; i++) { coefficients = xpwr[i - 1] - > data; coeff1 = xpwr[i] - > data; element_set0(coeff1[0]); for (j = 1; j < n; j++) { element_set(coeff1[j], coefficients[j - 1]); } polymod_const_mul(p0, coefficients[n - 1], pwrn); element_add(xpwr[i], xpwr[i], p0); } element_clear(p0); */ } }
4,404
26.53125
91
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/poly/PolyUtils.java
package it.unisa.dia.gas.plaf.jpbc.field.poly; import it.unisa.dia.gas.jpbc.Element; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class PolyUtils { public static PolyElement constMul(Element a, PolyElement poly) { int n = poly.getCoefficients().size(); PolyElement res = poly.getField().newElement(); res.ensureSize(n); for (int i = 0; i < n; i++) { res.getCoefficient(i).set(a).mul(poly.getCoefficient(i)); } res.removeLeadingZeroes(); return res; } public static void div(Element quot, Element rem, PolyElement a, PolyElement b) { if (b.isZero()) throw new IllegalArgumentException("Division by zero!"); int n = b.getDegree(); int m = a.getDegree(); if (n > m) { rem.set(a); quot.setToZero(); return; } int k = m - n; PolyElement r = a.duplicate(); PolyElement q = a.getField().newElement(); q.ensureSize(k + 1); Element temp = a.getField().getTargetField().newElement(); Element bn = b.getCoefficient(n).duplicate().invert(); while (k >= 0) { Element qk = q.getCoefficient(k); qk.set(bn).mul(r.getCoefficient(m)); for (int i = 0; i <= n; i++) { temp.set(qk).mul(b.getCoefficient(i)); r.getCoefficient(i + k).sub(temp); } k--; m--; } r.removeLeadingZeroes(); quot.set(q); rem.set(r); } public static void reminder(Element rem, PolyElement a, PolyElement b) { if (b.isZero()) throw new IllegalArgumentException("Division by zero!"); int n = b.getDegree(); int m = a.getDegree(); if (n > m) { rem.set(a); return; } int k = m - n; PolyElement r = a.duplicate(); PolyElement q = a.getField().newElement(); q.ensureSize(k + 1); Element temp = a.getField().getTargetField().newElement(); Element bn = b.getCoefficient(n).duplicate().invert(); while (k >= 0) { Element qk = q.getCoefficient(k); qk.set(bn).mul(r.getCoefficient(m)); for (int i = 0; i <= n; i++) { temp.set(qk).mul(b.getCoefficient(i)); r.getCoefficient(i + k).sub(temp); } k--; m--; } r.removeLeadingZeroes(); rem.set(r); } }
2,547
23.980392
85
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/DegreeTwoExtensionQuadraticElement.java
package it.unisa.dia.gas.plaf.jpbc.field.quadratic; import it.unisa.dia.gas.jpbc.Element; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class DegreeTwoExtensionQuadraticElement<E extends Element> extends QuadraticElement<E> { public DegreeTwoExtensionQuadraticElement(DegreeTwoExtensionQuadraticField field) { super(field); this.x = (E) field.getTargetField().newElement(); this.y = (E) field.getTargetField().newElement(); } public DegreeTwoExtensionQuadraticElement(DegreeTwoExtensionQuadraticElement element) { super((QuadraticField) element.field); this.x = (E) element.x.duplicate(); this.y = (E) element.y.duplicate(); } public DegreeTwoExtensionQuadraticElement duplicate() { return new DegreeTwoExtensionQuadraticElement(this); } public DegreeTwoExtensionQuadraticElement square() { Element e0 = x.duplicate(); Element e1 = x.duplicate(); e0.add(y).mul(e1.sub(y)); e1.set(x).mul(y).twice()/*add(e1)*/; x.set(e0); y.set(e1); return this; } public DegreeTwoExtensionQuadraticElement invert() { Element e0 = x.duplicate(); Element e1 = y.duplicate(); e0.square().add(e1.square()).invert(); x.mul(e0); y.mul(e0.negate()); return this; } public DegreeTwoExtensionQuadraticElement mul(Element e) { DegreeTwoExtensionQuadraticElement element = (DegreeTwoExtensionQuadraticElement) e; Element e0 = x.duplicate(); Element e1 = element.x.duplicate(); Element e2 = x.getField().newElement(); // e2 = (x+y) * (x1+y1) e2.set(e0.add(y)).mul(e1.add(element.y)); // e0 = x*x1 e0.set(x).mul(element.x); // e1 = y*y1 e1.set(y).mul(element.y); // e2 = (x+y)*(x1+y1) - x*x1 e2.sub(e0); // x = x*x1 - y*y1 x.set(e0).sub(e1); // y = (x+y)*(x1+y1)- x*x1 - y*y1 y.set(e2).sub(e1); return this; } public boolean isSqr() { /* //x + yi is a square <=> x^2 + y^2 is (in the base field) // Proof: (=>) if x+yi = (a+bi)^2, // then a^2 - b^2 = x, 2ab = y, // thus (a^2 + b^2)^2 = (a^2 - b^2)^2 + (2ab)^2 = x^2 + y^2 // (<=) Suppose A^2 = x^2 + y^2 // then if there exist a, b satisfying: // a^2 = (+-A + x)/2, b^2 = (+-A - x)/2 // then (a + bi)^2 = x + yi. // We show that exactly one of (A + x)/2, (-A + x)/2 // is a quadratic residue (thus a, b do exist). // Suppose not. Then the product // (x^2 - A^2) / 4 is some quadratic residue, a contradiction // since this would imply x^2 - A^2 = -y^2 is also a quadratic residue, // but we know -1 is not a quadratic residue. */ return x.duplicate().square().add(y.duplicate().square()).isSqr(); } public DegreeTwoExtensionQuadraticElement sqrt() { //if (a+bi)^2 = x+yi then //2a^2 = x +- sqrt(x^2 + y^2) //(take the sign such that a exists) and 2ab = y //[thus 2b^2 = - (x -+ sqrt(x^2 + y^2))] Element e0 = x.duplicate().square(); Element e1 = y.duplicate().square(); e0.add(e1).sqrt(); //e0 = sqrt(x^2 + y^2) e1.set(x).add(e0); Element e2 = x.getField().newElement().set(2).invert(); e1.mul(e2); //e1 = (x + sqrt(x^2 + y^2))/2 if (e1.isSqr()) { e1.sub(e0); //e1 should be a square } e0.set(e1).sqrt(); e1.set(e0).add(e0); e1.invert(); y.mul(e1); x.set(e0); return this; } public boolean isEqual(Element e) { if (e == this) return true; DegreeTwoExtensionQuadraticElement element = (DegreeTwoExtensionQuadraticElement) e; return x.isEqual(element.x) && y.isEqual(element.y); } public String toString() { return String.format("{x=%s,y=%s}", x, y); } @Override public Element getImmutable() { return new ImmutableDegreeTwoExtensionQuadraticElement(this); } }
4,195
26.973333
96
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/DegreeTwoExtensionQuadraticField.java
package it.unisa.dia.gas.plaf.jpbc.field.quadratic; import it.unisa.dia.gas.jpbc.Field; import java.security.SecureRandom; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class DegreeTwoExtensionQuadraticField<F extends Field> extends QuadraticField<F, DegreeTwoExtensionQuadraticElement> { public DegreeTwoExtensionQuadraticField(SecureRandom random, F targetField) { super(random, targetField); } public DegreeTwoExtensionQuadraticElement newElement() { return new DegreeTwoExtensionQuadraticElement(this); } }
565
24.727273
126
java
CP-ABE
CP-ABE-master/src/jpbc-plaf/src/main/java/it/unisa/dia/gas/plaf/jpbc/field/quadratic/ImmutableDegreeTwoExtensionQuadraticElement.java
package it.unisa.dia.gas.plaf.jpbc.field.quadratic; import it.unisa.dia.gas.jpbc.Element; import java.math.BigInteger; /** * @author Angelo De Caro (jpbclib@gmail.com) */ public class ImmutableDegreeTwoExtensionQuadraticElement<E extends Element> extends DegreeTwoExtensionQuadraticElement<E> { public ImmutableDegreeTwoExtensionQuadraticElement(DegreeTwoExtensionQuadraticElement<E> element) { super((DegreeTwoExtensionQuadraticField)element.getField()); this.x = (E) element.getX().getImmutable(); this.y = (E) element.getY().getImmutable(); this.immutable = true; } @Override public Element getImmutable() { return this; } @Override public DegreeTwoExtensionQuadraticElement duplicate() { return super.duplicate(); } @Override public QuadraticElement set(Element e) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement set(int value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement set(BigInteger value) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement setToZero() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement setToOne() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement setToRandom() { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public QuadraticElement twice() { return (QuadraticElement) super.duplicate().twice().getImmutable(); } @Override public QuadraticElement mul(int z) { return (QuadraticElement) super.duplicate().mul(z).getImmutable(); } @Override public DegreeTwoExtensionQuadraticElement square() { return (DegreeTwoExtensionQuadraticElement) super.duplicate().square().getImmutable(); } @Override public DegreeTwoExtensionQuadraticElement invert() { return (DegreeTwoExtensionQuadraticElement) super.duplicate().invert().getImmutable(); } @Override public QuadraticElement negate() { return (QuadraticElement) super.duplicate().negate().getImmutable(); } @Override public QuadraticElement add(Element e) { return (QuadraticElement) super.duplicate().add(e).getImmutable(); } @Override public QuadraticElement sub(Element e) { return (QuadraticElement) super.duplicate().sub(e).getImmutable(); } @Override public DegreeTwoExtensionQuadraticElement mul(Element e) { return (DegreeTwoExtensionQuadraticElement) super.duplicate().mul(e).getImmutable(); } @Override public QuadraticElement mul(BigInteger n) { return (QuadraticElement) super.duplicate().mul(n).getImmutable(); } @Override public QuadraticElement mulZn(Element e) { return (QuadraticElement) super.duplicate().mulZn(e).getImmutable(); } @Override public DegreeTwoExtensionQuadraticElement sqrt() { return (DegreeTwoExtensionQuadraticElement) super.duplicate().sqrt().getImmutable(); } @Override public QuadraticElement powZn(Element n) { return (QuadraticElement) super.duplicate().powZn(n).getImmutable(); } @Override public QuadraticElement setFromHash(byte[] source, int offset, int length) { return (QuadraticElement) super.duplicate().setFromHash(source, offset, length).getImmutable(); } @Override public int setFromBytesCompressed(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesCompressed(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesX(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytesX(byte[] source, int offset) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public int setFromBytes(byte[] source) { throw new IllegalStateException("Invalid call on an immutable element"); } @Override public Element pow(BigInteger n) { return (QuadraticElement) super.duplicate().pow(n).getImmutable(); } @Override public Element halve() { return (QuadraticElement) super.duplicate().halve().getImmutable(); } @Override public Element div(Element element) { return (QuadraticElement) super.duplicate().div(element).getImmutable(); } }
5,062
28.436047
123
java