Ejemplo n.º 1
0
def checkForButton():
    global isOn
    global currentColor
    global savedColor
    lastChange = datetime.now()
    while True:
        if (GPIO.input(27)):
            if savedColor != currentColor:
                transition(currentColor, savedColor, TRANSITION_DURATION, FPS)
                currentColor = savedColor
                print("On! Saved: {} Current: {}".format(
                    savedColor, currentColor))
            lastChange = datetime.now()
        else:
            if (datetime.now() - lastChange).seconds < 1:
                isOn = True
            else:
                isOn = False
                if not currentColor == "#000000":
                    savedColor = currentColor
                    currentColor = "#000000"
                    print("Off! Saved: {} Current: {}".format(
                        savedColor, currentColor))
                    transition(currentColor, currentColor, TRANSITION_DURATION,
                               FPS)
        time.sleep(0.05)
Ejemplo n.º 2
0
def set_color():
    global currentColor
    data = request.get_json()
    print(data["color"])
    color = data["color"]  #if isOn else "#000000"
    # print("Color: {} isOn: {}".format(color, isOn))
    transition(currentColor, color, TRANSITION_DURATION, FPS)
    currentColor = color
    return jsonify({"success": True})
Ejemplo n.º 3
0
def simulate_posterior(region, params, dates, initial, N = 1000, weekly = False,
                       parI = (1,1), parR = (1,1),parD = (1,1), random_params = False):
    """Simulate from the HMM model.
    
    Args:
        region (str): Region for the data.
        params (list): Optimized parameters.
        dates (tuple (2)): Date range of the data.
        initial (dict): Initial values in dict with keys S,E,I,R,D.
        N (int): Number of samples.
        weekly (bool, optional): Weekly time step if True, otherwise daily.
        parI (tuple (2)): Prior parameters for emission model I. By default (1,1).
        parR (tuple (2)): Prior parameters for emission model R. By default (1,1).
        parD (tuple (2)): Prior parameters for emission model D. By default (1,1).
        random_params (bool, optional): Bayesian parameters if True, otherwise single point.
    """
    x = _posterior_data(region, dates, weekly=weekly)\
        .reset_index(drop = True)
    POP = population.get_population(region)
    # filter param
    params = params[params.start <= dates[1]]
    if (params.end > dates[1]).any():
        params.loc[params.end > dates[1], 'end'] = dates[1]
    latent = transition(POP, initial, params, random_params=random_params)
    xx = x.merge(latent, how='left', on=['date'])
    Dw = xx.shape[0]
    D = (dates[1] - dates[0]).days + 1
    sim_lat = np.zeros((5,N,Dw))
    sim_obs = np.zeros((5,N,Dw))
    for i in range(N):
        if i == 0 or (i+1) % 100 == 0:
            print('%4d / %d' % (i+1,N))
        # transition
        latent = transition(POP, initial, params, random_params=random_params)
        latent[latent.I < 0]['I'] = 0
        xx = x.merge(latent, how='left', on=['date'])
        xx.tests = xx['tests'].apply(lambda t: t if t >= 0 else 1)
        sim_lat[:,i,:] = xx[['S','E','I','R','D']].to_numpy().T
        # emission
        try:
            sim_obs[2,i,:] = emission(np.abs(xx.I.to_numpy()), xx.tests.to_numpy(), *parI)
        except:
            print(xx.I)
            print(xx.tests)
            raise
        sim_obs[3,i,:] = emission(xx.R.to_numpy(), xx.cumtests.to_numpy(), *parR)
        sim_obs[4,i,:] = emission(xx.D.to_numpy(), xx.cumtests.to_numpy(), *parD)
    # spare last
    last_values = sim_lat[:,:,-1].mean(axis = 1)
    # denormalize probability
    sim_lat[1:3,:,:] = sim_lat[1:3,:,:] * x.tests.to_numpy()
    sim_lat[3:5,:,:] = sim_lat[3:5,:,:] * x.cumtests.to_numpy()
    sim_obs[1:3,:,:] = sim_obs[1:3,:,:] * x.tests.to_numpy()
    sim_obs[3:5,:,:] = sim_obs[3:5,:,:] * x.cumtests.to_numpy()
    return (sim_lat, sim_obs), last_values
Ejemplo n.º 4
0
 def __init__(self):
     self.Input_Alpha = Input_Alphabet()
     self.Stack_Alpha = Stack_Alphabet()
     self.States = States()
     self.Final_States = Final_States()
     self.Transition = transition()
     self.operating = False
     #Add Transition_Function here
     file_path = ''
     description = ''
     initial_state = ''
     start_character = ''
Ejemplo n.º 5
0
def main():
    tool.preprocess('../data/POS/train', '../data/POS/ptrain')
    tool.preprocess('../data/NPC/train', '../data/NPC/ptrain')

    e0 = em.emission()
    t0 = tr.transition()
    print "without preprocessor"
    e0.compute('../data/POS/train')
    t0.compute('../data/POS/train')
    e0.predict('../data/POS/dev.in','../data/POS/dev.p2.out',p=False)
    print "POS,MLE:", tool.evaluate('../data/POS/dev.p2.out','../data/POS/dev.out')
    viterbi_best(e0,t0,'../data/POS/dev.in','../data/POS/dev.p3.out',p=False)
    print "POS,DP:", tool.evaluate('../data/POS/dev.p3.out','../data/POS/dev.out')
Ejemplo n.º 6
0
 def processRecurse(self, parent, treeObj, queryObj, category):
     if type(treeObj) != nltk.tree.Tree:  # leaf node
         transition_obj = transition(parent, treeObj, None, queryObj,
                                     category)
         return treeObj, transition_obj
     if "." == treeObj.label() or "DT" == treeObj.label(
     ):  # do not handle determiners or punctuation
         return "", None
     str_transition = treeObj.label() + " " + "->"
     current_children = []
     for i in range(len(treeObj)):
         label, transition_obj_inter = self.processRecurse(
             treeObj.label(), treeObj[i], queryObj, category)
         if transition_obj_inter is not None:
             current_children.append(transition_obj_inter)
             str_transition += " " + label
     if treeObj.label() != 'ROOT':
         transition_obj_fin = transition(parent, str_transition,
                                         current_children, queryObj,
                                         category)
     else:  # Root of the tree is encountered
         transition_obj_fin = None
     return treeObj.label(), transition_obj_fin
Ejemplo n.º 7
0
    def transition(self,
                   parname='rho',
                   val=0.014,
                   KN0=33.22430956,
                   KNST=31.45765379,
                   do_print=True,
                   step_size=0.1,
                   tol=1e-5,
                   load=False,
                   maxiter=100):

        KN_path = transition.transition(self, parname, val, KN0, KNST,
                                        do_print, step_size, tol, load,
                                        maxiter)

        return KN_path
Ejemplo n.º 8
0
def main():
    tool.preprocess('../data/POS/train', '../data/POS/ptrain')
    tool.preprocess('../data/NPC/train', '../data/NPC/ptrain')

    e0 = em.emission()
    t0 = tr.transition()
    print "without preprocessor"
    e0.compute('../data/POS/train')
    t0.compute('../data/POS/train')
    e0.predict('../data/POS/dev.in', '../data/POS/dev.p2.out', p=False)
    print "POS,MLE:", tool.evaluate('../data/POS/dev.p2.out',
                                    '../data/POS/dev.out')
    viterbi_best(e0,
                 t0,
                 '../data/POS/dev.in',
                 '../data/POS/dev.p3.out',
                 p=False)
    print "POS,DP:", tool.evaluate('../data/POS/dev.p3.out',
                                   '../data/POS/dev.out')
Ejemplo n.º 9
0
def posterior_objective(params, region, dates, initial, fixparams = None, weekly=False,
                        attributes = 'IRD', parI = (1,1), parR = (1,1), parD = (1,1)):
    """Objective function of the HMM model for optimization.
    
    Args:
        params (list): Optimized parameters.
        region (str): Region for the data.
        dates (tuple (2)): Date range of the data.
        initial (dict): Initial values in dict with keys S,E,I,R,D.
        fixparams (list): Fixed parameters.
        weekly (bool, optional): Weekly time step if True, otherwise daily.
        attributes (str, optional): Attributes used for optimization, 'I', 'R' or 'D'.
        parI (tuple (2)): Prior parameters for emission model I.
        parR (tuple (2)): Prior parameters for emission model R.
        parD (tuple (2)): Prior parameters for emission model D.
    """
    x = _posterior_data(region, dates, weekly=weekly)
    POP = population.get_population(region)
    # construct params dataframe
    a,c,b,d = _parse_params(params, fixparams)
    params = pd.DataFrame({'start': [dates[0]], 'end': [dates[1]],
                            'a': [a], 'b': [b], 'c': [c], 'd': [d]})
    # compute score
    D = (dates[1] - dates[0]).days + 1
    score = 0
    latent = transition(POP, initial, params)
    latent.loc[latent.I < 0,'I'] = 0
    x = x.merge(latent, how='left', on=['date'])
    if 'I' in attributes:
        score += emission_objective(x.confirmed.to_numpy() / x.tests.to_numpy(),
                                    np.abs(x.I.to_numpy()), x.tests.to_numpy(), *parI)
    if 'D' in attributes:
        score += emission_objective(x.deaths.cumsum().to_numpy() / x.cumtests.to_numpy(),
                                    x.D.to_numpy(), x.cumtests.to_numpy(), *parD)
    if 'R' in attributes:
        score += emission_objective(x.recovered.cumsum().to_numpy() / x.cumtests.to_numpy(),
                                    x.R.to_numpy(), x.cumtests.to_numpy(), *parR)
    return score / D
Ejemplo n.º 10
0
def turing_machine(config, input_):
    '''
    The actual turing machine parser. We create a loop that keeps running until
    a final state has been reached. using a for/in we find the right transition
    and let the transition function handle the transition, and print the status
    everytime we go through a transition.
    '''

    state = config['initial']
    tape = list(input_)
    i = 0
    while state not in config['finals']:
        for item in config['transitions'][state]:
            if item['read'] == tape[i]:
                (i, state) = transition(i, tape, item, config['blank'])
                print_status(tape.copy(), i, state, item)
                break
        else:
            print_status(tape.copy(), i, state, item)
            raise MachineError(
                f"No valid transition found for state '{state}' and character '{tape[i]}'"
            )
    print("".join(tape))
Ejemplo n.º 11
0
def tran():
    transition(input_path)
    # "/Users/sf/Desktop/RU/Capstone/SourceCode/Web/resource/xiaoxingxing.wav"
    return "transend"
p_u = .25
p_d = .25
p_mn = 0
probabilities = [p_r, p_l, p_u, p_d, p_mn]
iterations = 0

memory = {(m, n)}
locations = [[-1.5, 0], [-1, -0.5], [-1, 0.5], [-0.5, -1], [-0.5, 0],
             [-0.5, 1], [0, -1.5], [0, -0.5], [0, 0.5], [0, 1.5], [0.5, -1],
             [0.5, 0], [0.5, 1], [1, -0.5], [1, 0.5], [1.5, 0]]

while iterations < 200000:
    chemo = []
    for i in locations:
        if (m + i[0], n + i[1]) in memory:
            conc = 0
        else:
            conc = concentration(m + i[0], n + i[1], source_m, source_n)
        chemo.append(chemoattractant(conc, tip))

    transitions = transition(chemo, k)
    normal_transitions = normal_transition(transitions)
    probabilities = probability(normal_transitions, probabilities)
    m, n = movement(probabilities, memory, workspace, m, n, size, iterations)

    iterations += 1

plt.imshow(workspace)
cm.get_cmap("jet")
plt.show()
Ejemplo n.º 13
0
def tran():
    global i
    transition(input_file_path + str(i) + '/audio' + str(i) + '.wav', i)
    i += 1
    # "/Users/sf/Desktop/RU/Capstone/SourceCode/Web/resource/xiaoxingxing.wav"
    return "transend"
Ejemplo n.º 14
0
parser.add_argument('-p',dest='process',type=bool,default=True,help='whether do process or not')
args = parser.parse_args()
print args
if args.algorithm==0:
	e = em.emission()
	e.compute(args.trainfile)
	e.predict(args.infile,args.outfile,args.process)
	# print tool.evaluate('../data/POS/dev.out',args.outfile,col=1)

elif args.algorithm==1:
	if args.best != 1:
		print "Error: best must be 1 with algorithm 1"
		exit(0)
#run original version of viterbi
	e = em.emission()
	e.compute(args.trainfile)
	t = tr.transition()
	t.compute(args.trainfile)
	viterbi.viterbi_best(e,t,args.infile,args.outfile,args.process)
	# print tool.evaluate('../data/POS/dev.out',args.outfile,col=1)
elif args.algorithm==2:
	e = em.emission()
	e.compute(args.trainfile)
	t = tr.transition()
	t.compute(args.trainfile)

	viterbi.viterbi_Nbest(e,t,args.infile,args.outfile,args.best, args.process)
	# c = 1
	# while c<=args.best:
		# print tool.evaluate(args.outfile,'../data/POS/dev.out',col=c)
		# c = c+1
Ejemplo n.º 15
0
    def __init__(self, grille):
        self.grille = grille
        self.playerPos = (grille.size[0] - 1, grille.size[1] - 1)
        #CREATE THE STATES
        self.grille = grille
        for i in range(grille.size[0]):
            for j in range(grille.size[1]):
                for sword in range(2):
                    for tresor in range(2):
                        for key in range(2):
                            for health in range(1, 5):
                                if grille.tab[i][j] != 'M' and grille.tab[i][
                                        j] != 'P' and grille.tab[i][j] != 'W':

                                    self.listState[((i, j), sword, key, health,
                                                    tresor, 0)] = st.state(
                                                        sword, tresor, key,
                                                        health, (i, j), 0,
                                                        grille)
                                if grille.tab[i][j] != 'W':
                                    self.listState[((i, j), sword, key, health,
                                                    tresor, 1)] = st.state(
                                                        sword, tresor, key,
                                                        health, (i, j), 1,
                                                        grille)
        self.listState[((-1, -1), -1, -1, -1, -1, 1)] = st.state(-1,
                                                                 -1,
                                                                 -1,
                                                                 -1, (-1, -1),
                                                                 1,
                                                                 grille,
                                                                 param="fail")

        self.listState[((-2, -2), -2, -2, -2, -2,
                        1)] = st.state(-2,
                                       -2,
                                       -2,
                                       -2, (-2, -2),
                                       1,
                                       grille,
                                       param="sucess")

        self.listState[((-1, -1), -1, -1, -1, -1, 2)] = st.state(type=2,
                                                                 param="fail")
        self.listState[((-2, -2), -2, -2, -2, -2,
                        2)] = st.state(type=2, param="sucess")

        self.listTrans[((-1, -1), -1, -1, -1, -1, 1)] = [
            ts.transition(self.grille,
                          self.listState[((-1, -1), -1, -1, -1, -1, 1)],
                          [self.listState[((-1, -1), -1, -1, -1, -1, 2)]], [1],
                          -3000)
        ]
        self.listTrans[((-2, -2), -2, -2, -2, -2, 1)] = [
            ts.transition(self.grille,
                          self.listState[((-2, -2), -2, -2, -2, -2, 2)],
                          [self.listState[((-2, -2), -2, -2, -2, -2, 2)]], [1],
                          30000)
        ]
        self.listTrans[((-1, -1), -1, -1, -1, -1, 2)] = []
        self.listTrans[((-2, -2), -2, -2, -2, -2, 2)] = []
        #create the transitions
        for i in range(grille.size[0]):
            for j in range(grille.size[1]):
                for sword in range(2):
                    for tresor in range(2):
                        for key in range(2):
                            for health in range(1, 5):
                                if grille.tab[i][j] != 'M' and grille.tab[i][
                                        j] != 'P' and grille.tab[i][j] != 'W':
                                    stateCurrent = self.listState[((i,
                                                                    j), sword,
                                                                   key, health,
                                                                   tresor, 0)]
                                    #state where the player cannot move(don't have a choice) or go in
                                    self.listTrans[(
                                        (i, j), sword, key, health, tresor,
                                        0)] = ts.transitionDecision(
                                            stateCurrent, self.listState,
                                            grille)
                                if grille.tab[i][j] != 'W':
                                    stateCurrent = self.listState[((i,
                                                                    j), sword,
                                                                   key, health,
                                                                   tresor, 1)]
                                    self.listTrans[((i, j), sword, key, health,
                                                    tresor, 1)] = ts.action(
                                                        stateCurrent,
                                                        self.listState, grille)

        return
Ejemplo n.º 16
0
 def addTransition(self, id, From, To, condition=None, REQUEST=None):
     """ adds a transition """
     t = transition(id, From, To, condition)
     self._setObject(t.id, t)
     if REQUEST: REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)
Ejemplo n.º 17
0
 def __init__(self, all_transitions):
     self._list = [
         transition(line[0], line[2], line[1], line[3], line[4])
         for line in all_transitions
     ]
Ejemplo n.º 18
0
import emission as em
import transition as t

e = em.emission()
# e.process(train)
# e.process_input(infile)
# e.tokenize(self.X)
# e.tokenizedX = self.tokenize_test(self.testX)
# e.get_emission_prob(self.X, self.Y)
e.print_out('train', 'dev.in', 'dev.p2.out')

t = t.transition()
t.train('train')
print(t.get_trans_params(t.Y))
Ejemplo n.º 19
0
args = parser.parse_args()
print args
if args.algorithm == 0:
    e = em.emission()
    e.compute(args.trainfile)
    e.predict(args.infile, args.outfile, args.process)
    # print tool.evaluate('../data/POS/dev.out',args.outfile,col=1)

elif args.algorithm == 1:
    if args.best != 1:
        print "Error: best must be 1 with algorithm 1"
        exit(0)
#run original version of viterbi
    e = em.emission()
    e.compute(args.trainfile)
    t = tr.transition()
    t.compute(args.trainfile)
    viterbi.viterbi_best(e, t, args.infile, args.outfile, args.process)
    # print tool.evaluate('../data/POS/dev.out',args.outfile,col=1)
elif args.algorithm == 2:
    e = em.emission()
    e.compute(args.trainfile)
    t = tr.transition()
    t.compute(args.trainfile)

    viterbi.viterbi_Nbest(e, t, args.infile, args.outfile, args.best,
                          args.process)
    # c = 1
    # while c<=args.best:
    # print tool.evaluate(args.outfile,'../data/POS/dev.out',col=c)
    # c = c+1
Ejemplo n.º 20
0
    1-reject(ant.current, x) : at-nest(x, ant.current)
    reject(ant.current, x)   : search(ant.state)

accept-loc(ant, x):
    pass
'''

#def arrive(states, parameters, ant):
#pass


def accept(ant):
    pass


arrive = transition(substate='at-nest')

states = {
    'exploration': {
        'follow': {
            # arrive (Dependent on leader ant)
            'get-lost': transition(substate='search')
        },
        'search': {
            'picked-up': transition(substate='carried'),
            'find-0': move(0),
            'find-other': move_random
        },
        'carried': {
            #'arrive' : arrive (Dependent on number of ants in carrying state)
        },