def calcOrbit(self): #converts every coordinate into correct units #time0 = time.time() mag = max([x.mag for x in self.dets]) errs = 0.1 if mag <= 21: errs = 0.1 else: errs = 0.1 + (mag - 21.0) / 10.0 ralist = [ephem.hours(np.deg2rad(det.ra)) for det in self.dets] #time1 = time.time() declist = [ephem.degrees(np.deg2rad(det.dec)) for det in self.dets] #time2 = time.time() datelist = [ ephem.date((Time(det.mjd, format='mjd')).datetime) for det in self.dets ] #time3 = time.time() orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(len(self.dets), dtype=int) * 807, err=errs) self.orbit = orbit #time4 = time.time() #print('time1: ' + str(time1-time0)) #print('time2: ' + str(time2-time1)) # print('time3: ' + str(time3-time2)) #print('time4: ' + str(time4-time3)) orbit.get_elements() self.chiSq = orbit.chisq self.elements, self.errs = orbit.get_elements() return self.elements, self.errs
class DESKBO(object): def __init__(self, obsfile, name=None, field=None, pltcolor='k'): # print 'Reading file ', obsfile self.name=name self.field=field self.obsfile=obsfile self.observations = Catalog(self.obsfile, date=DateTime, ra=hours, dec=degrees, expnum=int, exptime=float, band=str, ccdnum=int, mag=float, \ ml_score=float, snobjid=int, orderedby='date') self.observations.add_constant('obscode', 807) self.observations.add_constant('err', 0.15) self.orbit = Orbit(self.observations) # Warning: somehow orbit.predict_pos() does not work from here. self.body = self.orbit.ellipticalBody(name=self.name) self.pltcolor=pltcolor self.elements, self.errs = self.orbit.get_elements() obsdates = sorted([o.date for o in self.observations]) self.body.compute(obsdates[0]) self.discoveryDistance = self.body.sun_distance self.size = KBOsize(self) self.epoch = self.orbit.jd0 self.mu = (self.epoch-self.elements['top'])*np.sqrt(combinedMass/self.elements['a']**3)*DAY*180/np.pi if self.mu<0: self.mu += 360.0 def predict(self, d, obscode=807): # d is an ephem.Date object self.body.compute(d) pos = {'ra':self.body.a_ra, 'dec':self.body.a_dec} return pos
class Planet(object): def __init__(self, index=0, seed=0, sun_position=(0, 0), radius=128, orbit=128, orbit_point=360, name='NULL'): random.seed(seed) self.radius = radius self.orbit = Orbit(position=sun_position, orbit=orbit, color=Color.gray) self.orbit_point = orbit_point self.name = name self.radius_mod = 10 self.planet_index = index self.planet_seed = int(str(seed)+str(index)) self.station = None # some stats # larger the planet, the more likely the atmosphere is thick self.atmosphere_density = round(self.radius / 255.0 * random.uniform(0.7, 1.0), 4) atmopshere_mod = self.atmosphere_density-0.5 self.temperature = 1000-orbit self.temperature += int(self.temperature * atmopshere_mod) self.map = Map(width=300, height=200, rando=False, seed=self.planet_seed, zoom=2, temperature=self.temperature) def draw(self, screen): # pygame.draw.circle(screen, (255, 255, 255), position, self.radius / 10) # pygame.draw.circle(screen, (0, 0, 0), position, max(self.radius / 10, 5), 1) pygame.draw.circle(screen, Color.gray, self.orbit.get_point(self.orbit_point), self.radius / self.radius_mod) pygame.draw.circle(screen, Color.black, self.orbit.get_point(self.orbit_point), max(self.radius / self.radius_mod, 5), 1)
def get_orbits(filename, areas, masses): f = open(filename) i = 0 orbits = [] line0 = f.readline() max_len = len(areas) while line0 != '' and i != max_len: # name name = line0.strip('\n') line1 = f.readline() line2 = f.readline() satellite = twoline2rv(line1, line2, wgs84) satellite.propagate(2017, 12, 1, 12, 00, 00) satellite_number = satellite.satnum inclination = satellite.inclo raan = satellite.nodeo eccentricity = satellite.ecco w = satellite.argpo mean_anomaly = satellite.mo mean_motion = satellite.no o = Orbit(name, satellite_number, inclination, raan, eccentricity, w, mean_anomaly, mean_motion, satellite.a * RE, areas[i], masses[i]) orbits.append(o) line0 = f.readline() i = i + 1 f.close() return np.array(orbits)
def check_Orbit(self, pair_index, mask, chisq_cut=2): pair = self.test_pairs.T[pair_index] #print pair_index #print pair #print "checking Orbit..." print pair.fakeid1, pair.fakeid2, x1 = pair.ra1 y1 = pair.dec1 x2 = pair.ra2 y2 = pair.dec2 d1 = pair.mjd1 - 15019.5 d2 = pair.mjd2 - 15019.5 for i in self.test_pairs.index[mask]: x3 = self.test_pairs.T[i].ra1 y3 = self.test_pairs.T[i].dec1 x4 = self.test_pairs.T[i].ra2 y4 = self.test_pairs.T[i].dec2 d3 = self.test_pairs.T[i].mjd1 - 15019.5 d4 = self.test_pairs.T[i].mjd2 - 15019.5 ra = [x1, x2, x3, x4] dec = [y1, y2, y3, y4] date = [d1, d2, d3, d4] if len(np.unique(date)) == 4: ralist = [str(ephem.hours(j)) for j in ra] declist = [str(ephem.degrees(j)) for j in dec] datelist = [str(ephem.date(j)) for j in date] #print ralist #print declist #print datelist orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(4, dtype=int) * 807, err=0.25) if orbit.chisq / orbit.ndof < chisq_cut: print self.test_pairs.T[i].fakeid1, self.test_pairs.T[ i].fakeid2, abg = orbit.get_elements_abg()[0] with open( "{0}cand_{1}.abg.json".format( output_dir, self.cand_num), 'w') as fp: json.dump(abg, fp) self.output(pair, self.test_pairs.T[i]) print ' '
def fit_orbit(df_obs): df_obs = df_obs.loc[['#' not in row['date'] for ind, row in df_obs.iterrows()]] # filter comment lines nobs = len(df_obs) ralist = [ephem.hours(r) for r in df_obs['ra'].values] declist = [ephem.degrees(d) for d in df_obs['dec'].values] datelist = [ephem.date(d) for d in df_obs['date'].values] orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(nobs, dtype=int)*807, err=0.15) fakeid = df_obs['fakeid'][3] return orbit
def fetchOrbit(dbLogicalLocation, orbitId): """ Fetch the full Orbit corresponding to the internal orbitId: orbitId = '%d-%d' %(movingObjectId, movingObjectVersion) @param dbLogicalLocation: pointer to the DB. @param orbitId: orbit ID. Return Orbit obj """ if (EXTRA_RIDICOLOUSLY_VERBOSE): t0 = time.time() # Init the persistance middleware. db = dafPer.DbStorage() # Connect to the DB. loc = dafPer.LogicalLocation(dbLogicalLocation) db.setRetrieveLocation(loc) # Remember that we defined a new internal orbitId as the concatenation of # movingObjectId and movingObjectVersion: # orbitId = '%d-%d' %(movingObjectId, movingObjectVersion) (movingObjectId, movingObjectVersion) = orbitId.split('-') # Prepare the query. where = 'movingObjectId=%s and movingObjectVersion=%s' \ %(movingObjectId, movingObjectVersion) cols = ['q', 'e', 'i', 'node', 'argPeri', 'timePeri', 'epoch', 'h_v', 'g'] cols += ['src%02d' % (i) for i in range(1, 22)] db.startTransaction() db.setTableForQuery('MovingObject') db.setQueryWhere(where) errs = map(lambda c: db.outColumn(c), cols) # Execute the query. db.query() if (not db.next()): if (RIDICOLOUSLY_VERBOSE): logit('fetchOrbit: SQL query failed!') logit('SQL: select %s from MovingObject where %s' \ %(','.join(cols), where)) return # Create the Orbit object and just spit it out. args = [int(movingObjectId), int(movingObjectVersion), ] + \ [db.getColumnByPosDouble(i) for i in range(9)] + \ [[db.getColumnByPosDouble(i) for i in range(9, 30, 1)]] # We are done with the query. db.finishQuery() if (EXTRA_RIDICOLOUSLY_VERBOSE): logit(' %.02fs: fetchOrbit()' % (time.time() - t0)) return (Orbit(*args))
def getOrbitSamples(weather): orbits = [] if GlobalVariables.ProblemNumber == 1: orbitSamples = GlobalVariables.orbitInformationSample1 else: orbitSamples = GlobalVariables.orbitInformationSample2 for index,orbitSample in orbitSamples.iterrows(): orbit = input() orbitinfo = orbit.split() orbitspeed = [int(speed) for speed in orbitinfo if speed.isnumeric()][0] name = orbitinfo[0] craters = orbitSample['craters'] distance = orbitSample['distance'] source = orbitSample['source'] destination = orbitSample['destination'] orbitObject = Orbit(name, orbitspeed, source, destination, distance, craters) orbitObject.setReducedCraterByWeather(weather) orbits.extend([orbitObject]) return orbits
def fit_orbit(self, df_obs): #df_obs = df_obs.ix[['#' not in row['date'] for ind, row in df_obs.iterrows()]] # filter comment lines nobs = len(df_obs) ralist = [ephem.hours(r) for r in df_obs['ra'].values] declist = [ephem.degrees(r) for r in df_obs['dec'].values] datelist = [ephem.date(d) for d in df_obs['date'].values] obscode = np.ones(nobs, dtype=int) * 807 orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=obscode, err=0.15) # print orbit.chisq return orbit
def get_orbit_ellipse(orbit_object: Orbit): orbit_center = ((image_center[0] + (orbit_object.semimajor_axis - orbit_object.get_periapsis()) * scale), image_center[1]) # Semimajor axis and eccentricity orbit_ellipse = svgwrite.shapes.Ellipse((0, 0), (orbit_object.get_apoapsis() * scale, orbit_object.get_periapsis() * scale)) # longitude of the ascending node orbit_ellipse.rotate(orbit_object.longitude_of_the_ascending_node, image_center) # replacing to the center orbit_ellipse.translate(orbit_center[0], orbit_center[1]) # inclination inclination_scale = 1 - abs(orbit_object.inclination) / 90 print("Scaling x by {} due to inclination of {}".format(inclination_scale, orbit_object.inclination)) orbit_ellipse.scale(inclination_scale, 1) # graphics orbit_ellipse.fill('none') orbit_ellipse.stroke('rgb(190, 190, 190)', orbit_stroke_width, opacity=0.6) return orbit_ellipse
def setOrbit(self): mag = min([x.mag for x in self.dets]) #time0 = time.time() errs = 0.1 if mag <= 21: errs = 0.15 else: errs = 0.15 + (mag - 21.0) / 40.0 #time1 = time.time() ralist = [ephem.hours(np.deg2rad(det.ra)) for det in self.dets] #print('ra:' + str(time.time()-time1)) #time2 = time.time() declist = [ephem.degrees(np.deg2rad(det.dec)) for det in self.dets] #print('dec:' + str(time.time()-time2)) datelist = [ ephem.date((Time(det.mjd, format='mjd')).datetime) for det in self.dets ] #time3 = time.time() #print('date:' + str(time3-time2)) #time2 = time.time()i orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(len(self.dets), dtype=int) * 807, err=errs) self.orbit = orbit self.chisq = orbit.chisq #time3 = time.time() self.elements, self.errs = orbit.get_elements() #time4 = time.time() #print('time0:' + str(time1-time0)) #print('dateTime:' + str(time2-time1)) #print('orbitTime:' + str(time3-time2)) #print('getTime:' + str(time4-time3)) return orbit
def getParameters(): print('Enter mu: ', end='') mu = getFloat64() print('Enter target orbital params') i, ra, ap, ta, e, h = getOrbitalParameters() orbitTarget = Orbit() orbitTarget.setOrbitFromParams(mu, h, e, np.radians(i), np.radians(ra), np.radians(ap), np.radians(ta)) print('Enter chaser orbital params') i, ra, ap, ta, e, h = getOrbitalParameters() orbitChaser = Orbit() orbitChaser.setOrbitFromParams(mu, h, e, np.radians(i), np.radians(ra), np.radians(ap), np.radians(ta)) print('Enter time(hours): ', end='') t = getFloat64() * 3600.0 return mu, orbitTarget, orbitChaser, t
def __init__(self, index=0, seed=0, sun_position=(0, 0), radius=128, orbit=128, orbit_point=360, name='NULL'): random.seed(seed) self.radius = radius self.orbit = Orbit(position=sun_position, orbit=orbit, color=Color.gray) self.orbit_point = orbit_point self.name = name self.radius_mod = 10 self.planet_index = index self.planet_seed = int(str(seed)+str(index)) self.station = None # some stats # larger the planet, the more likely the atmosphere is thick self.atmosphere_density = round(self.radius / 255.0 * random.uniform(0.7, 1.0), 4) atmopshere_mod = self.atmosphere_density-0.5 self.temperature = 1000-orbit self.temperature += int(self.temperature * atmopshere_mod) self.map = Map(width=300, height=200, rando=False, seed=self.planet_seed, zoom=2, temperature=self.temperature)
def fetchOrbit(orbitId): """ Fetch the full Orbit corresponding to the internal orbitId: orbitId = '%d-%d' %(movingObjectId, movingObjectVersion) @param dbLogicalLocation: pointer to the DB. @param orbitId: orbit ID. Return Orbit obj """ dbh = dbi.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASSWD, db=DB_DB) cur = dbh.cursor() # Remember that we defined a new internal orbitId as the concatenation of # movingObjectId and movingObjectVersion: # orbitId = '%d-%d' %(movingObjectId, movingObjectVersion) (movingObjectId, movingObjectVersion) = orbitId.split('-') # Prepare the query. where = 'movingObjectId=%s and movingObjectVersion=%s' \ %(movingObjectId, movingObjectVersion) cols = ['q', 'e', 'i', 'node', 'argPeri', 'timePeri', 'epoch', 'h_v', 'g'] cols += ['src%02d' % (i) for i in range(1, 22)] sql = '''select %s from MovingObject where %s''' # Execute the query. cur.execute(sql % (', '.join(cols), where)) res = cur.fetchone() # Create the Orbit object and just spit it out. elements = [float(res[i]) for i in range(0, 9)] src = [float(res[i]) for i in range(9, 30, 1)] args = [ int(movingObjectId), int(movingObjectVersion), ] + elements + [src] return (Orbit(*args))
def check_Orbit(self, ra, dec, date, chisq_cut=2.): #print "checking Orbit..." x1 = self.test_tri['ra1'] y1 = self.test_tri['dec1'] x2 = self.test_tri['ra2'] y2 = self.test_tri['dec2'] x3 = self.test_tri['ra3'] y3 = self.test_tri['dec3'] d1 = self.test_tri['mjd1'] - 15019.5 d2 = self.test_tri['mjd2'] - 15019.5 d3 = self.test_tri['mjd3'] - 15019.5 ra = [x1, x2, x3] + list(ra) dec = [y1, y2, y3] + list(dec) date = [d1, d2, d3] + list(date) ralist = [str(ephem.hours(i)) for i in ra] declist = [str(ephem.degrees(i)) for i in dec] datelist = [str(ephem.date(i)) for i in date] orbit = Orbit(dates=datelist, ra=ralist, dec=declist, obscode=np.ones(5, dtype=int) * 807, err=0.25) return orbit.chisq / orbit.ndof < chisq_cut
def addOrbit(self, textVars, xMax, yMax): self.orbits.append(Orbit(xMax, yMax, textVars, self.resolution))
def append_subsystem(self, subsystem, orbit_radius, orbit_time, init_orbit_angle=0.0): self.subsystems.append(subsystem) orbit = Orbit(self.master, subsystem.master, orbit_radius, orbit_time, init_orbit_angle) self.orbits.append(orbit)
def add_satellite(self, satellite, orbit_radius, orbit_time, init_orbit_angle=0.0): self.satellites.append(satellite) orbit = Orbit(self.master, satellite, orbit_radius, orbit_time, init_orbit_angle) self.orbits.append(orbit)
def load(self, filename): # Convert array to string (MAT-files store strings as # arrays with 2 bytes per character) if filename.endswith('.mat'): tos = lambda v: "".join(map(chr, v[:, :][:, 0].tolist())) else: tos = lambda v: v[:].tostring().decode('utf-8') with h5py.File(filename, 'r') as f: self.T = f['t'][:, :] self.NORBITS = self.T.shape[0] self.NT = self.T.shape[1] self.P = f['p'][:, :] self.P2 = f['p2'][:, :] self.SOLUTION = f['solution'][:, :] self.XYZ = f['x'][:, :] self.PPAR = f['ppar'][:] self.PPERP = f['pperp'][:] self.B = f['B'][:] self.BABS = f['Babs'][:] self.BHAT = f['bhat'][:] self.CLASSIFICATION = f['classification'][:] try: self.WALL = f['wall'][:] except: self.WALL = None try: self.SEPARATRIX = f['separatrix'][:] except: self.SEPARATRIX = None try: self.JACOBIAN = f['Jdtdrho'][:] except: self.JACOBIAN = None try: self._radius = f['r'][:] self._param1name = tos(f['param1name'][:]) self._param2name = tos(f['param2name'][:]) self._param1 = f['param1'][:] self._param2 = f['param2'][:] self._nr = self._radius.size self._n1 = self._param1.size self._n2 = self._param2.size except: # Grid parameters not found... self._r = None self._param1name = None self._param2name = None self._param1 = None self._param2 = None for i in range(0, self.NORBITS): if self.CLASSIFICATION[i] != self.CLASS_DISCARDED: Jdtdrho = None if self.JACOBIAN is None else self.JACOBIAN[ i, :] self.ORBITS.append( Orbit(self.NT, self.T[i, :], self.XYZ[i, :], self.P[i, :], self.SOLUTION[i, :], self.PPAR[i, :], self.PPERP[i, :], self.P2[i, :], self.B[i, :], self.BABS[i, :], self.BHAT[i, :], Jdtdrho, self.CLASSIFICATION[i], wall=self.WALL)) else: self.ORBITS.append(None)
def get_orbits(filename, out_dir, areas, masses): f = open(filename) i = 0 orbits = [] line0 = f.readline() already_computed = [] files = listdir(out_dir) for file in files: already_computed.append(int(file.split('.')[0])) while line0 != '' and i != len(areas): # name name = line0.strip('\n') line1 = f.readline() line2 = f.readline() satellite = twoline2rv(line1, line2, wgs84) satellite.propagate(2017, 12, 1, 12, 00, 00) satellite_number = satellite.satnum inclination = satellite.inclo raan = satellite.nodeo eccentricity = satellite.ecco w = satellite.argpo mean_anomaly = satellite.mo mean_motion = satellite.no o = Orbit(name, satellite_number, inclination, raan, eccentricity, w, mean_anomaly, mean_motion, satellite.a * RE, areas[i], masses[i]) # orbital decay print("Computing satellite {}".format(o.satnum)) if not o.satnum in already_computed: P, t = compute_orbital_decay(orbits, o.a / 1000, o.eccentricity, o.area, o.mass) is_loaded = False else: print(" P loaded from {}.npz".format(o.satnum)) loaded = np.load(out_dir + str(o.satnum) + ".npz") P = loaded["P"] t = loaded["t"] loaded.close() is_loaded = True if t[-1] < MIN_ORBIT_TIME: print(" skipping satellite: {}".format(o.satnum)) del P, t, o else: if not is_loaded: np.savez_compressed(out_dir + "{}.npz".format(o.satnum), P=P, t=t) print(" saved file: {}.npz".format(o.satnum)) else: print(" already saved file: {}.npz".format(o.satnum)) i = i + 1 o.P = P orbits.append(o) line0 = f.readline() f.close() return np.array(orbits)
def orbit_from_pos_vel(pos, vel, center_body_mu=398600): # Cast vectors into numpy arrays for computational ease pos_inertial = np.array(pos) vel_inertial = np.array(vel) # Find magnitudes of position and velocity pos_mag = np.linalg.norm(pos_inertial) vel_mag = np.linalg.norm(vel_inertial) # Angular momentum angular_momentum_vector_inertial = np.cross(pos_inertial, vel_inertial) angular_momentum_mag = np.linalg.norm(angular_momentum_vector_inertial) h_hat = angular_momentum_vector_inertial / angular_momentum_mag line_of_nodes_vec = np.cross([0, 0, 1], angular_momentum_vector_inertial) # Flight path angles (double signed) (radians) gam_1 = np.arccos(angular_momentum_mag / (pos_mag * vel_mag)) gam_2 = -np.arccos(angular_momentum_mag / (pos_mag * vel_mag)) # Energy eps = np.linalg.norm( vel_inertial)**2 / 2 - center_body_mu / np.linalg.norm(pos_inertial) # Semi-Major Axis a = -center_body_mu / (2 * eps) # Eccentricity term_1 = (pos_mag * vel_mag**2 / center_body_mu - 1)**2 ecc = np.sqrt(term_1 * np.cos(gam_1)**2 + np.sin(gam_1)**2) ecc_vec = ( (vel_mag**2 - center_body_mu / pos_mag) * pos_inertial - np.dot(pos_inertial, vel_inertial) * vel_inertial) / center_body_mu if (ecc >= 1): print('Orbit is not closed') return -1 # True anomaly num = a * (1 - ecc**2) / pos_mag - 1 theta_star = np.arccos(num / ecc) # Inclination (projection of h onto z axis) inc = np.arccos(angular_momentum_vector_inertial[2] / angular_momentum_mag) * 180 / np.pi # Right angle to ascending node omega = np.arccos( line_of_nodes_vec[0] / np.linalg.norm(line_of_nodes_vec)) * 180 / np.pi if (line_of_nodes_vec[1]): omega = 360 - omega # Argument of perigee AOP = np.arccos( np.dot(line_of_nodes_vec, ecc_vec) / (np.linalg.norm(line_of_nodes_vec) * ecc)) # Check for NaN values for orbital elements if (ecc_vec[2] < 0): AOP = 360 - AOP if (math.isnan(AOP)): AOP = 0 if (math.isnan(omega)): omega = 0 if (math.isnan(inc)): inc = 0 # Generate orbit object orbit = Orbit(eccentricity=ecc, semiMajorAxis=a, inclination=inc, raan=omega, aop=AOP) return orbit
def orbit_from_pos_pos_p(r_1, r_2, p, mu=398600): # Changing vectors to numpy arrays to increase computational efficiency r_1 = np.array(r_1) r_2 = np.array(r_2) # Find magnitudes of both vectors r_1_mag = np.linalg.norm(r_1) r_2_mag = np.linalg.norm(r_2) # Solve for angular momentum h_hat = np.cross(r_1, r_2) / np.linalg.norm(np.cross(r_1, r_2)) # Use vector 1 for DCM resolution to find orbital parameters r_1_hat = r_1 / r_1_mag # h_hat cross r_1_hat will yield theta_1 hat by RHR theta_1_hat = np.cross(h_hat, r_1_hat) # Forming DCM DCM = np.matrix([r_1_hat, theta_1_hat, h_hat]).transpose() # Check to see if matrix is 2d if (DCM[0, 2] == 0 and DCM[1, 2] == 0 and DCM[2, 0] == 0 and DCM[2, 1] == 0): two_dim = True # Find Inclination inc = np.arccos(DCM[2, 2]) * 180 / np.pi if (inc < 0): inc = -inc # Find RAAN o1_1 = np.arcsin(DCM[0, 2] / np.sin(np.radians(inc))) * 180 / np.pi o1_2 = 180 - o1_1 omega_1 = [o1_1, o1_2] o2_1 = np.arccos(-DCM[1, 2] / np.sin(np.radians(inc))) * 180 / np.pi omega_2 = [o2_1, -o2_1] omega = -1 for omega1 in omega_1: for omega2 in omega_2: try: if nearly_equal(omega1, omega2): omega = omega1 except: omega = 0 # Find longitudinal anomaly ta_1 = np.arcsin(DCM[2, 0] / np.sin(np.radians(inc))) * 180 / np.pi ta_2 = 180 - ta_1 theta_a = [ta_1, ta_2] tb_1 = np.arccos(DCM[2, 1] / np.sin(np.radians(inc))) * 180 / np.pi theta_b = [tb_1, -tb_1] theta_1 = -1 for thetaA in theta_a: for thetaB in theta_b: try: if nearly_equal(thetaA, thetaB): theta_1 = thetaA except: theta_1 = 0 # Find f and g functions d_theta_star = np.arccos(np.dot(r_1, r_2) / (r_1_mag * r_2_mag)) * 180 / np.pi f = 1 - r_2_mag / p * (1 - np.cos(np.radians(d_theta_star))) g = r_1_mag * r_2_mag / np.sqrt(mu * p) * np.sin(np.radians(d_theta_star)) # Find velocity vector assoc. with r_1 vector v_1 = (r_2 - f * r_1) * 1 / g # Find whether satellite is ascending or descending (sign of Flight path angle) FPA_sign = 1 r1_dot = np.dot(v_1, r_1) / r_1_mag if r1_dot < 0: FPA_sign = -1 # Find remaining orbital elements v_1_mag = np.linalg.norm(v_1) sp_en = v_1_mag**2 / 2 - mu / r_1_mag # Semi-major axis a = -mu / (2 * sp_en) # Eccentricity ecc = np.sqrt(1 - p / a) # True anomalies theta_1_star = FPA_sign * np.arccos(1 / ecc * (p / r_1_mag - 1)) * 180 / np.pi theta_2_star = theta_1_star + d_theta_star # Argument of perigee AOP = theta_1 - theta_1_star # Create orbit object orbit = Orbit(eccentricity=ecc, semiMajorAxis=a, inclination=inc, raan=omega, aop=AOP) # Return orbit and two true anomalies return [orbit, theta_1_star, theta_2_star]
["Mercury", 0.38709893, 0.20563069, 7.00487, 48.33167, 77.45645, 252.25084], ["Venus", 0.72333199, 0.00677323, 3.39471, 76.68069, 131.53298, 181.97973], ["Earth", 1.00000011, 0.01671022, 0.00005, -11.26064, 102.94719, 100.46435], ["Mars", 1.52366231, 0.09341233, 1.85061, 49.57854, 336.04084, 355.45332], ["Jupiter", 5.20336301, 0.04839266, 1.30530, 100.55615, 14.75385, 34.40438], ["Saturn", 9.53707032, 0.05415060, 2.48446, 113.71504, 92.43194, 49.94432], ["Uranus", 19.19126393, 0.04716771, 0.76986, 74.22988, 170.96424, 313.23218], ["Neptune", 30.06896348, 0.00858587, 1.76917, 131.72169, 44.97135, 304.88003], ["Pluto", 39.48168677, 0.24880766, 17.14175, 110.30347, 224.06676, 238.92881] ] ss_planets = {} for name,a,e,i,LAN,long_peri,L0 in elements: planet = CelestialBody(name) planet.orbit = Orbit(primary=Sun) arg_peri = long_peri - LAN M0 = L0 - long_peri planet.orbit.from_elements(a=a*AU, e=e, i=i, arg=arg_peri, LAN=LAN, M=M0, time=J2000) ss_planets[name] = planet ss_planets["Earth"].mu = 3.986004418e14 ss_planets["Earth"].radius = 6370.0e3 Mercury = ss_planets["Mercury"] Venus = ss_planets["Venus"] Earth = ss_planets["Earth"] Mars = ss_planets["Mars"] Jupiter = ss_planets["Jupiter"] Saturn = ss_planets["Saturn"]
def addOrbit(self, textVars, xMax, yMax, topMenuRow, bottomMenuRow, initValues): self.orbits.append(Orbit(xMax, yMax, textVars, self.resolution, topMenuRow, bottomMenuRow, initValues, self.showFlightPath))