Example #1
0
 def resultSet(self, Bag):
     bagArrayVariable = Variable()
     for l1 in self.resultArray(bagArrayVariable):
         bagArray = bagArrayVariable.getValue()
         YP.sortArray(bagArray)
         for l2 in YP.unify(Bag, ListPair.makeWithoutRepeatedTerms(bagArray)):
             yield False
Example #2
0
def dame_valores(archivo_entrada):
    try:
        archivo_lectura = open(archivo_entrada, 'r+')
        # Linea de las Variables: 
        linea = archivo_lectura.readline()
        linea = linea.upper()
        linea = linea.replace("VARIABLE:","")
        linea = linea.replace("VARIABLES:","")
        linea = linea.replace(" ","")
        formato = linea.find("[")
        if formato == -1:
            raise Exception('El formato del archivo es incorrecto')
        linea = linea.replace("[","")
        linea = linea.replace("]","")
        variables = linea.split("},{")
        var1 = {}
        for x in variables:
            x = x.replace("{","")
            x = x.replace("}","")
            nom_valor = x.split(':')
            nombre = nom_valor[0]
            valores = nom_valor[1]
            variable_var = Variable("",[])
            variable_var.set_nombre(nombre)
            valoreslist = valores.split(',')            
            for y in valoreslist:
                variable_var.agrega_valor(y)                
            var1[nombre] = variable_var
        # Linea de las Probabilidades:
        linea = archivo_lectura.readline()
        linea = linea.upper()
        linea = linea.replace("PROBABILIDADES:","")
        linea = linea.replace("PROBABILIDAD:","")
        linea = linea.replace(" ","")
        formato = linea.find("[")
        if formato == -1:
            raise Exception('El formato del archivo es incorrecto')
        linea = linea.replace("[","")
        linea = linea.replace("]","")
        variables = linea.split("},{")
        var2 = {}
        for x in variables:
            x = x.replace("{","")
            x = x.replace("}","")
            cada_proba = x.split(",P")
            for y in cada_proba:
                y = y.replace("P(","")
                nombre = y[0]
                valor = y[2]
                print(nombre+" "+valor)
            # Aquí se complica la cosa.        
        return (var1,linea)
    except Exception as e:
        print(e)
        print("El archivo no tiene el formato correcto o esta corrupto")
        print("El archivo debe tener el siguiente fomato en dos lineas:")
        print("[{< V ar1 >:< val0 >, ..., < valm >},..., {<Varn >:<val0 >,...,<valm >}]")
        print("[{P(<Vari >=0)=0,1,P(<Vari >=1)=0,5,P"
        +"(<Vari >=2)=0,4}, {P(<Vari >|varj =0,...,vark =0)=<val>,P(<Vari >|varj =0,...,vark =1)=<val>,...}...]")
Example #3
0
def main():
    print "Return a list of 2 elements:"
    List = Variable()
    for l1 in makeList("a", "b", List):
        print "List =", List.getValue()

    print "Unify two lists:"
    Second = Variable()
    for l1 in makeList("x", Second, ListPair("x", ListPair("y", Atom.NIL))):
        print "The second element is", Second.getValue()
Example #4
0
def queens3(UnplacedQs, SafeQs, Qs):
    UnplacedQsListPair = YP.getValue(UnplacedQs)
    if isinstance(UnplacedQsListPair, ListPair):
        UnplacedQs1 = Variable()
        Q = Variable()
        for l1 in selectq(Q, UnplacedQsListPair, UnplacedQs1):
            if not (isinstance(SafeQs, ListPair) and hasAttack(Q.getValue(), SafeQs)):
                for l2 in queens3(UnplacedQs1, ListPair(Q, SafeQs), Qs):
                    yield False
    else:
        for l1 in Qs.unify(SafeQs):
            yield False
Example #5
0
def attack3(X, N, Arg3):
    Y = Variable()
    for l1 in ListPair(Y, Variable()).unify(Arg3):
        if YP.getValue(X) == Y.getValue() + YP.getValue(N):
            yield False
        if YP.getValue(X) == Y.getValue() - YP.getValue(N):
            yield False

    Ys = Variable()
    N1 = Variable()
    for l1 in ListPair(Variable(), Ys).unify(Arg3):
        for l2 in N1.unify(YP.getValue(N) + 1):
            for l3 in attack3(X, N1, Ys):
                yield False
Example #6
0
def main():
    YP.assertFact(Atom.a("brother"), \
        [Atom.a("Hillary"), Atom.a("Hugh")])
    YP.assertFact(Atom.a("brother"), \
        [Atom.a("Hillary"), Atom.a("Tony")])
    YP.assertFact(Atom.a("brother"), \
        [Atom.a("Bill"), Atom.a("Roger")])

    Brother = Variable()
    print "Using dynamic assert:"
    for l1 in YP.matchDynamic \
              (Atom.a("brother"), \
               [Atom.a("Hillary"), Brother]):
        print "Hillary has brother", \
            Brother.getValue()

    prologCode = \
        "uncle(Person, Uncle) :- \n" + \
        "  parent(Person, Parent), \n" + \
        "  brother(Parent, Uncle). \n"
    print "# Compiled code:"
    compileAndWrite(prologCode)

    prologCode = \
        ":- import('', [parent/2]). \n" + \
        "uncle(Person, Uncle) :- \n" + \
        "  parent(Person, Parent), \n" + \
        "  brother(Parent, Uncle). \n"
    print "# Calling an imported function:"
    compileAndWrite(prologCode)

    prologCode = \
        "parent('Chelsea', 'Hillary'). \n" + \
        "parent('Chelsea', 'Bill'). \n" + \
        \
        "uncle(Person, Uncle) :- \n" + \
        "  parent(Person, Parent), \n" + \
        "  brother(Parent, Uncle). \n"
    print "# Calling a locally-defined function:"
    compileAndWrite(prologCode)

    prologCode = \
        ":- import('', [parent/2]). \n" + \
        "uncle(Person, Uncle) :- \n" + \
        "  Goal = parent(Person, Parent), \n" + \
        "  Goal, \n" + \
        "  brother(Parent, Uncle). \n"
    print "# Calling a dynamic goal:"
    compileAndWrite(prologCode)

    print "Calling compiled code having a dynamic goal:"
    Person = Variable()
    Uncle = Variable()
    for l1 in uncle(Person, Uncle):
        print Person.getValue(), "has uncle", \
              Uncle.getValue()
Example #7
0
def evaluate(line, mode):
    global _do_block
    global _looking_for_end_bracket
    global _record_lines
    global _lines
    global _same_string

    if line == "quit": return 1
    sline = line.split(" ")

    sline = _convert_to_values(1, sline)
    sline = Arithmetic.do_arithmetic_statements(sline)
    sline = IfElse.do_boolean_expressions(sline)
    sline = _booleans_to_ints(sline)

    # Checking if the line is both from a file and an if statement
    if mode:
        if _is_if_statement_true(sline) or _is_else_if_statement_true(sline, _same_string) or _is_else_statement_true(sline, _same_string):
            _do_block = True
            _same_string = True
        elif _is_start_bracket(sline):
            _record_lines = True
            _looking_for_end_bracket = True
        elif _looking_for_end_bracket and _is_end_bracket(sline):
            _record_lines = False
            _looking_for_end_bracket = False
            if _do_block: IfElse.perform_block_statement(_lines, mode)
            _lines = []
            _do_block = False
        elif _record_lines:
            _lines.append(line)
            return 0
        elif _is_else_if_statement(sline) or _is_else_statement(sline) or _do_block:
            pass
        else:
            _same_string = False

    # Checking if the line is a variable set statement
    if _is_variable_set_statement(sline):
        val = Variable.variable_set_statement(sline)
        if val: return val

    # Checking if the line is a print statement
    if _is_print_statement(sline):
        val = Print.print_statement(sline)
        if val: return val
    
    return 0
Example #8
0
 def exitBasicmsg(self, ctx):
     if Variable(ctx.getText()
                 ) in self.variables_pattern | self.variables_pcdef:
         self.state.append(Variable(ctx.getText()))
     else:
         self.state.append(BasicMsg(NameRepr(ctx.getText())))
Example #9
0
def queens(N, Qs):
    Ns = Variable()
    for l1 in rangeList(1, N, Ns):
        for l2 in queens3(Ns, Atom.NIL, Qs):
            yield False
Example #10
0
 def load():
     type = Ls3._loadType()
     variable = Variable("", type)
     Ls3.__loadVariable(variable, type)
     return variable
Example #11
0
def solve(problem):
    ret = polynomial.polynomial()
    problem = problem.strip()
    problem = problem.replace(")(", ")*(")
    problem = problem.replace(")x", ")*x")
    problem = problem.replace("x(", "x*(")
    if sf.checkBrackets(problem) == False:
        ret.errorCode = 5
        ret.isError = True
        return ret
    while (sf.isThereBrackets(problem)):
        problem = problem[1:len(problem) - 1]
    if problem == "":
        return ret
    if "=" in problem and not ("==" in problem) and not ("!=" in problem):
        return Variable.addValue(problem)
    if problem[0:7] == "Canvas ":
        return Canvas.mkpol(problem)
    if problem[0:5] == "draw ":
        return Canvas.adpol(problem)
    if problem[0:5] == "show ":
        return Canvas.shpol(problem)
    if problem[0:10] == "polarshow ":
        return Canvas.shpolarpol(problem)
    if problem[0:6] == "clear ":
        return Canvas.clearcanvas(problem)
    if problem[0:5] == "plot ":
        if "from" in problem and "to" in problem:
            index1 = problem.find("from")
            index2 = problem.find("to")
            a = solve(problem[index1 + 4:index2])
            b = solve(problem[index2 + 2:])
            if a.coefArr[0] >= b.coefArr[0]:
                ret.isError = True
                ret.errorCode = 4
                return ret
            solve(problem[5:index1]).plot(a.coefArr[0], b.coefArr[0])
            return False
        solve(problem[5:]).plot(-5, 5)
        return False
    if problem[0:10] == "polarplot ":

        if "from" in problem and "to" in problem:
            index1 = problem.find("from")
            index2 = problem.find("to")
            a = solve(problem[index1 + 4:index2])
            b = solve(problem[index2 + 2:])
            if a.coefArr[0] >= b.coefArr[0]:
                ret.isError = True
                ret.errorCode = 4
                return ret
            solve(problem[10:index1]).polarplot(a.coefArr[0], b.coefArr[0])
            return False
        solve(problem[10:]).polarplot(-5, 5)
        return False
    if problem[0:6] == "solve ":
        function = solve(problem[6:])
        if function.isError:
            return function
        newtonMethodans = function.advancedNewtonMethod()
        if len(newtonMethodans) != 0:
            return str(newtonMethodans) + "\n"
        biSectionans = function.biSection(0, 5)
        if biSectionans:
            return "bisection : " + str(biSectionans) + "\n"
        else:
            return "no roots found\n"
    if problem[0:9] == "derivate ":
        newstr = problem[8:]
        if "at" in newstr:
            index1 = newstr.find("at")
            a = solve(newstr[index1 + 2:])
            f = solve(newstr[0:index1]).derivate().applyPol(a)
            return f
        else:
            return solve(problem[9:]).derivate()
    if problem[0:10] == "integrate ":
        if "from" in problem and "to" in problem:
            index1 = problem.find("from")
            index2 = problem.find("to")
            a = solve(problem[index1 + 4:index2])
            b = solve(problem[index2 + 2:])
            funct = solve(problem[9:index1]).integrate()
            return funct.applyPol(b) - funct.applyPol(a)

        else:
            return solve(problem[9:]).integrate()
    if sf.doesCharExist(problem, ">"):
        index = sf.whereIsChar(problem, ">")
        if solve(problem[:index]).coefArr[0] > solve(
                problem[index + 1:]).coefArr[0]:
            ret.coefArr[0] = 1
            return ret
        return ret
    if sf.doesCharExist(problem, "<"):
        index = sf.whereIsChar(problem, "<")
        if solve(problem[:index]).coefArr[0] < solve(
                problem[index + 1:]).coefArr[0]:
            ret.coefArr[0] = 1
            return ret
        return ret

    if sf.doesStringExist(problem, "=="):
        index = sf.whereIsString(problem, "==")
        if solve(problem[:index]) == solve(problem[index + 2:]):
            ret.coefArr[0] = 1
            return ret
        return ret
    if sf.doesStringExist(problem, "!="):
        index = sf.whereIsString(problem, "!=")
        if solve(problem[:index]) != solve(problem[index + 2:]):
            ret.coefArr[0] = 1
            return ret
        return ret
    if sf.doesCharExist(problem, '+'):
        index = sf.whereIsChar(problem, '+')
        return solve(problem[:index]) + solve(problem[index + 1:])

    if sf.doesCharExist(problem, '-'):
        index = sf.whereIsChar(problem, '-')
        return solve(problem[:index]) - solve(problem[index + 1:])

    if sf.doesCharExist(problem, '*'):
        index = sf.whereIsChar(problem, '*')
        return solve(problem[:index]) * solve(problem[index + 1:])
    if sf.doesCharExist(problem, '/'):
        index = sf.whereIsChar(problem, '/')
        return solve(problem[:index]) / solve(problem[index + 1:])
    if sf.doesCharExist(problem, '^'):
        index = sf.whereIsChar(problem, "^")
        return solve(problem[:index]).power(
            solve(problem[index + 1:]).coefArr[0])
    if problem[0:4] == "sqrt":
        a = solve(problem[5:-1])
        return a.sqrt()
    for variable in Variable.variableArray:
        if problem == variable.functionName:
            return variable.functionBody
    for variable in Variable.variableArray:
        if problem[0:len(variable.functionName)] == variable.functionName:
            if problem[len(variable.functionName)] == "(":
                a = solve(problem[len(variable.functionName) + 1:-1])
                return variable.functionBody.applyPol(a)
    if problem == "x":
        ret.coefArr[1] = 1
        return ret
    if problem == "ans":
        return Variable.recent
    try:
        ret.coefArr[0] = float(problem)
    except:
        ret.isError = True
        ret.errorStatement = problem
        ret.errorCode = 1
    return ret
# optimizer for the discriminator
optimizerD = optim.Adam(netD.parameters(), lr = 0.0002, betas = (0.5, 0.999)) 


# Training the Deep Convolutional GANs(DCGAN)
epochs = 50
for epoch in range(epochs):
    for i, data in enumerate(dataloader, 0): # iterating thru all the images in the dataset one batch at a time
        
        # ----------------- STEP 1: Updating the weights of the neural network of the discriminator -----------------
        
        netD.zero_grad() # initializing the gradients of the discriminator with respect to the weights

        # Training the discriminator with a real image
        real, _ = data # each batch at a time(we only care about the data.so we can ignore the labels)
        input = Variable(real) # converting the data into paytorch format
        target = Varibale(torch.ones(input.size()[0]))
        # target of the discriminator(in case of real images) is always the 1s. input.size()[0] gives the length of the batch
        output = netD(input) # propagating the a batch of real images thru the discriminator network
        errD_real = criterion(output, target) # Measure of how close the generated image is to the actual image
        
        
        # Training the discriminator with a fake image generated by the generator
        '''
        We want to propagate randon noise of size 100 thru to genrator to generate fake images
        ''' 
        noise = Variable(torch.randn(input.size()[0]), # random noise as input
                         100, # size of the input noise
                         1, 1 # 100 features of size 1 X 1(to have feature maps in matrix form)
                        )
        fake = netG(noise) # propagating the noise thru the generator network
Example #13
0
	def evalExpression(self, s):
		print("evaling: ", s)
		valueStack = []
		operatorStack = []
		for x in spacedThings:
			s = s.replace(x, " "+x+" ")
		tokens = shlex.split(s,posix=False)
		print('tokens: ', tokens)
		#print('varDicts', self.varDicts[-1])
		y = 0
		while y < len(tokens):
			print(y, tokens[y], operatorStack, valueStack, self.varDicts[-1])
			token = tokens[y]
			#print(token)
			if stringIsInt(token):
				valueStack.append(Variable.Variable(None, '$I', int(token), None))
			elif token in ['true', 'false']:
				valueStack.append(Variable.Variable(None, '$B', token=='true', None)) 
			elif token == 'NULL':
				valueStack.append(Variable.Variable(None, '$P', None, None))
			elif (token[0] == '"' and token[-1] == '"') or (token[0] == "'" and token[-1] == "'"):
				#print("added string", token)
				valueStack.append(Variable.Variable(None, '$S', token[1:-1], None))
			elif token in self.varDicts[-1].keys():
				valueStack.append(self.varDicts[-1][token])
			elif token[1:] in self.varDicts[-1].keys() and token[0] == "*" and token[1] != '*': #dereferencing
				#print("deref!")
				valueStack.append(self.heapDict[(self.varDicts[-1][token[1:]]).value]['0'])
			elif token.strip('*') in self.varDicts[-1].keys() and token[0] == "*": #dereferencing more than once
				#print("deref! multiple!")
				valueStack.append(self.heapDict[self.evalExpression(token[1:]).value]['0'])
			elif token == "[": #indexing into array
				array = valueStack.pop()
				indexexpr = ""
				print(self.heapDict)
				for nexttoken in tokens[y+1:]:
					if nexttoken == "]":
						valueStack.append(self.heapDict[array.value][str(self.evalExpression(indexexpr).value)])
						break
					indexexpr += nexttoken
					y += 1
			elif token == '->':
				y += 1
				array = valueStack.pop()
				structfield = tokens[y]
				valueStack.append(self.heapDict[array.value][str(structfield)])
				print("struct field: ", structfield)
			elif token == "(":
				operatorStack.append(token)
			elif token == ")":
				x = operatorStack.pop()
				while x != "(":
					v1 = valueStack.pop()
					v2 = valueStack.pop()
					valueStack.append(applyOperator(x, v1, v2))
					x = operatorStack.pop()
			elif token in operators:
				while len(operatorStack) > 0 and precedence[operatorStack[-1]] >= precedence[token]:
					x = operatorStack.pop()
					v1 = valueStack.pop()
					v2 = valueStack.pop()
					valueStack.append(applyOperator(x, v1, v2))
				operatorStack.append(token)
			elif token in self.funcDict.keys():
				paramstring = ""
				i = 0
				for z in range(y+1, len(tokens)):
					y += 1
					if tokens[z] == "(":
						i += 1
					elif tokens[z] == ")":
						i -= 1
					paramstring += tokens[z]
					if i == 0:
						valueStack.append(self.getFuncValue(token, self.evalFunctionParams(paramstring)))
						break
			y += 1
		while len(operatorStack) != 0:
			x = operatorStack.pop()
			v1 = valueStack.pop()
			v2 = valueStack.pop()
			valueStack.append(applyOperator(x, v1, v2))
		print("------", self.varDicts[-1])
		print("returning", valueStack)
		return valueStack[0]
Example #14
0
 def result(self, Bag):
     bagArrayVariable = Variable()
     for l1 in self.resultArray(bagArrayVariable):
         for l2 in YP.unify(Bag, ListPair.make(bagArrayVariable.getValue())):
             yield False
Example #15
0
class CompanyAccountCreated(Event):
    identifier = "company_account_created"

    contact = Variable("CompanyContact", type=Model("E-Commerce.CompanyContact"))
    customer_email = Variable(_("Customer Email"), type=Email)
 def __init__(self, constant):
     self.constant = constant
     self.var_name = Variable.alloc_name('c_0x%x' % self.constant)
def csp_model(minesweeper):
    '''Initialize a csp model.
    '''

    csp = CSP("Minesweeper")

    # list of lists, same structure as board in minesweeper
    variables = []

    # Initialize all variables in board.
    for row in range(minesweeper.row):
        temp_row = []
        for col in range(minesweeper.col):
            name = str(row) + " " + str(col)
            if minesweeper.board[row][col].is_flag():
                domain = [1]
            elif minesweeper.board[row][col].is_seen():
                domain = [0]
            else:
                domain = [0, 1]
            var = Variable(name, domain)
            temp_row.append(var)
            csp.add_var(var)
        variables.append(temp_row)

    # Initialize all constraints.
    # cons = [[name(str), [variable, variable,..], sum(int)], ...]
    cons = []
    unassign = []
    for button in minesweeper.cells:
        # Assign value to all known variables.
        if button.is_seen():
            variables[button.x][button.y].assign(0)
        elif button.is_flag():
            variables[button.x][button.y].assign(1)
        else:
            unassign.append(variables[button.x][button.y])
        # Constraint info for a non-empty visible button.
        if button.is_seen() and not button.value == 0:
            surrounding = minesweeper.get_adj_cells(button.x, button.y)
            scope = []
            sum1 = button.value
            for sur in surrounding:
                if sur.is_flag():
                    sum1 -= 1
                if not sur.is_seen() and not sur.is_flag():
                    scope.append(variables[sur.x][sur.y])
            name = str(button.x) + " " + str(button.y)
            # Avoid empty scope. (All surrounding buttons are either visible or flagged.)
            if scope:
                cons.append([name, scope, sum1])

    # end-game: give it a fixed # 20:
    if len(unassign) <= 20:
        cons.append(["endgame", unassign, minesweeper.mines_left])

    # Sort cons by length of scope.
    cons.sort(key=lambda x: len(x[1]))
    # Reduce constraint's scope.
    # ex: c1=[v1,v2,v3], c2=[v1,v2] => reduce c1 to [v3]
    for i in range(len(cons) - 1):
        con1 = cons[i]
        for j in range(i + 1, len(cons)):
            con2 = cons[j]
            if set(con1[1]) == set(con2[1]):
                continue
            if set(con1[1]) & set(con2[1]) == set(con1[1]):
                con2[1] = list(set(con2[1]).difference(set(con1[1])))
                con2[2] = con2[2] - con1[2]

    # Sort cons by length of scope.
    cons.sort(key=lambda x: len(x[1]))
    # overlap cons, same structure as cons list: [[name(str), [variable, variable,..], sum(int)], ...]
    ol_cons = []
    # list of lists, with [{var, var, var...},{}...]
    ol_set = []
    ol_var = []

    # Add new constraints if two constraints has at least two same variables in scope.
    # Create a new variable for overlap variables.
    # ex: c1=[v1,v2,v3], c2=[v2,v3,v4] => add c3=[v1,v2v3], c4=[v2v3,v4]. v2v3 is a new variable.
    for i in range(len(cons) - 1):
        con1 = cons[i]
        for j in range(i + 1, len(cons)):
            con2 = cons[j]
            if set(con1[1]) == set(con2[1]):
                continue
            if 1 < len(set(con1[1]) & set(con2[1])):
                ol_vars = set(con1[1]) & set(con2[1])
                con1_vars = set(con1[1]) - ol_vars
                con2_vars = set(con2[1]) - ol_vars
                con1_sum = con1[2]
                con2_sum = con2[2]
                name = ""

                if not ol_vars in ol_set:
                    for i in ol_vars:
                        name += i.name + ", "
                    name = "(" + name + ")"
                    var = Variable(name, list(range(len(ol_vars) + 1)))
                    csp.add_var(var)
                    ol_var.append(var)
                    ol_set.append(ol_vars)
                else:
                    index = ol_set.index(ol_vars)
                    var = ol_var[index]

                con1_vars.add(var)
                con2_vars.add(var)
                ol_cons.append(["", list(con1_vars), con1_sum])
                ol_cons.append(["", list(con2_vars), con2_sum])

    cons.extend(ol_cons)

    # Create Constraint object for constraint in cons list.
    for con in cons:
        constraint = Constraint(con[0], con[1])
        tuples = satisfy_tuples(con[1], con[2])
        constraint.add_satisfying_tuples(tuples)
        csp.add_constraint(constraint)

    return csp
Example #18
0
def make_rows(rows_size, cols_size, rows, i, qr):
    qr.put(Variable.Variable(True, i, rows[i], cols_size))
    return True
Example #19
0
def make_cols(cols_size, rows_size, cols, i, qc):
    qc.put(Variable.Variable(False, i, cols[i], rows_size))
    return True
Example #20
0
 def exitVariable(self, ctx):
     self.state.append(Variable(ctx.getText()))
Example #21
0
 def __init__(self):
     self.var_name = Variable.alloc_name('srv')
Example #22
0
def main():
    Brother = Variable()
    print "Find relations:" 
    for l1 in brother("Hillary", Brother):
        print "Hillary has brother", \
              Brother.getValue(), "."

    print "Check if it is square:"
    for l1 in squaredRectangle(10, 10):
        print "10 by 10 rectangle is square."

    print "Make it square:"
    Width = Variable()
    Height = Variable()
    for l1 in Width.unify(10):
        for l2 in squaredRectangle(Width, Height):
            print "A square of width", \
                Width.getValue(), "has height", \
                Height.getValue(), "."

    print "Make it square before we know the width:"
    for l1 in squaredRectangle(Width, Height):
        for l2 in Width.unify(10):
            print "A square of width", \
                Width.getValue(), "has height", \
                Height.getValue(), "." 

    print "Get one match:"
    for l1 in anyBrother("Hillary", Brother):
        print "Hillary has a brother", \
              Brother.getValue(), "."
    for l1 in anyBrother("Bill", Brother):
        print "Bill has a brother", \
              Brother.getValue(), "."

    print "Use cut for negation:"
    for l1 in noBrother("Hillary"):
        print "Hillary has no brother."
    for l1 in noBrother("Chelsea"):
        print "Chelsea has no brother."
Example #23
0
def noBrother(Person):
    Brother = Variable()
    for l1 in brother(Person, Brother):
        return
    yield False
    def __init__(self, sboard=None):
        self.constraints = []
        self.variables = []

        if sboard != None:
            board = sboard.board
            temp = []
            value = 0

            for i in range(sboard.N):
                for j in range(sboard.N):
                    value = board[i][j]
                    domain = []
                    if value == 0:
                        d = 1
                        while d <= sboard.N:
                            domain.append(d)
                            d += 1
                    else:
                        domain.append(value)

                    block = int(((floor(i / sboard.p) * sboard.p) +
                                 floor(j / sboard.q)))
                    temp.append(Variable.Variable(domain, i, j, block))

            rows = dict()
            cols = dict()
            blocks = dict()

            for v in temp:
                row = v.row
                col = v.col
                block = v.block

                if not (row in rows.keys()):
                    rows[row] = []
                if not (col in cols.keys()):
                    cols[col] = []
                if not (block in blocks.keys()):
                    blocks[block] = []

                rows[row].append(v)
                cols[col].append(v)
                blocks[block].append(v)

            for v in temp:
                self.addVariable(v)

            for e in rows:
                c = Constraint.Constraint()
                for v in rows[e]:
                    c.addVariable(v)
                self.addConstraint(c)

            for e in cols:
                c = Constraint.Constraint()
                for v in cols[e]:
                    c.addVariable(v)
                self.addConstraint(c)

            for e in blocks:
                c = Constraint.Constraint()
                for v in blocks[e]:
                    c.addVariable(v)
                self.addConstraint(c)
    def generate_scramble(self):
        if DISABLE_SCRAMBLE:
            return 'u32 {0} = {1};\n'.format(self.var_name, self.constant)

        ret = ''

        ret += '// Scrambling constant %d (0x%x)\n' % (self.constant, self.constant)
        secrets = SecretGenerators.get_N_random_secrets(5 + Random.get_u32()%3)
        for s in secrets:
            ret += s.generate_code()

        ret += '// Beginning scramble\n'
        op = secrets[0]
        for i in range(1, len(secrets)):
            OpType = Operators.get_random_op()
            op = OpType(op, secrets[i])
            ret += op.generate_code()

        ret += '// Ending scramble\n'

        last_op_name = op.get_var_name()
        last_op_val  = op.get_result()

        ret += 'u32 {0} = {1} ^ 0x{2:08x};\n'.format(self.var_name, last_op_name, last_op_val ^ self.constant)

        ret += '// %s == %d\n' % (self.var_name, self.constant)

        if TEST:
            ret += 'if (%s != %d) fatalSimple(MAKERESULT(222, %d));\n' % (self.var_name, self.constant, Variable.alloc_err())

        ret += '\n'
        return ret
Example #26
0
__author__ = 'sunbeansoft'

import Variable as v

v.varDemos()
Example #27
0
 def add_var(self, vname, vkind, vtype):
     self.lastvar += 1
     c = self.levels[0]  # current block number
     v = Variable(vname, self.lastvar, vkind, vtype)
     vbl = self.vars[c]  # list of variables in current block
     vbl[vname] = v
Example #28
0
def main():
    Brother = Variable()
    print("Find relations:")
    for l1 in brother("Hillary", Brother):
        print("Hillary has brother", Brother.getValue(), ".")

    print("Check if it is square:")
    for l1 in squaredRectangle(10, 10):
        print("10 by 10 rectangle is square.")

    print("Make it square:")
    Width = Variable()
    Height = Variable()
    for l1 in Width.unify(10):
        for l2 in squaredRectangle(Width, Height):
            print("A square of width", Width.getValue(), "has height",
                  Height.getValue(), ".")

    print("Make it square before we know the width:")
    for l1 in squaredRectangle(Width, Height):
        for l2 in Width.unify(10):
            print("A square of width", Width.getValue(), "has height",
                  Height.getValue(), ".")

    print("Get one match:")
    for l1 in anyBrother("Hillary", Brother):
        print("Hillary has a brother", Brother.getValue(), ".")
    for l1 in anyBrother("Bill", Brother):
        print("Bill has a brother", Brother.getValue(), ".")

    print("Use cut for negation:")
    for l1 in noBrother("Hillary"):
        print("Hillary has no brother.")
    for l1 in noBrother("Chelsea"):
        print("Chelsea has no brother.")
Example #29
0
import torch
import torch.autograd import Variable
import matplotlib.pyplot as plt
x = torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
y = x.pow(2)
x,y = Variable(x),Variable(y)

x = x.data.numpy()
y = y.data.numpy()

plt.plot(x,y)
plt.show()