1 """Contains various object definitions needed by the weather utility."""
3 weather_copyright = """\
4 # Copyright (c) 2006-2020 Jeremy Stanley <fungi@yuggoth.org>. Permission to
5 # use, copy, modify, and distribute this software is granted under terms
6 # provided in the LICENSE file distributed with this software.
9 weather_version = "2.4"
11 radian_to_km = 6372.795484
12 radian_to_mi = 3959.871528
14 def pyversion(ref=None):
15 """Determine the Python version and optionally compare to a reference."""
17 ver = platform.python_version()
20 int(x) for x in ver.split(".")[:2]
22 int(x) for x in ref.split(".")[:2]
27 """An object to contain selection data."""
29 """Store the config, options and arguments."""
30 self.config = get_config()
31 self.options, self.arguments = get_options(self.config)
32 if self.get_bool("cache") and self.get_bool("cache_search") \
33 and not self.get_bool("longlist"):
34 integrate_search_cache(
39 if not self.arguments:
40 if "id" in self.options.__dict__ \
41 and self.options.__dict__["id"]:
42 self.arguments.append( self.options.__dict__["id"] )
43 del( self.options.__dict__["id"] )
45 message = "WARNING: the --id option is deprecated and will eventually be removed\n"
46 sys.stderr.write(message)
47 elif "city" in self.options.__dict__ \
48 and self.options.__dict__["city"] \
49 and "st" in self.options.__dict__ \
50 and self.options.__dict__["st"]:
51 self.arguments.append(
53 self.options.__dict__["city"],
54 self.options.__dict__["st"]
57 del( self.options.__dict__["city"] )
58 del( self.options.__dict__["st"] )
60 message = "WARNING: the --city/--st options are deprecated and will eventually be removed\n"
61 sys.stderr.write(message)
62 def get(self, option, argument=None):
63 """Retrieve data from the config or options."""
65 if self.config.has_section(argument) and (
66 self.config.has_option(argument, "city") \
67 or self.config.has_option(argument, "id") \
68 or self.config.has_option(argument, "st")
70 self.config.remove_section(argument)
72 message = "WARNING: the city/id/st options are now unsupported in aliases\n"
73 sys.stderr.write(message)
74 if not self.config.has_section(argument):
77 path=self.get("setpath"),
78 info=self.get("info"),
80 self.get("cache") and self.get("cache_search")
82 cachedir=self.get("cachedir"),
83 quiet=self.get_bool("quiet")
85 self.config.add_section(argument)
86 for item in guessed.items():
87 self.config.set(argument, *item)
88 if self.config.has_option(argument, option):
89 return self.config.get(argument, option)
90 if option in self.options.__dict__:
91 return self.options.__dict__[option]
94 message = "%s error: no URI defined for %s\n" % (
95 os.path.basename( sys.argv[0] ),
98 sys.stderr.write(message)
100 def get_bool(self, option, argument=None):
101 """Get data and coerce to a boolean if necessary."""
102 return bool(self.get(option, argument))
103 def getint(self, option, argument=None):
104 """Get data and coerce to an integer if necessary."""
105 value = self.get(option, argument)
106 if value: return int(value)
110 """Average a list of coordinates."""
117 return (x/count, y/count)
119 def filter_units(line, units="imperial"):
120 """Filter or convert units in a line of text between US/UK and metric."""
122 # filter lines with both pressures in the form of "X inches (Y hPa)" or
125 "(.* )(\d*(\.\d+)? (inches|in\. Hg)) \((\d*(\.\d+)? hPa)\)(.*)",
129 preamble, in_hg, i_fr, i_un, hpa, h_fr, trailer = dual_p.groups()
130 if units == "imperial": line = preamble + in_hg + trailer
131 elif units == "metric": line = preamble + hpa + trailer
132 # filter lines with both temperatures in the form of "X F (Y C)"
134 "(.* )(-?\d*(\.\d+)? F) \((-?\d*(\.\d+)? C)\)(.*)",
138 preamble, fahrenheit, f_fr, celsius, c_fr, trailer = dual_t.groups()
139 if units == "imperial": line = preamble + fahrenheit + trailer
140 elif units == "metric": line = preamble + celsius + trailer
141 # if metric is desired, convert distances in the form of "X mile(s)" to
143 if units == "metric":
144 imperial_d = re.match(
145 "(.* )(\d+)( mile\(s\))(.*)",
149 preamble, mi, m_u, trailer = imperial_d.groups()
150 line = preamble + str(int(round(int(mi)*1.609344))) \
151 + " kilometer(s)" + trailer
152 # filter speeds in the form of "X MPH (Y KT)" to just "X MPH"; if metric is
153 # desired, convert to "Z KPH"
154 imperial_s = re.match(
155 "(.* )(\d+)( MPH)( \(\d+ KT\))(.*)",
159 preamble, mph, m_u, kt, trailer = imperial_s.groups()
160 if units == "imperial": line = preamble + mph + m_u + trailer
161 elif units == "metric":
162 line = preamble + str(int(round(int(mph)*1.609344))) + " KPH" + \
164 imperial_s = re.match(
165 "(.* )(\d+)( MPH)( \(\d+ KT\))(.*)",
169 preamble, mph, m_u, kt, trailer = imperial_s.groups()
170 if units == "imperial": line = preamble + mph + m_u + trailer
171 elif units == "metric":
172 line = preamble + str(int(round(int(mph)*1.609344))) + " KPH" + \
174 # if imperial is desired, qualify given forcast temperatures like "X F"; if
175 # metric is desired, convert to "Y C"
176 imperial_t = re.match(
177 "(.* )(High |high |Low |low )(\d+)(\.|,)(.*)",
181 preamble, parameter, fahrenheit, sep, trailer = imperial_t.groups()
182 if units == "imperial":
183 line = preamble + parameter + fahrenheit + " F" + sep + trailer
184 elif units == "metric":
185 line = preamble + parameter \
186 + str(int(round((int(fahrenheit)-32)*5/9))) + " C" + sep \
188 # hand off the resulting line
198 """Return a string containing the results of a URI GET."""
200 import urllib, urllib.error, urllib.request
201 URLError = urllib.error.URLError
202 urlopen = urllib.request.urlopen
204 import urllib2 as urllib
205 URLError = urllib.URLError
206 urlopen = urllib.urlopen
209 dcachedir = os.path.join( os.path.expanduser(cachedir), "datacache" )
210 if not os.path.exists(dcachedir):
211 try: os.makedirs(dcachedir)
212 except (IOError, OSError): pass
213 dcache_fn = os.path.join(
215 uri.split(":")[1].replace("/","_")
218 if cache_data and os.access(dcache_fn, os.R_OK) \
219 and now-cacheage < os.stat(dcache_fn).st_mtime <= now:
220 dcache_fd = open(dcache_fn)
221 data = dcache_fd.read()
225 if pyversion("3"): data = urlopen(uri).read().decode("utf-8")
226 else: data = urlopen(uri).read()
228 if ignore_fail: return ""
230 import os, sys, traceback
231 message = "%s error: failed to retrieve\n %s\n %s" % (
232 os.path.basename( sys.argv[0] ),
234 traceback.format_exception_only(
239 sys.stderr.write(message)
241 # Some data sources are HTML with the plain text wrapped in pre tags
243 data = data[data.find("<pre>")+5:data.find("</pre>")]
247 dcache_fd = codecs.open(dcache_fn, "w", "utf-8")
248 dcache_fd.write(data)
250 except (IOError, OSError): pass
264 """Return a summarized METAR for the specified station."""
267 message = "%s error: METAR URI required for conditions\n" % \
268 os.path.basename( sys.argv[0] )
269 sys.stderr.write(message)
273 cache_data=cache_data,
277 if pyversion("3") and type(metar) is bytes: metar = metar.decode("utf-8")
278 if verbose: return metar
281 lines = metar.split("\n")
284 "relative_humidity," \
285 + "precipitation_last_hour," \
286 + "sky conditions," \
292 headerlist = headers.lower().replace("_"," ").split(",")
295 title = "Current conditions at %s"
296 place = lines[0].split(", ")
298 place = "%s, %s" % ( place[0].title(), place[1] )
299 else: place = "<UNKNOWN>"
300 output.append(title%place)
301 output.append("Last updated " + lines[1])
303 for header in headerlist:
305 if line.lower().startswith(header + ":"):
306 if re.match(r".*:\d+$", line): line = line[:line.rfind(":")]
307 if imperial: line = filter_units(line, units="imperial")
308 elif metric: line = filter_units(line, units="metric")
309 if quiet: output.append(line)
310 else: output.append(" " + line)
314 "(no conditions matched your header list, try with --verbose)"
316 return "\n".join(output)
326 """Return alert notice for the specified URI."""
329 message = "%s error: Alert URI required for alerts\n" % \
330 os.path.basename( sys.argv[0] )
331 sys.stderr.write(message)
336 cache_data=cache_data,
340 if pyversion("3") and type(alert) is bytes: alert = alert.decode("utf-8")
342 if verbose: return alert
344 if alert.find("\nNATIONAL WEATHER SERVICE") == -1:
348 lines = alert.split("\n")
350 valid_time = time.strftime("%Y%m%d%H%M")
353 if line.startswith("Expires:") \
354 and "Expires:" + valid_time > line:
356 if muted and line.startswith("NATIONAL WEATHER SERVICE"):
363 if line and not muted:
364 if quiet: output.append(line)
365 else: output.append(" " + line)
366 return "\n".join(output)
368 def get_options(config):
369 """Parse the options passed on the command line."""
371 # for optparse's builtin -h/--help option
373 "usage: %prog [options] [alias1|search1 [alias2|search2 [...]]]"
375 # for optparse's builtin --version option
376 verstring = "%prog " + weather_version
380 option_parser = optparse.OptionParser(usage=usage, version=verstring)
381 # separate options object from list of arguments and return both
383 # the -a/--alert option
384 if config.has_option("default", "alert"):
385 default_alert = bool(config.get("default", "alert"))
386 else: default_alert = False
387 option_parser.add_option("-a", "--alert",
390 default=default_alert,
391 help="include local alert notices")
393 # the --atypes option
394 if config.has_option("default", "atypes"):
395 default_atypes = config.get("default", "atypes")
398 "coastal_flood_statement," \
399 + "flash_flood_statement," \
400 + "flash_flood_warning," \
401 + "flash_flood_watch," \
402 + "flood_statement," \
404 + "marine_weather_statement," \
405 + "river_statement," \
406 + "severe_thunderstorm_warning," \
407 + "severe_weather_statement," \
408 + "short_term_forecast," \
409 + "special_marine_warning," \
410 + "special_weather_statement," \
411 + "tornado_warning," \
412 + "urgent_weather_message"
413 option_parser.add_option("--atypes",
415 default=default_atypes,
416 help="list of alert notification types to display")
418 # the --build-sets option
419 option_parser.add_option("--build-sets",
423 help="(re)build location correlation sets")
425 # the --cacheage option
426 if config.has_option("default", "cacheage"):
427 default_cacheage = config.getint("default", "cacheage")
428 else: default_cacheage = 900
429 option_parser.add_option("--cacheage",
431 default=default_cacheage,
432 help="duration in seconds to refresh cached data")
434 # the --cachedir option
435 if config.has_option("default", "cachedir"):
436 default_cachedir = config.get("default", "cachedir")
437 else: default_cachedir = "~/.weather"
438 option_parser.add_option("--cachedir",
440 default=default_cachedir,
441 help="directory for storing cached searches and data")
443 # the -f/--forecast option
444 if config.has_option("default", "forecast"):
445 default_forecast = bool(config.get("default", "forecast"))
446 else: default_forecast = False
447 option_parser.add_option("-f", "--forecast",
450 default=default_forecast,
451 help="include a local forecast")
453 # the --headers option
454 if config.has_option("default", "headers"):
455 default_headers = config.get("default", "headers")
459 + "relative_humidity," \
464 + "sky_conditions," \
465 + "precipitation_last_hour"
466 option_parser.add_option("--headers",
468 default=default_headers,
469 help="list of conditions headers to display")
471 # the --imperial option
472 if config.has_option("default", "imperial"):
473 default_imperial = bool(config.get("default", "imperial"))
474 else: default_imperial = False
475 option_parser.add_option("--imperial",
478 default=default_imperial,
479 help="filter/convert conditions for US/UK units")
482 option_parser.add_option("--info",
486 help="output detailed information for your search")
488 # the -l/--list option
489 option_parser.add_option("-l", "--list",
493 help="list all configured aliases and cached searches")
495 # the --longlist option
496 option_parser.add_option("--longlist",
500 help="display details of all configured aliases")
502 # the -m/--metric option
503 if config.has_option("default", "metric"):
504 default_metric = bool(config.get("default", "metric"))
505 else: default_metric = False
506 option_parser.add_option("-m", "--metric",
509 default=default_metric,
510 help="filter/convert conditions for metric units")
512 # the -n/--no-conditions option
513 if config.has_option("default", "conditions"):
514 default_conditions = bool(config.get("default", "conditions"))
515 else: default_conditions = True
516 option_parser.add_option("-n", "--no-conditions",
518 action="store_false",
519 default=default_conditions,
520 help="disable output of current conditions")
522 # the --no-cache option
523 if config.has_option("default", "cache"):
524 default_cache = bool(config.get("default", "cache"))
525 else: default_cache = True
526 option_parser.add_option("--no-cache",
528 action="store_false",
530 help="disable all caching (searches and data)")
532 # the --no-cache-data option
533 if config.has_option("default", "cache_data"):
534 default_cache_data = bool(config.get("default", "cache_data"))
535 else: default_cache_data = True
536 option_parser.add_option("--no-cache-data",
538 action="store_false",
540 help="disable retrieved data caching")
542 # the --no-cache-search option
543 if config.has_option("default", "cache_search"):
544 default_cache_search = bool(config.get("default", "cache_search"))
545 else: default_cache_search = True
546 option_parser.add_option("--no-cache-search",
548 action="store_false",
550 help="disable search result caching")
552 # the -q/--quiet option
553 if config.has_option("default", "quiet"):
554 default_quiet = bool(config.get("default", "quiet"))
555 else: default_quiet = False
556 option_parser.add_option("-q", "--quiet",
559 default=default_quiet,
560 help="skip preambles and don't indent")
562 # the --setpath option
563 if config.has_option("default", "setpath"):
564 default_setpath = config.get("default", "setpath")
565 else: default_setpath = ".:~/.weather"
566 option_parser.add_option("--setpath",
568 default=default_setpath,
569 help="directory search path for correlation sets")
571 # the -v/--verbose option
572 if config.has_option("default", "verbose"):
573 default_verbose = bool(config.get("default", "verbose"))
574 else: default_verbose = False
575 option_parser.add_option("-v", "--verbose",
578 default=default_verbose,
579 help="show full decoded feeds")
582 if config.has_option("default", "city"):
583 default_city = config.get("default", "city")
584 else: default_city = ""
585 option_parser.add_option("-c", "--city",
587 default=default_city,
588 help=optparse.SUPPRESS_HELP)
589 if config.has_option("default", "id"):
590 default_id = config.get("default", "id")
591 else: default_id = ""
592 option_parser.add_option("-i", "--id",
595 help=optparse.SUPPRESS_HELP)
596 if config.has_option("default", "st"):
597 default_st = config.get("default", "st")
598 else: default_st = ""
599 option_parser.add_option("-s", "--st",
602 help=optparse.SUPPRESS_HELP)
604 options, arguments = option_parser.parse_args()
605 return options, arguments
608 """Parse the aliases and configuration."""
609 if pyversion("3"): import configparser
610 else: import ConfigParser as configparser
611 config = configparser.ConfigParser()
615 "/etc/weather/weatherrc",
616 os.path.expanduser("~/.weather/weatherrc"),
617 os.path.expanduser("~/.weatherrc"),
620 for rcfile in rcfiles:
621 if os.access(rcfile, os.R_OK): config.read(rcfile)
622 for section in config.sections():
623 if section != section.lower():
624 if config.has_section(section.lower()):
625 config.remove_section(section.lower())
626 config.add_section(section.lower())
627 for option,value in config.items(section):
628 config.set(section.lower(), option, value)
631 def integrate_search_cache(config, cachedir, setpath):
632 """Add cached search results into the configuration."""
633 if pyversion("3"): import configparser
634 else: import ConfigParser as configparser
636 scache_fn = os.path.join( os.path.expanduser(cachedir), "searches" )
637 if not os.access(scache_fn, os.R_OK): return config
638 scache_fd = open(scache_fn)
639 created = float( scache_fd.readline().split(":")[1].strip().split()[0] )
642 datafiles = data_index(setpath)
644 data_freshness = sorted(
645 [ x[1] for x in datafiles.values() ],
648 else: data_freshness = now
649 if created < data_freshness <= now:
652 print( "[clearing outdated %s]" % scache_fn )
653 except (IOError, OSError):
656 scache = configparser.ConfigParser()
657 scache.read(scache_fn)
658 for section in scache.sections():
659 if not config.has_section(section):
660 config.add_section(section)
661 for option,value in scache.items(section):
662 config.set(section, option, value)
665 def list_aliases(config, detail=False):
666 """Return a formatted list of aliases defined in the config."""
668 output = "\n# configured alias details..."
669 for section in sorted(config.sections()):
670 output += "\n\n[%s]" % section
671 for item in sorted(config.items(section)):
672 output += "\n%s = %s" % item
675 output = "configured aliases and cached searches..."
676 for section in sorted(config.sections()):
677 if config.has_option(section, "description"):
678 description = config.get(section, "description")
679 else: description = "(no description provided)"
680 output += "\n %s: %s" % (section, description)
683 def data_index(path):
686 for filename in ("airports", "places", "stations", "zctas", "zones"):
687 for dirname in path.split(":"):
688 for extension in ("", ".gz", ".txt"):
689 candidate = os.path.expanduser(
690 os.path.join( dirname, "".join( (filename, extension) ) )
692 if os.path.exists(candidate):
693 datafiles[filename] = (
695 os.stat(candidate).st_mtime
698 if filename in datafiles:
712 """Find URIs using airport, gecos, placename, station, ZCTA/ZIP, zone."""
713 import codecs, datetime, time, os, re, sys
714 if pyversion("3"): import configparser
715 else: import ConfigParser as configparser
716 datafiles = data_index(path)
717 if re.match("[A-Za-z]{3}$", expression): searchtype = "airport"
718 elif re.match("[A-Za-z0-9]{4}$", expression): searchtype = "station"
719 elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", expression): searchtype = "zone"
720 elif re.match("[0-9]{5}$", expression): searchtype = "ZCTA"
722 r"[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?, *[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?$",
725 searchtype = "coordinates"
726 elif re.match(r"(FIPS|fips)\d+$", expression): searchtype = "FIPS"
730 if cache_search: action = "caching"
731 else: action = "using"
740 (0.995, "excellent"),
743 if not quiet: print("Searching via %s..."%searchtype)
744 stations = configparser.ConfigParser()
745 dataname = "stations"
746 if dataname in datafiles:
747 datafile = datafiles[dataname][0]
748 if datafile.endswith(".gz"):
751 stations.read_string(
752 gzip.open(datafile).read().decode("utf-8") )
753 else: stations.readfp( gzip.open(datafile) )
755 stations.read(datafile)
757 message = "%s error: can't find \"%s\" data file\n" % (
758 os.path.basename( sys.argv[0] ),
761 sys.stderr.write(message)
763 zones = configparser.ConfigParser()
765 if dataname in datafiles:
766 datafile = datafiles[dataname][0]
767 if datafile.endswith(".gz"):
770 zones.read_string( gzip.open(datafile).read().decode("utf-8") )
771 else: zones.readfp( gzip.open(datafile) )
775 message = "%s error: can't find \"%s\" data file\n" % (
776 os.path.basename( sys.argv[0] ),
779 sys.stderr.write(message)
787 if searchtype == "airport":
788 expression = expression.lower()
789 airports = configparser.ConfigParser()
790 dataname = "airports"
791 if dataname in datafiles:
792 datafile = datafiles[dataname][0]
793 if datafile.endswith(".gz"):
796 airports.read_string(
797 gzip.open(datafile).read().decode("utf-8") )
798 else: airports.readfp( gzip.open(datafile) )
800 airports.read(datafile)
802 message = "%s error: can't find \"%s\" data file\n" % (
803 os.path.basename( sys.argv[0] ),
806 sys.stderr.write(message)
808 if airports.has_section(expression) \
809 and airports.has_option(expression, "station"):
810 search = (expression, "IATA/FAA airport code %s" % expression)
811 station = ( airports.get(expression, "station"), 0 )
812 if stations.has_option(station[0], "zone"):
813 zone = eval( stations.get(station[0], "zone") )
815 if not ( info or quiet ) \
816 and stations.has_option( station[0], "description" ):
820 stations.get(station[0], "description")
824 message = "No IATA/FAA airport code \"%s\" in the %s file.\n" % (
826 datafiles["airports"][0]
828 sys.stderr.write(message)
830 elif searchtype == "station":
831 expression = expression.lower()
832 if stations.has_section(expression):
833 station = (expression, 0)
835 search = (expression, "ICAO station code %s" % expression)
836 if stations.has_option(expression, "zone"):
837 zone = eval( stations.get(expression, "zone") )
839 if not ( info or quiet ) \
840 and stations.has_option(expression, "description"):
844 stations.get(expression, "description")
848 message = "No ICAO weather station \"%s\" in the %s file.\n" % (
850 datafiles["stations"][0]
852 sys.stderr.write(message)
854 elif searchtype == "zone":
855 expression = expression.lower()
856 if zones.has_section(expression) \
857 and zones.has_option(expression, "station"):
858 zone = (expression, 0)
859 station = eval( zones.get(expression, "station") )
861 search = (expression, "NWS/NOAA weather zone %s" % expression)
862 if not ( info or quiet ) \
863 and zones.has_option(expression, "description"):
867 zones.get(expression, "description")
871 message = "No usable NWS weather zone \"%s\" in the %s file.\n" % (
873 datafiles["zones"][0]
875 sys.stderr.write(message)
877 elif searchtype == "ZCTA":
878 zctas = configparser.ConfigParser()
880 if dataname in datafiles:
881 datafile = datafiles[dataname][0]
882 if datafile.endswith(".gz"):
886 gzip.open(datafile).read().decode("utf-8") )
887 else: zctas.readfp( gzip.open(datafile) )
891 message = "%s error: can't find \"%s\" data file\n" % (
892 os.path.basename( sys.argv[0] ),
895 sys.stderr.write(message)
898 if zctas.has_section(expression) \
899 and zctas.has_option(expression, "station"):
900 station = eval( zctas.get(expression, "station") )
901 search = (expression, "Census ZCTA (ZIP code) %s" % expression)
902 if zctas.has_option(expression, "zone"):
903 zone = eval( zctas.get(expression, "zone") )
905 message = "No census ZCTA (ZIP code) \"%s\" in the %s file.\n" % (
907 datafiles["zctas"][0]
909 sys.stderr.write(message)
911 elif searchtype == "coordinates":
912 search = (expression, "Geographic coordinates %s" % expression)
914 for station in stations.sections():
915 if stations.has_option(station, "location"):
916 stationtable[station] = {
917 "location": eval( stations.get(station, "location") )
919 station = closest( gecos(expression), stationtable, "location", 0.1 )
921 message = "No ICAO weather station found near %s.\n" % expression
922 sys.stderr.write(message)
925 for zone in zones.sections():
926 if zones.has_option(zone, "centroid"):
928 "centroid": eval( zones.get(zone, "centroid") )
930 zone = closest( gecos(expression), zonetable, "centroid", 0.1 )
932 message = "No NWS weather zone near %s; forecasts unavailable.\n" \
934 sys.stderr.write(message)
935 elif searchtype in ("FIPS", "name"):
936 places = configparser.ConfigParser()
938 if dataname in datafiles:
939 datafile = datafiles[dataname][0]
940 if datafile.endswith(".gz"):
944 gzip.open(datafile).read().decode("utf-8") )
945 else: places.readfp( gzip.open(datafile) )
947 places.read(datafile)
949 message = "%s error: can't find \"%s\" data file\n" % (
950 os.path.basename( sys.argv[0] ),
953 sys.stderr.write(message)
956 place = expression.lower()
957 if places.has_section(place) and places.has_option(place, "station"):
958 station = eval( places.get(place, "station") )
959 search = (expression, "Census Place %s" % expression)
960 if places.has_option(place, "description"):
963 search[1] + ", %s" % places.get(place, "description")
965 if places.has_option(place, "zone"):
966 zone = eval( places.get(place, "zone") )
967 if not ( info or quiet ) \
968 and places.has_option(place, "description"):
972 places.get(place, "description")
976 for place in places.sections():
977 if places.has_option(place, "description") \
978 and places.has_option(place, "station") \
981 places.get(place, "description"),
984 possibilities.append(place)
985 for place in stations.sections():
986 if stations.has_option(place, "description") \
989 stations.get(place, "description"),
992 possibilities.append(place)
993 for place in zones.sections():
994 if zones.has_option(place, "description") \
995 and zones.has_option(place, "station") \
998 zones.get(place, "description"),
1001 possibilities.append(place)
1002 if len(possibilities) == 1:
1003 place = possibilities[0]
1004 if places.has_section(place):
1005 station = eval( places.get(place, "station") )
1006 description = places.get(place, "description")
1007 if places.has_option(place, "zone"):
1008 zone = eval( places.get(place, "zone" ) )
1009 search = ( expression, "%s: %s" % (place, description) )
1010 elif stations.has_section(place):
1011 station = (place, 0.0)
1012 description = stations.get(place, "description")
1013 if stations.has_option(place, "zone"):
1014 zone = eval( stations.get(place, "zone" ) )
1015 search = ( expression, "ICAO station code %s" % place )
1016 elif zones.has_section(place):
1017 station = eval( zones.get(place, "station") )
1018 description = zones.get(place, "description")
1020 search = ( expression, "NWS/NOAA weather zone %s" % place )
1021 if not ( info or quiet ):
1022 print( "[%s result %s]" % (action, description) )
1023 if not possibilities and not station[0]:
1024 message = "No FIPS code/census area match in the %s file.\n" % (
1025 datafiles["places"][0]
1027 sys.stderr.write(message)
1030 uris["metar"] = stations.get( station[0], "metar" )
1032 for key,value in zones.items( zone[0] ):
1033 if key not in ("centroid", "description", "station"):
1036 count = len(possibilities)
1037 if count <= max_results:
1038 print( "Your search is ambiguous, returning %s matches:" % count )
1039 for place in sorted(possibilities):
1040 if places.has_section(place):
1044 places.get(place, "description")
1047 elif stations.has_section(place):
1051 stations.get(place, "description")
1054 elif zones.has_section(place):
1058 zones.get(place, "description")
1063 "Your search is too ambiguous, returning %s matches." % count
1070 for section in dataset.sections():
1071 if dataset.has_option(section, "station"):
1073 eval( dataset.get(section, "station") )[1]
1075 if dataset.has_option(section, "zone"):
1076 zonelist.append( eval( dataset.get(section, "zone") )[1] )
1079 scount = len(stationlist)
1080 zcount = len(zonelist)
1083 for score in scores:
1085 sranks.append( stationlist[ int( (1-score[0]) * scount ) ] )
1087 zranks.append( zonelist[ int( (1-score[0]) * zcount ) ] )
1088 description = search[1]
1089 uris["description"] = description
1091 "%s\n%s" % ( description, "-" * len(description) )
1096 stations.get( station[0], "description" )
1099 km = radian_to_km*station[1]
1100 mi = radian_to_mi*station[1]
1101 if sranks and not description.startswith("ICAO station code "):
1102 for index in range(0, len(scores)):
1103 if station[1] >= sranks[index]:
1104 score = scores[index][1]
1107 " (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1109 elif searchtype is "coordinates":
1110 print( " (%.3gkm, %.3gmi)" % (km, mi) )
1113 "%s: %s" % ( zone[0], zones.get( zone[0], "description" ) )
1115 km = radian_to_km*zone[1]
1116 mi = radian_to_mi*zone[1]
1117 if zranks and not description.startswith("NWS/NOAA weather zone "):
1118 for index in range(0, len(scores)):
1119 if zone[1] >= zranks[index]:
1120 score = scores[index][1]
1123 " (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1125 elif searchtype is "coordinates" and zone[0]:
1126 print( " (%.3gkm, %.3gmi)" % (km, mi) )
1129 nowstamp = "%s (%s)" % (
1131 datetime.datetime.isoformat(
1132 datetime.datetime.fromtimestamp(now),
1136 search_cache = ["\n"]
1137 search_cache.append( "[%s]\n" % search[0] )
1138 search_cache.append( "description = cached %s\n" % nowstamp )
1139 for uriname in sorted(uris.keys()):
1140 search_cache.append( "%s = %s\n" % ( uriname, uris[uriname] ) )
1141 real_cachedir = os.path.expanduser(cachedir)
1142 if not os.path.exists(real_cachedir):
1143 try: os.makedirs(real_cachedir)
1144 except (IOError, OSError): pass
1145 scache_fn = os.path.join(real_cachedir, "searches")
1146 if not os.path.exists(scache_fn):
1148 [ x[1] for x in datafiles.values() ],
1151 thenstamp = "%s (%s)" % (
1153 datetime.datetime.isoformat(
1154 datetime.datetime.fromtimestamp(then),
1158 search_cache.insert(
1160 "# based on data files from: %s\n" % thenstamp
1163 scache_existing = configparser.ConfigParser()
1164 scache_existing.read(scache_fn)
1165 if not scache_existing.has_section(search[0]):
1166 scache_fd = codecs.open(scache_fn, "a", "utf-8")
1167 scache_fd.writelines(search_cache)
1169 except (IOError, OSError): pass
1173 def closest(position, nodes, fieldname, angle=None):
1175 if not angle: angle = 2*math.pi
1178 if fieldname in nodes[name]:
1179 node = nodes[name][fieldname]
1180 if node and abs( position[0]-node[0] ) < angle:
1181 if abs( position[1]-node[1] ) < angle \
1182 or abs( abs( position[1]-node[1] ) - 2*math.pi ) < angle:
1183 if position == node:
1187 candidate = math.acos(
1188 math.sin( position[0] ) * math.sin( node[0] ) \
1189 + math.cos( position[0] ) \
1190 * math.cos( node[0] ) \
1191 * math.cos( position[1] - node[1] )
1193 if candidate < angle:
1196 if match: match = str(match)
1197 return (match, angle)
1199 def gecos(formatted):
1201 coordinates = formatted.split(",")
1202 for coordinate in range(0, 2):
1203 degrees, foo, minutes, bar, seconds, hemisphere = re.match(
1204 r"([\+-]?\d+\.?\d*)(-(\d+))?(-(\d+))?([ensw]?)$",
1205 coordinates[coordinate].strip().lower()
1207 value = float(degrees)
1208 if minutes: value += float(minutes)/60
1209 if seconds: value += float(seconds)/3600
1210 if hemisphere and hemisphere in "sw": value *= -1
1211 coordinates[coordinate] = math.radians(value)
1212 return tuple(coordinates)
1215 import codecs, csv, datetime, hashlib, os, re, sys, tarfile, time, zipfile
1216 if pyversion("3"): import configparser
1217 else: import ConfigParser as configparser
1218 for filename in os.listdir("."):
1219 if re.match("[0-9]{4}_Gaz_counties_national.zip$", filename):
1220 gcounties_an = filename
1221 gcounties_fn = filename[:-4] + ".txt"
1222 elif re.match("[0-9]{4}_Gaz_cousubs_national.zip$", filename):
1223 gcousubs_an = filename
1224 gcousubs_fn = filename[:-4] + ".txt"
1225 elif re.match("[0-9]{4}_Gaz_place_national.zip$", filename):
1226 gplace_an = filename
1227 gplace_fn = filename[:-4] + ".txt"
1228 elif re.match("[0-9]{4}_Gaz_zcta_national.zip$", filename):
1230 gzcta_fn = filename[:-4] + ".txt"
1231 elif re.match("bp[0-9]{2}[a-z]{2}[0-9]{2}.dbx$", filename):
1232 cpfzcf_fn = filename
1233 nsdcccc_fn = "nsd_cccc.txt"
1234 ourairports_fn = "airports.csv"
1235 overrides_fn = "overrides.conf"
1236 overrideslog_fn = "overrides.log"
1240 airports_fn = "airports"
1241 places_fn = "places"
1242 stations_fn = "stations"
1247 # generated by %s on %s from these public domain sources:
1249 # https://www.census.gov/geographies/reference-files/time-series/geo/gazetteer-files.html
1255 # https://www.weather.gov/gis/ZoneCounty/
1258 # https://tgftp.nws.noaa.gov/data/
1261 # https://ourairports.com/data/
1264 # ...and these manually-generated or hand-compiled adjustments:
1270 os.path.basename( sys.argv[0] ),
1271 datetime.date.isoformat(
1272 datetime.datetime.fromtimestamp( time.time() )
1274 hashlib.md5( open(gcounties_an, "rb").read() ).hexdigest(),
1275 datetime.date.isoformat(
1276 datetime.datetime.fromtimestamp( os.path.getmtime(gcounties_an) )
1279 hashlib.md5( open(gcousubs_an, "rb").read() ).hexdigest(),
1280 datetime.date.isoformat(
1281 datetime.datetime.fromtimestamp( os.path.getmtime(gcousubs_an) )
1284 hashlib.md5( open(gplace_an, "rb").read() ).hexdigest(),
1285 datetime.date.isoformat(
1286 datetime.datetime.fromtimestamp( os.path.getmtime(gplace_an) )
1289 hashlib.md5( open(gzcta_an, "rb").read() ).hexdigest(),
1290 datetime.date.isoformat(
1291 datetime.datetime.fromtimestamp( os.path.getmtime(gzcta_an) )
1294 hashlib.md5( open(cpfzcf_fn, "rb").read() ).hexdigest(),
1295 datetime.date.isoformat(
1296 datetime.datetime.fromtimestamp( os.path.getmtime(cpfzcf_fn) )
1299 hashlib.md5( open(nsdcccc_fn, "rb").read() ).hexdigest(),
1300 datetime.date.isoformat(
1301 datetime.datetime.fromtimestamp( os.path.getmtime(nsdcccc_fn) )
1304 hashlib.md5( open(ourairports_fn, "rb").read() ).hexdigest(),
1305 datetime.date.isoformat(
1306 datetime.datetime.fromtimestamp( os.path.getmtime(ourairports_fn) )
1309 hashlib.md5( open(overrides_fn, "rb").read() ).hexdigest(),
1310 datetime.date.isoformat(
1311 datetime.datetime.fromtimestamp( os.path.getmtime(overrides_fn) )
1314 hashlib.md5( open(slist_fn, "rb").read() ).hexdigest(),
1315 datetime.date.isoformat(
1316 datetime.datetime.fromtimestamp( os.path.getmtime(slist_fn) )
1319 hashlib.md5( open(zlist_fn, "rb").read() ).hexdigest(),
1320 datetime.date.isoformat(
1321 datetime.datetime.fromtimestamp( os.path.getmtime(zlist_fn) )
1330 message = "Reading %s:%s..." % (gcounties_an, gcounties_fn)
1331 sys.stdout.write(message)
1334 gcounties = zipfile.ZipFile(gcounties_an).open(gcounties_fn, "rU")
1335 columns = gcounties.readline().decode("utf-8").strip().split("\t")
1336 for line in gcounties:
1337 fields = line.decode("utf-8").strip().split("\t")
1338 f_geoid = fields[ columns.index("GEOID") ].strip()
1339 f_name = fields[ columns.index("NAME") ].strip()
1340 f_usps = fields[ columns.index("USPS") ].strip()
1341 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1342 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1343 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1344 fips = "fips%s" % f_geoid
1345 if fips not in places: places[fips] = {}
1346 places[fips]["centroid"] = gecos(
1347 "%s,%s" % (f_intptlat, f_intptlong)
1349 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1352 print("done (%s lines)." % count)
1353 message = "Reading %s:%s..." % (gcousubs_an, gcousubs_fn)
1354 sys.stdout.write(message)
1357 gcousubs = zipfile.ZipFile(gcousubs_an).open(gcousubs_fn, "rU")
1358 columns = gcousubs.readline().decode("utf-8").strip().split("\t")
1359 for line in gcousubs:
1360 fields = line.decode("utf-8").strip().split("\t")
1361 f_geoid = fields[ columns.index("GEOID") ].strip()
1362 f_name = fields[ columns.index("NAME") ].strip()
1363 f_usps = fields[ columns.index("USPS") ].strip()
1364 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1365 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1366 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1367 fips = "fips%s" % f_geoid
1368 if fips not in places: places[fips] = {}
1369 places[fips]["centroid"] = gecos(
1370 "%s,%s" % (f_intptlat, f_intptlong)
1372 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1375 print("done (%s lines)." % count)
1376 message = "Reading %s:%s..." % (gplace_an, gplace_fn)
1377 sys.stdout.write(message)
1380 gplace = zipfile.ZipFile(gplace_an).open(gplace_fn, "rU")
1381 columns = gplace.readline().decode("utf-8").strip().split("\t")
1383 fields = line.decode("utf-8").strip().split("\t")
1384 f_geoid = fields[ columns.index("GEOID") ].strip()
1385 f_name = fields[ columns.index("NAME") ].strip()
1386 f_usps = fields[ columns.index("USPS") ].strip()
1387 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1388 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1389 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1390 fips = "fips%s" % f_geoid
1391 if fips not in places: places[fips] = {}
1392 places[fips]["centroid"] = gecos(
1393 "%s,%s" % (f_intptlat, f_intptlong)
1395 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1398 print("done (%s lines)." % count)
1399 message = "Reading %s..." % slist_fn
1400 sys.stdout.write(message)
1403 slist = codecs.open(slist_fn, "rU", "utf-8")
1405 icao = line.split("#")[0].strip()
1408 "metar": "https://tgftp.nws.noaa.gov/data/observations/"\
1409 + "metar/decoded/%s.TXT" % icao.upper()
1413 print("done (%s lines)." % count)
1414 message = "Reading %s..." % nsdcccc_fn
1415 sys.stdout.write(message)
1418 nsdcccc = codecs.open(nsdcccc_fn, "rU", "utf-8")
1419 for line in nsdcccc:
1421 fields = line.split(";")
1422 icao = fields[0].strip().lower()
1423 if icao in stations:
1425 name = " ".join( fields[3].strip().title().split() )
1426 if name: description.append(name)
1427 st = fields[4].strip()
1428 if st: description.append(st)
1429 country = " ".join( fields[5].strip().title().split() )
1430 if country: description.append(country)
1432 stations[icao]["description"] = ", ".join(description)
1433 lat, lon = fields[7:9]
1435 stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1436 elif "location" not in stations[icao]:
1437 lat, lon = fields[5:7]
1439 stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1442 print("done (%s lines)." % count)
1443 message = "Reading %s..." % ourairports_fn
1444 sys.stdout.write(message)
1447 ourairports = open(ourairports_fn, "rU")
1448 for row in csv.reader(ourairports):
1449 icao = row[12].decode('utf-8').lower()
1450 if icao in stations:
1451 iata = row[13].decode('utf-8').lower()
1452 if len(iata) == 3: airports[iata] = { "station": icao }
1453 if "description" not in stations[icao]:
1455 name = row[3].decode('utf-8')
1456 if name: description.append(name)
1457 municipality = row[10].decode('utf-8')
1458 if municipality: description.append(municipality)
1459 region = row[9].decode('utf-8')
1460 country = row[8].decode('utf-8')
1463 c,r = region.split("-", 1)
1464 if c == country: region = r
1465 description.append(region)
1467 description.append(country)
1469 stations[icao]["description"] = ", ".join(description)
1470 if "location" not in stations[icao]:
1471 lat = row[4].decode('utf-8')
1473 lon = row[5].decode('utf-8')
1475 stations[icao]["location"] = gecos(
1476 "%s,%s" % (lat, lon)
1480 print("done (%s lines)." % count)
1481 message = "Reading %s..." % zlist_fn
1482 sys.stdout.write(message)
1485 zlist = codecs.open(zlist_fn, "rU", "utf-8")
1487 line = line.split("#")[0].strip()
1492 print("done (%s lines)." % count)
1493 message = "Reading %s..." % cpfzcf_fn
1494 sys.stdout.write(message)
1498 cpfzcf = codecs.open(cpfzcf_fn, "rU", "utf-8")
1500 fields = line.strip().split("|")
1501 if len(fields) == 11 \
1502 and fields[0] and fields[1] and fields[9] and fields[10]:
1503 zone = "z".join( fields[:2] ).lower()
1507 zones[zone]["coastal_flood_statement"] = (
1508 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1509 "flood/coastal/%s/%s.txt" % (state.lower(), zone))
1510 zones[zone]["flash_flood_statement"] = (
1511 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1512 "flash_flood/statement/%s/%s.txt"
1513 % (state.lower(), zone))
1514 zones[zone]["flash_flood_warning"] = (
1515 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1516 "flash_flood/warning/%s/%s.txt"
1517 % (state.lower(), zone))
1518 zones[zone]["flash_flood_watch"] = (
1519 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1520 "flash_flood/watch/%s/%s.txt" % (state.lower(), zone))
1521 zones[zone]["flood_statement"] = (
1522 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1523 "flood/statement/%s/%s.txt" % (state.lower(), zone))
1524 zones[zone]["flood_warning"] = (
1525 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1526 "flood/warning/%s/%s.txt" % (state.lower(), zone))
1527 zones[zone]["severe_thunderstorm_warning"] = (
1528 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1529 "thunderstorm/%s/%s.txt" % (state.lower(), zone))
1530 zones[zone]["severe_weather_statement"] = (
1531 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1532 "severe_weather_stmt/%s/%s.txt"
1533 % (state.lower(), zone))
1534 zones[zone]["short_term_forecast"] = (
1535 "https://tgftp.nws.noaa.gov/data/forecasts/nowcast/"
1536 "%s/%s.txt" % (state.lower(), zone))
1537 zones[zone]["special_weather_statement"] = (
1538 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1539 "special_weather_stmt/%s/%s.txt"
1540 % (state.lower(), zone))
1541 zones[zone]["state_forecast"] = (
1542 "https://tgftp.nws.noaa.gov/data/forecasts/state/"
1543 "%s/%s.txt" % (state.lower(), zone))
1544 zones[zone]["urgent_weather_message"] = (
1545 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1546 "non_precip/%s/%s.txt" % (state.lower(), zone))
1547 zones[zone]["zone_forecast"] = (
1548 "https://tgftp.nws.noaa.gov/data/forecasts/zone/"
1549 "%s/%s.txt" % (state.lower(), zone))
1550 description = fields[3].strip()
1551 fips = "fips%s"%fields[6]
1554 if description.endswith(county):
1555 description += " County"
1557 description += ", %s County" % county
1558 description += ", %s, US" % state
1559 zones[zone]["description"] = description
1560 zones[zone]["centroid"] = gecos( ",".join( fields[9:11] ) )
1561 if fips in places and not zones[zone]["centroid"]:
1562 zones[zone]["centroid"] = places[fips]["centroid"]
1565 print("done (%s lines)." % count)
1566 message = "Reading %s:%s..." % (gzcta_an, gzcta_fn)
1567 sys.stdout.write(message)
1570 gzcta = zipfile.ZipFile(gzcta_an).open(gzcta_fn, "rU")
1571 columns = gzcta.readline().decode("utf-8").strip().split("\t")
1573 fields = line.decode("utf-8").strip().split("\t")
1574 f_geoid = fields[ columns.index("GEOID") ].strip()
1575 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1576 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1577 if f_geoid and f_intptlat and f_intptlong:
1578 if f_geoid not in zctas: zctas[f_geoid] = {}
1579 zctas[f_geoid]["centroid"] = gecos(
1580 "%s,%s" % (f_intptlat, f_intptlong)
1584 print("done (%s lines)." % count)
1585 message = "Reading %s..." % overrides_fn
1586 sys.stdout.write(message)
1592 overrides = configparser.ConfigParser()
1593 overrides.readfp( codecs.open(overrides_fn, "r", "utf8") )
1595 for section in overrides.sections():
1598 if section.startswith("-"):
1599 section = section[1:]
1601 else: delete = False
1602 if re.match("[A-Za-z]{3}$", section):
1604 if section in airports:
1605 del( airports[section] )
1606 logact = "removed airport %s" % section
1609 logact = "tried to remove nonexistent airport %s" % section
1611 if section in airports:
1612 logact = "changed airport %s" % section
1615 airports[section] = {}
1616 logact = "added airport %s" % section
1618 for key,value in overrides.items(section):
1619 if key in airports[section]: chgopt += 1
1621 if key in ("centroid", "location"):
1622 airports[section][key] = eval(value)
1624 airports[section][key] = value
1625 if addopt and chgopt:
1626 logact += " (+%s/!%s options)" % (addopt, chgopt)
1627 elif addopt: logact += " (+%s options)" % addopt
1628 elif chgopt: logact += " (!%s options)" % chgopt
1629 elif re.match("[A-Za-z0-9]{4}$", section):
1631 if section in stations:
1632 del( stations[section] )
1633 logact = "removed station %s" % section
1636 logact = "tried to remove nonexistent station %s" % section
1638 if section in stations:
1639 logact = "changed station %s" % section
1642 stations[section] = {}
1643 logact = "added station %s" % section
1645 for key,value in overrides.items(section):
1646 if key in stations[section]: chgopt += 1
1648 if key in ("centroid", "location"):
1649 stations[section][key] = eval(value)
1651 stations[section][key] = value
1652 if addopt and chgopt:
1653 logact += " (+%s/!%s options)" % (addopt, chgopt)
1654 elif addopt: logact += " (+%s options)" % addopt
1655 elif chgopt: logact += " (!%s options)" % chgopt
1656 elif re.match("[0-9]{5}$", section):
1658 if section in zctas:
1659 del( zctas[section] )
1660 logact = "removed zcta %s" % section
1663 logact = "tried to remove nonexistent zcta %s" % section
1665 if section in zctas:
1666 logact = "changed zcta %s" % section
1670 logact = "added zcta %s" % section
1672 for key,value in overrides.items(section):
1673 if key in zctas[section]: chgopt += 1
1675 if key in ("centroid", "location"):
1676 zctas[section][key] = eval(value)
1678 zctas[section][key] = value
1679 if addopt and chgopt:
1680 logact += " (+%s/!%s options)" % (addopt, chgopt)
1681 elif addopt: logact += " (+%s options)" % addopt
1682 elif chgopt: logact += " (!%s options)" % chgopt
1683 elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", section):
1685 if section in zones:
1686 del( zones[section] )
1687 logact = "removed zone %s" % section
1690 logact = "tried to remove nonexistent zone %s" % section
1692 if section in zones:
1693 logact = "changed zone %s" % section
1697 logact = "added zone %s" % section
1699 for key,value in overrides.items(section):
1700 if key in zones[section]: chgopt += 1
1702 if key in ("centroid", "location"):
1703 zones[section][key] = eval(value)
1705 zones[section][key] = value
1706 if addopt and chgopt:
1707 logact += " (+%s/!%s options)" % (addopt, chgopt)
1708 elif addopt: logact += " (+%s options)" % addopt
1709 elif chgopt: logact += " (!%s options)" % chgopt
1710 elif re.match("fips[0-9]+$", section):
1712 if section in places:
1713 del( places[section] )
1714 logact = "removed place %s" % section
1717 logact = "tried to remove nonexistent place %s" % section
1719 if section in places:
1720 logact = "changed place %s" % section
1723 places[section] = {}
1724 logact = "added place %s" % section
1726 for key,value in overrides.items(section):
1727 if key in places[section]: chgopt += 1
1729 if key in ("centroid", "location"):
1730 places[section][key] = eval(value)
1732 places[section][key] = value
1733 if addopt and chgopt:
1734 logact += " (+%s/!%s options)" % (addopt, chgopt)
1735 elif addopt: logact += " (+%s options)" % addopt
1736 elif chgopt: logact += " (!%s options)" % chgopt
1738 overrideslog.append("%s\n" % logact)
1740 if os.path.exists(overrideslog_fn):
1741 os.rename(overrideslog_fn, "%s_old"%overrideslog_fn)
1742 overrideslog_fd = codecs.open(overrideslog_fn, "w", "utf8")
1743 overrideslog_fd.writelines(overrideslog)
1744 overrideslog_fd.close()
1745 print("done (%s overridden sections: +%s/-%s/!%s)." % (
1751 estimate = 2*len(places) + len(stations) + 2*len(zctas) + len(zones)
1753 "Correlating places, stations, ZCTAs and zones (upper bound is %s):" % \
1757 milestones = list( range(51) )
1759 sys.stdout.write(message)
1762 centroid = places[fips]["centroid"]
1764 station = closest(centroid, stations, "location", 0.1)
1766 places[fips]["station"] = station
1769 level = int(50*count/estimate)
1770 if level in milestones:
1771 for remaining in milestones[:milestones.index(level)+1]:
1774 sys.stdout.write(message)
1777 message = "%s%%" % (remaining*2,)
1778 sys.stdout.write(message)
1780 milestones.remove(remaining)
1782 zone = closest(centroid, zones, "centroid", 0.1)
1784 places[fips]["zone"] = zone
1787 level = int(50*count/estimate)
1788 if level in milestones:
1789 for remaining in milestones[:milestones.index(level)+1]:
1792 sys.stdout.write(message)
1795 message = "%s%%" % (remaining*2,)
1796 sys.stdout.write(message)
1798 milestones.remove(remaining)
1799 for station in stations:
1800 if "location" in stations[station]:
1801 location = stations[station]["location"]
1803 zone = closest(location, zones, "centroid", 0.1)
1805 stations[station]["zone"] = zone
1808 level = int(50*count/estimate)
1809 if level in milestones:
1810 for remaining in milestones[:milestones.index(level)+1]:
1813 sys.stdout.write(message)
1816 message = "%s%%" % (remaining*2,)
1817 sys.stdout.write(message)
1819 milestones.remove(remaining)
1820 for zcta in zctas.keys():
1821 centroid = zctas[zcta]["centroid"]
1823 station = closest(centroid, stations, "location", 0.1)
1825 zctas[zcta]["station"] = station
1828 level = int(50*count/estimate)
1829 if level in milestones:
1830 for remaining in milestones[ : milestones.index(level)+1 ]:
1833 sys.stdout.write(message)
1836 message = "%s%%" % (remaining*2,)
1837 sys.stdout.write(message)
1839 milestones.remove(remaining)
1841 zone = closest(centroid, zones, "centroid", 0.1)
1843 zctas[zcta]["zone"] = zone
1846 level = int(50*count/estimate)
1847 if level in milestones:
1848 for remaining in milestones[:milestones.index(level)+1]:
1851 sys.stdout.write(message)
1854 message = "%s%%" % (remaining*2,)
1855 sys.stdout.write(message)
1857 milestones.remove(remaining)
1858 for zone in zones.keys():
1859 if "centroid" in zones[zone]:
1860 centroid = zones[zone]["centroid"]
1862 station = closest(centroid, stations, "location", 0.1)
1864 zones[zone]["station"] = station
1867 level = int(50*count/estimate)
1868 if level in milestones:
1869 for remaining in milestones[:milestones.index(level)+1]:
1872 sys.stdout.write(message)
1875 message = "%s%%" % (remaining*2,)
1876 sys.stdout.write(message)
1878 milestones.remove(remaining)
1879 for remaining in milestones:
1882 sys.stdout.write(message)
1885 message = "%s%%" % (remaining*2,)
1886 sys.stdout.write(message)
1888 print("\n done (%s correlations)." % count)
1889 message = "Writing %s..." % airports_fn
1890 sys.stdout.write(message)
1893 if os.path.exists(airports_fn):
1894 os.rename(airports_fn, "%s_old"%airports_fn)
1895 airports_fd = codecs.open(airports_fn, "w", "utf8")
1896 airports_fd.write(header)
1897 for airport in sorted( airports.keys() ):
1898 airports_fd.write("\n\n[%s]" % airport)
1899 for key, value in sorted( airports[airport].items() ):
1900 if type(value) is float: value = "%.7f"%value
1901 elif type(value) is tuple:
1903 for element in value:
1904 if type(element) is float: elements.append("%.7f"%element)
1905 else: elements.append( repr(element) )
1906 value = "(%s)"%", ".join(elements)
1907 airports_fd.write( "\n%s = %s" % (key, value) )
1909 airports_fd.write("\n")
1911 print("done (%s sections)." % count)
1912 message = "Writing %s..." % places_fn
1913 sys.stdout.write(message)
1916 if os.path.exists(places_fn):
1917 os.rename(places_fn, "%s_old"%places_fn)
1918 places_fd = codecs.open(places_fn, "w", "utf8")
1919 places_fd.write(header)
1920 for fips in sorted( places.keys() ):
1921 places_fd.write("\n\n[%s]" % fips)
1922 for key, value in sorted( places[fips].items() ):
1923 if type(value) is float: value = "%.7f"%value
1924 elif type(value) is tuple:
1926 for element in value:
1927 if type(element) is float: elements.append("%.7f"%element)
1928 else: elements.append( repr(element) )
1929 value = "(%s)"%", ".join(elements)
1930 places_fd.write( "\n%s = %s" % (key, value) )
1932 places_fd.write("\n")
1934 print("done (%s sections)." % count)
1935 message = "Writing %s..." % stations_fn
1936 sys.stdout.write(message)
1939 if os.path.exists(stations_fn):
1940 os.rename(stations_fn, "%s_old"%stations_fn)
1941 stations_fd = codecs.open(stations_fn, "w", "utf-8")
1942 stations_fd.write(header)
1943 for station in sorted( stations.keys() ):
1944 stations_fd.write("\n\n[%s]" % station)
1945 for key, value in sorted( stations[station].items() ):
1946 if type(value) is float: value = "%.7f"%value
1947 elif type(value) is tuple:
1949 for element in value:
1950 if type(element) is float: elements.append("%.7f"%element)
1951 else: elements.append( repr(element) )
1952 value = "(%s)"%", ".join(elements)
1953 stations_fd.write( "\n%s = %s" % (key, value) )
1955 stations_fd.write("\n")
1957 print("done (%s sections)." % count)
1958 message = "Writing %s..." % zctas_fn
1959 sys.stdout.write(message)
1962 if os.path.exists(zctas_fn):
1963 os.rename(zctas_fn, "%s_old"%zctas_fn)
1964 zctas_fd = codecs.open(zctas_fn, "w", "utf8")
1965 zctas_fd.write(header)
1966 for zcta in sorted( zctas.keys() ):
1967 zctas_fd.write("\n\n[%s]" % zcta)
1968 for key, value in sorted( zctas[zcta].items() ):
1969 if type(value) is float: value = "%.7f"%value
1970 elif type(value) is tuple:
1972 for element in value:
1973 if type(element) is float: elements.append("%.7f"%element)
1974 else: elements.append( repr(element) )
1975 value = "(%s)"%", ".join(elements)
1976 zctas_fd.write( "\n%s = %s" % (key, value) )
1978 zctas_fd.write("\n")
1980 print("done (%s sections)." % count)
1981 message = "Writing %s..." % zones_fn
1982 sys.stdout.write(message)
1985 if os.path.exists(zones_fn):
1986 os.rename(zones_fn, "%s_old"%zones_fn)
1987 zones_fd = codecs.open(zones_fn, "w", "utf8")
1988 zones_fd.write(header)
1989 for zone in sorted( zones.keys() ):
1990 zones_fd.write("\n\n[%s]" % zone)
1991 for key, value in sorted( zones[zone].items() ):
1992 if type(value) is float: value = "%.7f"%value
1993 elif type(value) is tuple:
1995 for element in value:
1996 if type(element) is float: elements.append("%.7f"%element)
1997 else: elements.append( repr(element) )
1998 value = "(%s)"%", ".join(elements)
1999 zones_fd.write( "\n%s = %s" % (key, value) )
2001 zones_fd.write("\n")
2003 print("done (%s sections)." % count)
2004 message = "Starting QA check..."
2005 sys.stdout.write(message)
2007 airports = configparser.ConfigParser()
2008 airports.read(airports_fn)
2009 places = configparser.ConfigParser()
2010 places.read(places_fn)
2011 stations = configparser.ConfigParser()
2012 stations.read(stations_fn)
2013 zctas = configparser.ConfigParser()
2014 zctas.read(zctas_fn)
2015 zones = configparser.ConfigParser()
2016 zones.read(zones_fn)
2018 places_nocentroid = 0
2019 places_nodescription = 0
2020 for place in sorted( places.sections() ):
2021 if not places.has_option(place, "centroid"):
2022 qalog.append("%s: no centroid\n" % place)
2023 places_nocentroid += 1
2024 if not places.has_option(place, "description"):
2025 qalog.append("%s: no description\n" % place)
2026 places_nodescription += 1
2027 stations_nodescription = 0
2028 stations_nolocation = 0
2029 stations_nometar = 0
2030 for station in sorted( stations.sections() ):
2031 if not stations.has_option(station, "description"):
2032 qalog.append("%s: no description\n" % station)
2033 stations_nodescription += 1
2034 if not stations.has_option(station, "location"):
2035 qalog.append("%s: no location\n" % station)
2036 stations_nolocation += 1
2037 if not stations.has_option(station, "metar"):
2038 qalog.append("%s: no metar\n" % station)
2039 stations_nometar += 1
2040 airports_badstation = 0
2041 airports_nostation = 0
2042 for airport in sorted( airports.sections() ):
2043 if not airports.has_option(airport, "station"):
2044 qalog.append("%s: no station\n" % airport)
2045 airports_nostation += 1
2047 station = airports.get(airport, "station")
2048 if station not in stations.sections():
2049 qalog.append( "%s: bad station %s\n" % (airport, station) )
2050 airports_badstation += 1
2051 zctas_nocentroid = 0
2052 for zcta in sorted( zctas.sections() ):
2053 if not zctas.has_option(zcta, "centroid"):
2054 qalog.append("%s: no centroid\n" % zcta)
2055 zctas_nocentroid += 1
2056 zones_nocentroid = 0
2057 zones_nodescription = 0
2058 zones_noforecast = 0
2059 zones_overlapping = 0
2061 for zone in zones.sections():
2062 if zones.has_option(zone, "centroid"):
2064 "centroid": eval( zones.get(zone, "centroid") )
2066 for zone in sorted( zones.sections() ):
2067 if zones.has_option(zone, "centroid"):
2068 zonetable_local = zonetable.copy()
2069 del( zonetable_local[zone] )
2070 centroid = eval( zones.get(zone, "centroid") )
2072 nearest = closest(centroid, zonetable_local, "centroid", 0.1)
2073 if nearest[1]*radian_to_km < 1:
2074 qalog.append( "%s: within one km of %s\n" % (
2078 zones_overlapping += 1
2080 qalog.append("%s: no centroid\n" % zone)
2081 zones_nocentroid += 1
2082 if not zones.has_option(zone, "description"):
2083 qalog.append("%s: no description\n" % zone)
2084 zones_nodescription += 1
2085 if not zones.has_option(zone, "zone_forecast"):
2086 qalog.append("%s: no forecast\n" % zone)
2087 zones_noforecast += 1
2088 if os.path.exists(qalog_fn):
2089 os.rename(qalog_fn, "%s_old"%qalog_fn)
2090 qalog_fd = codecs.open(qalog_fn, "w", "utf8")
2091 qalog_fd.writelines(qalog)
2094 print("issues found (see %s for details):"%qalog_fn)
2095 if airports_badstation:
2096 print(" %s airports with invalid station"%airports_badstation)
2097 if airports_nostation:
2098 print(" %s airports with no station"%airports_nostation)
2099 if places_nocentroid:
2100 print(" %s places with no centroid"%places_nocentroid)
2101 if places_nodescription:
2102 print(" %s places with no description"%places_nodescription)
2103 if stations_nodescription:
2104 print(" %s stations with no description"%stations_nodescription)
2105 if stations_nolocation:
2106 print(" %s stations with no location"%stations_nolocation)
2107 if stations_nometar:
2108 print(" %s stations with no METAR"%stations_nometar)
2109 if zctas_nocentroid:
2110 print(" %s ZCTAs with no centroid"%zctas_nocentroid)
2111 if zones_nocentroid:
2112 print(" %s zones with no centroid"%zones_nocentroid)
2113 if zones_nodescription:
2114 print(" %s zones with no description"%zones_nodescription)
2115 if zones_noforecast:
2116 print(" %s zones with no forecast"%zones_noforecast)
2117 if zones_overlapping:
2118 print(" %s zones within one km of another"%zones_overlapping)
2119 else: print("no issues found.")
2120 print("Indexing complete!")