def runSimulationTime(state_machine, max_time): # Assumptions # time starts at zero xyz_hist = np.array([None, None, None]) w_hist = [] q_hist = [] torque_hist = [] power_hist = [] time_hist = [] #J, J_inv, m_max, power_max = ps.hardware.getHardwareProperties() time = 0 while time <= max_time: delta_t, _ = state_machine.runStep(None) state_machine.hardware.state = propagate(state_machine.hardware, delta_t, str(state_machine.getCurrentState())) state_machine.hardware.time += (delta_t/86400) time += delta_t state_machine.hardware.time += (delta_t/86400) print('current time: %.1f min' %(time/60)) xyz_hist = np.vstack((xyz_hist, state_machine.hardware.state[0:3])) w_hist = np.append(w_hist, state_machine.hardware.state[6:9]) q_hist = np.append(q_hist, state_machine.hardware.state[9:13]) torque_hist = np.append(torque_hist, state_machine.hardware.state[13:16]) power_hist = np.append(power_hist, state_machine.hardware.state[16:18]) time_hist = np.append(time_hist, time) return (time_hist, xyz_hist, w_hist, q_hist, torque_hist, power_hist)
def runSimulationSteps(state_machine, num_steps): # Assumptions # time starts at zero xyz_hist = np.zeros((num_steps, 3)) w_hist = np.zeros((num_steps, 3)) q_hist = np.zeros((num_steps, 4)) torque_hist = np.zeros((num_steps, 3)) power_hist = np.zeros((num_steps, 2)) time_hist = np.zeros(num_steps) time = 0 for i in range(num_steps): #print(state_machine.getCurrentState()) delta_t, _ = state_machine.runStep(None) state_machine.hardware.state = propagate(state_machine.hardware, delta_t, str(state_machine.getCurrentState())) state_machine.hardware.time += (delta_t/86400) time += delta_t xyz_hist[i, :] = state_machine.hardware.state[0:3] w_hist[i,:] = state_machine.hardware.state[6:9] q_hist[i,:] = state_machine.hardware.state[9:13] torque_hist[i,:] = state_machine.hardware.state[13:16] power_hist[i,:] = state_machine.hardware.state[16:18] time_hist[i] = time #print('current time: %.1f min' %(time/60)) return (time_hist, xyz_hist, w_hist, q_hist, torque_hist, power_hist)
def run_sim(dat, route_step, n_hop, max_con, avg_con, n_sat, perimiter_only, length, year): current_file_path = Path(__file__).resolve() code_source_path = str(current_file_path.parents[0]) TLE_path = code_source_path + f'/TLEs/{n_sat}.txt' # Create directory for sim results results_path = f'{code_source_path}/results/{dat}' try: os.mkdir(results_path) except: pass print('________ ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' ________') print(data_name) # Propagate orbits pos_table = propagate(TLE_path, length, year) # Provision at every time step. Returns results from routing time steps (distable_linkdicts, all_xyz_rsteps) = provision(pos_table, route_step, nbr_hop=n_hop, max_conn=max_con, avg_conn=avg_con, length=length+1) # print links and distance table for each routing time step for i in range(len(distable_linkdicts)): print_txt(distable_linkdicts, all_xyz_rsteps, i, results_path) return
def evaluationPerformed(self, iterations_count, evaluations_count, orbits, estimated_orbital_parameters, estimated_propagator_parameters, estimated_measurements_parameters, evaluations_provider, lsp_evaluation): drivers = estimated_orbital_parameters.getDrivers() state = orekit_drivers_to_values(drivers) print("{}:\t{} {} {}\t{} {} {}".format(iterations_count, *state)) print("r = {}\tv = {}".format(norm(state[0:3]), norm(state[3:6]))) earth_moon_state = np.zeros(48) earth_moon_state[0:6] = state earth_moon_state[6:12] = spice.spkez(301, et0, 'J2000', 'NONE', 399)[0] * 1000.0 earth_moon_state[12:] = np.identity(6).reshape(36) print("Trying to plot...") t0 = orbits[0].date x0 = orekit_state(state) tf = orekit_time(self.tf) eph = propagate(t0, x0, tf, write=False) ax.plot(eph.x[:, 0] * 1000.0, eph.x[:, 1] * 1000.0, eph.x[:, 2] * 1000.0, label="{}".format(iterations_count), alpha=(1 / 40.0) * iterations_count, c='r')
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False): costs = [] for i in range(num_iterations): # Cost and gradient calculation (≈ 1-4 lines of code) ### START CODE HERE ### grads, cost = prop.propagate(w, b, X, Y) ### END CODE HERE ### # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule (≈ 2 lines of code) ### START CODE HERE ### w = w - learning_rate * dw b = b - learning_rate * db ### END CODE HERE ### # Record the costs if i % 100 == 0: costs.append(cost) # Print the cost every 100 training examples if print_cost and i % 100 == 0: print("Cost after iteration %i: %f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs
def optimize(w, b, X, y, num_iterations, learning_rate, print_cost=False): costs = [ ] #This is an empty list created so that it stores all the values later for i in range(num_iterations): grads, cost = pp.propagate( w, b, X, y) #we are calling the previously defined function dw = grads[ 'dw'] #we are accessing the derivatives of cost with respect to w db = grads[ 'db'] #we are accessing the derivatives of cost with respect to b w = w - learning_rate * dw #we are modifying the parameter w so that the cost would reduce in the long run b = b - learning_rate * db #we are modifying the parameter b so that the cost would reduce in the long run np.squeeze(cost) if i % 100 == 0: costs.append( cost ) #we are giving all the cost values to the empty list that was created initially if print_cost and i % 1000 == 0: print("cost after iteration {}: {}".format(i, cost)) plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate = " + str(learning_rate)) plt.show() params = { 'w': w, 'b': db } #we are storing this value in the dictionary so that it could be accessed later grads = { 'dw': dw, 'db': db } #we are storing these valeus in the dictionary so that they could be accessed later return params, grads, costs
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False): costs = [] for i in range(num_iterations): grads, cost = propagate(w, b, X, Y) dw = grads["dw"] db = grads["db"] w = w - (learning_rate * dw) b = b - (learning_rate * db) if i % 100 == 0: costs.append(cost) if print_cost and i % 100 == 0: print("Cost after iteration %i: %f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs
def main(rays_per_side, nr_of_propagations, raster_dimension, mirror, normalize_brightness, to_png): t0 = time.time() raster = None dx_source = np.array([[0], [0], [-1]]) environment = Environment() x_camera = np.array([[3], [1], [3]]) dx_camera = np.array([[0], [-1], [0]]) focal_directions = get_raster_focal_directions(raster_dimension, dx_camera) camera = Camera(x_camera, dx_camera, raster_dimension) for epoch in range(NR_OF_EPOCHS): foolog('starting epoch {0} of {1}...'.format(epoch + 1, NR_OF_EPOCHS)) #foolog('generating rays...') #x, dx, intensity = generate_rays(rays_per_side) x, dx, intensity = generate_rays_from_light_source( 2, 8, 2, 8, 9, dx_source, True, rays_per_side) #foolog('starting ray propagation...') for r in range(nr_of_propagations + 1): #foolog('Step {0}. Remaining average intensity: {1:2.3f}'.format(r, np.average(intensity))) #foolog('Average position: {0}'.format(np.average(x, axis=1))) # foolog('rasterize...') # result = rasterize3(x, dx, intensity, x_camera, dx_camera, RASTER_DIMENSION, focal_directions) # if raster is None: # raster = result # else: # raster += result if r < nr_of_propagations: # foolog('propagate...') x, dx, intensity = propagate(x, dx, intensity, environment, camera, mirror=mirror) if to_png: # foolog('output to png...') camera.to_png(epoch, normalize_brightness) # brightness_factor = 1 # if normalize_brightness: # m = np.max(raster) # if m > 0: # brightness_factor = 255.0 / m # # output_raster = (brightness_factor * raster).astype(np.uint8) # png.from_array(output_raster, 'L').save('output/output_epoch={0}.png'.format(epoch)) t1 = time.time() foolog('total time: {0:2.3f} seconds'.format(t1 - t0))
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. Tips: You basically need to write down two steps and iterate through them: 1) Calculate the cost and the gradient for the current parameters. Use propagate(). 2) Update the parameters using gradient descent rule for w and b. """ costs = [] for i in range(num_iterations): # Cost and gradient calculation (≈ 1-4 lines of code) ### START CODE HERE ### grads, cost = propagate(w, b, X, Y) ### END CODE HERE ### # Retrieve derivatives from grads dw = grads["dw"] db = grads["db"] # update rule (≈ 2 lines of code) ### START CODE HERE ### w = w - learning_rate * dw # need to broadcast b = b - learning_rate * db ### END CODE HERE ### # Record the costs if i % 100 == 0: costs.append(cost) # Print the cost every 100 training examples if print_cost and i % 100 == 0: print("Cost after iteration %i: %f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs
def test_propagate(self): w, b, X, Y = np.array([[1., 2.]]), 2., np.array([[1., 2., -1.], [3., 4., -3.2] ]), np.array([[1, 0, 1]]) parameters = {'W1': w, 'b1': b} grads, cost = propagate(parameters, X, Y) self.assertTrue( np.allclose(grads['dW1'], np.array([[0.99845601, 2.39507239]]))) self.assertTrue(np.allclose(grads['db1'], np.array([[0.00145558]]))) self.assertEqual(cost, 5.801545319394553)
def update_parameters(w, b, X, Y, num_iterations, learning_rate, print_cost=True): """ This function optimizes w and b by running a gradient descent algorithm Parameters ---------- w : weights, a numpy array of size (num_px * num_px * 3, 1) b : bias, a scalar X : data of shape (num_px * num_px * 3, number of examples) Y : true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations : number of iterations of the optimization loop learning_rate : learning rate of the gradient descent update rule print_cost : True to print the loss every 100 steps Returns ------- params : dictionary containing the weights w and bias b grads : dictionary containing the gradients of the weights and bias with respect to the cost function costs : list of all the costs computed during the optimization, this will be used to plot the learning curve. """ # Create a list to keep the cost on every iteration so that we can print it costs = [] for i in range(num_iterations): # Calculate cost and gradients for every iteration grads, cost = propagate(w, b, X, Y) # Retrieve derivatives from grads dictionary dw = grads["dw"] db = grads["db"] # Update the parameters w = w - learning_rate * dw b = b - learning_rate * db # Record the costs if i % 100 == 0: costs.append(cost) if print_cost and i % 100 == 0: print("Cost after iteration %i: %f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params, grads, costs
def run_sim(dat, route_step, n_hop, max_con, avg_con, n_sat, perimiter_only, length, year): current_file_path = Path(__file__).resolve() code_source_path = str(current_file_path.parents[0]) TLE_path = code_source_path + f'/TLE/{n_sat}.txt' # Create directory for sim results results_path = f'{code_source_path}/dial_results/{dat}' data_path = f'{results_path}/{dat}_data.csv' try: os.mkdir(results_path) except: pass print('________ ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' ________') print(data_name) # Propagate orbits pos_table = propagate(TLE_path, length, year) # Provision at every time step. Returns results from routing time steps (distable_linkdicts, all_xyz_rsteps) = provision(pos_table, route_step, nbr_hop=n_hop, max_conn=max_con, avg_conn=avg_con, length=length + 1) # print links and distance table of last time step print_txt(distable_linkdicts, all_xyz_rsteps, -1, results_path) # # Perform routing at specified time steps # @timing # def route_sum(): # sim_data = [] # for i in range(len(distable_linkdicts)): # route_data_time_i = route(n_node=n_sat, nbrhood_hop=n_hop, # border=perimiter_only, # linkdict=distable_linkdicts[i][1], # distable=distable_linkdicts[i][0], # results_path=results_path) # # append routing results from a single time step # sim_data.append(route_data_time_i) # return sim_data # route_data = route_sum() # # Write routing results to csv # np_data = pd.DataFrame(route_data) # initialize pd dataframe # np_data.columns = ['n_node', 'n_hop', 'total', 'bad', 'loop', 'no_path'] # np_data.to_csv(data_path, index=False) return
def run(): # text = u'Surface expression of mir-21 activates tgif beta receptor type II expression. Expression of mir-21 and mir-132 directly mediates cell migration . mir-21 mediates cell migration and proliferation. mir-21 seems to mediate apoptosis. mir-21 is involved in cellular processes, such as cell migration and cell proliferation. mir-21 regulates the ectopic expression of smad2 .' # text = u'transport of annexin 2 not only to dynamic actin-rich ruffles at the cell cortex but also to cytoplasmic and perinuclear vesicles.' doc_id = '99999999' rule_phase0_filename = '/home/leebird/Projects/nlputils/visual/uploads/rules_phase0.txt' rule_phase1_filename = '/home/leebird/Projects/nlputils/visual/uploads/rules_phase1.txt' rule_phase2_filename = '/home/leebird/Projects/nlputils/visual/uploads/rules_phase2.txt' fh0 = open(rule_phase0_filename, "r") rule0_lines = fh0.readlines() fh0.close() fh1 = open(rule_phase1_filename, "r") rule1_lines = fh1.readlines() fh1.close() fh2 = open(rule_phase2_filename, "r") rule2_lines = fh2.readlines() fh2.close() with open('/home/leebird/Projects/nlputils/utils/typing/test.json') as f: json_doc = json.load(f) for t in json_doc['entity'].values(): t['entityType'] = t['entityType'].upper() text = json.dumps(json_doc) raw_doc = json_format.Parse(text, document_pb2.Document(), True) param_helper = ParamHelper(text, doc_id, rule0_lines, rule1_lines, rule2_lines) # raw_doc = document_pb2.Document() edg_rules = edgRules_pb2.EdgRules() # param_helper.setDocProtoAttributes(raw_doc) param_helper.setRuleProtoAttributes(edg_rules) # Parse using Bllip parser. doc = parse_using_bllip(raw_doc, edg_rules) helper = DocHelper(doc) invalid_deps = constraint_args(helper, {'arg0': {document_pb2.Entity.GENE}}) print(invalid_deps) propagate(helper, {'arg0': {document_pb2.Entity.GENE}}, invalid_deps)
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shape (num_px * num_px * 3, number of examples) Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples) num_iterations -- number of iterations of the optimization loop learning_rate -- learning rate of the gradient descent update rule print_cost -- True to print the loss every 100 steps Returns: params -- dictionary containing the weights w and bias b grads -- dictionary containing the gradients of the weights and bias with respect to the cost function costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve. Tips: You basically need to write down two steps and iterate through them: 1) Calculate the cost and the gradient for the current parameters. Use propagate(). 2) Update the parameters using gradient descent rule for w and b. """ costs = [] for i in range(num_iterations): # 计算代价和梯度 grads, cost = propagate(w, b, X, Y) dw = grads["dw"] db = grads["db"] # 更新参数 w = w - learning_rate * dw b = b - learning_rate * db # 记录代价 if i % 100 == 0: costs.append(cost) # 每100次迭代打印代价 if print_cost and i % 100 == 0: print("第%i次迭代的代价为:%f" % (i, cost)) params = {"w": w, "b": b} grads = {"dw": dw, "db": db} return params,grads,costs
def predict(pointing): field, ra, dec, mjd = pointing.split() jd = float(mjd) + 2400000.5 ra = float(ra) dec = float(dec) p = propagate(np.array(known.a), np.array(known.e), np.array(known.i), np.array(known.w), np.array(known.W), np.array(known.M), np.array(known.epoch), np.zeros(len(known.a)) + jd, helio=True) mag = known.H + 5 * np.log10(p.r * (p.delta)) ra_matched = abs(p.ra * 180 / np.pi - ra) < 0.17 dec_matched = abs(p.dec * 180 / np.pi - dec) < 0.1 matched = ra_matched * dec_matched if matched.sum() != 0: print(field, jd, list(known.name[matched]), p.ra[matched] * 180 / np.pi, p.dec[matched] * 180 / np.pi, list(mag[matched]))
init_t = init_target(frame) if init_t is not None: target, target_model, target_hist, weights, particles = init_t #TODO MAKE EVENT FOR MOUSE RELEASE INSTEAD OF THIS else: ret, frame = capture.read() while target is None: init_t = init_target(frame) if init_t is not None: target, target_model, target_hist, weights, particles = init_t print(target_model[4] * target_model[5]) while True: start = time.time() particles = resample(particles, weights) particles = propagate(particles, noise, (width, height), Events[EVENT_RANDOM_GENERATOR]) # get frame ret, frame = capture.read() if not ret: break if CAPTURE_FROM == WEBCAM: frame = cv2.flip(frame, 1) # draw all particles frame_copy = copy.deepcopy(frame) if Events[EVENT_SHOW_PARTICLES]: for particle in particles: top_left, bottom_right = particle_center_to_particle_corners( particle) cv2.rectangle(frame_copy, top_left, bottom_right, (0, 0, 255), 1)
seed = [] '''seed = list(np.loadtxt("seed_index.txt", dtype=int))''' T = propagate.get_t(train_words, "train_graph") o = propagate.get_score("da.csv") o_train = o[train_words_index] beta = 0.3 while len(seed) < 30: coefficient_index = -1 i = 0 max_coefficient = 0 while i < train_words_number: if i not in seed: s = propagate.get_seed_score_fb(i, o_train, seed) P = propagate.propagate(s, T, beta) i_list = [i] index = seed + i_list coefficient = evaluate.get_pearson_correlation_coefficient( o_train, P, index) if coefficient > max_coefficient: max_coefficient = coefficient coefficient_index = i i = i + 1 if coefficient_index != -1: seed.append(coefficient_index) print max_coefficient np.savetxt("seed_index.txt", seed, fmt='%d') print "testing..."
def success_user(): user_email = flask.session['authenticated_email'] user = database.query_user(email=user_email) credentials = user_to_credentials(user) propagate.propagate(credentials) return flask.redirect('https://calendar.google.com/calendar/r')
print("sanity check after reshaping: " + str(train_set_x_flatten[0:5, 0])) train_set_x = train_set_x_flatten / 255. test_set_x = test_set_x_flatten / 255. print("sigmoid(0) = " + str(sigmoid(0))) print("sigmoid(9.2) = " + str(sigmoid(9.2))) dim = 2 w, b = initialize_with_zeros(dim) print("w = " + str(w)) print("b = " + str(b)) w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1, 2], [3, 4]]), np.array([[1, 0]]) grads, cost = propagate(w, b, X, Y) print("dw = " + str(grads["dw"])) print("db = " + str(grads["db"])) print("cost = " + str(cost)) params, grads, costs = optimize(w, b, X, Y, num_iterations=100, learning_rate=0.009, print_cost=False) print("w = " + str(params["w"])) print("b = " + str(params["b"])) print("dw = " + str(grads["dw"])) print("db = " + str(grads["db"]))
def graph_theory(dV_max, disp_flag): #------------------------------------------------------------------------- ### IMPORTS ### #------------------------------------------------------------------------- #local files needed from distance_SSP_to_target import distance_SSP_to_target from load_hurricane_data import import_hurricane from lowering_maneuver import lowering_maneuver from raising_maneuver import raising_maneuver from propagate import propagate #Other python packages needed import math import numpy as np import networkx as nx import datetime import os import csv #for plotting: import matplotlib.pyplot as plt #imports below from https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_circular_tree.html try: import pygraphviz from nx.drawing.nx_agraph import graphviz_layout except ImportError: try: import pydot from networkx.drawing.nx_pydot import graphviz_layout except ImportError: raise ImportError("This example needs Graphviz and either " "PyGraphviz or pydot") #------------------------------------------------------------------------- ### INPUTS ### #------------------------------------------------------------------------- #delta-V for each manuever given as an input #- the number of values corresponds to the number of manuevers which is equal to the number of targets #possible dV options (negative dV represents lowering maneuvers, positive dV represents raising maneuvers) dV_min = -dV_max dV_step = 0.5 dV_list = np.arange(dV_min, dV_max + dV_step, dV_step).tolist() ###Initialize satellites-------------------------------------------------- #A list of lists is used to store satellite(s) states and their #maneuver info, and target access information num_sats = 1 #epoch Oct 10, 2010, 12:00 UTC date_epoch = datetime.datetime(2010, 10, 10, 12) #note that AOL and RAAN at epoch start are used as opposed to RAAN and argument of perigee sat_elems = ['Satellite Number', 'Semi-major Axis (m)', 'Inclination (deg)',\ 'RAAN (deg)', 'Argument of Latitude (deg)', 'RA at Epoch Start (deg)', \ 'SSP Lat. (deg)', 'SSP Lon. (deg)', \ 'Time Since Epoch (sec)', \ 'Delta-V Used in current maneuver', 'Dist to Current Target (km)'] satellites = [] for i in range(num_sats): semi_major_axis = 7074000 #m incl = 40 #deg RAAN0 = 0 + 20 * i #deg - this means for multiple satellites, satellites are spaced by 20 deg RAAN u0 = 0 #deg RAepoch = -161.155 #deg satellites.append([i, semi_major_axis, incl, \ RAAN0, u0, RAepoch, \ 0, 0, \ 0, 0,\ 0,\ 0]) #note the ssp, delt-V and dist to target are initially clear if disp_flag == 1: print('---') print('Satellite(s) initial states:') print('---') for i in range(num_sats): for x in range(len(sat_elems)): print(sat_elems[x], x, ':\t', satellites[i][x]) print('---') #this is the max acceleration available on the satellite satellite_mass = 4 #kg max_thrust = 0.35 * 10**(-3) #N accel = max_thrust / satellite_mass #m/s^2 ###Initialize Targets----------------------------------------------------- num_targets = 3 targets = [] dir = os.path.dirname(__file__) file = os.path.join( dir, 'target_tracks\megi_data.xlsx' ) #(!) path may need to be changed for non-Windows users #These are locations of the eye of Typhoon Megi (2010) target_interval = 2.5 * 24 * 3600 #sec targets_time, targets_lat, targets_long, time_since_epoch, latitude, longitude = import_hurricane( file, date_epoch, num_targets, target_interval) targets = [[targets_time[i], targets_lat[i], targets_long[i]] for i in range(num_targets)] #Time window corresponds to allowed viewing time around each target (ie +/- 20 hrs target time) time_window = 20 * 3600 #sec #Establishes minimum acceptable distance to eye of the storm min_distance_to_eye = 100000 #m #------------------------------------------------------------------------- ### PARAMETERS ### #------------------------------------------------------------------------- #Model Parameters--------------------------------------------------------- mu = 3.98600 * 10**14 # standard gravitational parameter, m^3/s^2 Re = 6371000 # mean Earth radius, m J2 = 1082.7 * ( 10**-6 ) # coefficient of the Earth's gravitational zonal harmonic of the 2nd degree vel_e = 7.29212 * 10**(-5) # angular velocity of the earth, rad/s rad = math.pi / 180 # conversion of deg to rad flattening = 0.00335281 # flattening factor of the earth time_step = 10 # propagation time step (for viewing window propagation) #------------------------------------------------------------------------- ### CODE START ### #------------------------------------------------------------------------- #Satellite state is stored in dictionary nodes, and node numbers themselves in Graph G nodes = {0: satellites} G = nx.Graph() if disp_flag == 1: print("Executing maneuvers...") node_per_target = { } #this stores which nodes correspond to which targets for plotting clarity #the node we are starting to pull from origin_node = 0 # the node we are creating current_node = 1 #the information we start with old_sat_list = nodes[origin_node].copy() calc_nodes_last_target = [0] num_target = 0 #start with first target in list calc_nodes_current_target = [] for target in targets: num_target = num_target + 1 solution_found = False #Define viewing window for each target time_min = target[0] - time_window time_max = target[0] + time_window time_list = np.arange(time_min, time_max + time_step, time_step) #Interpolate between known track points for the viewing window time #this will be used to see if the satellite gets close to the storm lat_interp = np.interp(time_list, time_since_epoch, latitude) long_interp = np.interp(time_list, time_since_epoch, longitude) current_target = [time_list, lat_interp, long_interp] if disp_flag == 1: print('---') print("\nChecking accesses for target:" + "\t" + str(num_target)) print('Target time: ' + str(target[0] / 3600 / 24) + ' days') print('Target latitude: ' + str(target[1]) + ' deg') print('Target longitude: ' + str(target[2]) + ' deg') #Create new place to store satellite states new_sat_list = [] for i in range(num_sats): new_sat_list.append([]) # (leftover from tree generation approach)- move from one set of notes to the next for origin in calc_nodes_last_target: old_sat_list = nodes[origin].copy() #for multiple satellites, each will be manuevered in sequence for sat in range(len(old_sat_list)): maneuvering_sat = old_sat_list[sat][:] sat_time = maneuvering_sat[8] #Define the vewing window duration for each target, relative to satellite duration_min = time_min - sat_time duration_max = time_max - sat_time duration_list = np.arange(duration_min, duration_max + time_step, time_step) for dV in dV_list: #Now execute the maneuvers- either propagate/lower/raise according to the delta-V if dV == 0: flag = 'N/A' updated_sat = propagate(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, duration_min) if dV < 0: flag = 'LOWER' #timing of manuevers (seconds of manuever, propogate, maneuver duration which correspond to the 3 phases can also be stored) [updated_sat, timing] = lowering_maneuver(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, abs(dV), duration_min) if updated_sat != None: updated_sat[9] = abs(dV) if dV > 0: flag = 'RAISE' #timing of manuevers (seconds of manuever, propogate, maneuver duration which correspond to the 3 phases can also be stored) [updated_sat, timing] = raising_maneuver(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, dV, duration_min) if updated_sat != None: updated_sat[9] = abs(dV) #If the manuever was successful (time was sufficient for the delta-V), updated sat will have been created if updated_sat != None: #now propogate the satellite to the end of the time window to see the number/quality of accesses propagate_sat_options = propagate( mu, Re, J2, vel_e, rad, flattening, updated_sat, accel, (duration_list - duration_min)) distance = distance_SSP_to_target( mu, Re, rad, propagate_sat_options[6], propagate_sat_options[7], lat_interp, long_interp) num_accesses = 0 num_accesses = sum(1 for x in distance if x < min_distance_to_eye) if num_accesses > 0: #If the storm was accessed, record the accesses in the 'satellite' list #also maneuver timing can be stored- not currently done access_distance = [] index = 0 for x in distance: #record number of accesses index = index + 1 if x < min_distance_to_eye: #record access distance at each possible access: access_distance.append(x) lat = propagate_sat_options[6][index] long = propagate_sat_options[7][index] lateye = lat_interp[index] longeye = long_interp[index] distance = distance_SSP_to_target( mu, Re, rad, lat, long, lateye, longeye) totalSeconds = time_min + index * time_step #time since epoch in sec if disp_flag == 1: print('---successful access---') print('Distance: ' + str(x / 1000) + 'km') print('Current Time: ' + str( datetime.datetime( 2010, 10, 10, 12) + datetime.timedelta( seconds=totalSeconds)) + 'UTC') print('Hurricane: Lat. ' + str(lat) + ' deg Long. ' + str(long) + ' deg') #Mark that a solution has been found for this target solution_found = True #Record the mean and minimum access distances mean_distance_pass = sum( access_distance) / num_accesses min_distance_pass = min(access_distance) #Either distance can be saved updated_sat[10] = min_distance_pass propagate_sat = propagate(mu, Re, J2, vel_e, rad, flattening, updated_sat, accel, time_window * 2) new_sat_list[updated_sat[0]] = propagate_sat nodes[current_node] = new_sat_list.copy() propagate_sat = [] updated_sat = [] calc_nodes_current_target.append(current_node) if dV == 0: dV_adj = 0.00001 #to ensure graph is connected (edge length cannot be 0) else: dV_adj = abs( dV ) #to ensure graph is connected (edge length cannot be negative) #Leftover from tree generation- add edge and then move on to next node G.add_edge(origin, current_node, dV=dV_adj, dist_to_target=mean_distance_pass, target_accesses=num_accesses, man_type=flag) current_node = current_node + 1 if disp_flag == 1: print('---summary of accesses for target ', str(num_target), '---') print('Mean Distance: ' + str(round(mean_distance_pass / 1000, 2)) + ' km') print('Min Distance: ' + str(round(min_distance_pass / 1000, 2)) + ' km') print('Delta-V Used: ' + str(dV) + ' m/s') print('Total Access Time: ' + str(num_accesses * time_step) + ' s') print('') if solution_found == False: #if a solution cannot be found, propogate sat, and record 0 accesses for origin in calc_nodes_last_target: old_sat_list = nodes[origin].copy() for x in range(len(old_sat_list)): flag = 'N/A' sat = old_sat_list[x][:] propagate_sat = propagate(mu, Re, J2, vel_e, rad, flattening, sat, accel, duration_max) propagate_sat[10] = 999999 new_sat_list[sat[0]] = propagate_sat.copy() nodes[current_node] = new_sat_list.copy() propagate_sat = [] calc_nodes_current_target.append(current_node) G.add_edge(origin, current_node, target_accesses=0, dV=0.00001, dist_to_target=999999, man_type=flag) current_node = current_node + 1 calc_nodes_last_target = calc_nodes_current_target[:] calc_nodes_current_target = [] node_per_target[num_target] = calc_nodes_last_target #Leftover from tree generation #Tree Generation is complete... finding shortest path: complete_path = {} #record all possible path lengths path = nx.dijkstra_path(G, source=0, target=None, weight='dV') #only want the complete paths that view all targets for key in path: if len(path[key]) == num_targets + 1: current_path = path[key] length = nx.dijkstra_path_length(G, source=current_path[0], target=current_path[-1], weight='dV') complete_path[length] = current_path #then select shortest path #note that this will just select one of the shortest lengths if multiple of the same length exist min_path_length = 9999 for path_length in complete_path: if path_length < min_path_length: min_path_length = path_length shortest_complete_path = complete_path[path_length] shortest_complete_path_edges = zip(shortest_complete_path, shortest_complete_path[1:]) shortest_complete_path_edges = set(shortest_complete_path_edges) #Left over from tree generation- record the shortest path information dV_total = 0 num_accesses_total = 0 dist_sum_length = [] for i in shortest_complete_path_edges: dV_total = dV_total + G.edges[i]['dV'] num_accesses_total = (num_accesses_total + G.edges[i]['target_accesses']) if G.edges[i]['dist_to_target'] < min_distance_to_eye: dist_sum_length.append(G.edges[i]['dist_to_target']) if len(dist_sum_length) > 0: dist_mean = sum(dist_sum_length) / len(dist_sum_length) else: dist_mean = 99999 total_access_time = num_accesses_total * time_step if disp_flag == 1: print('---') print('Total delta-V used: ', round(dV, 2), ' m/s') print('Total access time: ', total_access_time, ' s') print('Mean distance to storm (across all accesses): ', round(dist_mean / 1000, 2), ' km') #------------------------------------------------------------------------- ### EXPORTS- TO CSV AND PLOTTING ### #------------------------------------------------------------------------- #CSV with open("output/graph_theory_nodes_example.csv", 'w') as f: w = csv.writer(f) for key, val in nodes.items(): w.writerow([key, val]) #Generate a visuzalition of the graph pos = graphviz_layout(G, prog='twopi') plt.figure(figsize=(100, 100)) #color nodes based on which target they are associated with #(!) change this for different numbers of targets! color_map = ['gray'] for node in G: if node in node_per_target[1]: color_map.append('blue') if node in node_per_target[2]: color_map.append('green') if node in node_per_target[3]: color_map.append('pink') # if node in node_per_target[4]: # color_map.append('orange') # if node in node_per_target[5]: # color_map.append('purple') #create plot and edge labels nx.draw(G, pos, node_size=1000, node_color=color_map, with_labels=True) #edge labels from https://stackoverflow.com/questions/60397606/how-to-round-off-values-corresponding-to-edge-labels-in-a-networkx-graph edge_labels = dict([(( u, v, ), f"{d['dV']:.2f} m/s, {d['dist_to_target']:.2f}, {d['target_accesses']:.2f} accesses" ) for u, v, d in G.edges(data=True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, width=2) nx.draw_networkx_nodes(G, pos, nodelist=shortest_complete_path, node_color='r') nx.draw_networkx_edges(G, pos, edgelist=shortest_complete_path_edges, edge_color='r', width=5) plt.axis('equal') #save the figure to a new file plt.savefig('output/graph_theory_tree_example.png') return [dV_total, -num_accesses_total, dist_mean, G, nodes]
import numpy as np from initgame import initgame from visualize import visualize from propagate import propagate import pickle import matplotlib.pyplot as plt from tick import tick import time t = np.arange(10) g, sidx = initgame(1000) mode = 'Store' if mode == 'Store': G = propagate(g, t) ani = visualize(G) elif mode == 'Live': fig = plt.figure() ax = fig.gca() fig.show() G = g # Im = plt.imshow(g) # Im.show() while 1: plt.imshow(G) fig.canvas.draw() t = time.time() G = tick(G) elapsed = time.time() - t print(elapsed)
def optimize(W, b, X, Y, num_iteration, learning_rate=0.009): for i in range(num_iteration): _, dW, db = propagate(W, b, X, Y) W = W - learning_rate * dW b = b - learning_rate * db return W, b
def series_of_maneuvers(dV1, dV2, dV3, disp_flag): #------------------------------------------------------------------------- ### IMPORTS ### #------------------------------------------------------------------------- #local files needed from distance_SSP_to_target import distance_SSP_to_target from load_hurricane_data import import_hurricane from lowering_maneuver import lowering_maneuver from raising_maneuver import raising_maneuver from propagate import propagate #Other python packages needed import math import numpy as np import networkx as nx import datetime import os #------------------------------------------------------------------------- ### INPUTS ### #------------------------------------------------------------------------- #delta-V for each manuever given as an input #- the number of values corresponds to the number of manuevers which is equal to the number of targets #delta-V stored here dV_list = [[dV1, dV2, dV3]] ###Initialize satellites-------------------------------------------------- #A list of lists is used to store satellite(s) states and their #maneuver info, and target access information num_sats = 1 #epoch Oct 10, 2010, 12:00 UTC date_epoch = datetime.datetime(2010, 10, 10, 12) #note that AOL and RAAN at epoch start are used as opposed to RAAN and argument of perigee sat_elems = ['Satellite Number', 'Semi-major Axis (m)', 'Inclination (deg)',\ 'RAAN (deg)', 'Argument of Latitude (deg)', 'RA at Epoch Start (deg)', \ 'SSP Lat. (deg)', 'SSP Lon. (deg)', \ 'Time Since Epoch (sec)', \ 'Delta-V Used in current maneuver', 'Dist to Current Target (km)'] satellites = [] for i in range(num_sats): semi_major_axis = 7074000 #m incl = 40 #deg RAAN0 = 0 + 20 * i #deg - this means for multiple satellites, satellites are spaced by 20 deg RAAN u0 = 0 #deg RAepoch = -161.155 #deg satellites.append([i, semi_major_axis, incl, \ RAAN0, u0, RAepoch, \ 0, 0, \ 0, 0,\ 0,\ 0]) #note the ssp, delt-V and dist to target are initially clear if disp_flag == 1: print('---') print('Satellite(s) initial states:') print('---') for i in range(num_sats): for x in range(len(sat_elems)): print(sat_elems[x], x, ':\t', satellites[i][x]) print('---') #this is the max acceleration available on the satellite satellite_mass = 4 #kg max_thrust = 0.35 * 10**(-3) #N accel = max_thrust / satellite_mass #m/s^2 ###Initialize Targets----------------------------------------------------- num_targets = len(dV_list[0]) targets = [] dir = os.path.dirname(__file__) file = os.path.join( dir, 'target_tracks\megi_data.xlsx' ) #(!) path may need to be changed for non-Windows users #These are locations of the eye of Typhoon Megi (2010) target_interval = 2.5 * 24 * 3600 #sec targets_time, targets_lat, targets_long, time_since_epoch, latitude, longitude = import_hurricane( file, date_epoch, num_targets, target_interval) targets = [[targets_time[i], targets_lat[i], targets_long[i]] for i in range(num_targets)] #Time window corresponds to allowed viewing time around each target (ie +/- 20 hrs target time) time_window = 20 * 3600 #sec #Establishes minimum acceptable distance to eye of the storm min_distance_to_eye = 100000 #m #------------------------------------------------------------------------- ### PARAMETERS ### #------------------------------------------------------------------------- #Model Parameters--------------------------------------------------------- mu = 3.98600 * 10**14 # standard gravitational parameter, m^3/s^2 Re = 6371000 # mean Earth radius, m J2 = 1082.7 * ( 10**-6 ) # coefficient of the Earth's gravitational zonal harmonic of the 2nd degree vel_e = 7.29212 * 10**(-5) # angular velocity of the earth, rad/s rad = math.pi / 180 # conversion of deg to rad flattening = 0.00335281 # flattening factor of the earth time_step = 10 # propagation time step (for viewing window propagation) #------------------------------------------------------------------------- ### CODE START ### #------------------------------------------------------------------------- #Satellite state is stored in dictionary nodes, and node numbers themselves in Graph G nodes = {0: satellites} G = nx.Graph() if disp_flag == 1: print("Executing maneuvers...") #the node we are starting to pull from origin_node = 0 # the node we are creating current_node = 1 #the information we start with old_sat_list = nodes[origin_node].copy() calc_nodes_last_target = [0] num_target = 0 #start with first target in list calc_nodes_current_target = [] for target in targets: num_target = num_target + 1 solution_found = False #Define viewing window for each target time_min = target[0] - time_window time_max = target[0] + time_window time_list = np.arange(time_min, time_max + time_step, time_step) #Interpolate between known track points for the viewing window time #this will be used to see if the satellite gets close to the storm lat_interp = np.interp(time_list, time_since_epoch, latitude) long_interp = np.interp(time_list, time_since_epoch, longitude) current_target = [time_list, lat_interp, long_interp] if disp_flag == 1: print('---') print("\nChecking accesses for target:" + "\t" + str(num_target)) print('Target time: ' + str(target[0] / 3600 / 24) + ' days') print('Target latitude: ' + str(target[1]) + ' deg') print('Target longitude: ' + str(target[2]) + ' deg') #Create new place to store satellite states new_sat_list = [] for i in range(num_sats): new_sat_list.append([]) # (leftover from tree generation approach)- move from one set of notes to the next for origin in calc_nodes_last_target: old_sat_list = nodes[origin].copy() #for multiple satellites, each will be manuevered in sequence for sat in range(len(old_sat_list)): maneuvering_sat = old_sat_list[sat][:] sat_time = maneuvering_sat[8] #Define the vewing window duration for each target, relative to satellite duration_min = time_min - sat_time duration_max = time_max - sat_time duration_list = np.arange(duration_min, duration_max + time_step, time_step) dV = dV_list[sat][num_target - 1] #Now execute the maneuvers- either propagate/lower/raise according to the delta-V if dV == 0: flag = 'N/A' updated_sat = propagate(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, duration_min) if dV < 0: flag = 'LOWER' #timing of manuevers (seconds of manuever, propogate, maneuver duration which correspond to the 3 phases can also be stored) [updated_sat, timing] = lowering_maneuver(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, abs(dV), duration_min) if updated_sat != None: updated_sat[9] = abs(dV) if dV > 0: flag = 'RAISE' #timing of manuevers (seconds of manuever, propogate, maneuver duration which correspond to the 3 phases can also be stored) [updated_sat, timing] = raising_maneuver(mu, Re, J2, vel_e, rad, flattening, maneuvering_sat, accel, dV, duration_min) if updated_sat != None: updated_sat[9] = abs(dV) #If the manuever was successful (time was sufficient for the delta-V), updated sat will have been created if updated_sat != None: #now propogate the satellite to the end of the time window to see the number/quality of accesses propagate_sat_options = propagate( mu, Re, J2, vel_e, rad, flattening, updated_sat, accel, (duration_list - duration_min)) distance = distance_SSP_to_target(mu, Re, rad, propagate_sat_options[6], propagate_sat_options[7], lat_interp, long_interp) num_accesses = 0 num_accesses = sum(1 for x in distance if x < min_distance_to_eye) if num_accesses > 0: #If the storm was accessed, record the accesses in the 'satellite' list #also maneuver timing can be stored- not currently done access_distance = [] index = 0 for x in distance: #record number of accesses index = index + 1 if x < min_distance_to_eye: #record access distance at each possible access: access_distance.append(x) lat = propagate_sat_options[6][index] long = propagate_sat_options[7][index] lateye = lat_interp[index] longeye = long_interp[index] distance = distance_SSP_to_target( mu, Re, rad, lat, long, lateye, longeye) totalSeconds = time_min + index * time_step #time since epoch in sec if disp_flag == 1: print('---successful access---') print('Distance: ' + str(x / 1000) + 'km') print('Current Time: ' + str( datetime.datetime(2010, 10, 10, 12) + datetime.timedelta( seconds=totalSeconds)) + 'UTC') print('Hurricane: Lat. ' + str(lat) + ' deg Long. ' + str(long) + ' deg') #Mark that a solution has been found for this target solution_found = True #Record the mean and minimum access distances mean_distance_pass = sum( access_distance) / num_accesses min_distance_pass = min(access_distance) #Either distance can be saved updated_sat[10] = min_distance_pass propagate_sat = propagate(mu, Re, J2, vel_e, rad, flattening, updated_sat, accel, time_window * 2) new_sat_list[updated_sat[0]] = propagate_sat nodes[current_node] = new_sat_list.copy() propagate_sat = [] updated_sat = [] calc_nodes_current_target.append(current_node) if dV == 0: dV_adj = 0.00001 #to ensure graph is connected (edge length cannot be 0) else: dV_adj = abs( dV ) #to ensure graph is connected (edge length cannot be negative) #Leftover from tree generation- add edge and then move on to next node G.add_edge(origin, current_node, dV=dV_adj, dist_to_target=mean_distance_pass, target_accesses=num_accesses, man_type=flag) current_node = current_node + 1 if disp_flag == 1: print('---summary of accesses for target ', str(num_target), '---') print('Mean Distance: ' + str(round(mean_distance_pass / 1000, 2)) + ' km') print('Min Distance: ' + str(round(min_distance_pass / 1000, 2)) + ' km') print('Delta-V Used: ' + str(dV) + ' m/s') print('Total Access Time: ' + str(num_accesses * time_step) + ' s') print('') if solution_found == False: #if a solution cannot be found, propogate sat, and record 0 accesses if disp_flag == 1: print('---no access available---') for origin in calc_nodes_last_target: old_sat_list = nodes[origin].copy() for x in range(len(old_sat_list)): flag = 'N/A' sat = old_sat_list[x][:] propagate_sat = propagate(mu, Re, J2, vel_e, rad, flattening, sat, accel, duration_max) propagate_sat[10] = 999999 new_sat_list[sat[0]] = propagate_sat.copy() nodes[current_node] = new_sat_list.copy() propagate_sat = [] calc_nodes_current_target.append(current_node) G.add_edge(origin, current_node, target_accesses=0, dV=0.00001, dist_to_target=999999, man_type=flag) current_node = current_node + 1 calc_nodes_last_target = calc_nodes_current_target[:] calc_nodes_current_target = [] #Leftover from tree generation #Tree Generation is complete... finding shortest path: complete_path = {} #record all possible path lengths path = nx.dijkstra_path(G, source=0, target=None, weight='dV') #only want the complete paths that view all targets for key in path: if len(path[key]) == num_targets + 1: current_path = path[key] length = nx.dijkstra_path_length(G, source=current_path[0], target=current_path[-1], weight='dV') complete_path[length] = current_path #then select shortest path min_path_length = 9999 for path_length in complete_path: if path_length < min_path_length: min_path_length = path_length shortest_complete_path = complete_path[path_length] shortest_complete_path_edges = zip(shortest_complete_path, shortest_complete_path[1:]) shortest_complete_path_edges = set(shortest_complete_path_edges) #Left over from tree generation- record the shortest path information dV_total = 0 num_accesses_total = 0 dist_sum_length = [] for i in shortest_complete_path_edges: dV_total = dV_total + G.edges[i]['dV'] num_accesses_total = (num_accesses_total + G.edges[i]['target_accesses']) if G.edges[i]['dist_to_target'] < min_distance_to_eye: dist_sum_length.append(G.edges[i]['dist_to_target']) if len(dist_sum_length) > 0: dist_mean = sum(dist_sum_length) / len(dist_sum_length) else: dist_mean = 99999 total_access_time = num_accesses_total * time_step if disp_flag == 1: print('---') print('Total delta-V used: ', round(dV, 2), ' m/s') print('Total access time: ', total_access_time, ' s') print('Mean distance to storm (across all accesses): ', round(dist_mean / 1000, 2), ' km') # For GA use, simply return the summary objectives: # Note that the GA assumes minimization of all objectives by default, so a negative total access time is returned # (want to minimize dV use, maximize total access time, minimize mean distance) # Different objectives could be used here as well (minimum distance) return [dV_total, -total_access_time, dist_mean]