Skip to content

Commit

Permalink
Merge 503b8cd into 7cae87f
Browse files Browse the repository at this point in the history
  • Loading branch information
mraspaud committed Apr 27, 2018
2 parents 7cae87f + 503b8cd commit c56e436
Show file tree
Hide file tree
Showing 6 changed files with 359 additions and 187 deletions.
19 changes: 14 additions & 5 deletions trollsched/boundary.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,10 @@ def contour_poly(self):
np.deg2rad(np.vstack(self.contour()).T))
return self._contour_poly

def draw(self, mapper, options):
def draw(self, mapper, options, **more_options):
"""Draw the current boundary on the *mapper*
"""
self.contour_poly.draw(mapper, options)
self.contour_poly.draw(mapper, options, **more_options)


class AreaBoundary(Boundary):
Expand Down Expand Up @@ -130,16 +130,25 @@ def get_instrument_points(self, overpass, utctime,
scan_angle = 55.37
if instrument == "modis":
scan_angle = 55.0
instrument = "avhrr"
elif instrument == "viirs":
scan_angle = 55.84
instrument = "avhrr"
elif instrument == "iasi":
scan_angle = 48.3
instrument = "avhrr"
elif overpass.satellite == "noaa 16":
scan_angle = 55.25
instrument = "avhrr"
instrument = "avhrr"

instrument_fun = getattr(geoloc_instrument_definitions, instrument)
sgeom = instrument_fun(scans_nb, scanpoints,
scan_angle=scan_angle, frequency=frequency)

if instrument == "olci":
sgeom = instrument_fun(scans_nb, scanpoints)
else:
sgeom = instrument_fun(scans_nb, scanpoints,
scan_angle=scan_angle, frequency=frequency)

times = sgeom.times(utctime)

pixel_pos = geoloc.compute_pixels((self.orb.tle._line1,
Expand Down
34 changes: 17 additions & 17 deletions trollsched/combine.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def count_neq_passes(pl):
for s, g in graphs.items():
logger.debug("station: %s, order: %d", s, g.order)

# Graphs and allpasses are hashmaps of sets, or similar, but we need
# Graphs and allpasses are hashmaps of sets, or similar, but we need
# lists of lists, forthat they are copied.
grl = []
pl = []
Expand Down Expand Up @@ -197,8 +197,8 @@ def overlap_any(this, test_list):
try:
gn = g.neighbours(passes_list[statnr].index(p[0]) + 1)
except:
print "len(passes_list)", len(passes_list), " len(graph_set)", len(graph_set), " statnr", statnr, " p", p
print "passes_list", passes_list
print("len(passes_list)", len(passes_list), " len(graph_set)", len(graph_set), " statnr", statnr, " p", p)
print("passes_list", passes_list)
raise

if gn[0] > len(passes_list[statnr]):
Expand Down Expand Up @@ -276,13 +276,13 @@ def overlap_any(this, test_list):
bufflist.append(cc)

else:
print "uh-oh, something curious happened ..."
print("uh-oh, something curious happened ...")

except:
print "\nCATCH\ngn:", gn, "-> n", n, " col:", col, "-> cx", cx, "statnr", statnr, "statnr+i", statnr + 1
print "len(passes_list -n -cx)", len(passes_list[statnr]), len(passes_list[statnr + 1])
print("\nCATCH\ngn:", gn, "-> n", n, " col:", col, "-> cx", cx, "statnr", statnr, "statnr+i", statnr + 1)
print("len(passes_list -n -cx)", len(passes_list[statnr]), len(passes_list[statnr + 1]))
for s in range(statnr, len(passes_list)):
print "passes_list[", s, "] =>", passes_list[s]
print("passes_list[", s, "] =>", passes_list[s])
raise

return bufflist
Expand Down Expand Up @@ -320,10 +320,10 @@ def print_matrix(m, ly=-1, lx=-1):
the last lx columns from the last ly rows.
"""
for i, l in zip(range(ly), m[0:ly]):
print i, ":", l[:lx], "..."
print "[..., ...]"
print(i, ":", l[:lx], "...")
print("[..., ...]")
for i, l in zip(range(len(m) - ly - 1, len(m) - 1), m[-ly:]):
print i, ": ...", l[-lx:]
print(i, ": ...", l[-lx:])


def test_folding(g):
Expand All @@ -335,7 +335,7 @@ def test_folding(g):
for u in range(g.order):
for n in g.neighbours(u):
if n < u:
print n, "<", u
print(n, "<", u)
r = True
return r

Expand Down Expand Up @@ -398,7 +398,7 @@ def test_folding(g):
}
dir_output = build_filename("dir_output", pattern, pattern_args)
if not os.path.exists(dir_output):
print dir_output, "does not exist!"
print(dir_output, "does not exist!")
sys.exit(1)
ph = open(os.path.join(dir_output, "opts.pkl"), "rb")
opts = pickle.load(ph)
Expand Down Expand Up @@ -428,14 +428,14 @@ def test_folding(g):
from trollsched.schedule import conflicting_passes
totpas = []
for s, sp in allpasses.items():
print "len(sp)", s, len(sp)
print("len(sp)", s, len(sp))
totpas.extend(list(sp))
passes = sorted(totpas, key=lambda x: x.risetime)
cpg = conflicting_passes(passes, timedelta(seconds=600))
print "ALLPASSES", len(allpasses) # ,allpasses
print "PASSES", len(passes) # ,passes
print "CONFLGRPS", len(cpg) # ,cpg
print "MAX", max([len(g) for g in cpg])
print("ALLPASSES", len(allpasses)) # ,allpasses
print("PASSES", len(passes)) # ,passes
print("CONFLGRPS", len(cpg)) # ,cpg
print("MAX", max([len(g) for g in cpg]))

combined_stations(opts, pattern, station_list, graph, allpasses, start_time, start, forward)

Expand Down
52 changes: 28 additions & 24 deletions trollsched/satpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import operator
import os
import socket
import urlparse
import urllib
from datetime import datetime, timedelta
from tempfile import mkstemp

Expand Down Expand Up @@ -86,7 +86,11 @@ class SimplePass(object):
buffer = timedelta(minutes=2)

def __init__(self, satellite, risetime, falltime):
self.satellite = satellite
if not hasattr(satellite, 'name'):
from trollsched.schedule import Satellite
self.satellite = Satellite(satellite, 0, 0)
else:
self.satellite = satellite
self.risetime = risetime
self.falltime = falltime
self.score = {}
Expand Down Expand Up @@ -116,7 +120,7 @@ def __eq__(self, other):
# or if the later is not available
# b) the time difference between rise- and fall-times.
if other is not None and isinstance(self, Pass) and isinstance(other, Pass):
return (self.satellite == other.satellite and
return (self.satellite.name == other.satellite.name and
self.orb.get_orbit_number(self.risetime) == other.orb.get_orbit_number(other.risetime))
tol = timedelta(seconds=1)
return (other is not None and
Expand All @@ -125,7 +129,7 @@ def __eq__(self, other):
self.satellite == other.satellite)

def __str__(self):
return (self.satellite + " "
return (self.satellite.name + " "
+ self.risetime.isoformat() + " " + self.falltime.isoformat())

def __repr__(self):
Expand Down Expand Up @@ -236,7 +240,7 @@ def save_fig(self, poly=None, directory="/tmp/plots",
logger.debug("Create plot dir " + directory)
os.makedirs(directory)
filename = os.path.join(directory,
(rise + self.satellite.replace(" ", "_") + fall + extension))
(rise + self.satellite.name.replace(" ", "_") + fall + extension))

self.fig = filename
if not overwrite and os.path.exists(filename):
Expand Down Expand Up @@ -275,10 +279,10 @@ def show(self, poly=None, labels=None, other_poly=None, proj=None):
plt.figtext(*label[0], **label[1])
plt.show()

def draw(self, mapper, options):
def draw(self, mapper, options, **more_options):
"""Draw the pass to the *mapper* object (basemap).
"""
self.boundary.contour_poly.draw(mapper, options)
self.boundary.contour_poly.draw(mapper, options, **more_options)

def print_vcs(self, coords):
"""Should look like this::
Expand Down Expand Up @@ -314,7 +318,7 @@ def print_vcs(self, coords):
"{duration:>4.1f}",
]
line = " ".join(line_list).format(
satellite=self.satellite.upper(),
satellite=self.satellite.name.upper(),
orbit=self.orb.get_orbit_number(self.risetime),
risetime=self.risetime.strftime("%Y%m%d %H%M%S"),
falltime=self.falltime.strftime("%Y%m%d %H%M%S"),
Expand All @@ -328,13 +332,13 @@ def print_vcs(self, coords):
HOST = "ftp://is.sci.gsfc.nasa.gov/ancillary/ephemeris/schedule/%s/downlink/"


def get_aqua_terra_dumps_from_ftp(start_time, end_time, satorb, sat_name):
logger.info("Fetch %s dump info from internet" % sat_name)
url = urlparse.urlparse(HOST % sat_name)
def get_aqua_terra_dumps_from_ftp(start_time, end_time, satorb, sat):
logger.info("Fetch %s dump info from internet" % sat.name)
url = urllib.urlparse(HOST % sat.name)
logger.debug("Connect to ftp server")
try:
f = ftplib.FTP(url.netloc)
except (socket.error, socket.gaierror), e:
except (socket.error, socket.gaierror) as e:
logger.error('cannot reach to %s ' % HOST + str(e))
f = None

Expand All @@ -351,7 +355,7 @@ def get_aqua_terra_dumps_from_ftp(start_time, end_time, satorb, sat_name):
data = []
try:
f.dir(url.path, data.append)
except socket.error, e:
except socket.error as e:
logger.error("Can't get any data: " + str(e))
f.quit()
f = None
Expand Down Expand Up @@ -395,7 +399,7 @@ def get_aqua_terra_dumps_from_ftp(start_time, end_time, satorb, sat_name):
los = datetime.strptime(los, "%Y:%j:%H:%M:%S")
if los >= start_time and aos <= end_time:
uptime = aos + (los - aos) / 2
overpass = Pass(sat_name, aos, los, satorb, uptime, "modis")
overpass = Pass(sat, aos, los, satorb, uptime, "modis")
overpass.station = station
overpass.max_elev = elev
dumps.append(overpass)
Expand Down Expand Up @@ -424,21 +428,21 @@ def get_next_passes(satellites, utctime, forward, coords, tle_file=None, aqua_te
tlefile.fetch(tle_file)

for sat in satellites:
satorb = orbital.Orbital(sat, tle_file=tle_file)
orbitals[sat] = satorb
satorb = orbital.Orbital(sat.name, tle_file=tle_file)
orbitals[sat.name] = satorb
passlist = satorb.get_next_passes(utctime,
forward,
*coords)
if sat.lower().startswith("metop") or sat.lower().startswith("noaa"):
if sat.name.lower().startswith("metop") or sat.name.lower().startswith("noaa"):
instrument = "avhrr"
elif sat in ["aqua", "terra"]:
elif sat.name in ["aqua", "terra"]:
instrument = "modis"
elif sat.endswith("npp"):
elif sat.name.endswith("npp") or sat.name.startswith("jpss"):
instrument = "viirs"
else:
instrument = "unknown"
# take care of metop-a
if sat == "metop-a":
if sat.name == "metop-a":
metop_passes = [Pass(sat, rtime, ftime, satorb, uptime, instrument)
for rtime, ftime, uptime in passlist if rtime < ftime]

Expand All @@ -452,7 +456,7 @@ def get_next_passes(satellites, utctime, forward, coords, tle_file=None, aqua_te
if overpass.seconds() > MIN_PASS * 60:
passes["metop-a"].append(overpass)
# take care of aqua (dumps in svalbard and poker flat)
elif sat in ["aqua", "terra"] and aqua_terra_dumps:
elif sat.name in ["aqua", "terra"] and aqua_terra_dumps:

wpcoords = (-75.457222, 37.938611, 0)
passlist_wp = satorb.get_next_passes(utctime - timedelta(minutes=30),
Expand Down Expand Up @@ -539,7 +543,7 @@ def get_next_passes(satellites, utctime, forward, coords, tle_file=None, aqua_te
if pf_pass not in used_pf:
dumps.append(pf_pass)

passes[sat] = []
passes[sat.name] = []
for overpass in aqua_passes:
add = True
for dump_pass in dumps:
Expand All @@ -562,10 +566,10 @@ def get_next_passes(satellites, utctime, forward, coords, tle_file=None, aqua_te
add = False
logger.debug("skipping " + str(overpass))
if add and overpass.seconds() > MIN_PASS * 60:
passes[sat].append(overpass)
passes[sat.name].append(overpass)

else:
passes[sat] = [Pass(sat, rtime, ftime, satorb, uptime, instrument)
passes[sat.name] = [Pass(sat, rtime, ftime, satorb, uptime, instrument)
for rtime, ftime, uptime in passlist
if ftime - rtime > timedelta(minutes=MIN_PASS)]

Expand Down

0 comments on commit c56e436

Please sign in to comment.