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
def plotdata(name, plot): x = [] y = [] with open(states[name]['value'], mode='r') as infile: mappingfile = csv.reader(infile) for row in mappingfile: x.append(row[0].strip()) y.append(row[1].strip()) # 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="Data Visualization", tools=TOOLS, x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness #p.line(x, y, legend=output, line_width=2) p.circle(x, y, size=10, color="navy", alpha=0.5) from bokeh.resources import CDN from bokeh.embed import components script, div = components(p) states[plot] = {'meta': {}} states[plot]['meta'] = {'what': 'plot', 'script': script, 'div': div} helper.save_states() return 'Data plot created. Type gdisplay ' + plot + ' to display'
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()
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.'
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 + "."
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.'
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'
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())
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()) y.append(row[1].strip()) theta = np.ones(2) states[prestatestor] = { 'value': theta, 'meta': { 'what': 'lin_reg_pred', 'value': theta } } helper.save_states()
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
def uniform_gaussian_process(plot): size = 500 i, j = np.mgrid[:size, :size] / size x = np.linspace(0, 1, size) K = np.exp(-0.5 * (i - j) * (i - j) / 0.0005) + 0.001 * np.identity(size) L = np.linalg.cholesky(K) mu, sigma = 0, 1 # mean and standard deviation u = np.random.normal(mu, sigma, (size, 1)) m = np.zeros(size).reshape(size, 1) y = m + np.matrix(L) * np.asmatrix(u) y = np.asarray(y).reshape(-1) print(x, file=sys.stderr) print(y, 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="Data Visualization", tools=TOOLS, x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness #p.line(x, y, legend=output, line_width=2) p.circle(x, y, size=1, color="navy", alpha=0.5) from bokeh.resources import CDN from bokeh.embed import components script, div = components(p) states[plot] = {'meta': {}} states[plot]['meta'] = {'what': 'plot', 'script': script, 'div': div} helper.save_states() return 'Data plot created. Type gdisplay ' + plot + ' to display'
cost = train(inp, tar) error += cost weights_changed = True if (i+1) % log_steps == 0: error /= log_steps errors.append(error) print('epoch: %d\titerations: %d\terror: %f' %(e, (i+1), error)) print(resample(embeddings, h_size)) print() error = 0 if (i+1) % save_steps == 0: helper.save_states([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-%d-%d.weights' % (timestamp, e, (i+1)), work_dir) helper.save_errors(errors, '%s-%d-%d.errors' % (timestamp, e, (i+1)), work_dir) weights_changed = False print('weights saved:') print('%s-%d-%d.weights' % (timestamp, e, (i+1))) print('errors saved:') print('%s-%d-%d.errors' % (timestamp, e, (i+1))) print() print('end training') print() # save current weights if training has been performed
def gaussian_process(data_name, plot): x = [] y = [] with open(states[data_name]['value'], mode='r') as infile: mappingfile = csv.reader(infile) for row in mappingfile: x.append(float(row[0].strip())) y.append(float(row[1].strip())) xi, xj = np.meshgrid(x, x) K = np.exp(-0.5 * (xi - xj) * (xi - xj) / 0.0001) # + 0.001*np.identity(len(x)) size = 1000 #i, j = np.mgrid[:size, :size]/size xs = np.linspace(0, 20, size) xsi, xsj = np.meshgrid(xs, xs) Ks = np.exp(-0.5 * (xsi - xsj) * (xsi - xsj) / 0.0001) # + 0.001*np.identity(size) xs2i, xs2j = np.meshgrid(x, xs) Ks2 = np.exp(-0.5 * (xs2i - xs2j) * (xs2i - xs2j) / 0.0001) Kinv = np.linalg.inv(K) #+ 0.001*np.identity(K.shape[0]) mean = np.asmatrix(Ks2) * np.asmatrix(Kinv) * np.asmatrix(y).transpose() cov = np.asmatrix(Ks) - np.asmatrix(Ks2) * Kinv * np.asmatrix( Ks2).transpose() # + 0.01*np.identity(size) L = np.linalg.cholesky(cov) mu, sigma = 0, 1 # mean and standard deviation u = np.random.normal(mu, sigma, (size, 1)) m = np.zeros(size).reshape(size, 1) ys = mean + np.matrix(L) * np.asmatrix(u) ys = np.asarray(ys).reshape(-1) # 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="Data Visualization", tools=TOOLS, x_axis_label='x', y_axis_label='y') # add a line renderer with legend and line thickness p.circle(xs, ys, size=1, color="black", alpha=0.9) p.square(x, y, size=5, color="blue", alpha=0.2) p.quad(top=ys + np.diag(cov), bottom=ys - np.diag(cov), left=xs - 0.01, right=xs + 0.01, color="#B3DE69", alpha=0.1) from bokeh.resources import CDN from bokeh.embed import components script, div = components(p) states[plot] = {'meta': {}} states[plot]['meta'] = {'what': 'plot', 'script': script, 'div': div} helper.save_states() return 'Data plot created. Type gdisplay ' + plot + ' to display'
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
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()
cost = train(inp, tar) error += cost weights_changed = True if (i + 1) % log_steps == 0: error /= log_steps errors.append(error) print('epoch: %d\titerations: %d\terror: %f' % (e, (i + 1), error)) print(resample(embeddings, h_size)) print() error = 0 if (i + 1) % save_steps == 0: helper.save_states([ 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-%d-%d.weights' % (timestamp, e, (i + 1)), work_dir) helper.save_errors(errors, '%s-%d-%d.errors' % (timestamp, e, (i + 1)), work_dir) weights_changed = False print('weights saved:') print('%s-%d-%d.weights' % (timestamp, e, (i + 1))) print('errors saved:') print('%s-%d-%d.errors' % (timestamp, e, (i + 1))) print() print('end training') print() # save current weights if training has been performed
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
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
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