def initDeals(self): self.initializedDeals = True # set of all possible deals[B i = self.hSize dType = [i, i, i] # Ignore (for now) that eaves has no card. self.deals = ut.allDeals(dType, [a,b,c], self.cards) # Now the possible deals models if (after a run) the # deal is possible or not. self.possibleDeals = z3.BoolVector('d', len(self.deals))
def __init__(self, hSize): ''' Agents are ['a', 'b', 'c', 'e'] ''' self.agents = [a,b,c] # Eaves is outside the system self.hSize = hSize i = hSize dLst = [i, i, i, 0] deal = ut.minDeal(dLst, [a,b,c,e], range(3*i)) s0 = cps.cpState(dLst, [a,b,c,e], deal, [a,b,c], e) self.cards = range(3*i) # Knowledge/Possibility formula for Eaves. self.pe = {} self.peN = {} self.ke = {} self.keN = {} nCards = len(self.cards) # Initialize all propositions with respect to each agent for agt in ['a','b','c']: self.pe[agt] = z3.BoolVector ('Pe'+agt, nCards) self.peN[agt] = z3.BoolVector('PeN'+agt, nCards) self.ke[agt] = z3.BoolVector ('Ke'+agt, nCards) self.keN[agt] = z3.BoolVector('KeN'+agt, nCards) self.keFml = {} self.keNFml = {} eavesKL = [] eavesKNL = [] for agt in [a,b,c]: self.keFml[agt] = self.eavesK(agt) self.keNFml[agt] = self.eavesKN(agt) eavesKL.append ( And(self.keFml[agt]) ) eavesKNL.append( And(self.keNFml[agt])) self.eavesKFml = And(eavesKL) self.eavesKNFml = And(eavesKNL) self.initializedHands = False self.initializedDeals = False self.initializedAnn = False self.wComputed = False self.pComputed = False self.ann2D = False self.d2Ann = False
def scalability_Z3(numberOfBoolVars, numOfRealVars, constraints, max_sensors_under_attack): print '\n=======================================================' print ' TEST Z3' print ' #Real Varabiles = ', numOfRealVars print ' #Bool Varabiles = ', numberOfBoolVars print ' #Bool Constraints = ', len(constraints) print '=======================================================\n' SMTsolver = z3.Solver() bVars = z3.BoolVector('b', numberOfBoolVars) rVars = z3.RealVector('y', numOfRealVars) #---------------------------------------------------------------------------- print '--> Z3: FEEDING CONSTRAINTS' #---------------------------------------------------------------------------- for constraint in constraints: boolConstraint = constraint['bool'] convexConstraint = constraint['convex'] firstVar = boolConstraint[0] Q = convexConstraint['Q'] b = convexConstraint['b'] c = convexConstraint['c'] quadConstraint = 0 for counter1 in range(0, numOfRealVars): for counter2 in range(0, numOfRealVars): quadConstraint = quadConstraint + rVars[counter1] * rVars[ counter2] * Q[counter1, counter2] linearConstraint = 0 for counter1 in range(0, numOfRealVars): linearConstraint = linearConstraint + rVars[counter1] * c[counter1] #quadConstraint = sum([i * j for i,j in zip(rVars,A)] + [-1*b[0]]) SMTsolver.add( z3.Implies(bVars[firstVar], quadConstraint + linearConstraint < b)) SMTsolver.add( sum([BoolVar2Int(bVars[i]) for i in range(0, numberOfBoolVars)]) == max_sensors_under_attack) #---------------------------------------------------------------------------- print '--> Z3: SEARCHING FOR A SOLUTION' #---------------------------------------------------------------------------- SMTsolver.set("timeout", TIMEOUTE_LIMIT * 1000) start = timeit.default_timer() SMTsolver.check() end = timeit.default_timer() time_smt_SMT = end - start print('Z3 time = ', time_smt_SMT) return time_smt_SMT
def scalability_Z3(numberOfBoolVars, numOfRealVars, constraints): print '\n=======================================================' print ' TEST Z3' print ' #Real Varabiles = ', numOfRealVars print ' #Bool Varabiles = ', numberOfBoolVars print ' #Bool Constraints = ', len(constraints) print '=======================================================\n' SMTsolver = z3.Solver() bVars = z3.BoolVector('b', numberOfBoolVars) rVars = z3.RealVector('y', numOfRealVars) #---------------------------------------------------------------------------- print '--> Z3: FEEDING CONSTRAINTS' #---------------------------------------------------------------------------- for constraint in constraints: boolConstraint = constraint['bool'] positiveVars = [abs(i) - 1 for i in boolConstraint if i > 0] negativeVars = [abs(i) - 1 for i in boolConstraint if i < 0] Z3Constraint = [bVars[i] for i in positiveVars ] + [NOT(bVars[i]) for i in negativeVars] SMTsolver.add(z3.Or(*Z3Constraint)) convexConstraint = constraint['convex'] if convexConstraint is not None: firstVar = abs(boolConstraint[-1]) - 1 A = convexConstraint['A'] b = convexConstraint['b'] linConst = sum([i * j for i, j in zip(rVars, A)] + [-1 * b[0]]) SMTsolver.add(z3.Implies(bVars[firstVar], linConst < 0)) #---------------------------------------------------------------------------- print '--> Z3: SEARCHING FOR A SOLUTION' #---------------------------------------------------------------------------- SMTsolver.set("timeout", TIMEOUTE_LIMIT * 1000) start = timeit.default_timer() SMTsolver.check() end = timeit.default_timer() time_smt_SMT = end - start print('Z3 time = ', time_smt_SMT) return time_smt_SMT
def initAnn(self, nRounds): ''' initialize boolean variables denoting possible announcements by each agent for nRounds. At each round, every agent essentially announces a subset of self.handList. ''' self.initializedAnn = True self.ann = {} for agt in self.agents: self.ann[agt] = [] if not self.initializedHands: self.initHands() handLst = self.handList nHands = len(handLst) for agt in self.agents: for r in range(nRounds): # Due to the symmetric nature of [i,i,i] # no need to look at actual dType currently. self.ann[agt].append(z3.BoolVector(agt+str(r), nHands)) self.nRounds = nRounds
def __init__(self,input_size,hidden_units,output_dim, num_bool_vars, network = None, maxIter = 100000): self.maxNumberOfIterations = maxIter self.network = network #TODO: self.__parse_network() #compute the dims of input and hidden nodes self.__input_dim = input_size self.__hidden_units = hidden_units self.__output_dim = output_dim self.SATsolver = z3.Solver() self.convIFClauses = z3.BoolVector('bConv', self.__hidden_units) self.SATsolver.reset() #Add variables self.state_vars = LpVariable.dicts("x", [i for i in range(4)]) self.im_vars = LpVariable.dicts("i", [i for i in range(self.__input_dim)]) self.net_vars = LpVariable.dicts("y", [i for i in range(self.__hidden_units)]) self.relu_vars = LpVariable.dicts("z", [i for i in range(self.__hidden_units)]) self.slack_vars = LpVariable.dicts("s", [i for i in range(self.__hidden_units)], lowBound = 0) self.out_vars = LpVariable.dicts("u", [i for i in range( self.__output_dim)]) self.next_state_vars = LpVariable.dicts("w", [i for i in range(4)]) #network weights seed(12) hidden_weights= network.layers[0].get_weights() output_weights= network.layers[-1].get_weights() self.W = hidden_weights[0].T self.b = hidden_weights[1] self.W_out = output_weights[0].T self.b_out = output_weights[1] # self.W = [[2*(random()-0.5) for i in range(input_size)] for j in range(hidden_units)] # self.W_out = [[2*(random() -0.5 ) for i in range(hidden_units)] for j in range(output_dim)] # self.b = [2*(random()-0.5)]* hidden_units # self.b_out = [2*(random()-0.5)]* output_dim self.linear_constraints = [] self.curr_problem = [] self.preprocessing = True # set to False after first call to solve self.preprocess_counter_examples = []
# Question 1 # Consider the following program: # a := 1; b := 1; # for i := 1 to 10 do # if ? then {a := a+2b; b := b+i} else {b := a+b; a := a+i}; # if b = 600+n then crash # Here '?' is an unknown test that may yield false or true in any situation. # Establish for which values of n = 1,2...,10 it is safe, that is, will not reach 'crash'. import z3 A = z3.IntVector('A', 11) B = z3.IntVector('B', 11) Q = z3.BoolVector('?', 11) # Q for question mark, note Q[0] is not used at all # Initial conditions init_conds = [A[0] == 1, B[0] == 1] # Iteration conditions iter_conds = [] for i in range(1, 11): iter_conds += [A[i] == z3.If(Q[i], A[i - 1] + 2 * B[i - 1], A[i - 1] + i)] iter_conds += [B[i] == z3.If(Q[i], B[i - 1] + i, A[i - 1] + B[i - 1])] conditions = init_conds + iter_conds solver = z3.Solver() solver.add(conditions) solver.push()
def getHandLst(): handBLst = [] for h in boolHands: handBLst.append(h) return handBLst pe = {} peN = {} ke = {} keN = {} for agt in ['a', 'b', 'c']: pe[agt] = z3.BoolVector('Pe' + agt, 12) peN[agt] = z3.BoolVector('PeN' + agt, 12) ke[agt] = z3.BoolVector('Ke' + agt, 12) keN[agt] = z3.BoolVector('KeN' + agt, 12) def eavesK4Ann1(): ''' The +ve knowledge version of what Eaves knows ''' eKP = [] for i in range(12): f = ke[a][i] g = Not(peN[a][i]) f1 = Implies(f, g) f2 = Implies(g, f)
def __init__(self, nbits, pol): self.nbits = nbits self.slvr = z3.Solver() self.init = z3.BoolVector('init', nbits) self.state = self.init self.pol = tobools(pol, nbits)
def __init__(self, numOfBoolVars, numOfRealVars, numOfConvexIFClauses, maxNumberOfIterations = 1000, slackTolerance = 1E-6, counterExampleStrategy = 'IIS', verbose = 'OFF', profiling = 'true', numberOfCores = 2): # TODO: check that numOfConvexIFConstraints > 0 # ------------ Initialize SAT Solvers --------------------------------------- self.SATsolver = z3.Solver() self.SATsolver.reset() # ------------ Initialize Public Variables ------------------------------------ self.bVars = z3.BoolVector('b', numOfBoolVars) self.rVars = ['x'+str(i) for i in range(0, numOfRealVars)] self.convIFClauses = z3.BoolVector('bConv', numOfConvexIFClauses) # Boolean abstraction of ConvIFClauses self.counterExamples = list() # ------------ Initialize Private Variables ------------------------------------ self.__convIFClauses = [None] * numOfConvexIFClauses # the actual ConvIFClauses self.__slackIFVars = ['s'+str(i)+'_' for i in range(0, numOfConvexIFClauses)] # list to hold "real-valued" slack variables self.__slackIFVarsBound = ['t'+str(i) for i in range(0, numOfConvexIFClauses)] # list to hold "real-valued" slack # ------------ Initialize Solver Parameters ------------------------------------ self.maxNumberOfIterations = maxNumberOfIterations self.slackTolerance = slackTolerance self.counterExampleStrategy = counterExampleStrategy self.verbose = verbose self.profiling = profiling self.numberOfCores = numberOfCores self.slackRatio = 1 # ------------ Initialize Convex Solver --------------------------------------- self.ConvSolver = cplex.Cplex() if self.verbose == 'OFF': self.ConvSolver.set_results_stream(None) # set verbose = 0 self.ConvSolver.set_log_stream(None) self.ConvSolver.objective.set_sense(self.ConvSolver.objective.sense.minimize) # we minimize the slack # CPLEX default LB is 0.0, we change it to -infinty. These variables do not appear in the optimization objective (only slack variables appear there, so we omit the "obj" parameter) self.ConvSolver.variables.add( names = self.rVars, ub = [cplex.infinity] * numOfRealVars, lb = [-cplex.infinity] * numOfRealVars ) # add slack variabels self.ConvSolver.variables.add( names = self.__slackIFVars, ub = [cplex.infinity] * numOfConvexIFClauses, lb = [-cplex.infinity] * numOfConvexIFClauses ) if self.counterExampleStrategy == 'PREFIX' or self.counterExampleStrategy == 'SMC': # our objective is to minimize the sum of absolute value of slack variabeles ,i.e., min |s_0| + |s_1| + .... # the trick is to define new "bounding" variables t_0, t_1, .... and then minimze t_0 + t_1 + ... # subject to |s_i| \le t_i which translates to s_i \le t_i and -s_i \le t_i self.ConvSolver.variables.add( obj = [1.0] * numOfConvexIFClauses, names = self.__slackIFVarsBound, ub = [cplex.infinity] * numOfConvexIFClauses, lb = [-cplex.infinity] * numOfConvexIFClauses ) else: # in IIS and trivial we do not minimize the sum of slack, it is just feasability. # When using the IIS-based strategy, we would like to force infeasibility and leave the solver to relax the slack variables # in order to discover conflicts. Thus, we put the upper bound equal to 0.0. self.ConvSolver.variables.add( names = self.__slackIFVarsBound, ub = [0.0] * numOfConvexIFClauses, lb = [0.0] * numOfConvexIFClauses ) for slackIFcounter in range(0, numOfConvexIFClauses): self.ConvSolver.linear_constraints.add( lin_expr = [cplex.SparsePair(ind = [self.__slackIFVars[slackIFcounter], self.__slackIFVarsBound[slackIFcounter]], val = [1.0, -1.0])], senses = ['L'], rhs = [0.0], ) self.ConvSolver.linear_constraints.add( lin_expr = [cplex.SparsePair(ind = [self.__slackIFVars[slackIFcounter], self.__slackIFVarsBound[slackIFcounter]], val = [-1.0, -1.0])], senses = ['L'], rhs = [0.0], )
def generateFiniteLenInts(name, count, tp, ctx): tp = np.dtype(tp) bitsCount = tp.itemsize * 8 return [z3.BitVec(name + "__" + str(i), bitsCount) for i in range(count)] def generateFiniteLenFloats(name, count, tp, ctx): tp = np.dtype(tp) fpSort = floatTypes[tp.itemsize] if isinstance(fpSort, tuple): fpSort = z3.FPSort(*fpSort) return [z3.FP(name + "__" + str(i), fpSort) for i in range(count)] typesRemapping = { np.bool_: lambda name, count, tp, ctx: z3.BoolVector(name, count, ctx), bool: lambda name, count, tp, ctx: z3.BoolVector(name, count, ctx), int: lambda name, count, tp, ctx: z3.IntVector(name, count, ctx), float: lambda name, count, tp, ctx: z3.RealVector(name, count, ctx), } floatTypes = { 1: (4, 4), #2: (5, 11), 2: z3.FloatHalf(), #4: (8, 24), 4: z3.FloatSingle(), #8: (11, 53), 8: z3.FloatDouble(), 10: (15, 63), #16: (15, 111),