def get_star_position( recv_time, star_name, star_name2, user_longlatdist=geographic_position): # if not star_name: # star_name = 57632 #Denebola # if not star_name2: # star_name2 = 109074 #Sadalmelik user_longlatdist = np.array(user_longlatdist)#46.07983746062874, 26.232615661106784, 659.5100082775696 with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) planets = load('de421.bsp') earth = planets['earth'] user_position = earth + Topos('{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) #user_longlatdist user_longlatdist[0],user_longlatdist[1] terrestrial_time = format_time(recv_time) ts = load.timescale() t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5]) denebola = Star.from_dataframe(df.loc[star_name]) astrometric_denebola = user_position.at(t).observe(denebola) alt_d, az_d, distance_d = astrometric_denebola.apparent().altaz()#astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) print('S1 (alt/az): ',alt_d, az_d) star_pos_d = pm.aer2ecef( az_d.degrees,alt_d.degrees, distance_d.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2]) sadalmelik = Star.from_dataframe(df.loc[star_name2]) astrometric_sadalmelik = user_position.at(t).observe(sadalmelik) alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz() print('S2 (alt/az): ',alt_s, az_s) star_pos_s = pm.aer2ecef( az_s.degrees,alt_s.degrees, distance_s.m,user_longlatdist[0],user_longlatdist[1],user_longlatdist[2]) stars_pos=[star_pos_d,star_pos_s] return stars_pos
def get_stars_azimut_altitude(self, constellation): azimut_alt = list() for el in constellation: t = self.ts.now() #print(el[0] , " and " , el[1]) star = Star.from_dataframe(self.df.loc[el[0]]) star_next = Star.from_dataframe(self.df.loc[el[1]]) astro = self.position.at(t).observe(star) astro_next = self.position.at(t).observe(star_next) app = astro.apparent() app_next = astro_next.apparent() alt, az, distance = app.altaz() alt_next, az_next, distance_next = app_next.altaz() azimut_alt.append( ((az.dstr().split("deg", 1)[0], alt.dstr().split("deg", 1)[0]), (az_next.dstr().split("deg", 1)[0], alt_next.dstr().split("deg", 1)[0]))) return azimut_alt
def print_constellation(constellation): for el in constellation: #print(el[0] , " and " , el[1]) star = Star.from_dataframe(df.loc[el[0]]) star_prev = Star.from_dataframe(df.loc[el[1]]) astrometric_star = earth.at(t).observe(star) ra_s, dec_s, distance_s = astrometric_star.radec() astrometric_star_p = earth.at(t).observe(star_prev) ra_s_p, dec_s_p, distance_s_p = astrometric_star_p.radec() hours_s = list() hours_s.append(ra_s.hours) hours_s.append(ra_s_p.hours) deg_s = list() deg_s.append(dec_s.degrees) deg_s.append(dec_s_p.degrees) #print(hours_s[0], " and " , deg_s[0]) #print(hours_s[1], " and " , deg_s[1]) plt.plot(hours_s, deg_s, 'bo-', linewidth=2) #plt.scatter(ra.hours, dec.degrees, 8 - df['magnitude'], 'k') plt.show()
def get_probe_coords(hip_id, distance): # set timezone + load planet info utcTZ = timezone("UTC") local_tz = get_localzone() ts = load.timescale() planets = load('de421.bsp') # get time of observation and locations of observation t = ts.from_datetime(datetime(2020, 11, 9, 00, 00, tzinfo=utcTZ)) sun = planets['sun'] earth = planets['earth'] # load in the hipparcos data with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) # # match on star coords # ra_inds = [] # for ind, cat_ra in enumerate(df['ra_degrees'].values): # if isclose(cat_ra, ra_star, rel_tol=1e-2): # ra_inds.append(ind) # dec_inds = [] # for ind, cat_dec in enumerate(df['dec_degrees'].values): # if isclose(cat_dec, dec_star, rel_tol=1e-2): # dec_inds.append(ind) # # find where ra & dec match within tolerance # sets = set(ra_inds).intersection(set(dec_inds)) # inds = [x for x in iter(sets)] # print(inds) # just take the first one for now the_star = Star.from_dataframe(df.loc[hip_id]) # "observe" the star from Earth starPosObj = earth.at(t).observe(the_star) ra, dec, dist = starPosObj.radec() # get coords of opposite point on the sky ra = ((ra._degrees + 180.0) % 360) * (24.0 / 360.0) dec = -1.0 * dec._degrees # get coords of the probe and return ra dec in degree probe = position_of_radec(ra, dec, distance, t=t) sunPosObj = earth.at(t).observe(sun) inverseSunCoord = -1.0 * sunPosObj.position.au probeCoord = probe.position.au probeDir = ICRF(probeCoord + inverseSunCoord).radec() return probeDir[0]._degrees, probeDir[1]._degrees
def stellar_info(d): # used in starstab # returns a list of lists with name, SHA and Dec all navigational stars for epoch of date. t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0) #calculate at noon out = [] for line in db.strip().split('\n'): x1 = line.index(',') name = line[0:x1] HIPnum = line[x1 + 1:] star = Star.from_dataframe(df.loc[int(HIPnum)]) astrometric = earth.at(t12).observe(star).apparent() ra, dec, distance = astrometric.radec(epoch='date') sha = fmtgha(0, ra.hours) decl = fmtdeg(dec.degrees) out.append([name, sha, decl]) return out
def load_stars(max_magnitude, verbose=False): """Load the Hipparcos catalog data and find all applicable stars. Returns a list of StarObs, one per star. """ if verbose: print("[ CATALOG] Loading star catalog data.") with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) df = df[df['magnitude'] <= max_magnitude] df = df[df['ra_degrees'].notnull()] if verbose: print( f'[ CATALOG] Found {len(df)} stars brighter than magnitude {max_magnitude:.4f}.' ) return [ StarObs(str(idx), Star.from_dataframe(df.loc[idx]), df.loc[idx].magnitude) for idx in df.index ]
def mp_stellar_info(d, ts, df, n): # used in starstab # returns a list of lists with name, SHA and Dec all navigational stars for epoch of date. # load the Hipparcos catalog as a 118,218 row Pandas dataframe. #with load.open(hipparcos.URL) as f: #hipparcos_epoch = ts.tt(1991.25) # df = hipparcos.load_dataframe(f) eph = load(config.ephemeris[config.ephndx][0]) # load chosen ephemeris earth = eph['earth'] t00 = ts.ut1(d.year, d.month, d.day, 0, 0, 0) #calculate at midnight #t12 = ts.ut1(d.year, d.month, d.day, 12, 0, 0) #calculate at noon out = [] if n == 0: db = db1 elif n == 1: db = db2 elif n == 2: db = db3 elif n == 3: db = db4 elif n == 4: db = db5 else: db = db6 for line in db.strip().split('\n'): x1 = line.index(',') name = line[0:x1] HIPnum = line[x1 + 1:] star = Star.from_dataframe(df.loc[int(HIPnum)]) astrometric = earth.at(t00).observe(star).apparent() ra, dec, distance = astrometric.radec(epoch='date') sha = fmtgha(0, ra.hours) decl = fmtdeg(dec.degrees) out.append([name, sha, decl]) return out
edges = [edge for name, edges in constellations for edge in edges] edges_star1 = [star1 for star1, star2 in edges] edges_star2 = [star2 for star1, star2 in edges] # We will center the chart on the comet's middle position. center = earth.at(t).observe(comet) projection = build_stereographic_projection(center) field_of_view_degrees = 45.0 limiting_magnitude = 7.0 # Now that we have constructed our projection, compute the x and y # coordinates that each star and the comet will have on the plot. star_positions = earth.at(t).observe(Star.from_dataframe(stars)) stars['x'], stars['y'] = projection(star_positions) comet_x, comet_y = projection(earth.at(t_comet).observe(comet)) # Create a True/False mask marking the stars bright enough to be # included in our plot. And go ahead and compute how large their # markers will be on the plot. bright_stars = (stars.magnitude <= limiting_magnitude) magnitude = stars['magnitude'][bright_stars] marker_size = (0.5 + limiting_magnitude - magnitude) ** 2.0 # The constellation lines will each begin at the x,y of one star and end # at the x,y of another. We have to "rollaxis" the resulting coordinate # array into the shape that matplotlib expects.
def create_starmap(name, timestamp, days_past, days_future, fov, magnitude): # The comet is plotted on several dates `t_transient`. But the stars only # need to be drawn once, so we take the middle comet date as the single # time `t` we use for everything else. try: # first try comets d, transient = algorithms.get_comet(name, timestamp) except: # then try asteroids d, transient = algorithms.get_asteroid(name, timestamp) ts = load.timescale() t_timestamp = ts.utc(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, timestamp.minute) t_transient = ts.utc( timestamp.year, timestamp.month, range(timestamp.day - days_past, timestamp.day + days_future)) t = t_transient[len(t_transient) // 2] # middle date # An ephemeris from the JPL provides Sun and Earth positions. eph = load('de421.bsp') earth = eph['earth'] # The Hipparcos mission provides our star catalog. # with load.open(hipparcos.URL) as f: with load.open(settings.MY_HIPPARCOS_URL) as f: stars = hipparcos.load_dataframe(f) # And the constellation outlines come from Stellarium. We make a list # of the stars at which each edge stars, and the star at which each edge # ends. url = ('https://raw.githubusercontent.com/Stellarium/stellarium/master' '/skycultures/western_SnT/constellationship.fab') with load.open(url) as f: constellations = stellarium.parse_constellations(f) edges = [edge for name, edges in constellations for edge in edges] edges_star1 = [star1 for star1, star2 in edges] edges_star2 = [star2 for star1, star2 in edges] # We will center the chart on the comet's middle position. center = earth.at(t).observe(transient) #star = Star(ra_hours=(17, 57, 48.49803), dec_degrees=(4, 41, 36.2072)) #center = earth.at(t).observe(star) projection = build_stereographic_projection(center) field_of_view_degrees = float(fov) limiting_magnitude = magnitude # Now that we have constructed our projection, compute the x and y # coordinates that each star and the comet will have on the plot. star_positions = earth.at(t).observe(Star.from_dataframe(stars)) stars['x'], stars['y'] = projection(star_positions) transient_x, transient_y = projection( earth.at(t_transient).observe(transient)) # Create a True/False mask marking the stars bright enough to be # included in our plot. And go ahead and compute how large their # markers will be on the plot. bright_stars = (stars.magnitude <= limiting_magnitude) magnitude = stars['magnitude'][bright_stars] marker_size = (0.5 + limiting_magnitude - magnitude)**2.0 # The constellation lines will each begin at the x,y of one star and end # at the x,y of another. We have to "rollaxis" the resulting coordinate # array into the shape that matplotlib expects. xy1 = stars[['x', 'y']].loc[edges_star1].values xy2 = stars[['x', 'y']].loc[edges_star2].values lines_xy = np.rollaxis(np.array([xy1, xy2]), 1) # Time to build the figure! fig, ax = plt.subplots(figsize=[12, 12]) # Draw the constellation lines. ax.add_collection(LineCollection(lines_xy, colors='#00f2')) # Draw the stars. ax.scatter(stars['x'][bright_stars], stars['y'][bright_stars], s=marker_size, color='k') # Draw the comet positions, and label them with dates. transient_color = '#f00' offset = 0.0005 ax.plot(transient_x, transient_y, '+', c=transient_color, zorder=3) for xi, yi, tstr in zip(transient_x, transient_y, t_transient.utc_strftime('%m/%d')): tstr = tstr.lstrip('0') text = ax.text(xi + offset, yi - offset, tstr, color=transient_color, ha='left', va='top', fontsize=9, weight='bold', zorder=-1) text.set_alpha(0.5) # Finally, title the plot and set some final parameters. angle = np.pi - field_of_view_degrees / 360.0 * np.pi limit = np.sin(angle) / (1.0 - np.cos(angle)) ax.set_xlim(-limit, limit) ax.set_ylim(-limit, limit) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(1.0) ax.set_title('{} {} through {}'.format( d['designation'], t_transient[0].utc_strftime('%d %B %Y'), t_transient[-1].utc_strftime('%d %B %Y'), )) # Save. filename = 'starmap.png' path = os.path.join(settings.MEDIA_ROOT, filename) fig.savefig(path, bbox_inches='tight') image_url = os.path.join(settings.MEDIA_URL, filename) return image_url
boston = earth + Topos('42.3583 N', '71.0603 W') astro = boston.at(ts.utc(1980, 3, 1)).observe(mars) app = astro.apparent() alt, az, distance = app.altaz() print(alt.dstr()) print(az.dstr()) print(distance) # Measure a star with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) barnards_star = Star.from_dataframe(df.loc[87937]) planets = load('de421.bsp') earth = planets['earth'] ts = load.timescale() t = ts.now() astrometric = boston.at(t).observe(barnards_star) app_b = astrometric.apparent() alt_b, az_b, distance_b = app_b.altaz() print("Bernard star") print(alt_b.dstr()) print(az_b.dstr()) print(distance)
object = json.loads(sys.argv[3]) executionTime = int(sys.argv[4]) # setting up redis redis = redis.Redis(host="localhost", port=6379) pubsub = redis.pubsub(ignore_subscribe_messages=True) pubsub.subscribe("astro_calculator") # loading all nedeed info for astro calculations timescale = load.timescale() planets = load("de421.bsp") with load.open("hip_main.dat") as f: stars = hipparcos.load_dataframe(f) if object["type"] == "star": trackedObject = Star.from_dataframe(stars.loc[int(object["id"])]) elif object["type"] == "planet": trackedObject = planets[object["id"]] earth = planets["earth"] place = earth + wgs84.latlon(lat * N, long * E) # main loop that transmits data to arduino serial port while True: message = pubsub.get_message() if message: if (message["data"].decode("utf-8")) == "stop": print("Execution stopped with redis message from server") break currentTime = timescale.now()
from utils.declination_presenter import declination_presenter import utils.constants with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) HYP_POLARIS_IDENTIFIER = 11767 arg_parser = argparse.ArgumentParser() arg_parser.add_argument("--latitude") arg_parser.add_argument("--longitude") arg_parser.add_argument("--elevation") arg_parser.add_argument("--datetime") args = arg_parser.parse_args() polaris = Star.from_dataframe(df.loc[HYP_POLARIS_IDENTIFIER]) polaris_ra = polaris.ra polaris_dec = polaris.dec eph = load("de421.bsp") earth = eph["earth"] ts = load.timescale(builtin=True) observation_datetime = datetime.strptime( args.datetime, utils.constants.DATETIME_FORMAT).replace(tzinfo=utc) observation_time = ts.utc(observation_datetime) observer_topos = Topos( latitude_degrees=round(float(args.latitude), utils.constants.COORDINATES_PRECISION), longitude_degrees=round(float(args.longitude),
def galactic_Sun_north_center_SD_directions( measurement_date, recv_time, user_longlatdist=geographic_position, prints=False): user_longlatdist = np.array(user_longlatdist) with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) planets = load('de421.bsp') earth = planets['earth'] user_position = earth + Topos( '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1]) ) #user_longlatdist user_longlatdist[0],user_longlatdist[1] terrestrial_time = format_time_auto(measurement_date, recv_time) ts = load.timescale() t = ts.tt(terrestrial_time[0], terrestrial_time[1], terrestrial_time[2], terrestrial_time[3], terrestrial_time[4], terrestrial_time[5]) sun = planets['sun'] astrometric_sun = user_position.at(t).observe(sun) alt_sun, az_sun, distance_sun = astrometric_sun.apparent().altaz( ) #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() sun_position = pm.aer2ecef(az_sun.degrees, alt_sun.degrees, distance_sun.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) # Északi Galaktikus Pólus (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) coma_berenices = Star(ra_hours=(12, 51, 25.2), dec_degrees=(27, 7, 48.0)) astrometric_berenice = user_position.at(t).observe(coma_berenices) alt_b, az_b, distance_b = astrometric_berenice.apparent().altaz() berenice_position = pm.aer2ecef(az_b.degrees, alt_b.degrees, distance_b.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) # Galaktikus Center (RA: 12h 51.42m; D: 27° 07.8′, epocha J2000.0) 17h 45.6m −28.94° galactic_center = Star(ra_hours=(17, 45, 36.0), dec_degrees=(-28, 56, 24.0)) astrometric_center = user_position.at(t).observe(galactic_center) alt_c, az_c, distance_c = astrometric_center.apparent().altaz() center_position = pm.aer2ecef(az_c.degrees, alt_c.degrees, distance_c.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) nunki = Star.from_dataframe(df.loc[92855]) astrometric_nunki = user_position.at(t).observe(nunki) alt_n, az_n, distance_n = astrometric_nunki.apparent().altaz( ) #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() star_pos_n = pm.aer2ecef(az_n.degrees, alt_n.degrees, distance_n.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) capella = Star.from_dataframe(df.loc[24608]) astrometric_capella = user_position.at(t).observe(capella) alt_ca, az_ca, distance_ca = astrometric_capella.apparent().altaz( ) #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() star_pos_ca = pm.aer2ecef(az_ca.degrees, alt_ca.degrees, distance_ca.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) denebola = Star.from_dataframe(df.loc[57632]) astrometric_denebola = user_position.at(t).observe(denebola) alt_d, az_d, distance_d = astrometric_denebola.apparent().altaz( ) #astrometric.apparent().altaz() = astrometric_denebola.apparent().altaz() star_pos_d = pm.aer2ecef(az_d.degrees, alt_d.degrees, distance_d.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) sadalmelik = Star.from_dataframe(df.loc[109074]) astrometric_sadalmelik = user_position.at(t).observe(sadalmelik) alt_s, az_s, distance_s = astrometric_sadalmelik.apparent().altaz() star_pos_s = pm.aer2ecef(az_s.degrees, alt_s.degrees, distance_s.m, user_longlatdist[0], user_longlatdist[1], user_longlatdist[2]) if prints: print('Time: ', terrestrial_time) print('Location: ', '{} N'.format(user_longlatdist[0]), '{} E'.format(user_longlatdist[1])) print('Sun (alt/az): ', alt_sun, az_sun) print('Coma Berenice (alt/az): ', alt_b, az_b) print('Galactic Center (alt/az): ', alt_c, az_c) print('Nunki (alt/az): ', alt_n, az_n) print('Capella (alt/az): ', alt_ca, az_ca) print('Denebola (alt/az): ', alt_d, az_d) print('Sadalmelik (alt/az): ', alt_s, az_s) stars_pos = [ sun_position, berenice_position, center_position, star_pos_n, star_pos_ca, star_pos_d, star_pos_s ] return stars_pos
plt.style.use(['dark_background']) with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) ts = load.timescale() t = ts.now() eph = load('de421.bsp') earth = eph['earth'] print(f'There are {len(df)} stars in the Hipparcos catalog ({hipparcos.URL}).') limiting_magnitude = 5.0 df_lim = df[df['magnitude'] <= limiting_magnitude] print(f'After filtering out stars dimmer than mag {limiting_magnitude}, there are {len(df_lim)}') bright_stars = Star.from_dataframe(df_lim) df_lim['magnitude'].min() fig, ax = plt.subplots(5, figsize=(10,48)) for mag in range(1,6): df_lim = df[df['magnitude'] <= mag] bright_stars = Star.from_dataframe(df_lim) astrometric = earth.at(t).observe(bright_stars) ra, dec, distance = astrometric.radec() ax[mag-1].scatter(ra.hours, dec.degrees, 2*(5-df_lim['magnitude']), 'w') ax[mag-1].set_xlim(7.0, 4.0) ax[mag-1].set_ylim(-20, 20) ax[mag-1].grid(color='gray', linestyle='-', linewidth=.5, alpha=.5) ax[mag-1].set(title=f'Stars in Orion brighter than magnitude {mag}') ax[mag-1].set_xlabel('right ascension') ax[mag-1].set_ylabel('declination')
timezoneString = searchEngine.timezone_at(lng=location.longitude, lat=location.latitude) # Update the datetime config['datetime'].replace(tzinfo=timezone(timezoneString)) timestamp = timescale.from_datetime(config['datetime']) # The Hipparcos mission provides our star catalog. with load.open(hipparcos.URL) as file: stars = hipparcos.load_dataframe(file) # Now that we have constructed our projection, compute the x and y # coordinates that each star and the comet will have on the plot. star_positions = location.at(timestamp).observe(Star.from_dataframe(stars)) with warnings.catch_warnings(): warnings.simplefilter('ignore') alt, az, _ = star_positions.apparent().altaz() star_centers = SCALE * np.stack( stereographicProjection(alt.radians, az.radians + np.pi)).T def brightness(magnitude): return 20 * 100**(-0.02 * magnitude) star_markers = brightness(stars['magnitude'].values) star_markers -= brightness(config['output']['max_magnitude']) # Normalise bright, = np.where(
# Create a True/False mask marking the stars bright enough to be # included in our plot. And go ahead and compute how large their # markers will be on the plot. from time import time print('Total stars:', stars.shape) t0 = time() #bright_stars = (stars.magnitude <= limiting_magnitude) print(time() - t0, 's to filter all stars on 1 var') #magnitude = stars['magnitude'] #[bright_stars] # Now that we have constructed our projection, compute the x and y # coordinates that each star and the comet will have on the plot. star_positions = barycenter.observe(Star.from_dataframe(stars)) def set_positions(): #t0 = time() stars['x'], stars['y'] = projection(star_positions) #print(time() - t0) set_positions() def run(): # Time to build the figure! fig, ax = plt.subplots(figsize=[9, 9]) # Draw the stars.
def create_starmap(command, observation_id): # The comet is plotted on several dates `t_comet`. But the stars only # need to be drawn once, so we take the middle comet date as the single # time `t` we use for everything else. ts = load.timescale() t_comet = ts.utc(2020, 8, range(1, 10)) t = t_comet[len(t_comet) // 2] # middle date # An ephemeris from the JPL provides Sun and Earth positions. eph = load('de421.bsp') sun = eph['sun'] earth = eph['earth'] # The Minor Planet Center data file provides the comet orbit. with load.open(mpc.COMET_URL) as f: comets = mpc.load_comets_dataframe(f) comets = (comets.sort_values('reference') .groupby('designation', as_index=False).last() .set_index('designation', drop=False)) row = comets.loc['C/2020 F3 (NEOWISE)'] comet = sun + mpc.comet_orbit(row, ts, GM_SUN) # The Hipparcos mission provides our star catalog. # with load.open(hipparcos.URL) as f: with load.open(settings.MY_HIPPARCOS_URL) as f: stars = hipparcos.load_dataframe(f) # And the constellation outlines come from Stellarium. We make a list # of the stars at which each edge stars, and the star at which each edge # ends. url = ('https://raw.githubusercontent.com/Stellarium/stellarium/master' '/skycultures/western_SnT/constellationship.fab') with load.open(url) as f: constellations = stellarium.parse_constellations(f) edges = [edge for name, edges in constellations for edge in edges] edges_star1 = [star1 for star1, star2 in edges] edges_star2 = [star2 for star1, star2 in edges] # We will center the chart on the comet's middle position. center = earth.at(t).observe(comet) projection = build_stereographic_projection(center) field_of_view_degrees = 30.0 limiting_magnitude = 8.0 # Now that we have constructed our projection, compute the x and y # coordinates that each star and the comet will have on the plot. star_positions = earth.at(t).observe(Star.from_dataframe(stars)) stars['x'], stars['y'] = projection(star_positions) comet_x, comet_y = projection(earth.at(t_comet).observe(comet)) # Create a True/False mask marking the stars bright enough to be # included in our plot. And go ahead and compute how large their # markers will be on the plot. bright_stars = (stars.magnitude <= limiting_magnitude) magnitude = stars['magnitude'][bright_stars] marker_size = (0.5 + limiting_magnitude - magnitude) ** 2.0 # The constellation lines will each begin at the x,y of one star and end # at the x,y of another. We have to "rollaxis" the resulting coordinate # array into the shape that matplotlib expects. xy1 = stars[['x', 'y']].loc[edges_star1].values xy2 = stars[['x', 'y']].loc[edges_star2].values lines_xy = np.rollaxis(np.array([xy1, xy2]), 1) # Time to build the figure! fig, ax = plt.subplots(figsize=[9, 9]) # Draw the constellation lines. ax.add_collection(LineCollection(lines_xy, colors='#00f2')) # Draw the stars. ax.scatter(stars['x'][bright_stars], stars['y'][bright_stars], s=marker_size, color='k') # Draw the comet positions, and label them with dates. comet_color = '#f00' offset = 0.002 ax.plot(comet_x, comet_y, '+', c=comet_color, zorder=3) for xi, yi, tstr in zip(comet_x, comet_y, t_comet.utc_strftime('%m/%d')): tstr = tstr.lstrip('0') text = ax.text(xi + offset, yi - offset, tstr, color=comet_color, ha='left', va='top', fontsize=9, weight='bold', zorder=-1) text.set_alpha(0.5) # Finally, title the plot and set some final parameters. angle = np.pi - field_of_view_degrees / 360.0 * np.pi limit = np.sin(angle) / (1.0 - np.cos(angle)) ax.set_xlim(-limit, limit) ax.set_ylim(-limit, limit) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_aspect(1.0) ax.set_title('Comet NEOWISE {} through {}'.format( t_comet[0].utc_strftime('%Y %B %d'), t_comet[-1].utc_strftime('%Y %B %d'), )) # Save. filename = 'starmap.png' path = os.path.join(settings.MEDIA_ROOT, filename) fig.savefig(path, bbox_inches='tight') image_url = os.path.join(settings.MEDIA_URL, filename) return image_url
#vega #vega_star = Star.from_dataframe(df.loc[91262]) #astrometric = earth.at(t).observe(vega_star) #c = SkyCoord('00 42 30 +41 12 00', unit=(u.hourangle, u.deg)) # ra, dec, distance = astrometric.radec() # print(ra.hours) # print("vega", ra.hours*15, dec.degrees, distance) stars_ra = [] stars_dec = [] #big bear constellation #Dubhe d_star = Star.from_dataframe(df.loc[54061]) a1 = earth.at(t).observe(d_star) ra, dec, distance = a1.radec() stars_ra.append(ra.hours * 15) stars_dec.append(dec.degrees) #Merek me_star = Star.from_dataframe(df.loc[53910]) a2 = earth.at(t).observe(me_star) ra, dec, distance = a2.radec() stars_ra.append(ra.hours * 15) stars_dec.append(dec.degrees) #Phecda ph_star = Star.from_dataframe(df.loc[58001]) a3 = earth.at(t).observe(ph_star)
print(""" from dataclasses import dataclass @dataclass class Star: ra: float dec: float hipparcos: int @dataclass class SkyPoint: ra: float dec: float """) print() print('STARS = [') #ALL_STARS = [5372] for n in ALL_STARS: if df.loc[n].magnitude >= 5: # ignore faint stars continue s = Star.from_dataframe(df.loc[n]) s.magnitude = df.loc[n].magnitude if np.isnan(s.ra.radians) or np.isnan(s.dec.radians): continue print(' %s,' % star(s, n)) print(']')
def index(request): stars = [] if request.body: req = json.loads(request.body) if req['type'] == 'GET_VISIBLE_STARS': planets = load('de421.bsp') earth = planets['earth'] ts = load.timescale() dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ') dt = dt.replace(tzinfo=timezone.utc) t = ts.utc(dt) observerLocation = earth + \ Topos(latitude_degrees=req['lat'], longitude_degrees=req['long']) with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) for key in navigationStarsHip: starname = key hipNo = navigationStarsHip[key] star = Star.from_dataframe(df.loc[hipNo]) apparent = observerLocation.at(t).observe(star).apparent() alt, az, dist = apparent.altaz() eachStar = { 'name': key, 'hip': navigationStarsHip[key], 'alt': alt.degrees, 'az': az.degrees, 'dist': dist.km } if eachStar['alt'] > 0 : stars.append(eachStar) if req['type'] == 'GET_TBRG_STAR': planets = load('de421.bsp') earth = planets['earth'] ts = load.timescale() dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ') dt = dt.replace(tzinfo=timezone.utc) t = ts.utc(dt) observerLocation = earth + \ Topos(latitude_degrees=req['lat'], longitude_degrees=req['long']) with load.open(hipparcos.URL) as f: df = hipparcos.load_dataframe(f) starname = req['selectedStar'] hipNo = navigationStarsHip[starname] star = Star.from_dataframe(df.loc[hipNo]) apparent = observerLocation.at(t).observe(star).apparent() alt, az, dist = apparent.altaz() return JsonResponse({ 'name': starname, 'hipNo': navigationStarsHip[starname], 'alt': alt.degrees, 'az': az.degrees, 'dist': dist.km }) if (req['type'] == 'GET_TBRG_PLANET'): planets = load('de421.bsp') earth = planets['earth'] ts = load.timescale() dt = datetime.strptime(req['date'], '%Y-%m-%dT%H:%M:%S.%fZ') dt = dt.replace(tzinfo=timezone.utc) t = ts.utc(dt) observerLocation = earth + \ Topos(latitude_degrees=req['lat'], longitude_degrees=req['long']) planet = planets[req['body']] apparent = observerLocation.at(t).observe(planet).apparent() alt, az, dist = apparent.altaz() return JsonResponse({ "alt": alt.degrees, "az": az.degrees, "dist": dist.km })