Skip to content
This repository has been archived by the owner on Nov 30, 2023. It is now read-only.

Format python code with black #503

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 41 additions & 35 deletions examples/filter_unused_stops.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,40 +24,46 @@


def main():
parser = optparse.OptionParser(
usage="usage: %prog [options] input_feed output_feed",
version="%prog "+transitfeed.__version__)
parser.add_option("-l", "--list_removed", dest="list_removed",
default=False,
action="store_true",
help="Print removed stops to stdout")
(options, args) = parser.parse_args()
if len(args) != 2:
print(parser.format_help(), file=sys.stderr)
print("\n\nYou must provide input_feed and output_feed\n\n", file=sys.stderr)
sys.exit(2)
input_path = args[0]
output_path = args[1]

loader = transitfeed.Loader(input_path)
schedule = loader.Load()

print("Removing unused stops...")
removed = 0
for stop_id, stop in schedule.stops.items():
if not stop.GetTrips(schedule):
removed += 1
del schedule.stops[stop_id]
if options.list_removed:
print("Removing %s (%s)" % (stop_id, stop.stop_name))
if removed == 0:
print("No unused stops.")
elif removed == 1:
print("Removed 1 stop")
else:
print("Removed %d stops" % removed)

schedule.WriteGoogleTransitFeed(output_path)
parser = optparse.OptionParser(
usage="usage: %prog [options] input_feed output_feed",
version="%prog " + transitfeed.__version__,
)
parser.add_option(
"-l",
"--list_removed",
dest="list_removed",
default=False,
action="store_true",
help="Print removed stops to stdout",
)
(options, args) = parser.parse_args()
if len(args) != 2:
print(parser.format_help(), file=sys.stderr)
print("\n\nYou must provide input_feed and output_feed\n\n", file=sys.stderr)
sys.exit(2)
input_path = args[0]
output_path = args[1]

loader = transitfeed.Loader(input_path)
schedule = loader.Load()

print("Removing unused stops...")
removed = 0
for stop_id, stop in schedule.stops.items():
if not stop.GetTrips(schedule):
removed += 1
del schedule.stops[stop_id]
if options.list_removed:
print("Removing %s (%s)" % (stop_id, stop.stop_name))
if removed == 0:
print("No unused stops.")
elif removed == 1:
print("Removed 1 stop")
else:
print("Removed %d stops" % removed)

schedule.WriteGoogleTransitFeed(output_path)


if __name__ == "__main__":
main()
main()
220 changes: 122 additions & 98 deletions examples/google_random_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@


def Distance(lat0, lng0, lat1, lng1):
"""
"""
Compute the geodesic distance in meters between two points on the
surface of the Earth. The latitude and longitude angles are in
degrees.
Expand All @@ -52,83 +52,91 @@ def Distance(lat0, lng0, lat1, lng1):
(see "When is it NOT okay to assume the Earth is a sphere?" in the
same faq).
"""
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat*0.5)
b = math.sin(dlng*0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c
deg2rad = math.pi / 180.0
lat0 = lat0 * deg2rad
lng0 = lng0 * deg2rad
lat1 = lat1 * deg2rad
lng1 = lng1 * deg2rad
dlng = lng1 - lng0
dlat = lat1 - lat0
a = math.sin(dlat * 0.5)
b = math.sin(dlng * 0.5)
a = a * a + math.cos(lat0) * math.cos(lat1) * b * b
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0 - a))
return 6367000.0 * c


def AddNoiseToLatLng(lat, lng):
"""Add up to 500m of error to each coordinate of lat, lng."""
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1)))
"""Add up to 500m of error to each coordinate of lat, lng."""
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (
lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_100m * 5 * (random.random() * 2 - 1)),
)


def GetRandomLocationsNearStops(schedule):
"""Return a list of (lat, lng) tuples."""
locations = []
for s in schedule.GetStopList():
locations.append(AddNoiseToLatLng(s.stop_lat, s.stop_lon))
return locations
"""Return a list of (lat, lng) tuples."""
locations = []
for s in schedule.GetStopList():
locations.append(AddNoiseToLatLng(s.stop_lat, s.stop_lon))
return locations


def GetRandomDatetime():
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0)
"""Return a datetime in the next week."""
seconds_offset = random.randint(0, 60 * 60 * 24 * 7)
dt = datetime.today() + timedelta(seconds=seconds_offset)
return dt.replace(second=0, microsecond=0)


def FormatLatLng(lat_lng):
"""Format a (lat, lng) tuple into a string for maps.google.com."""
return "%0.6f,%0.6f" % lat_lng
"""Format a (lat, lng) tuple into a string for maps.google.com."""
return "%0.6f,%0.6f" % lat_lng


def LatLngsToGoogleUrl(source, destination, dt):
"""Return a URL for routing between two (lat, lng) at a datetime."""
params = {"saddr": FormatLatLng(source),
"daddr": FormatLatLng(destination),
"time": dt.strftime("%I:%M%p"),
"date": dt.strftime("%Y-%m-%d"),
"dirflg": "r",
"ie": "UTF8",
"oe": "UTF8"}
url = urlparse.urlunsplit(("http", "maps.google.com", "/maps",
urllib.urlencode(params), ""))
return url
"""Return a URL for routing between two (lat, lng) at a datetime."""
params = {
"saddr": FormatLatLng(source),
"daddr": FormatLatLng(destination),
"time": dt.strftime("%I:%M%p"),
"date": dt.strftime("%Y-%m-%d"),
"dirflg": "r",
"ie": "UTF8",
"oe": "UTF8",
}
url = urlparse.urlunsplit(
("http", "maps.google.com", "/maps", urllib.urlencode(params), "")
)
return url


def LatLngsToGoogleLink(source, destination):
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source), FormatLatLng(destination),
dt.ctime())
"""Return a string "<a ..." for a trip at a random time."""
dt = GetRandomDatetime()
return "<a href='%s'>from:%s to:%s on %s</a>" % (
LatLngsToGoogleUrl(source, destination, dt),
FormatLatLng(source),
FormatLatLng(destination),
dt.ctime(),
)


def WriteOutput(title, locations, limit, f):
"""Write html to f for up to limit trips between locations.
"""Write html to f for up to limit trips between locations.

Args:
title: String used in html title
locations: list of (lat, lng) tuples
limit: maximum number of queries in the html
f: a file object
"""
output_prefix = """
output_prefix = (
"""
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Expand Down Expand Up @@ -163,34 +171,41 @@ def WriteOutput(title, locations, limit, f):
</ul>
If you find a problem be sure to save the URL. This file is generated randomly.
<ol>
""" % locals()
"""
% locals()
)

output_suffix = """
output_suffix = (
"""
</ol>
</body>
</html>
""" % locals()
"""
% locals()
)

f.write(transitfeed.EncodeUnicode(output_prefix))
for source, destination in zip(locations[0:limit], locations[1:limit + 1]):
f.write(transitfeed.EncodeUnicode("<li>%s\n" %
LatLngsToGoogleLink(source, destination)))
f.write(transitfeed.EncodeUnicode(output_suffix))
f.write(transitfeed.EncodeUnicode(output_prefix))
for source, destination in zip(locations[0:limit], locations[1 : limit + 1]):
f.write(
transitfeed.EncodeUnicode(
"<li>%s\n" % LatLngsToGoogleLink(source, destination)
)
)
f.write(transitfeed.EncodeUnicode(output_suffix))


def ParentAndBaseName(path):
"""Given a path return only the parent name and file name as a string."""
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename)
"""Given a path return only the parent name and file name as a string."""
dirname, basename = os.path.split(path)
dirname = dirname.rstrip(os.path.sep)
if os.path.altsep:
dirname = dirname.rstrip(os.path.altsep)
_, parentname = os.path.split(dirname)
return os.path.join(parentname, basename)


def main():
usage = \
"""%prog [options] <input GTFS.zip>
usage = """%prog [options] <input GTFS.zip>

Create an HTML page of random URLs for the Google Maps transit trip
planner. The queries go between places near stops listed in a <input GTFS.zip>.
Expand All @@ -200,37 +215,46 @@ def main():
https://github.com/google/transitfeed/wiki/GoogleRandomQueries
"""

parser = optparse.OptionParser(
usage=usage,
version="%prog "+transitfeed.__version__)
parser.add_option("-l", "--limit", dest="limit", type="int",
help="Maximum number of URLs to generate")
parser.add_option("-o", "--output", dest="output", metavar="HTML_OUTPUT_PATH",
help="write HTML output to HTML_OUTPUT_PATH")
parser.set_defaults(output="google_random_queries.html", limit=50)
(options, args) = parser.parse_args()
if len(args) != 1:
print(parser.format_help(), file=sys.stderr)
print("\n\nYou must provide the path of a single feed\n\n", file=sys.stderr)
sys.exit(2)
feed_path = args[0]

# ProblemReporter prints problems on console.
loader = transitfeed.Loader(feed_path, problems=transitfeed.ProblemReporter(),
load_stop_times=False)
schedule = loader.Load()
locations = GetRandomLocationsNearStops(schedule)
random.shuffle(locations)
agencies = ", ".join([a.agency_name for a in schedule.GetAgencyList()])
title = "%s (%s)" % (agencies, ParentAndBaseName(feed_path))

WriteOutput(title,
locations,
options.limit,
open(options.output, "w"))
print ("Load %s in your web browser. It contains more instructions." %
options.output)
parser = optparse.OptionParser(
usage=usage, version="%prog " + transitfeed.__version__
)
parser.add_option(
"-l",
"--limit",
dest="limit",
type="int",
help="Maximum number of URLs to generate",
)
parser.add_option(
"-o",
"--output",
dest="output",
metavar="HTML_OUTPUT_PATH",
help="write HTML output to HTML_OUTPUT_PATH",
)
parser.set_defaults(output="google_random_queries.html", limit=50)
(options, args) = parser.parse_args()
if len(args) != 1:
print(parser.format_help(), file=sys.stderr)
print("\n\nYou must provide the path of a single feed\n\n", file=sys.stderr)
sys.exit(2)
feed_path = args[0]

# ProblemReporter prints problems on console.
loader = transitfeed.Loader(
feed_path, problems=transitfeed.ProblemReporter(), load_stop_times=False
)
schedule = loader.Load()
locations = GetRandomLocationsNearStops(schedule)
random.shuffle(locations)
agencies = ", ".join([a.agency_name for a in schedule.GetAgencyList()])
title = "%s (%s)" % (agencies, ParentAndBaseName(feed_path))

WriteOutput(title, locations, options.limit, open(options.output, "w"))
print(
"Load %s in your web browser. It contains more instructions." % options.output
)


if __name__ == "__main__":
main()
main()
Loading