Ejemplo n.º 1
0
def controller(A, B1, B2, C, D1, D2, name):
    states = helper.load_states()
    states[name] = {
        'value': [A, B1, B2, C, D1, D2],
        'A': states[A],
        'B1': states[B1],
        'B2': states[B2],
        'C': states[C],
        'D1': states[D1],
        'D2': states[D2],
        'controls': {},
        'outputs': {},
        'meta': {
            'what': 'controller',
            'A': states[A]['meta'],
            'B1': states[B1]['meta'],
            'B2': states[B2]['meta'],
            'C': states[C]['meta'],
            'D1': states[D1]['meta'],
            'D2': states[D2]['meta']
        }
    }
    helper.save_states(states)
    result = 'x_c\' = ' + A + 'x_c + ' + B1 + 'y + ' + B2 + 'r , u = ' + C + 'x_c + ' + D1 + 'y + ' + D2 + 'r'
    return result
Ejemplo n.º 2
0
def matrix(name, value):
    states = helper.load_states()
    val = np.matrix(json.loads(value))
    str_vec = helper.to_str_repr(val)
    #print(states, file=sys.stderr)

    states[name] = {'value': val, 'meta': {'what': 'matrix', 'value': str_vec}}
    helper.save_states(states)

    return states[name]['value'].tolist()
Ejemplo n.º 3
0
def generate_grid(name, height, width):
    image_shape = (height, width)
    states = helper.load_states()
    f = os.path.join(app.config['UPLOAD_FOLDER'], states[name]['value'])
    image = scipy.misc.imresize(scipy.misc.imread(name=f, flatten=True), image_shape)
    str_vec = helper.to_str_repr(np.array(image))
    states[name+'_grid'] = {'value': np.matrix(image), 'meta': {'what': 'matrix', 'value': str_vec}}
    helper.save_states(states)
    #matrix(name+'_grid', np.array(image))
    return 'Grid matrix generated.  Type gdisplay ' + name + '_grid to display.'
Ejemplo n.º 4
0
def lambert(r1, r2, t, prograde, mu, name):
    omt_ins = omt.omt()
    omt_ins.lambert(json.loads(r1), json.loads(r2), float(t), bool(prograde), float(mu))
    #omt_ins.lambert([5000,10000,2100], [-14600,2500,7000], 3600, True, 398600)
    #return "Initial position: " + str(r1) + ", initial velocity: " + str(omt_ins.get_v0())
    states = helper.load_states()

    states[name] = {'value': [r1, omt_ins.get_v0()], 'meta': {'what': 'orbit', 'h': omt_ins.get_h(), 'a': omt_ins.get_a(),
      'e': omt_ins.get_e(), 'Omega': omt_ins.get_Omega(), 'i': omt_ins.get_i(), 'omega': omt_ins.get_omega()}}
    helper.save_states(states)

    return "Orbit calculated.  To display orbital elements type gdisplay " + name + "."
Ejemplo n.º 5
0
def generate_grid_obstacles(name, threshold_value, new_name):
    states = helper.load_states()
    array_np = np.array(states[name]['value'])
    more_then = array_np >= threshold_value
    less_then = array_np < threshold_value
    array_np[more_then] = 1
    array_np[less_then] = 0
    # print(array_np, file=sys.stderr)
    str_vec = helper.to_str_repr(array_np)
    states[new_name] = {'value': np.matrix(array_np), 'meta': {'what': 'matrix', 'value': str_vec}}
    helper.save_states(states)
    return 'New grid matrix generated.  Type gdisplay ' + new_name + ' to display.'
Ejemplo n.º 6
0
def simulate(output, G, init, inp, time, plot):
    states = helper.load_states()

    t1 = time
    dt = 0.1
    ts = []
    ys = []

    def f(t, y, arg1):
        return states[G]['A']['value'] * y.reshape(
            y.size, 1) + states[G]['B']['value'] * inp

    def jac(t, y, arg1):
        return states[G]['A']['value']

    def solout(t, y):
        ts.append(t)
        ys.append(y)

    r = ode(f, jac).set_integrator('vode', method='bdf', with_jacobian=True)
    r.set_initial_value(init, 0).set_f_params(0.0).set_jac_params(
        0.0)  #.set_solout(solout)

    solout(0, np.asscalar(init[states[G]['outputs'][output]].real))

    while r.successful() and r.t < t1:
        r.integrate(r.t + dt)
        out = states[G]['C']['value'] * r.y.reshape(
            r.y.size, 1) + states[G]['D']['value'] * inp
        solout(r.t, np.asscalar(out[states[G]['outputs'][output]].real))
        print([r.t, np.asscalar(out[states[G]['outputs'][output]].real)],
              file=sys.stderr)

    # create a new plot with a title and axis labels
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select,lasso_select"
    p = plt.figure(title="Reponse",
                   tools=TOOLS,
                   x_axis_label='time',
                   y_axis_label=output,
                   plot_width=800,
                   plot_height=300)

    # add a line renderer with legend and line thickness
    p.line(ts, ys, legend=output, line_width=2)

    script, div = components(p)
    states[plot] = {'meta': {}}
    states[plot]['meta'] = {'what': 'plot', 'script': script, 'div': div}

    helper.save_states(states)

    return 'Response plot created. Type gdisplay ' + plot + ' to display'
Ejemplo n.º 7
0
def modes(mat, V, E):
    states = helper.load_states()

    e_vals, e_vecs = np.linalg.eig(states[mat]['value'])
    str_vec = helper.to_str_repr(e_vecs)
    states[V] = {
        'value': np.matrix(e_vecs),
        'meta': {
            'what': 'matrix',
            'value': str_vec
        }
    }
    states[E] = {'value': e_vals, 'meta': {'what': 'vector', 'value': e_vals}}

    helper.save_states(states)

    return str(states[E]['value'].tolist())
Ejemplo n.º 8
0
def ss(A, B, C, D, name):
    states = helper.load_states()
    states[name] = {
        'value': [A, B, C, D],
        'A': states[A],
        'B': states[B],
        'C': states[C],
        'D': states[D],
        'controls': {},
        'outputs': {},
        'meta': {
            'what': 'ss',
            'A': states[A]['meta'],
            'B': states[B]['meta'],
            'C': states[C]['meta'],
            'D': states[D]['meta']
        }
    }
    helper.save_states(states)
    result = 'x\' = ' + A + 'x + ' + B + 'u , y = ' + C + 'x + ' + D + 'u'
    return result
Ejemplo n.º 9
0
from flask import Blueprint
from jsonrpc.backend.flask import api
import numpy as np
import bokeh.plotting as plt
import csv

import helper

data_api = Blueprint('data_api', __name__)
# @simple_page.route('/<page>')
# def show(page):

states = helper.load_states()


@api.dispatcher.add_method
def data(file, name):
    states[name] = {'value': file, 'meta': {'what': 'data', 'value': file}}
    helper.save_states()
    return 'Data in ' + file + ' will be referenced by: ' + name


@api.dispatcher.add_method
def fit(name, prestatestor):

    x = []
    y = []
    with open(states[name]['value'], mode='r') as infile:
        mappingfile = csv.reader(infile)
        for row in mappingfile:
            x.append(row[0].strip())
Ejemplo n.º 10
0
# init    
    
with open(corpus_file) as f:
    sents = [[twp.split('|')[0].lower() for twp in line.split()] for line in f]
    
embeddings = helper.char_embeddings(sents)

print('init network and compile theano functions...')

h_size = hidden_layer_size # hidden size

W_xi, W_hi, W_ci, b_i, \
W_xf, W_hf, W_cf, b_f, \
W_xc, W_hc, b_c, \
W_xo, W_ho, W_co, b_o, \
W_hy, b_y = helper.load_states(weights_file_name, work_dir)

S_h = helper.init_zero_vec(h_size) # init values for hidden units
S_c = helper.init_zero_vec(h_size) # init values for cell units

S_x = T.matrix() # inputs

# BEGIN code inspired by Christian Herta 
# http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php

def step(S_x, S_h, S_c, 
         W_xi, W_hi, W_ci, b_i, 
         W_xf, W_hf, W_cf, b_f, 
         W_xc, W_hc, b_c, 
         W_xo, W_ho, W_co, b_o, 
         W_hy, b_y):
Ejemplo n.º 11
0
    b_c = helper.init_zero_vec(h_size)

    W_xo = helper.init_weights((io_size, h_size))
    W_ho = helper.init_weights((h_size, h_size))
    W_co = helper.init_weights((h_size, h_size))
    b_o = helper.init_zero_vec(h_size)

    W_hy = helper.init_weights((h_size, io_size))
    b_y = helper.init_zero_vec(io_size)

else:
    W_xi, W_hi, W_ci, b_i, \
    W_xf, W_hf, W_cf, b_f, \
    W_xc, W_hc, b_c, \
    W_xo, W_ho, W_co, b_o, \
    W_hy, b_y = helper.load_states(load_weights, work_dir)

# LSTM code

S_h = helper.init_zero_vec(h_size)  # init values for hidden units
S_c = helper.init_zero_vec(h_size)  # init values for cell units

S_x = T.matrix()  # inputs
Y = T.matrix()  # targets

# BEGIN code inspired by Christian Herta
# http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php


def step(S_x, S_h, S_c, W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc,
         W_hc, b_c, W_xo, W_ho, W_co, b_o, W_hy, b_y):
Ejemplo n.º 12
0
def dijkstras(name, start, goal, result): #,x_spacing,y_spacing,start,goal):

    # Implements Dijkstra's shortest path algorithm
    # Input:
    # occupancyshhaa_map - an N by M numpy array of boolean values (represented
    #     as integers 0 and 1) that represents the locations of the obstacles
    #     in the world
    # x_spacing - parameter representing spacing between adjacent columns
    # y_spacing - parameter representing spacing between adjacent rows
    # start - a 3 by 1 numpy array of (x,y,theta) for the starting position
    # goal - a 3 by 1 numpy array of (x,y,theta) for the finishing position
    # Output:
    # path: list of the indices of the nodes on the shortest path found
    #     starting with "start" and ending with "end" (each node is in
    #     metric coordinates)

    states = helper.load_states()
    occupancy_map = np.array(states[name]['value'])
    color_map = np.array(states[name]['value'])
    # color_map = np.asmatrix(color_map)
    # print(color_map, file=sys.stderr)
    # print(occupancy_map, file=sys.stderr)

    INF = math.inf #100000
    mymap = np.zeros_like(occupancy_map)

    nrows = np.shape(mymap)[0]
    ncols = np.shape(mymap)[1]
    #print(ncols,nrows)
    start = np.array(json.loads(start))
    goal = np.array(json.loads(goal))

    start_indx = start[1] #int(np.ceil((start[0]/x_spacing)-0.5))
    start_indy = start[0] #int(np.ceil((start[1]/y_spacing)-0.5))
    dest_indx = goal[1] #int(np.ceil((goal[0]/x_spacing)-0.5))
    dest_indy = goal[0] #int(np.ceil((goal[1]/y_spacing)-0.5))

    distanceFromStart = np.zeros_like(occupancy_map, float)
    distanceFromStart.fill(INF)
    parent = np.zeros_like(occupancy_map)

    mymap[np.where(occupancy_map == 0)] = 1  # Mark free cells
    mymap[np.where(occupancy_map == 1)] = 2   # Mark obstacle cells

    # Generate linear indices of start and dest nodes
    dest_node = np.ravel_multi_index([dest_indy, dest_indx], np.shape(mymap), order='C')

    mymap[start_indy][start_indx] = 5
    mymap[dest_indy][dest_indx]  = 6

    distanceFromStart[start_indy][start_indx] = 0

    # keep track of number of nodes expanded
    numExpanded = 0
    # Main Loop
    count = 0
    while True:
        count = count + 1
        if (count == 1000):
            return "Iteration limit exceeded."

        # Find the node with the minimum distance
        min_dist = np.min(distanceFromStart)
        current = np.argmin(distanceFromStart)
        # Compute row, column coordinates of current node
        [i,j] = np.unravel_index(current, np.shape(mymap), order='C')

        if (current == dest_node or min_dist == INF):
            break

        # Update map
        mymap[i][j] = 3         # mark current node as visited

        distanceFromStart[i][j] = INF; # remove this node from further consideration
        numExpanded = numExpanded + 1;
        # Visit each neighbor of the current node and update the map, distances
        # and parent tables appropriately.

        if (i>0) and (mymap[i-1][j] != 3) and (mymap[i-1][j] != 5) and (mymap[i-1][j] != 2):
            if (min_dist+1 < distanceFromStart[i-1][j]):
                distanceFromStart[i-1][j] = min_dist+1
                mymap[i-1][j] = 4
                parent[i-1][j] = current

        if (i<nrows-1) and (mymap[i+1][j] != 3) and (mymap[i+1][j] != 5) and (mymap[i+1][j] != 2):
            if (min_dist+1 < distanceFromStart[i+1][j]):
                distanceFromStart[i+1][j] = min_dist+1;
                mymap[i+1][j]=4
                parent[i+1][j] = current

        if (j>0) and (mymap[i][j-1] != 3) and (mymap[i][j-1] != 5) and (mymap[i][j-1] != 2):
            if (min_dist+1 < distanceFromStart[i][j-1]):
                distanceFromStart[i][j-1] = min_dist+1
                mymap[i][j-1]=4
                parent[i][j-1] = current

        if (j<ncols-1) and (mymap[i][j+1] != 3) and (mymap[i][j+1] != 5) and (mymap[i][j+1] != 2):
            if (min_dist+1 < distanceFromStart[i][j+1]):
                distanceFromStart[i][j+1] = min_dist+1;
                mymap[i][j+1]=4
                parent[i][j+1] = current

        #print(distanceFromStart, file=sys.stderr)
        #print(mymap, file=sys.stderr)

    # Construct route from start to dest by following the parent links
    if (distanceFromStart[dest_indy][dest_indx] == INF):
        routep = np.array([])
    else:
        routep = np.array([[dest_indy,dest_indx]])

        [i,j] = np.unravel_index(dest_node, np.shape(mymap))
        while (parent[i][j] != 0):
            [i,j] = np.unravel_index(parent[i][j], np.shape(mymap))
            routep = np.concatenate((routep, np.array([[i,j]])), axis=0)
            #print(i,j)
        #[i,j] = np.unravel_index(start_node, np.shape(mymap))
        #routep = np.concatenate((routep, np.array([[i,j]])), axis=0)

    s = len(routep)
    a = start[0]#[0]
    b = start[1]#[0]

    route = np.array([[a,b]])

    for k in range(1,s+1):

        [a,b]= (routep[s-k])#+0.5)*[x_spacing, y_spacing]
        color_map[a][b] = 2
        route = np.concatenate((route, np.array([[a,b]])), axis=0)

    a = goal[0]#[0]
    b = goal[1]#[0]
    route = np.concatenate((route, np.array([[a,b]])), axis=0)

    str_vec = helper.to_str_repr(color_map)

    states[result] = {'value': color_map, 'meta': {'what': 'color_matrix', 'value': str_vec}}
    helper.save_states(states)

    return route.tolist()
Ejemplo n.º 13
0
def step(output, G, control, st, time, plot):
    states = helper.load_states()
    inp = np.zeros((states[G]['B']['value'].shape[1], 1))
    inp[states[G]['controls'][control], 0] = st
    init = np.zeros((states[G]['A']['value'].shape[0], 1))
    return simulate(output, G, init, inp, time, plot)
Ejemplo n.º 14
0
    W_xc = helper.init_weights((inp, hid))
    W_hc = helper.init_weights((hid, hid))
    b_c = helper.init_zero_vec(hid)

    W_xo = helper.init_weights((inp, hid))
    W_ho = helper.init_weights((hid, hid))
    W_co = helper.init_weights((hid, hid))
    b_o = helper.init_zero_vec(hid)

    W_hy = helper.init_weights((hid, out))
    b_y = helper.init_zero_vec(out)

else:
    W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc, W_hc, b_c, W_xo, W_ho, W_co, b_o, W_hy, b_y = helper.load_states(
        load_weights, work_dir
    )

# LSTM code

S_h = helper.init_zero_vec(hid)  # init values for hidden units
S_c = helper.init_zero_vec(hid)  # init values for cell units

S_x = T.matrix()  # inputs
Y = T.matrix()  # targets

# BEGIN code inspired by Christian Herta
# http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php


def step(
Ejemplo n.º 15
0
    b_c = helper.init_zero_vec(h_size)

    W_xo = helper.init_weights((io_size, h_size))
    W_ho = helper.init_weights((h_size, h_size))
    W_co = helper.init_weights((h_size, h_size))
    b_o = helper.init_zero_vec(h_size)

    W_hy = helper.init_weights((h_size, io_size))
    b_y = helper.init_zero_vec(io_size)

else:
    W_xi, W_hi, W_ci, b_i, \
    W_xf, W_hf, W_cf, b_f, \
    W_xc, W_hc, b_c, \
    W_xo, W_ho, W_co, b_o, \
    W_hy, b_y = helper.load_states(load_weights, work_dir)
    
# LSTM code

S_h = helper.init_zero_vec(h_size) # init values for hidden units
S_c = helper.init_zero_vec(h_size) # init values for cell units

S_x = T.matrix() # inputs
Y = T.matrix() # targets

# BEGIN code inspired by Christian Herta 
# http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php

def step(S_x, S_h, S_c, 
         W_xi, W_hi, W_ci, b_i, 
         W_xf, W_hf, W_cf, b_f, 
Ejemplo n.º 16
0
def output(num, G, name):
    states = helper.load_states()
    states[G]['outputs'][name] = num - 1
    helper.save_states(states)
    return 'Output number ' + str(num) + ' of ' + G + ' is set to ' + name
Ejemplo n.º 17
0
def feedback(G, K, name):
    states = helper.load_states()

    Ap = states[G]['A']['value']
    Bp = states[G]['B']['value']
    Cp = states[G]['C']['value']
    Dp = states[G]['D']['value']
    Ac = states[K]['A']['value']
    Bc1 = states[K]['B1']['value']
    Bc2 = states[K]['B2']['value']
    Cc = states[K]['C']['value']
    Dc1 = states[K]['D1']['value']
    Dc2 = states[K]['D2']['value']

    I = np.identity(Dc1.shape[0])
    Z = I - Dc1 * Dp
    Zinv = np.linalg.inv(Z)

    A11 = Ap + Bp * Zinv * Dc1 * Cp
    A12 = Bp * Zinv * Cc
    I = np.identity(Dp.shape[0])
    A21 = Bc1 * (I + Dp * Zinv * Dc1) * Cp
    A22 = Ac + Bc1 * Dp * Zinv * Cc
    A = np.bmat([[A11, A12], [A21, A22]])
    A_newname = states[G]['value'][0] + '_cl'

    B11 = Bp * Zinv * Dc2
    B21 = Bc2 + Bc1 * Dp * Zinv * Dc2
    B = np.bmat([[B11], [B21]])
    B_newname = states[G]['value'][1] + '_cl'

    C11 = I + Dp * Zinv * Dc1
    C12 = Cp * Dp * Zinv * Cc
    C = np.bmat([[C11, C12]])
    C_newname = states[G]['value'][2] + '_cl'

    D = Dp * Zinv * Dc2
    D_newname = states[G]['value'][3] + '_cl'

    helper.matrix(A_newname, A)
    helper.matrix(B_newname, B)
    helper.matrix(C_newname, C)
    helper.matrix(D_newname, D)

    states = helper.load_states()

    states[name] = {
        'value': [A_newname, B_newname, C_newname, D_newname],
        'A': states[A_newname],
        'B': states[B_newname],
        'C': states[C_newname],
        'D': states[D_newname],
        'controls': {},
        'outputs': {},
        'meta': {
            'what': 'feedback',
            'A': states[A_newname]['meta'],
            'B': states[B_newname]['meta'],
            'C': states[C_newname]['meta'],
            'D': states[D_newname]['meta']
        }
    }
    helper.save_states(states)
    result = 'x_a\' = ' + A_newname + 'x_a + ' + B_newname + 'r , y = ' + C_newname + 'x_a + ' + D_newname + 'r'
    return result
Ejemplo n.º 18
0
def control(num, G, name):
    states = helper.load_states()
    states[G]['controls'][name] = num - 1
    helper.save_states(states)
    return 'Control number ' + str(num) + ' of ' + G + ' is set to ' + name
Ejemplo n.º 19
0
# init

with open(corpus_file) as f:
    sents = [[twp.split('|')[0].lower() for twp in line.split()] for line in f]

embeddings = helper.char_embeddings(sents)

print('init network and compile theano functions...')

h_size = hidden_layer_size  # hidden size

W_xi, W_hi, W_ci, b_i, \
W_xf, W_hf, W_cf, b_f, \
W_xc, W_hc, b_c, \
W_xo, W_ho, W_co, b_o, \
W_hy, b_y = helper.load_states(weights_file_name, work_dir)

S_h = helper.init_zero_vec(h_size)  # init values for hidden units
S_c = helper.init_zero_vec(h_size)  # init values for cell units

S_x = T.matrix()  # inputs

# BEGIN code inspired by Christian Herta
# http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php


def step(S_x, S_h, S_c, W_xi, W_hi, W_ci, b_i, W_xf, W_hf, W_cf, b_f, W_xc,
         W_hc, b_c, W_xo, W_ho, W_co, b_o, W_hy, b_y):

    S_i = sigm(dot(S_x, W_xi) + dot(S_h, W_hi) + dot(S_c, W_ci) + b_i)
    S_f = sigm(dot(S_x, W_xf) + dot(S_h, W_hf) + dot(S_c, W_cf) + b_f)
Ejemplo n.º 20
0
def response(output, G, init, inp, time, plot):
    states = helper.load_states()
    inp = np.matrix(json.loads(inp))
    init = np.matrix(json.loads(init))
    return simulate(output, G, init, inp, time, plot)