def create_node_from_list(self, t_list, ind_list): """Returns a node, using the t_list and ind_list to specify the path. Args: t_list (list): Epochs (MJD) of depart/approach. ind_list (list): Indices of the asteroids to approach or depart from Returns: Node: Node that contains the full history of the path. """ # create the initial orbit: initial = Orbit(name='Initial', index=ind_list[0]) rv = select_asteroid(ind_list[0]).rv(t_list[0]) initial.from_rv(t_list[0], *rv) # create the initial node: node = Node(t_list[0], index=ind_list[0], approach_orbit=initial, parent=None) # create all the legs: for t, ind in zip(t_list[1:], ind_list[1:]): node = node.create_next_node(target_ind=ind, target_epoch=t) return node
def test_errors(requests_mock): client = Orbit(auth="f4k3") requests_mock.get("https://app.orbit.love/api/v1/workspaces", status_code=400) with pytest.raises(OrbitException): location = client.get_workspaces()
def __init__(self, weather, orbit_details): self.orbit1 = Orbit(config.ORBIT1_LENGTH, config.ORBIT1_CRATERS, "Orbit1", orbit_details["Orbit1"]) self.orbit2 = Orbit(config.ORBIT2_LENGTH, config.ORBIT2_CRATERS, "Orbit2", orbit_details["Orbit2"]) try: self.weather = config.WEATHER_CONDITIONS[weather.lower()] except KeyError: raise KeyError
def get_flyby_orbit(a, ecc, body, inOutDir, nDir, isOut=False): periapsis = a * (1 - ecc) tempOrb = Orbit(a, ecc, 0, 0, 0, 0, 0, body) delta = tempOrb.get_flight_angle_at_soi(isOut) rpDir = rodrigues_rotate(inOutDir, nDir, delta) vpDir = cross(nDir, rpDir) rp = rpDir * periapsis vp = vpDir * math.sqrt(body.mu * (2 / periapsis - 1 / a)) return Orbit.from_state_vector(rp, vp, 0, body)
def load_dataset(file = '../gtoc4_problem_data.txt'): df = pd.read_csv(file, skiprows=2,delimiter= '\s+',header=None) df.columns = ['Name','Epoch','a','e','i','LAN','omega','M0'] asteroids = set() for i in range(len(df)): o = Orbit(index=i) o.from_gtoc(*df.iloc[i]) asteroids.add(o) earth = create_earth() return asteroids, earth
def dict_to_body(body_dict, system_list): name = body_dict['name'] mu = float(body_dict['gm']) * 1E9 eqr = float(body_dict['radius']) * 1000 rotPeriod = float(body_dict['rotperiod']) rotIni = float(body_dict['rotini']) * pi/180 a = float(body_dict['sma']) * 1000 ecc = float(body_dict['ecc']) inc = float(body_dict['inc']) * pi/180 argp = float(body_dict['arg']) * pi/180 lan = float(body_dict['raan']) * pi/180 mo = float(body_dict['mean']) * pi/180 epoch = float(body_dict['epoch']) primName = body_dict['parent'] if primName == '': orb = None else: prim = [bd for bd in system_list if bd.name == primName][0] orb = Orbit(a, ecc, inc, argp, lan, mo, epoch, prim) try: colorStr = body_dict['color'] color = eval(colorStr) except: color = (255, 255, 255) ref = int(body_dict['id']) return Body(name, eqr, mu, None, rotPeriod, rotIni, orb, ref, None, color)
def test_client_workspaces_request(requests_mock): expected_json = { "data": [{ "id": "650", "type": "workspace", "attributes": {}, "relationships": {} }] } requests_mock.get("https://app.orbit.love/api/v1/workspaces", json=expected_json) client = Orbit(auth="f4k3") workspaces = client.get_workspaces() assert workspaces[0]["id"] == "650"
def create_next_node(self, target_ind, target_epoch): """Function creates next node to be visited by solving Lambert, updating current sc mass Args: target_ind (int): next asteroid to be visited target_epoch (float): epoch at which next asteroid is to be visited [MJD] Returns: (node): node object of input asteroid to be visited at input epoch """ t0 = self.epoch r0, v0 = self.approach_orbit.rv() # find next ast and get its position (vel not needed) ast = select_asteroid(target_ind) r_target, v_target = ast.rv(target_epoch) # solve lamberts problem v1, v2 = lb.lambert(mu, r0, r_target, (target_epoch - t0) * day2s) # note that a maneouver is needed at the initial epoch to set us on a rendevousz path with target ast dv = v1 - v0 # only the initial change in velocity needed #incrememental cost (delta V, mass) if self.parent_node is None: # starting at earth inc_cost = max(0, norm(dv) - 4.0) # call mass_at_node to compute remaining mass after maneuver #m_node = mass_at_node(1500, inc_cost) # FIXME - SAYS THAT mass_at_node() is not defined... else: inc_cost = norm(dv) # call mass_at_node? # create new orbit, index=-2 since it is a transfer o_new = Orbit(name=f'Trx{self.len_of_chain()+1:2.0f}') o_new.from_rv(target_epoch, r_target, v2) # create new node new_Node = Node(epoch=target_epoch, index=target_ind, approach_orbit=o_new, parent=self) # update cost and manouever history new_Node.maneuvers = self.maneuvers + [(t0, dv)] new_Node.cost = self.cost + inc_cost return new_Node
def init_patched_conic(x, rf=1837400.0, r0=6371000.0 + 185000.0, phi0=0.0, D=384402000.0, V=2.649e-6 * 384402000.0): """Generic objective function. x is [lam1, v0].""" lam1 = x[0] v0 = x[1] r_soi = PatchedConic.r_soi r1 = np.sqrt(D**2 + r_soi**2 - 2.0 * D * r_soi * np.cos(lam1)) depart = Orbit(PatchedConic.mu_earth, r0, v0, phi0) intercept = depart.at(r1, sign='+') if np.isnan(intercept.v): raise ValueError("expected radius is not reached") elif depart.energy >= 0: raise ValueError("expected elliptical orbit") return PatchedConic(depart, intercept, lam1=lam1, rf=rf)
def alter_orbits(self, orbit_list): modified_orbit = [] for iter in orbit_list: name = iter._name distance = iter._distance no_of_craters = iter._no_of_craters + (self._crater_effect * iter._no_of_craters / 100) orbit_speed = iter._speed orb_temp = Orbit(name, distance, no_of_craters) modified_orbit.append(OrbitWithTraffic(orb_temp, orbit_speed)) return modified_orbit
def populate_face_orbits(self): orbits = [] faces = self.faces[:] for i in range(72): orbit = Orbit() face = faces[0] seed = faces.pop() orbit.add_line(seed) moves = list(seed.moves) axis = moves[0] for j in range(9): face_centers = [face.center() for face in faces] mirror_index = face_centers.index(seed.center().mirror_around(self.cells[axis])) seed = faces.pop(mirror_index) orbit.add_line(seed) moves = list(seed.moves) moves.remove(axis) axis = moves[0] orbits.append(orbit) return orbits
def initialize_orbit(self): QApplication.instance().processEvents( ) #Need to call processEvents to make the status bar message show up before the live orbit connection stuff starts. orbit = Orbit.lcls_bpms(auto_connect=False, parent=self) self.x_magnet_list = MagnetList("X", "xcor_list.json", parent=self) self.total_progress = orbit.progress_total( ) + self.x_magnet_list.progress_total() num_pvs = orbit.pv_count() + self.x_magnet_list.pv_count() self.loading_label.setText("Connecting to {} PVs...".format(num_pvs)) self.loading_label.setAlignment(Qt.AlignCenter) self.progress_bar.setMaximum(self.total_progress) orbit.connectionProgress.connect(self.increment_progress) self.x_magnet_list.connectionProgress.connect(self.increment_progress) orbit.connect() orbit.name = "Live Orbit" self.live_orbit = orbit self.initialize_magnet_lists() self.connection_complete()
def flyby_height_objective(periapsis, *params): aIn, aOut, deltaAngle, body = params eccIn = 1 - periapsis / aIn eccOut = 1 - periapsis / aOut inOrb = Orbit(aIn, eccIn, 0, 0, 0, 0, 0, body) outOrb = Orbit(aOut, eccOut, 0, 0, 0, 0, 0, body) deltaIn = inOrb.get_flight_angle_at_soi() deltaOut = outOrb.get_flight_angle_at_soi() return abs(deltaAngle - deltaIn - deltaOut)
def project_to_surface(orb, times): """Takes list of positions and times and projects to body's surface.""" bd = orb.prim positions = orb.get_positions(times=times)[0] bodyThetas = 2*np.pi/bd.rotPeriod * np.array(times) + bd.rotIni sphericalPositions = cartesian_to_spherical(positions) surfaceCoords = sphericalPositions[:,1:] for ii in range(len(times)): longitude = surfaceCoords[ii,0] - Orbit.map_angle(bodyThetas[ii]) count = 0 while abs(longitude) > np.pi: longitude = longitude - np.sign(longitude) * 2*np.pi count = count+1 if count > 10: print('Why?') break surfaceCoords[ii,0] = longitude return surfaceCoords
from grid import Grid from orbit import Orbit import matplotlib.pyplot as plt # Set up grid Z = 1 G = Grid(Z, 0.0001 / Z, 80, 0.002) # Set up orbit n = 2 l = 0 expected_nodes = n - l - 1 orb = Orbit(G, n, l) # Shoot with a guess E E = -0.8 orb.shoot(E) eps = 0.0001 if n - l - 1 == 0: while abs(orb.delt_E) > eps: E += orb.delt_E * 1e-4 orb.shoot(E) print(E) else: while abs(orb.delt_E) > eps or orb.node != n - l - 1: E += orb.delt_E * 1e-4 if abs(orb.delt_E) < eps: E -= .3 * E orb.shoot(E) print(E) print("Number of nodes ", orb.node) #print(orb.tp)
def create_earth(): # create Earth earth = Orbit(name='Earth', index=-1) earth.from_gtoc('Earth',54000,0.999988049532578, 1.671681163160e-2, 0.8854353079654e-3, 175.40647696473, 287.61577546182, 257.60683707535) return earth
from weather import Weather from vehicle import Vehicle from orbit import Orbit from orbitwithtraffic import OrbitWithTraffic from decisionmaker import DecisionMaker from console import Console from vehicletype import VehicleType from orbitname import OrbitName from weather import WeatherFactory from weather import WeatherType if __name__ == '__main__': orb1 = Orbit("Orbit1", 18, 20) orb2 = Orbit("Orbit2", 20, 10) #orb1 = Orbit(OrbitName.Orbit1, 18, 20) #orb2 = Orbit(OrbitName.Orbit2, 20, 10) bike = Vehicle(VehicleType.Bike, 10, 1) tuktuk = Vehicle(VehicleType.TukTuk, 12, 1) car = Vehicle(VehicleType.Car, 20, 1) vehicle_list=[tuktuk,bike,car] #--------------------------- console=Console() inputs=console.getuserinput() #------------------------------ option = WeatherType(inputs[0]) weather = WeatherFactory.get_weather(option) orbit1 = OrbitWithTraffic(orb1, inputs[1]) orbit2 = OrbitWithTraffic(orb2, inputs[2]) orbit_list=[orbit1,orbit2]
def __init__(self, arrival_time): # Start with earth parking orbit leo = Orbit.circular(PatchedConic.mu_earth, 6378136.6 + 185000.0) # Get the state of the moon at arrival so we know how far out # we need to go and how fast. x_moon_arrive = spice.spkez(301, arrival_time, 'J2000', 'NONE', 399)[0] * 1000.0 # Produce patched conic x, pcx = pc.optimize_deltav(np.array( [49.9 * np.pi / 180.0, leo.v + 3200.0]), 1837400.0, leo.r, leo.phi, norm(x_moon_arrive[0:3]), norm(x_moon_arrive[3:6]), conjugate=True) depart_time = arrival_time - pcx.tof free_flight_sweep_angle = pcx.nu1 - pcx.nu0 # Get state of moon at departure so we can figure out the # plane of our trajectory. x_moon_depart = spice.spkez(301, depart_time, 'J2000', 'NONE', 399)[0] * 1000.0 # Get earth--moon frame at SOI arrival time rm0 = x_moon_depart[:3] rm0hat = rm0 / norm(rm0) rm1 = x_moon_arrive[:3] rm1hat = rm1 / norm(rm1) hhat = np.cross(rm0hat, rm1hat) hhat /= norm(hhat) T_eci_to_pqw = spice.twovec(rm1hat, 1, hhat, 3) # Get directions to initial and final vectors r1hat = T_eci_to_pqw.T.dot( rotate_z(pcx.gam1).dot(np.array([1.0, 0, 0]))) r0hat = T_eci_to_pqw.T.dot( rotate_z(pcx.gam1 - free_flight_sweep_angle).dot( np.array([1.0, 0.0, 0.0]))) v0hat = np.cross(hhat, r0hat) # post delta-v state: r0 = r0hat * leo.r v0 = v0hat * x[1] # pre delta-v state: v0m = v0hat * leo.v # arrival state: # r1 = r1hat * pcx.arrive.r # v1 = ? self.free_flight_sweep_angle = free_flight_sweep_angle self.depart_time = depart_time self.arrival_time = arrival_time self.x_depart_post = np.hstack((r0, v0)) self.x_depart_pre = np.hstack((r0, v0m)) self.x_moon_depart = x_moon_depart self.x_moon_arrive = x_moon_arrive self.deltav = v0 - v0m
from grid import Grid from orbit import Orbit import matplotlib.pyplot as plt Z = 1 G = Grid(Z, 0.0001 / Z, 50, 0.002) orb = Orbit(G, 3, 0) # That’s it! # Print resulting E #print(orb.E) #print(orb.Vh) # Plot #plt.plot(G.r, orb.u, linewidth =2) #plt.title(r"Numerical solution $u_{30}$") plt.plot(G.r, orb.vreal, "y-", linewidth=4, label="Analytical") plt.plot(G.r, orb.Vh, "k--", linewidth=1, label="Numerical") plt.legend(loc="best") plt.savefig("num30.png") plt.show()
max = orbit.max_anomaly * 0.95 thetas = [(2 * i / 100 - 1) * max for i in range(101)] data = [orbit.position_at(t).measure(1000 * METERS) for t in thetas] transpose = [[p[i] for p in data] for i in range(3)] ax.plot3D(*transpose) # Set boundaries SIZE = 10000 ax.set(xlim=(-SIZE, SIZE), ylim=(-SIZE, SIZE)) # Plot Kerbin itself ax.scatter3D(0, 0, 0) # Plot some orbits geosync = Orbit.circular_with_period(KERBIN, 21549.425 * SECS) radius = geosync.semimajor_axis sat = Satellite(KERBIN, radius * Vec3.X, geosync.speed_at(radius) * Vec3.Y) plot_orbit(sat.orbit) BoostPrograde(200 * METERS / SECS).apply(sat) plot_orbit(sat.orbit) WaitTime(sat.orbit.period / 4).apply(sat) BoostPrograde(200 * METERS / SECS).apply(sat) plot_orbit(sat.orbit) sat.wait_time(sat.orbit.period / 5) BoostPrograde(-50 * METERS / SECS).apply(sat) plot_orbit(sat.orbit)
def add_orbit(figure, orb, startTime, endTime=None, numPts=201, dateFormat=None, apses=False, nodes=False, fullPeriod=True, color=(255,255,255), name='', style='solid', fade=True,): if fade: fadedColor = fade_color(color,3) else: fadedColor = color period = orb.get_period() if fullPeriod and (endTime is None): endTime = startTime + period # start and end mean anomalies mStart = orb.get_mean_anomaly(startTime) if (period < (endTime-startTime) or fullPeriod) and (orb.ecc < 1): mEnd = mStart + 2*math.pi else: mEnd = mStart + 2*math.pi/period * (endTime-startTime) # get points clustered around apoapsis and periapsis if orb.ecc < 1: a = mStart - (mStart%math.pi) b = a + math.pi else: if mStart < 0: a = mStart b = 0 else: a = 0 b = mEnd # orbit crosses two apo/peri-apses if ((mEnd >= b + math.pi) and (orb.ecc < 1)): c = b + math.pi d = c + math.pi n = math.ceil(math.pi/(mEnd-mStart)*numPts) kStart = n*math.acos((a+b-2*mStart)/(b-a))/math.pi kEnd = n*math.acos((c+d-2*mEnd)/(d-c))/math.pi ks1 = [[kStart]] ks1.append([*range(math.ceil(kStart), n)]) ks1 = [k for sublist in ks1 for k in sublist] meanAnoms1 = \ [0.5*(a+b) + 0.5*(b-a) *math.cos((n-k)/n*math.pi) for k in ks1]; ks2 = [*range(0,n)] meanAnoms2 = \ [0.5*(b+c) + 0.5*(c-b) *math.cos((n-k)/n*math.pi) for k in ks2]; ks3 = [*range(0,math.ceil(kEnd))] ks3.append(kEnd) meanAnoms3 = \ [0.5*(c+d) + 0.5*(d-c) *math.cos((n-k)/n*math.pi) for k in ks3]; meanAnoms = np.append(meanAnoms1, meanAnoms2) meanAnoms = np.append(meanAnoms, meanAnoms3) times = startTime + period/(2*math.pi) * (meanAnoms - mStart) # orbit crosses one apo/peri-apsis elif mEnd > b: if orb.ecc < 1: c = b + math.pi n1 = math.ceil(math.pi/(mEnd-mStart)*numPts) n2 = n1 else: c = mEnd n1 = math.ceil(abs(mStart/(mEnd-mStart))*numPts) n2 = math.ceil(abs(mEnd/(mEnd-mStart))*numPts) kStart = n1*math.acos((a+b-2*mStart)/(b-a))/math.pi kEnd = n2*math.acos((b+c-2*mEnd)/(c-b))/math.pi ks1 = [[kStart]] ks1.append([*range(math.ceil(kStart), n1)]) ks1 = [k for sublist in ks1 for k in sublist] meanAnoms1 = \ [0.5*(a+b) + 0.5*(b-a) *math.cos((n1-k)/n1*math.pi) for k in ks1]; ks2 = [*range(0,math.ceil(kEnd))] ks2.append(kEnd) meanAnoms2 = \ [0.5*(b+c) + 0.5*(c-b) *math.cos((n2-k)/n2*math.pi) for k in ks2]; meanAnoms = np.append(meanAnoms1, meanAnoms2) times = startTime + period/(2*math.pi) * (meanAnoms - mStart) # orbit crosses no apo/peri-apses else: if orb.ecc < 1: n = math.ceil(2*math.pi/(mEnd-mStart)*numPts) else: n = numPts kStart = n*math.acos((a+b-2*mStart)/(b-a))/math.pi kEnd = n*math.acos((a+b-2*mEnd)/(b-a))/math.pi ks = [[kStart]] ks.append([*range(math.ceil(kStart), math.ceil(kEnd))]) ks.append([kEnd]) ks = [k for sublist in ks for k in sublist] meanAnoms = np.array( \ [0.5*(a+b) + 0.5*(b-a) *math.cos((n-k)/n*math.pi) for k in ks]); meanAnoms = meanAnoms.flatten() times = startTime + period/(2*math.pi) * (meanAnoms - mStart) pos, vel = orb.get_positions(times = times) pos = np.transpose(pos) vel = np.transpose(vel) if orb.ecc<1: for ii, m in enumerate(meanAnoms): meanAnoms[ii] = Orbit.map_angle(m) if not dateFormat is None: day = dateFormat['day'] year = dateFormat['year'] cData = np.stack((norm(pos, axis = 0)/1000, norm(vel, axis = 0), np.floor(times/(3600*day*year))+1, np.floor(times%(3600*day*year)/(day*3600)+1), np.floor((times%(3600*day))/3600), np.floor(((times%(3600*day))%3600)/60), np.floor(((times%(3600*day))%3600)%60), times, meanAnoms), axis=1); hoverLabel = "r = %{customdata[0]:.3e} km" + "<br>" +\ "v = %{customdata[1]:.3e} m/s" + "<br>" + "<br>" +\ "Year %{customdata[2]:.0f}, " +\ "Day %{customdata[3]:.0f} " +\ "%{customdata[4]:0>2d}" + ":" +\ "%{customdata[5]:0>2d}" + ":" +\ "%{customdata[6]:0>2d}" + "<br>" +\ "UT: %{customdata[7]:.3f} s" + "<br>" +\ "Mean Anomaly: %{customdata[8]:.5f} rad" + "<br>" + "<br>" +\ "Semi-major Axis = " + "{:.0f}".format(orb.a) + " m" + "<br>" +\ "Eccentricity = " + "{:.4f}".format(orb.ecc) + "<br>" +\ "Inclination = " + "{:.4f}".format(orb.inc*180/math.pi) + "°" + "<br>" +\ "Argument of the Periapsis = " + "{:.4f}".format(orb.argp*180/math.pi) + "°" + "<br>" +\ "Longitude of Ascending Node = " + "{:.4f}".format(orb.lan*180/math.pi) + "°" + "<br>" +\ "Mean Anomaly at Epoch = " + "{:.4f}".format(orb.mo) + " rad" + "<br>" +\ "Epoch = " + "{:.2f}".format(orb.epoch) + " s" else: cData = norm(pos, axis = 0)/1000 hoverLabel = "r = %{customdata:.4e} km" figure.add_trace(go.Scatter3d( x = pos[0], y = pos[1], z = pos[2], customdata = cData, mode = "lines", line = dict( color = times, colorscale = [[0, 'rgb'+str(fadedColor)], [1, 'rgb'+str(color)]], dash = style ), hovertemplate = hoverLabel, name = name, showlegend = False, )) if nodes: add_nodes(figure, orb) if apses: add_apses(figure, orb)
import os import json from orbit import Orbit, OrbitException client = Orbit(auth=os.environ['ORBIT_API_KEY']) repo_activities = {} activities = client.get_activities('650', items=250, start_date='2020-12-01', end_date='2021-02-08', direction="ASC", auto_paginated=True) for activity in activities: repo = activity['attributes']['tags'][1] last_activity = activity['attributes']['occurred_at'] print(activity['attributes']['type']) if not repo in repo_activities: repo_activities[repo] = {'count': 0, 'last_activity': None} else: repo_activities[repo]['count'] += 1 repo_activities[repo]['last_activity'] = last_activity print(json.dumps(repo_activities, indent=4, sort_keys=True))
def orbit(self) -> Orbit: return Orbit.from_cartesian(self.body, self.pos, self.vel)
Z = 1 g = Grid(Z, 0.0001 / Z, 110., 0.001) n = 1 epsilon = 0.0001 colors = ["black", "red", "blue", "green", "purple", "orange"] styles = ["-", "-.", "-", "--"] if n <= 6: factor = 0.3 else: factor = 0.1 for l in range(0, n): orb = Orbit(g, n, l) E = -0.45 orb.shoot(E) if n - l - 1 == 0: while abs(orb.delta_E) > epsilon: E += 1e-4 * orb.delta_E orb.shoot(E) print "----->" + str(E) else: while abs(orb.delta_E) > epsilon or orb.node != n - l - 1: E += 1e-4 * orb.delta_E if abs(orb.delta_E) < epsilon: E -= factor * E print "--------->" + str(E) orb.shoot(E) #print "I have done l="+str(l)
conjugate=conjugate, maxiter=alpha_maxiter, alphatol=alphatol, plot=plot_alpha, disp=disp) print("Warning: exceeded max iterations (gradient phase)") return x, pcx if __name__ == '__main__': D = 384402000.0 V = 2.649e-6 * D leo = Orbit.circular(PatchedConic.mu_earth, 6378136.6 + 185000.0) # earth parking XS = [] YS = [] optimize_deltav(np.array([49.9 * np.pi / 180.0, leo.v + 3200.0]), 1837400.0, leo.r, leo.phi, D, V, conjugate=True) YS = np.vstack(YS) import matplotlib.pyplot as plt fig = plt.figure()