def get_lla(t): orb = Orbital("TJREVERB", tle_file=(Path(__file__).parent.resolve() / "tjreverb_tle.txt")) return ({ 'lat': orb.get_lonlatalt(t)[0], 'lon': orb.get_lonlatalt(t)[1], 'alt': orb.get_lonlatalt(t)[2] })
def _get_avhrr_tiepoints(self, scan_points, scanline_nb): sgeom = avhrr(scanline_nb, scan_points, apply_offset=False) # no attitude error rpy = [0, 0, 0] s_times = sgeom.times(self.times[:, np.newaxis]) orb = Orbital(self.platform_name) pixels_pos = compute_pixels(orb, sgeom, s_times, rpy) lons, lats, alts = get_lonlatalt(pixels_pos, s_times) return lons, lats
def runProp(): #orb = Orbital(tle) orb = Orbital("TJREVERB", tle_file="FILE PATH TO TLE") now = datetime.utcnow() #print(tle.inclination) #print(orb.get_position(now)) print(orb.get_lonlatalt(now)) print() print(orb.get_next_passes(now, 12, -77.10428, 8.88101, 276, tol=0.001, horizon=0))
def create_orbital_track_shapefile_for_day(year, month, day, step_minutes, tle_line1, tle_line2, output_shapefile): try: orb = Orbital("N", tle_file=None, line1=tle_line1, line2=tle_line2) except (ChecksumError): print 'Invalid TLE' return 2 try: year = int(year) month = int(month) day = int(day) step_minutes = float(step_minutes) except: print 'Invalid date' return 3 w = shapefile.Writer(shapefile.POINT) w.field('ID', 'C', 40) w.field('TIME', 'C', 40) w.field('LAT', 'C', 40) w.field('LON', 'C', 40) i = 0 minutes = 0 while minutes < 1440: utc_hour = int(minutes // 60) utc_minutes = int((minutes - (utc_hour * 60)) // 1) utc_seconds = int(round( (minutes - (utc_hour * 60) - utc_minutes) * 60)) utc_string = str(utc_hour) + '-' + str(utc_minutes) + '-' + str( utc_seconds) utc_time = datetime.datetime(year, month, day, utc_hour, utc_minutes, utc_seconds) lon, lat, alt = orb.get_lonlatalt(utc_time) w.point(lon, lat) w.record(str(i), utc_string, str(lat), str(lon)) i += 1 minutes += step_minutes try: prj = open("%s.prj" % output_shapefile.replace('.shp', ''), "w") epsg = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]' prj.write(epsg) prj.close() w.save(output_shapefile) except: print 'Unable to save shapefile' return 4
def update_satellite(self, satellite): """Update satellite and renew the orbital instance. """ if satellite != self._satellite: self._satellite = satellite if self._tle_files is not None: filelist = glob(self._tle_files) tle_file = max(filelist, key=lambda x: os.stat(x).st_mtime) else: tle_file = None self._orbital = Orbital(self._satellite.upper(), tle_file)
def ground_truth(lat, lon, time, sat, duration): orb = Orbital(sat, tle_file="active.txt") delta = timedelta(seconds=1) azs = [] els = [] for i in range(duration): az, el = pwm_for(*orb.get_observer_look(time, lon, lat, 0)) azs.append(az) els.append(el) time += delta return azs, els
def __init__(self,name,file): self.file = file self.orbital = Orbital(name,file) self.xyz=[[],[],[]] self.now = datetime.now() self.position = self.orbital.get_position(self.now,False) for i in range(0,2000): self.now += timedelta(seconds=4) position = self.orbital.get_position(self.now,False) for i in range(0,3): self.xyz[i].append(position[0][i])
def serial_az_el(name, stop_time=( datetime.utcnow())): # sends data over serial to arduino format (az, el) satellite = Orbital(name, tle_file=nextPass.path_to_tle) now = datetime.utcnow() while int( (stop_time - now).total_seconds()) >= 0: # while pass is occurring now = datetime.utcnow() print( satellite.get_observer_look(now, nextPass.lon, nextPass.lat, nextPass.alt)) # print (az, el) sleep(2) # wait 2 seconds
def test_63(self): """Check that no runtimewarning is raised, #63.""" import warnings from pyorbital.orbital import Orbital from dateutil import parser warnings.filterwarnings('error') orb = Orbital("Suomi-NPP", line1="1 37849U 11061A 19292.84582509 .00000011 00000-0 25668-4 0 9997", line2="2 37849 98.7092 229.3263 0000715 98.5313 290.6262 14.19554485413345") orb.get_next_passes(parser.parse("2019-10-21 16:00:00"), 12, 123.29736, -13.93763, 0) warnings.filterwarnings('default')
def get_valid_orbit(platform_name, epoch): orb_nums = [] for tle_file in sorted(get_files(), reverse=True): try: orb = Orbital(platform_name, tle_file=tle_file) except AttributeError: continue except ChecksumError: continue orb_nums.append(orb.get_orbit_number(epoch)) return int(round(np.median(orb_nums)))
def track(): # tle = tlefile.read('ISS', 'orbit.txt') orbit = Orbital('ISS', 'Telescope/orbit.txt') while True: now = datetime.utcnow() # print(now) coords = (orbit.get_position(now)[0]) # print(orbit.get_lonlatalt(now)) # print(coords) print(convertCartesianToRaDec(coords[0], coords[1], coords[2])) time.sleep(1)
def __init__(self): self.ground_lat = EARTH_STATION_LAT self.ground_long = EARTH_STATION_LONG self.observer = ephem.Observer() self.observer.lat = self.ground_lat self.observer.long = self.ground_long self.observer.date = datetime.utcnow() self.tle = IN_TLE_FILE self.tles = [] self.satellite_name = TRK_SATELLITE self.orb = Orbital(self.satellite_name, tle_file=self.tle)
def tleCheck(self): if self.tle_file is not None: try: orb = Orbital(self.satName, tle_file=self.tle_file) except KeyError: print( "Satalite Not Found Offline, Check Satalite Exists In TLE File" ) sys.exit(0) else: try: orb = Orbital(self.satName) except KeyError: print("Satalite Not Found Online, Try Using -custom-tle") sys.exit(0) return orb
def __init__(self, tle_dict): if isinstance(tle_dict, list): self.line1 = tle_dict[0] self.line2 = tle_dict[1] self.line3 = tle_dict[2] else: self.line1 = tle_dict['line1'] self.line2 = tle_dict['line2'] self.line3 = tle_dict['line3'] self.pyOrbital = Orbital(self.line1, line1=self.line2, line2=self.line3)
def update_graph_live(n): satellite = Orbital('TERRA') data = {'time': [], 'Latitude': [], 'Longitude': [], 'Altitude': []} # Collect some data for i in range(180): time = datetime.datetime.now() - datetime.timedelta(seconds=i * 20) lon, lat, alt = satellite.get_lonlatalt(time) data['Longitude'].append(lon) data['Latitude'].append(lat) data['Altitude'].append(alt) data['time'].append(time) # Create the graph with subplots fig = plotly.tools.make_subplots(rows=3, cols=1, vertical_spacing=0.2) fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10} fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'} fig.append_trace( { 'x': data['time'], 'y': data['Altitude'], 'name': 'Altitude', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) fig.append_trace( { 'x': data['Longitude'], 'y': data['Latitude'], 'text': data['time'], 'name': 'Longitude vs Latitude', 'mode': 'lines+markers', 'type': 'scatter' }, 2, 1) df = px.data.iris() fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='petal_length', size='petal_length', size_max=18, symbol='species', opacity=0.7) # tight layout fig.update_layout(margin=dict(l=0, r=0, b=0, t=0)) return fig
def get_lonlat(scene, row, col): """Get the longitutes and latitudes for the give *rows* and *cols*. """ try: filename = get_filename(scene, "granules") except IOError: #from mpop.satin.eps1a import get_lonlat_avhrr # return get_lonlat_avhrr(scene, row, col) from pyorbital.orbital import Orbital import pyproj from datetime import timedelta start_time = scene.time_slot end_time = scene.time_slot + timedelta(minutes=3) orbital = Orbital("METOP-A") track_start = orbital.get_lonlatalt(start_time) track_end = orbital.get_lonlatalt(end_time) geod = pyproj.Geod(ellps='WGS84') az_fwd, az_back, dist = geod.inv(track_start[0], track_start[1], track_end[0], track_end[1]) del dist M02_WIDTH = 2821885.8962408099 pos = ((col - 1024) * M02_WIDTH) / 2048.0 if row > 520: lonlatdist = geod.fwd(track_end[0], track_end[1], az_back - 86.253533216206648, -pos) else: lonlatdist = geod.fwd(track_start[0], track_start[1], az_fwd - 86.253533216206648, pos) return lonlatdist[0], lonlatdist[1] try: if scene.lons is None or scene.lats is None: records, form = read_raw(filename) mdrs = [record[1] for record in records if record[0] == "mdr"] sphrs = [record for record in records if record[0] == "sphr"] sphr = sphrs[0][1] scene.lons, scene.lats = _get_lonlats(mdrs, sphr, form) return scene.lons[row, col], scene.lats[row, col] except AttributeError: records, form = read_raw(filename) mdrs = [record[1] for record in records if record[0] == "mdr"] sphrs = [record for record in records if record[0] == "sphr"] sphr = sphrs[0][1] scene.lons, scene.lats = _get_lonlats(mdrs, sphr, form) return scene.lons[row, col], scene.lats[row, col]
def get_angles(self): """Get azimuth and zenith angles. Azimuth angle definition is the same as in pyorbital, but with different units (degrees not radians for sun azimuth angles) and different ranges. Returns: sat_azi: satellite azimuth angle degree clockwise from north in range ]-180, 180], sat_zentih: satellite zenith angles in degrees in range [0,90], sun_azi: sun azimuth angle degree clockwise from north in range ]-180, 180], sun_zentih: sun zenith angles in degrees in range [0,90], rel_azi: absolute azimuth angle difference in degrees between sun and sensor in range [0, 180] """ self.get_times() self.get_lonlat() tle1, tle2 = self.get_tle_lines() times = self.times orb = Orbital(self.spacecrafts_orbital[self.spacecraft_id], line1=tle1, line2=tle2) sat_azi, sat_elev = orb.get_observer_look(times[:, np.newaxis], self.lons, self.lats, 0) sat_zenith = 90 - sat_elev sun_zenith = astronomy.sun_zenith_angle(times[:, np.newaxis], self.lons, self.lats) alt, sun_azi = astronomy.get_alt_az(times[:, np.newaxis], self.lons, self.lats) del alt sun_azi = np.rad2deg(sun_azi) rel_azi = get_absolute_azimuth_angle_diff(sun_azi, sat_azi) # Scale angles range to half open interval ]-180, 180] sat_azi = centered_modulus(sat_azi, 360.0) sun_azi = centered_modulus(sun_azi, 360.0) # Mask corrupt scanlines for arr in (sat_azi, sat_zenith, sun_azi, sun_zenith, rel_azi): arr[self.mask] = np.nan return sat_azi, sat_zenith, sun_azi, sun_zenith, rel_azi
def orbitpos(file_name, names, date): orbit = [] cont = 0 for nam in names: try: orb = Orbital(nam, file_name) orbit.append( [nam, orb.get_lonlatalt(date), orb.get_position(date)]) #altitudine in km da terra #pos normalizata r_sat/r_terra except: cont += 1 print(nam, cont) return orbit
def get_parallaxed_coor(sat, tle, t, lat, lon, alt, h): """ """ # Setup orbital class with TLE file orbit = Orbital(sat, line1=tle.line1, line2=tle.line2) pos = orbit.get_position(t) # Calculate observer azimuth and elevation azi, ele = orbit.get_observer_look(t, lon, lat, alt) # Apply parallax correction for given heights x, y, z = parallax_corr(h, azi, ele) # WGS84 parameters f = 1 / 298.257223563 a = 6378137. # Convert coordinates and azimuth to radians radlat = np.deg2rad(lat) radlon = np.deg2rad(lon) radazi = np.deg2rad(azi) # Calculate shifted point coordinates nlat, nlon, nazi = vinc_pt(f, a, radlat, radlon, radazi, z) # Reconvert to degree nlat = np.rad2deg(nlat) nlon = np.rad2deg(nlon) nazi = np.rad2deg(nazi) info = "\n--------------------------------------------------------" + \ "\n ----- Parallax correction summary -----" +\ "\n--------------------------------------------------------" + \ "\n Satellite Name: " + sat + \ "\n Observation Time: " + \ datetime.datetime.strftime(t, "%Y-%m-%d %H:%M:%S") + \ "\n Satellite Position: " + str(pos[0]) + \ "\n Satellite Velocity: " + str(pos[1]) + \ "\n-----------------------------------" + \ "\n Latitude: " + str(lat) + \ "\n Longitude: " + str(lon) + \ "\n Altitude: " + \ str(alt) + "\n Height: " + str(h) + \ "\n-----------------------------------" +\ "\n Azimuth: " + str(azi) + \ "\n Elevation: " + str(ele) + \ "\n Parallax Distance: " + str(z) + \ "\n New Latitude: " + str(nlat) + \ "\n New Longitude: " + str(nlon) + \ "\n--------------------------------------------------------" logger.debug(info) return(z, nlat, nlon)
def on_opened(self, event): fname = os.path.split(event.src_path)[1] if self._file is None and fnmatch(fname, self._file_pattern): logger.debug("Opening: " + event.src_path) self._filename = event.src_path self._file = open(event.src_path, "rb") self._where = 0 self._satellite = " ".join(event.src_path.split("_")[1:3])[:-5] if self._tle_files is not None: filelist = glob(self._tle_files) tle_file = max(filelist, key=lambda x: os.stat(x).st_mtime) else: tle_file = None self._orbital = Orbital(self._satellite, tle_file)
def loadAll(self): # read satellite TLE data and store by satellite ID with open(self.TLE_DB, 'r') as dbFile: while dbFile: header = dbFile.readline().rstrip() if not header: break line1 = dbFile.readline().rstrip() line2 = dbFile.readline().rstrip() name = header try: orb = Orbital(name, line1=line1, line2=line2) satID = orb.tle.satnumber self.orbByID[satID] = orb except: #print "Failed to create TLE for", name pass # read satellite communication parameters with open(self.SAT_DB, 'r') as dbFile: for line in dbFile: line = line.rstrip() fields = line.split(';') name = fields[0] satID = fields[1] uplink = fields[2].rstrip() downlink = fields[3].rstrip() beacon = fields[4].rstrip() mode = fields[5].rstrip() status = fields[7].rstrip() if satID: self.satByID[satID] = (uplink, downlink, beacon, mode, status, name) #else: #print "Ignoring", name, satID, status #if status == 'active' or status == 'Operational': #print name, name in self.orbByName #if name in nameFix: # name = nameFix[name] # print name # Intersection of satellites with TLE info and comms info self.satIDs = set(self.orbByID.keys()) & set(self.satByID.keys()) #missing = set(self.satByID.keys()) - set(self.orbByID.keys()) #print ', '.join(sorted([self.orbByID[x].satellite_name for x in self.satIDs])) return
def __init__(self, name, speed=60, orbit_count=1, swath_color=(255, 0, 0, 127), track_color=(255, 255, 255, 200), swath_width=10000): self.name = name self.orbit = Orbital(name) self.NUM_STEPS = 255 self.speed = speed self.orbit_count = orbit_count self.swath_width = swath_width # Styling self.swath_color = swath_color self.track_color = track_color
def generate_points_per_satellite(satellite, start, end): orb = Orbital(satellite) point_list = [] increment_in_minutes = 0.25 increment = datetime.timedelta(minutes=float(increment_in_minutes)) while start < end: lon, lat, alt = orb.get_lonlatalt(start) point_list.append([lat, lon, alt, str(start)]) start += increment light_list = [] for j in range((len(point_list)) - 1): if point_list[j][0] >= point_list[j + 1][0]: light_list.append(point_list[j]) return light_list
def get_view_zen_angles(sat_name, tle_filename, area_def_name, time_slot): """Calculate the satellite zenith angles for the given satellite (*sat_name*, *tle_filename*), *area_def_name* and *time slot*. Stores the result in the given *cache* parameter. """ try: from pyorbital.orbital import Orbital except ImportError: LOGGER.warning("Could not load pyorbital modules") return area_def = get_area_def(area_def_name) lons, lats = area_def.get_lonlats() orbital_obj = Orbital(sat_name, tle_filename) elevation = orbital_obj.get_observer_look(time_slot, lons, lats, 0)[1] view_zen_data = np.subtract(90, np.ma.masked_outside(elevation, 0, 90)) return view_zen_data
def getSentinel2Geometry(startDateUTC, lengthDays, lat, lon, alt=0.0, mission="Sentinel-2a", tleFile="../TLE/norad_resource_tle.txt"): """Calculate approximate geometry for Sentinel overpasses. Approximate because it assumes maximum satellite elevation is the time at which target is imaged. :param startDateUTC: a datetime object specifying when to start prediction. :type startDateUTC: object :param lengthDays: number of days over which to perform calculations. :type lengthDays: int :param lat: latitude of target. :type lat: float :param lon: longitude of target. :type lon: float :param alt: altitude of target (in km). :type alt: float :param mission: mission name as in TLE file. :type mission: str :param tleFile: TLE file. :type tleFile: str :return: a python list containing instances of the sensorGeometry class arranged in date order. :rtype: list """ orb = Orbital(mission, tleFile) passes = orb.get_next_passes(startDateUTC, 24 * lengthDays, lon, lat, alt) geomList = [] for p in passes: look = orb.get_observer_look(p[2], lon, lat, alt) vza = 90 - look[1] vaa = look[0] sza = ast.sun_zenith_angle(p[2], lon, lat) saa = np.rad2deg(ast.get_alt_az(p[2], lon, lat)[1]) if sza < 90 and vza < 10.3: thisGeom = sensorGeometry() thisGeom.date_utc = p[2] thisGeom.vza = vza thisGeom.vaa = vaa thisGeom.sza = sza thisGeom.saa = saa geomList.append(thisGeom) return geomList
def actuate_sats(): """ Use external library to get positions of requested satellites. Create new Satellite (look at models) object if there is no satellite with found name, or update existing satellite if it's already in the DB :return: None - only create/update/do nothing on DB objects """ for name in SAT_NAME: try: orb = Orbital(name) now = datetime.utcnow() # Get longitude, latitude and altitude of the satellite geo_position = orb.get_lonlatalt(now) print("Found {} - {}".format(name, geo_position)) try: if Satellite.objects.get(name=name): # if there is satellite with such name -> update info sat = Satellite.objects.get(name=name) # save past position sat_hist = SatHistory.objects.create(name=sat.name, longi=sat.longi, lati=sat.lati, alti=sat.alti) sat_hist.save() # update to actual position sat.longi = geo_position[0] sat.lati = geo_position[1] sat.alti = geo_position[2] sat.date = datetime.utcnow() sat.save() sat.hist = SatHistory.objects.filter(name=name) sat.save() except ObjectDoesNotExist: # if there is no satellite with such name # creating is possible sat = Satellite.objects.create(name=name, longi=geo_position[0], lati=geo_position[1], alti=geo_position[2] ) sat.save() # if there is no satellite with such name in sources except (KeyError, NotImplementedError): print('No satellite name found in the sources: {}'.format(name))
def update_graph_live(n): satellite = Orbital('TERRA') data = { 'time': [], 'Latitude': [], 'Longitude': [], 'Altitude': [] } # Collect some data for i in range(180): time = datetime.datetime.now() - datetime.timedelta(seconds=i*20) lon, lat, alt = satellite.get_lonlatalt( time ) data['Longitude'].append(lon) data['Latitude'].append(lat) data['Altitude'].append(alt) data['time'].append(time) # Create the graph with subplots fig = plotly.tools.make_subplots(rows=2, cols=1, vertical_spacing=0.2) fig['layout']['margin'] = { 'l': 30, 'r': 10, 'b': 30, 't': 10 } fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'} fig.append_trace({ 'x': data['time'], 'y': data['Altitude'], 'name': 'Altitude', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) fig.append_trace({ 'x': data['Longitude'], 'y': data['Latitude'], 'text': data['time'], 'name': 'Longitude vs Latitude', 'mode': 'lines+markers', 'type': 'scatter' }, 2, 1) return fig
def granule_inside_area(start_time, end_time, platform_name, instrument, area_def, thr_area_coverage, tle_file=None): """Check if a satellite data granule is over area interest, using the start and end times from the filename """ try: metop = Orbital(platform_name, tle_file) except KeyError: LOG.exception( 'Failed getting orbital data for {0}'.format(platform_name)) LOG.critical( 'Cannot determine orbit! Probably TLE file problems...\n' + 'Granule will be set to be inside area of interest disregarding') return True tle1 = metop.tle.line1 tle2 = metop.tle.line2 mypass = Pass(platform_name, start_time, end_time, instrument=instrument, tle1=tle1, tle2=tle2) acov = mypass.area_coverage(area_def) LOG.debug("Granule coverage of area %s: %f", area_def.area_id, acov) is_inside = (acov > thr_area_coverage) if is_inside: from pyresample.boundary import AreaDefBoundary from trollsched.drawing import save_fig area_boundary = AreaDefBoundary(area_def, frequency=100) area_boundary = area_boundary.contour_poly save_fig(mypass, poly=area_boundary, directory='/tmp') return
def update_graph_live(n): satellite = Orbital("TERRA") data = {"time": [], "Latitude": [], "Longitude": [], "Altitude": []} # Collect some data for i in range(180): time = datetime.datetime.now() - datetime.timedelta(seconds=i * 20) lon, lat, alt = satellite.get_lonlatalt(time) data["Longitude"].append(lon) data["Latitude"].append(lat) data["Altitude"].append(alt) data["time"].append(time) # Create the graph with subplots fig = plotly.tools.make_subplots(rows=2, cols=1, vertical_spacing=0.2) fig["layout"]["margin"] = {"l": 30, "r": 10, "b": 30, "t": 10} fig["layout"]["legend"] = {"x": 0, "y": 1, "xanchor": "left"} fig.append_trace( { "x": data["time"], "y": data["Altitude"], "name": "Altitude", "mode": "lines+markers", "type": "scatter", }, 1, 1, ) fig.append_trace( { "x": data["Longitude"], "y": data["Latitude"], "text": data["time"], "name": "Longitude vs Latitude", "mode": "lines+markers", "type": "scatter", }, 2, 1, ) return fig
def get_f_elev(satellite): """Get the elevation function for a given satellite """ if tle_files is not None: filelist = glob(tle_files) tle_file = max(filelist, key=lambda x: os.stat(x).st_mtime) else: tle_file = None orb = Orbital(satellite.upper(), tle_file) def f_elev(utctime): """Get the elevation for the given *utctime*. """ return orb.get_observer_look(utctime, *coords)[1] f_elev.satellite = satellite return f_elev