def score(self,n_ijk,alpha_ijk_in):
     alpha_ijk = copy.deepcopy(alpha_ijk_in)
     prod_k = sum22(subtract(matrixGammaLog(add(n_ijk,alpha_ijk)),matrixGammaLog(alpha_ijk)))
     alpha_ij = sum22(alpha_ijk_in)
     n_ij = sum22(n_ijk)
     prod_ij = subtract(matrixGammaLog(alpha_ij), matrixGammaLog(add(alpha_ij,n_ij)))
     return sum2(add(prod_ij,prod_k))
Exemple #2
0
    def adadelta(allparams,
                 nat_stepsize,
                 num_epochs,
                 seq_len,
                 num_seqs=None,
                 rho=0.95,
                 epsilon=1e-6,
                 num_samples=1,
                 permute=True):
        natparams, params = allparams[:1], allparams[1:]
        sum_gsq = zeros_like(params)  # accumulated sq. grads
        sum_usq = zeros_like(params)  # accumulated sq. updates
        accumulate = lambda a, b: add(scale(rho, a), scale(1 - rho, b))

        for epoch in xrange(num_epochs):
            vals = []
            batches, num_batches = split_into_batches(data, seq_len, num_seqs)
            for y in batches:
                val, grad = scale(
                    1. / num_datapoints,
                    val_and_grad(y, num_batches, num_samples, *allparams))
                natgrad, grad = grad[:1], grad[1:]
                sum_gsq = accumulate(sum_gsq, square(grad))
                diag_scaling = div(sqrt(add_scalar(epsilon, sum_usq)),
                                   sqrt(add_scalar(epsilon, sum_gsq)))
                update = mul(diag_scaling, grad)
                sum_usq = accumulate(sum_usq, square(update))

                natparams = add(natparams, scale(nat_stepsize, natgrad))
                params = add(params, update)
                allparams = concat(natparams, params)
                vals.append(val)

                if callback: callback(epoch, vals, natgrad, allparams)
        return allparams
Exemple #3
0
def itemConstants(itemFile, constantsFile, cwd, keywords=KW, suffix=""):
    cwd = util.find(cwd, util.root)
    fileName = util.find(itemFile, cwd)
    path = os.path.join(CONSTANTS_DIR, constantsFile)
    w = open(fileName, 'r')
    t = w.read()
    w.close()
    libName = itemFile.replace("_insert.j", "")
    header = "library " + libName.title() + "Constants\n"
    header = header.replace("_", "")
    header += "globals\n"
    itemId = getId.findall(t)[0]
    varNames = [util.name2Var(x) for x in getItemName.findall(t)]
    totals = [int(x) for x in getTotal.findall(t)]
    if totals != []:
        for var in range(0, len(varNames)):
            for x in range(0, totals[var]):
                header += "\tconstant integer " + varNames[var] + "_" + str(
                    x) + suffix + " = '" + itemId + "'\n"
                itemId = util.add(itemId)
    else:
        for var in range(0, len(varNames)):
            header += "\tconstant integer " + varNames[
                var] + suffix + " = '" + itemId + "'\n"
            itemId = util.add(itemId)
    header += "endglobals\nendlibrary"
    w = open(path, 'w')
    print >> w, header
    w.close()
Exemple #4
0
 def __init__(self, width, height, n_rivers=3, thickness=2, inverted=False, map_group=None, turn_limit=None, can_escape=True, max_view_distance=None):
     import util
     super().__init__(map_group, turn_limit, can_escape=can_escape, max_view_distance=max_view_distance)
     brush = [
         ['#' if inverted else '.'] * thickness
     ] * thickness
     self._fill(width, height, '.' if inverted else '#')
     for _i in range(n_rivers):
         roll = random.randint(0,3)
         if roll == 0:
             point = (0, random.randint(0, height-1))
         elif roll == 1:
             point = (width-1, random.randint(0, height-1))
         elif roll == 2:
             point = (random.randint(0, width-1), 0)
         elif roll == 3:
             point = (random.randint(0, width-1), height-1)
         center = (width/2, height/2)
         delta = util.normalize(util.difference(point, center))
         orig_delta = delta
         print(delta)
         turn_l = util.rot_ccw_90(orig_delta)
         turn_r = util.rot_cw_90(orig_delta)
         iterations = 0
         while self._in_bounds(point, width, height):
             self._apply_brush(brush, point, width, height)
             if iterations > width / 3:
                 pert = util.normalize(
                     util.add(delta, util.scalar_mult(random.choice([turn_l, turn_r]), 0.7 + 0.3*random.random())))
                 delta = util.normalize(util.add(delta, pert))
             point = util.add(point, delta)
             iterations += 1
     self._place_stairs(width, height)
Exemple #5
0
def multiply_karatsuba(x, y):
    """
    Multiplies two numbers represented as arrays
    using the Karatsuba algorithm, falling back
    on grade school algorithm for the base case

    :param x: []int
    :param y: []int
    :rtype []int
    """
    x, y = match_padding(x, y)
    a, b = split(x)
    c, d = split(y)

    if len(x) == 1:
        return multiply_simple(x, y)

    res_1 = multiply_karatsuba(a, c)
    res_2 = multiply_karatsuba(b, d)

    partial = multiply_karatsuba(add(a, b), add(c, d))
    # res_3 is partial - res_1 - res_2.
    # To simplify, just add res_1 and res_2 then subtract that sum from partial
    res_3 = subtract(partial, add(res_1, res_2))

    res = add(pad(res_1, len(x), 'right'), res_2,
              pad(res_3, (len(x) + 1) // 2, 'right'))

    return res
Exemple #6
0
def itemConstants(itemFile, constantsFile, cwd, keywords = KW, suffix = ""):
    cwd = util.find(cwd, util.root)
    fileName = util.find(itemFile, cwd)
    path = os.path.join(CONSTANTS_DIR, constantsFile)
    w = open(fileName, 'r')
    t = w.read()
    w.close()
    libName = itemFile.replace("_insert.j", "")
    header = "library " + libName.title() + "Constants\n"
    header = header.replace("_", "")
    header += "globals\n"
    itemId = getId.findall(t)[0]
    varNames = [util.name2Var(x) for x in getItemName.findall(t)]
    totals = [int(x) for x in getTotal.findall(t)]
    if totals != []:
        for var in range(0, len(varNames)):
            for x in range(0, totals[var]):
                header += "\tconstant integer " + varNames[var] + "_" + str(x) + suffix + " = '" + itemId + "'\n"
                itemId = util.add(itemId)
    else:
        for var in range(0, len(varNames)):
            header += "\tconstant integer " + varNames[var] + suffix + " = '" + itemId + "'\n"
            itemId = util.add(itemId)
    header += "endglobals\nendlibrary"
    w = open(path, 'w')
    print>>w, header
    w.close()
Exemple #7
0
 def get_jump(self, origin, vector):
     destination = add(origin, vector)
     destination_state = self.get_field(destination)
     if destination_state == None or destination_state == -1:
         return None
     if destination_state % 2 != self.player:
         destination = add(destination, vector)
         destination_state = self.get_field(destination)
         if destination_state == -1:
             return (origin, destination)
     return None
Exemple #8
0
 def getOutput(self, inputs):
     a_1 = [[
         util.sigmoid(x)
         for x in util.add(util.dot(inputs, self.ihWeights), self.ihBias)[0]
     ]]
     #a_2 = [[util.sigmoid(x) for x in util.add(util.dot(a_1, self.hhWeights), self.hhBias)[0]]] # uncomment and fix a_3 for 2 hidden layers
     a_3 = [[
         util.sigmoid(x)
         for x in util.add(util.dot(a_1, self.hoWeights), self.hoBias)[0]
     ]]
     return a_3[0]
def view(title=""):
    if title == "":
        return redirect('/home')
    user=""
    if verify():
        user=session['username']
    if request.method == "POST":
        form = request.form
        content = form['content']
        util.add("%s.db"%title,user, content)
    posts = util.getposts(title)
    return render_template('view.html',user=user,title=title,posts=posts)
Exemple #10
0
def view(title=""):
    if title == "":
        return redirect('/home')
    user = ""
    if verify():
        user = session['username']
    if request.method == "POST":
        form = request.form
        content = form['content']
        util.add("%s.db" % title, user, content)
    posts = util.getposts(title)
    return render_template('view.html', user=user, title=title, posts=posts)
def make():
    if request.method =="POST":
        form = request.form
        title=form['Title']
        content=form['content']
        button=form['button']
        user=session['username']
        if button=='Back':
            user=session['username']
            return render_template('home.html', user=user)
        util.add("%s.db"%title,user,content)
        return redirect('/view/%s'%title)
    if verify():
        user = session['username']
        return render_template('make.html',user=user)
    return redirect(url_for("login"))
Exemple #12
0
 def perform_action(self, move):
     if move is None:
         self.game_ended = True
         return
     origin, destination = move
     figure = self.get_field(origin)
     if figure == 0 and destination[0] == self.board_size - 1:
         figure = 2
     if figure == 1 and destination[0] == 0:
         figure = 3
     self.add_figure(figure, destination)
     self.remove_figure(origin)
     if abs(move[0][0] - move[1][0]) == 2:
         self.pacifist_turns = 0
         half_destination = div(add(origin, destination), 2)
         self.remove_figure(half_destination)
         move_type, _ = self.get_viable_moves_from_field(destination)
         if move_type == 1:
             self.only_viable_field = destination
         else:
             self.only_viable_field = None
             self.player = 1 - self.player
     else:
         self.pacifist_turns += 1
         self.player = 1 - self.player
Exemple #13
0
def constants(constantsDir, constantsFile, cwd, keywords = [], rawCode = "", suffix = "", alt = ""):
    fileNames = util.getFileNames(constantsDir, cwd, keywords)
    varNames = [util.getFileName.findall(x)[0] for x in fileNames]
    varNames = [x.replace("_hero", "") for x in varNames]
    varNames = [x.replace("_vendor", "") for x in varNames]
    path = os.path.join(CONSTANTS_DIR, constantsFile)
    w = open(path, 'w')
    header = "library " + (constantsDir + alt).title() + "Constants\n"
    header = header.replace("_", "")
    header += "globals\n"
    i = 0
    objID = rawCode + "000"
    if rawCode == "N":
        i = 1
    elif rawCode == "w":
        i = "vZZZ"
    elif rawCode == "g":
        objID = rawCode + "001"
    for var in varNames:
        value = i
        if rawCode != "" and rawCode != "w" and rawCode != "g":
            value = int2Rawcode(value, rawCode)
        elif rawCode == "w" or rawCode == "g":
            value = "'" + objID + "'"
            objID = util.add(objID)
        header += "\tconstant integer " + var.upper() + suffix + " = " + str(value) + "\n"
        if rawCode != "w" and rawCode != "g":
            i += 1
    header += "endglobals\nendlibrary"
    print>>w, header
    w.close()
Exemple #14
0
def make():
    if request.method == "POST":
        form = request.form
        title = form['Title']
        content = form['content']
        button = form['button']
        user = session['username']
        if button == 'Back':
            user = session['username']
            return render_template('home.html', user=user)
        util.add("%s.db" % title, user, content)
        return redirect('/view/%s' % title)
    if verify():
        user = session['username']
        return render_template('make.html', user=user)
    return redirect(url_for("login"))
Exemple #15
0
 def post(self, user_id, spotify_id):
     data = json.loads(self.request.body)
     song_name = data['song_name']
     artist_name = data['artist_name']
     album_name = data['album_name']
     album_cover_url = data['album_cover_url']
     u_id = int(user_id)
     self.write(util.add(u_id, spotify_id, song_name, artist_name, album_name, album_cover_url))
Exemple #16
0
def distance_along_edge_to_point(edge, distance_along_edge):
    edge_start, edge_end = edge
    edge_vector = util.subtract(edge_end, edge_start)
    edge_length = util.norm(edge_vector)    
    scale_factor = distance_along_edge / edge_length
    scaled_vector = util.scale(scale_factor, edge_vector)
    point = util.add(scaled_vector, edge_start)
    return point
Exemple #17
0
 def play(self):
     fullTime = util.lcm(self.government_period, self.public_period)
     self.government_strategy = self.getStrategyForAllPeriod(self.government_strategy, self.government_period,
                                                             fullTime)
     self.public_strategy = self.getStrategyForAllPeriod(self.public_strategy, self.public_period, fullTime)
     self.payoff = [0, 0]
     for x in range(0, fullTime):
         self.payoff = util.add(self.getPayoff(x), self.payoff)
     return self.payoff
Exemple #18
0
def make():
    if request.method =="POST":
        form = request.form
        title=form['Title']
        content=form['content']
        button=form['button']
        user=session['username']
        if button=='Back':
            user=session['username']
            return render_template('home.html', user=user)
        util.add("%s.db"%title,user,content)
        #Appears to be used to add posts, see Utils
        return redirect('/view/%s'%title)
        #Redirects to a post of the name that was added
    if verify():
        user = session['username']
        return render_template('make.html',user=user)
    return redirect(url_for("login"))
Exemple #19
0
	def onLeftUp(self, evt):
		self.moving = False
		self.update()
		
		#if self.moving_proved:
		#	return
			
		pos = util.add(self.offset_pos, util.div(evt.GetPosition(), float(self.cell_size)))
		wx.PostEvent(self.GetParent(), event.SelectObject(attr1=(int(round(pos[0])), int(round(pos[1]))), attr2=None))
Exemple #20
0
def make():
    if request.method == "POST":
        form = request.form
        title = form['Title']
        content = form['content']
        button = form['button']
        user = session['username']
        if button == 'Back':
            user = session['username']
            return render_template('home.html', user=user)
        util.add("%s.db" % title, user, content)
        #Appears to be used to add posts, see Utils
        return redirect('/view/%s' % title)
        #Redirects to a post of the name that was added
    if verify():
        user = session['username']
        return render_template('make.html', user=user)
    return redirect(url_for("login"))
Exemple #21
0
 def post(self, user_id, spotify_id):
     data = json.loads(self.request.body)
     song_name = data['song_name']
     artist_name = data['artist_name']
     album_name = data['album_name']
     album_cover_url = data['album_cover_url']
     u_id = int(user_id)
     self.write(
         util.add(u_id, spotify_id, song_name, artist_name, album_name,
                  album_cover_url))
Exemple #22
0
 def intersect(self, o, d):
     if abs(d[2]) < 1e-6:
         return None
     t = (self.z - o[2]) / d[2]
     if t <= 1e-6:
         return None
     p = util.add(o, util.mul_scalar(d, t))
     dist = (p[0] * p[0] + p[1] * p[1]) ** 0.5
     if dist > self.radius:
         return None
     return t
Exemple #23
0
    def adam(allparams,
             nat_stepsize,
             stepsize,
             num_epochs,
             seq_len,
             num_seqs=None,
             b1=0.9,
             b2=0.999,
             eps=1e-8,
             num_samples=1):
        natparams, params = allparams[:1], allparams[1:]
        m = zeros_like(params)
        v = zeros_like(params)
        i = 0
        accumulate = lambda rho, a, b: add(scale(1 - rho, a), scale(rho, b))

        for epoch in xrange(num_epochs):
            vals = []
            batches, num_batches = split_into_batches(data, seq_len, num_seqs)
            for y in batches:
                val, grad = scale(
                    1. / num_datapoints,
                    val_and_grad(y, num_batches, num_samples, *allparams))
                natgrad, grad = grad[:1], grad[1:]

                m = accumulate(b1, grad, m)  # first moment estimate
                v = accumulate(b2, square(grad), v)  # second moment estimate
                mhat = scale(1. / (1 - b1**(i + 1)), m)  # bias correction
                vhat = scale(1. / (1 - b2**(i + 1)), v)
                update = scale(stepsize, div(mhat, add_scalar(eps,
                                                              sqrt(vhat))))

                natparams = add(natparams, scale(nat_stepsize, natgrad))
                params = add(params, update)
                allparams = concat(natparams, params)
                vals.append(val)
                i += 1

                if callback: callback(epoch, vals, natgrad, allparams)

        return allparams
def multiply_karatsuba_parallel(x, y, key=None):
    """
    Multiplies two numbers represented as arrays
    using the Karatsuba algorithm, falling back
    on grade school algorithm for the base case

    :param x: []int
    :param y: []int
    :rtype []int
    """
    x, y = match_padding(x, y)
    a, b = split(x)
    c, d = split(y)

    # for base case, go simple
    if len(x) == 1:
        return multiply_simple(x, y)

    # for big numbers, go parallel
    if len(x) > 300:
        # generate random ids for the subprocess outputs
        r1 = random.random()
        r2 = random.random()
        r3 = random.random()

        # run the sub-multiplications in parallel
        p1 = Process(target=multiply_karatsuba_parallel, args=[a, c, r1])
        p2 = Process(target=multiply_karatsuba_parallel, args=[b, d, r2])
        p3 = Process(target=multiply_karatsuba_parallel,
                     args=[add(a, b), add(c, d), r3])

        p1.start()
        p2.start()
        p3.start()
        p1.join()
        p2.join()
        p3.join()

        # get the results
        res_1 = return_dict[r1]
        res_2 = return_dict[r2]
        partial = return_dict[r3]

    # for smaller numbers, don't bother parallelizing
    else:
        res_1 = multiply_karatsuba_parallel(a, c)
        res_2 = multiply_karatsuba_parallel(b, d)
        partial = multiply_karatsuba_parallel(add(a, b), add(c, d))

    # do the karatsuba shuffle
    res_3 = subtract(partial, add(res_1, res_2))
    res = add(pad(res_1, len(x), 'right'), res_2,
              pad(res_3, (len(x) + 1) // 2, 'right'))

    # if we are in parallel mode, write the result to the global dict
    if key is not None:
        return_dict[key] = res

    return res
Exemple #25
0
	def onScroll(self, evt):

		pos = evt.GetPosition()
		logicPos = util.div(pos, float(self.cell_size))

		diff = 1 if evt.GetWheelRotation()>0 else -1
		self.cell_size += diff
		if self.cell_size < 1:
			self.cell_size = 1
		elif self.cell_size > 40:
			self.cell_size = 40

		self.calcScreenSize()
		
		#make sure mouse is pointing on the centre  of the scroll area ( just move the pos so that this _is_ the center )
		newScreenPos = util.mul(logicPos, self.cell_size)
		newScreenDiff = util.sub(newScreenPos, pos)
		newLogicDiff = util.div(newScreenDiff, self.cell_size)
		self.offset_pos = util.add(self.offset_pos, newLogicDiff)

		self.update()
Exemple #26
0
def adam(gradfun, allparams, num_iters, step_size, b1=0.9, b2=0.999, eps=1e-8):
    natparams, params = allparams[:1], allparams[1:]
    m = zeros_like(params)
    v = zeros_like(params)
    i = 0
    accumulate = lambda rho, a, b: add(scale(1-rho, a), scale(rho, b))
 
    for i in xrange(num_iters):
        grad = gradfun(allparams, i)
        natgrad, grad = grad[:1], grad[1:]
 
        m = accumulate(b1, grad, m)          # first moment estimate
        v = accumulate(b2, square(grad), v)  # second moment estimate
        mhat = scale(1./(1 - b1**(i+1)), m)  # bias correction
        vhat = scale(1./(1 - b2**(i+1)), v)
        update = scale(step_size, div(mhat, add_scalar(eps, sqrt(vhat))))
 
        natparams = sub(natparams, scale(step_size, natgrad))
        params = sub(params, update)
        allparams = concat(natparams, params)
 
    return allparams
Exemple #27
0
 def __add__(self, other):
     import util
     return util.add(self, other)
Exemple #28
0
 def get_walk(self, origin, vector):
     destination = add(origin, vector)
     destination_state = self.get_field(destination)
     if destination_state == -1:
         return (origin, destination)
     return None
 def _():
     assert util.add(1, 1) == 2
def resnet_decode(z, phi):
    phi_linear, phi_mlp = phi
    return add(linear_decode(z, phi_linear), mlp_decode(z, phi_mlp, tanh_scale=2., sigmoid_output=False))
Exemple #31
0
#!/usr/bin/env python
# encoding: utf-8
"""
script.py

Created by mark henderson on 2013-02-19.
Copyright (c) 2013 __MyCompanyName__. All rights reserved.
"""
from util import add, connect

#create the main node
meetup = add(name='meetup')


#add everyone 
mark = add(name='mark')
patrick = add(name='patrick')
greg = add(name='greg')
joel = add(name='joel')
leila = add(name='leila')
howard = add(name='howard')
henry = add(name='henry')
brandon = add(name='brandon')
chris = add(name='chris')
kevin = add(name='kevin')
will = add(name='will')
mike = add(name='mike')
kathleen = add(name='kathleen')
foster = add(name='foster')
jeff = add(name='jeff')
matt = add(name='matt')
Exemple #32
0
 def gradfun(y_n, N, L, eta, phi, psi):
     objective = lambda (phi, psi): mc_vlb(eta, phi, psi, y_n, N, L)
     vlb, (phi_grad, psi_grad) = vgrad(objective)((phi, psi))
     eta_natgrad = sub(add(eta_prior, saved.stats), eta)
     return vlb, (eta_natgrad, phi_grad, psi_grad)
Exemple #33
0
	def rectFilter(self, rect):
		ps = self.screenPosToLogic(rect.GetPosition().Get())
		ps = util.sub(ps, (1,1))
		sz = util.div(rect.GetSize().Get(), self.cell_size)
		sz = util.add(sz, (1,1))
		return ['x>=%d AND y>=%d AND x<=%d AND y<=%d'%(ps[0], ps[1], ps[0]+sz[0], ps[1]+sz[1])]
Exemple #34
0
	def screenPosToLogic(self, pos):
		return util.add(self.offset_pos, util.div(pos, self.cell_size))
Exemple #35
0
def test_add():
    assert add(1, 2) == 3, "test failed"
Exemple #36
0
 def gradfun(y_n, N, L, eta, phi, psi):
     objective = lambda (phi, psi): mc_vlb(eta, phi, psi, y_n, N, L)
     vlb, (phi_grad, psi_grad) = vgrad(objective)((phi, psi))
     eta_natgrad = sub(add(eta_prior, saved.stats), eta)
     return vlb, (eta_natgrad, phi_grad, psi_grad)
def resnet_recognize(x, psi):
    psi_linear, psi_mlp = psi
    return add(linear_recognize(x, psi_linear),
               mlp_recognize(x, psi_mlp, tanh_scale=2.))
Exemple #38
0
import util

print(util.add(1,2))
    for i in range(repetitions):
        print("repetion: "+str(i))
        ds=initStates(data,statesPerVar,prior)
        gk = Gibbs(ds, ds.dens)
        dags,scores=runMCMConDAGonly(numIterations,ds)
        collDags.extend(gk.moves)
        collScores.extend(gk.scores)   


scores,indeces = maxScoresIndeces(collScores,nBest)  
scoresOld =scores 
scores = normVector(scores)
selectiveBest=[[0 for i in range(numVariables)]for j in range(numVariables)]

for i in range(nBest):
    selectiveBest=add(selectiveBest,multMatrixScalar(collDags[indeces[i]],scores[i]))    


print("##############")
print("selectiveBest")
for line in selectiveBest:
    print(line)
theBest=collDags[indeces[0]]
print("##############")
print("theBest")
for line in theBest:
    print(line)



writeMyCSV("selectiveBest.csv",selectiveBest)        
def test_answerFail():
    assert util.add(1,1) == 3
def test_add():
    nt.assert_equal(add(1,2), 3)
Exemple #42
0
 def __sub__(self, other):
     import util
     return util.add(self, other, scale2=-1)
def test_answer():
    assert util.add(1,1) == 2