1 """Contains various object definitions needed by the weather utility."""
3 weather_copyright = """\
4 # Copyright (c) 2006-2024 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.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]
93 message = "WARNING: no URI defined for %s\n" % option
94 sys.stderr.write(message)
96 def get_bool(self, option, argument=None):
97 """Get data and coerce to a boolean if necessary."""
98 # Mimic configparser's getboolean() method by treating
99 # false/no/off/0 as False and true/yes/on/1 as True values,
101 value = self.get(option, argument)
102 if isinstance(value, bool):
104 if isinstance(value, str):
105 vlower = value.lower()
106 if vlower in ('false', 'no', 'off', '0'):
108 elif vlower in ('true', 'yes', 'on', '1'):
110 raise ValueError("Not a boolean: %s" % value)
111 def getint(self, option, argument=None):
112 """Get data and coerce to an integer if necessary."""
113 value = self.get(option, argument)
114 if value: return int(value)
118 """Average a list of coordinates."""
125 return (x/count, y/count)
127 def filter_units(line, units="imperial"):
128 """Filter or convert units in a line of text between US/UK and metric."""
130 # filter lines with both pressures in the form of "X inches (Y hPa)" or
133 r"(.* )(\d*(\.\d+)? (inches|in\. Hg)) \((\d*(\.\d+)? hPa)\)(.*)",
137 preamble, in_hg, i_fr, i_un, hpa, h_fr, trailer = dual_p.groups()
138 if units == "imperial": line = preamble + in_hg + trailer
139 elif units == "metric": line = preamble + hpa + trailer
140 # filter lines with both temperatures in the form of "X F (Y C)"
142 r"(.* )(-?\d*(\.\d+)? F) \((-?\d*(\.\d+)? C)\)(.*)",
146 preamble, fahrenheit, f_fr, celsius, c_fr, trailer = dual_t.groups()
147 if units == "imperial": line = preamble + fahrenheit + trailer
148 elif units == "metric": line = preamble + celsius + trailer
149 # if metric is desired, convert distances in the form of "X mile(s)" to
151 if units == "metric":
152 imperial_d = re.match(
153 r"(.* )(\d+)( mile\(s\))(.*)",
157 preamble, mi, m_u, trailer = imperial_d.groups()
158 line = preamble + str(int(round(int(mi)*1.609344))) \
159 + " kilometer(s)" + trailer
160 # filter speeds in the form of "X MPH (Y KT)" to just "X MPH"; if metric is
161 # desired, convert to "Z KPH"
162 imperial_s = re.match(
163 r"(.* )(\d+)( MPH)( \(\d+ KT\))(.*)",
167 preamble, mph, m_u, kt, trailer = imperial_s.groups()
168 if units == "imperial": line = preamble + mph + m_u + trailer
169 elif units == "metric":
170 line = preamble + str(int(round(int(mph)*1.609344))) + " KPH" + \
172 imperial_s = re.match(
173 r"(.* )(\d+)( MPH)( \(\d+ KT\))(.*)",
177 preamble, mph, m_u, kt, trailer = imperial_s.groups()
178 if units == "imperial": line = preamble + mph + m_u + trailer
179 elif units == "metric":
180 line = preamble + str(int(round(int(mph)*1.609344))) + " KPH" + \
182 # if imperial is desired, qualify given forcast temperatures like "X F"; if
183 # metric is desired, convert to "Y C"
184 imperial_t = re.match(
185 r"(.* )(High |high |Low |low )(\d+)(\.|,)(.*)",
189 preamble, parameter, fahrenheit, sep, trailer = imperial_t.groups()
190 if units == "imperial":
191 line = preamble + parameter + fahrenheit + " F" + sep + trailer
192 elif units == "metric":
193 line = preamble + parameter \
194 + str(int(round((int(fahrenheit)-32)*5/9))) + " C" + sep \
196 # hand off the resulting line
206 """Return a string containing the results of a URI GET."""
208 import urllib, urllib.error, urllib.request
209 URLError = urllib.error.URLError
210 urlopen = urllib.request.urlopen
212 import urllib2 as urllib
213 URLError = urllib.URLError
214 urlopen = urllib.urlopen
217 dcachedir = os.path.join( os.path.expanduser(cachedir), "datacache" )
218 if not os.path.exists(dcachedir):
219 try: os.makedirs(dcachedir)
220 except (IOError, OSError): pass
221 dcache_fn = os.path.join(
223 uri.split(":",1)[1].replace("/","_")
226 if cache_data and os.access(dcache_fn, os.R_OK) \
227 and now-cacheage < os.stat(dcache_fn).st_mtime <= now:
228 dcache_fd = open(dcache_fn)
229 data = dcache_fd.read()
233 data = urlopen(uri).read().decode("utf-8")
235 if ignore_fail: return ""
237 sys.stderr.write("%s error: failed to retrieve\n %s\n\n" % (
238 os.path.basename( sys.argv[0] ), uri))
240 # Some data sources are HTML with the plain text wrapped in pre tags
242 data = data[data.find("<pre>")+5:data.find("</pre>")]
246 dcache_fd = codecs.open(dcache_fn, "w", "utf-8")
247 dcache_fd.write(data)
249 except (IOError, OSError): pass
263 """Return a summarized METAR for the specified station."""
266 message = "%s error: METAR URI required for conditions\n" % \
267 os.path.basename( sys.argv[0] )
268 sys.stderr.write(message)
272 cache_data=cache_data,
276 if pyversion("3") and type(metar) is bytes: metar = metar.decode("utf-8")
277 if verbose: return metar
280 lines = metar.split("\n")
283 "relative_humidity," \
284 + "precipitation_last_hour," \
285 + "sky conditions," \
291 headerlist = headers.lower().replace("_"," ").split(",")
294 title = "Current conditions at %s"
295 place = lines[0].split(", ")
297 place = "%s, %s" % ( place[0].title(), place[1] )
298 else: place = "<UNKNOWN>"
299 output.append(title%place)
300 output.append("Last updated " + lines[1])
302 for header in headerlist:
304 if line.lower().startswith(header + ":"):
305 if re.match(r".*:\d+$", line): line = line[:line.rfind(":")]
306 if imperial: line = filter_units(line, units="imperial")
307 elif metric: line = filter_units(line, units="metric")
308 if quiet: output.append(line)
309 else: output.append(" " + line)
313 "(no conditions matched your header list, try with --verbose)"
315 return "\n".join(output)
325 """Return alert notice for the specified URI."""
331 cache_data=cache_data,
335 if pyversion("3") and type(alert) is bytes: alert = alert.decode("utf-8")
337 if verbose: return alert
339 if alert.find("\nNATIONAL WEATHER SERVICE") == -1:
343 lines = alert.split("\n")
345 # TODO: make this offset configurable
346 # TODO: adjust offset relative to the difference between the user's
347 # local time and the zone's local time (will need to extend
348 # the schema in the zones file to store each tz
349 offset = 86400 # one day
351 # report alerts and forecasts that expired less than offset ago;
352 # this is a cheap hack since expiration times seem to be relative
353 # to the zone's local timezone, and converting from the user's
354 # would get complicated, but also there can sometimes be a lag
355 # between expiration and the next update
356 valid_time = time.strftime(
357 "%Y%m%d%H%M", time.localtime(time.time() - offset))
360 if line.startswith("Expires:") \
361 and "Expires:" + valid_time > line:
363 if muted and line.startswith("NATIONAL WEATHER SERVICE"):
370 if line and not muted:
371 if quiet: output.append(line)
372 else: output.append(" " + line)
373 return "\n".join(output)
375 def get_options(config):
376 """Parse the options passed on the command line."""
378 # for optparse's builtin -h/--help option
380 "usage: %prog [options] [alias1|search1 [alias2|search2 [...]]]"
382 # for optparse's builtin --version option
383 verstring = "%prog " + weather_version
387 option_parser = optparse.OptionParser(usage=usage, version=verstring)
388 # separate options object from list of arguments and return both
390 # the -a/--alert option
391 if config.has_option("default", "alert"):
392 default_alert = config.getboolean("default", "alert")
393 else: default_alert = False
394 option_parser.add_option("-a", "--alert",
397 default=default_alert,
398 help="include local alert notices")
400 # the --atypes option
401 if config.has_option("default", "atypes"):
402 default_atypes = config.get("default", "atypes")
405 "coastal_flood_statement," \
406 + "flash_flood_statement," \
407 + "flash_flood_warning," \
408 + "flash_flood_watch," \
410 + "severe_thunderstorm_warning," \
411 + "severe_weather_statement," \
412 + "special_weather_statement," \
414 + "urgent_weather_message"
415 option_parser.add_option("--atypes",
417 default=default_atypes,
418 help="list of alert notification types to display")
420 # the --build-sets option
421 option_parser.add_option("--build-sets",
425 help="(re)build location correlation sets")
427 # the --cacheage option
428 if config.has_option("default", "cacheage"):
429 default_cacheage = config.getint("default", "cacheage")
430 else: default_cacheage = 900
431 option_parser.add_option("--cacheage",
433 default=default_cacheage,
434 help="duration in seconds to refresh cached data")
436 # the --cachedir option
437 if config.has_option("default", "cachedir"):
438 default_cachedir = config.get("default", "cachedir")
439 else: default_cachedir = "~/.weather"
440 option_parser.add_option("--cachedir",
442 default=default_cachedir,
443 help="directory for storing cached searches and data")
445 # the -f/--forecast option
446 if config.has_option("default", "forecast"):
447 default_forecast = config.getboolean("default", "forecast")
448 else: default_forecast = False
449 option_parser.add_option("-f", "--forecast",
452 default=default_forecast,
453 help="include a local forecast")
455 # the --headers option
456 if config.has_option("default", "headers"):
457 default_headers = config.get("default", "headers")
461 + "relative_humidity," \
466 + "sky_conditions," \
467 + "precipitation_last_hour"
468 option_parser.add_option("--headers",
470 default=default_headers,
471 help="list of conditions headers to display")
473 # the --imperial option
474 if config.has_option("default", "imperial"):
475 default_imperial = config.getboolean("default", "imperial")
476 else: default_imperial = False
477 option_parser.add_option("--imperial",
480 default=default_imperial,
481 help="filter/convert conditions for US/UK units")
484 option_parser.add_option("--info",
488 help="output detailed information for your search")
490 # the -l/--list option
491 option_parser.add_option("-l", "--list",
495 help="list all configured aliases and cached searches")
497 # the --longlist option
498 option_parser.add_option("--longlist",
502 help="display details of all configured aliases")
504 # the -m/--metric option
505 if config.has_option("default", "metric"):
506 default_metric = config.getboolean("default", "metric")
507 else: default_metric = False
508 option_parser.add_option("-m", "--metric",
511 default=default_metric,
512 help="filter/convert conditions for metric units")
514 # the -n/--no-conditions option
515 if config.has_option("default", "conditions"):
516 default_conditions = config.getboolean("default", "conditions")
517 else: default_conditions = True
518 option_parser.add_option("-n", "--no-conditions",
520 action="store_false",
521 default=default_conditions,
522 help="disable output of current conditions")
524 # the --no-cache option
525 if config.has_option("default", "cache"):
526 default_cache = config.getboolean("default", "cache")
527 else: default_cache = True
528 option_parser.add_option("--no-cache",
530 action="store_false",
532 help="disable all caching (searches and data)")
534 # the --no-cache-data option
535 if config.has_option("default", "cache_data"):
536 default_cache_data = config.getboolean("default", "cache_data")
537 else: default_cache_data = True
538 option_parser.add_option("--no-cache-data",
540 action="store_false",
542 help="disable retrieved data caching")
544 # the --no-cache-search option
545 if config.has_option("default", "cache_search"):
546 default_cache_search = config.getboolean("default", "cache_search")
547 else: default_cache_search = True
548 option_parser.add_option("--no-cache-search",
550 action="store_false",
552 help="disable search result caching")
554 # the -q/--quiet option
555 if config.has_option("default", "quiet"):
556 default_quiet = config.getboolean("default", "quiet")
557 else: default_quiet = False
558 option_parser.add_option("-q", "--quiet",
561 default=default_quiet,
562 help="skip preambles and don't indent")
564 # the --setpath option
565 if config.has_option("default", "setpath"):
566 default_setpath = config.get("default", "setpath")
567 else: default_setpath = ".:~/.weather"
568 option_parser.add_option("--setpath",
570 default=default_setpath,
571 help="directory search path for correlation sets")
573 # the -v/--verbose option
574 if config.has_option("default", "verbose"):
575 default_verbose = config.getboolean("default", "verbose")
576 else: default_verbose = False
577 option_parser.add_option("-v", "--verbose",
580 default=default_verbose,
581 help="show full decoded feeds")
584 if config.has_option("default", "city"):
585 default_city = config.get("default", "city")
586 else: default_city = ""
587 option_parser.add_option("-c", "--city",
589 default=default_city,
590 help=optparse.SUPPRESS_HELP)
591 if config.has_option("default", "id"):
592 default_id = config.get("default", "id")
593 else: default_id = ""
594 option_parser.add_option("-i", "--id",
597 help=optparse.SUPPRESS_HELP)
598 if config.has_option("default", "st"):
599 default_st = config.get("default", "st")
600 else: default_st = ""
601 option_parser.add_option("-s", "--st",
604 help=optparse.SUPPRESS_HELP)
606 options, arguments = option_parser.parse_args()
607 return options, arguments
610 """Parse the aliases and configuration."""
611 if pyversion("3"): import configparser
612 else: import ConfigParser as configparser
613 config = configparser.ConfigParser()
617 "/etc/weather/weatherrc",
618 os.path.expanduser("~/.weather/weatherrc"),
619 os.path.expanduser("~/.weatherrc"),
622 for rcfile in rcfiles:
623 if os.access(rcfile, os.R_OK):
625 config.read(rcfile, encoding="utf-8")
628 for section in config.sections():
629 if section != section.lower():
630 if config.has_section(section.lower()):
631 config.remove_section(section.lower())
632 config.add_section(section.lower())
633 for option,value in config.items(section):
634 config.set(section.lower(), option, value)
637 def integrate_search_cache(config, cachedir, setpath):
638 """Add cached search results into the configuration."""
639 if pyversion("3"): import configparser
640 else: import ConfigParser as configparser
642 scache_fn = os.path.join( os.path.expanduser(cachedir), "searches" )
643 if not os.access(scache_fn, os.R_OK): return config
644 scache_fd = open(scache_fn)
645 created = float( scache_fd.readline().split(":")[1].strip().split()[0] )
648 datafiles = data_index(setpath)
650 data_freshness = sorted(
651 [ x[1] for x in datafiles.values() ],
654 else: data_freshness = now
655 if created < data_freshness <= now:
658 print( "[clearing outdated %s]" % scache_fn )
659 except (IOError, OSError):
662 scache = configparser.ConfigParser()
664 scache.read(scache_fn, encoding="utf-8")
666 scache.read(scache_fn)
667 for section in scache.sections():
668 if not config.has_section(section):
669 config.add_section(section)
670 for option,value in scache.items(section):
671 config.set(section, option, value)
674 def list_aliases(config, detail=False):
675 """Return a formatted list of aliases defined in the config."""
677 output = "\n# configured alias details..."
678 for section in sorted(config.sections()):
679 output += "\n\n[%s]" % section
680 for item in sorted(config.items(section)):
681 output += "\n%s = %s" % item
684 output = "configured aliases and cached searches..."
685 for section in sorted(config.sections()):
686 if config.has_option(section, "description"):
687 description = config.get(section, "description")
688 else: description = "(no description provided)"
689 output += "\n %s: %s" % (section, description)
692 def data_index(path):
695 for filename in ("airports", "places", "stations", "zctas", "zones"):
696 for dirname in path.split(":"):
697 for extension in ("", ".gz", ".txt"):
698 candidate = os.path.expanduser(
699 os.path.join( dirname, "".join( (filename, extension) ) )
701 if os.path.exists(candidate):
702 datafiles[filename] = (
704 os.stat(candidate).st_mtime
707 if filename in datafiles:
721 """Find URIs using airport, gecos, placename, station, ZCTA/ZIP, zone."""
722 import codecs, datetime, time, os, re, sys
723 if pyversion("3"): import configparser
724 else: import ConfigParser as configparser
725 datafiles = data_index(path)
726 if re.match("[A-Za-z]{3}$", expression): searchtype = "airport"
727 elif re.match("[A-Za-z0-9]{4}$", expression): searchtype = "station"
728 elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", expression): searchtype = "zone"
729 elif re.match("[0-9]{5}$", expression): searchtype = "ZCTA"
731 r"[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?, *[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?$",
734 searchtype = "coordinates"
735 elif re.match(r"(FIPS|fips)\d+$", expression): searchtype = "FIPS"
739 if cache_search: action = "caching"
740 else: action = "using"
749 (0.995, "excellent"),
752 if not quiet: print("Searching via %s..."%searchtype)
753 stations = configparser.ConfigParser()
754 dataname = "stations"
755 if dataname in datafiles:
756 datafile = datafiles[dataname][0]
757 if datafile.endswith(".gz"):
760 stations.read_string(
761 gzip.open(datafile).read().decode("utf-8") )
762 else: stations.read_file( gzip.open(datafile) )
765 stations.read(datafile, encoding="utf-8")
767 stations.read(datafile)
769 message = "%s error: can't find \"%s\" data file\n" % (
770 os.path.basename( sys.argv[0] ),
773 sys.stderr.write(message)
775 zones = configparser.ConfigParser()
777 if dataname in datafiles:
778 datafile = datafiles[dataname][0]
779 if datafile.endswith(".gz"):
782 zones.read_string( gzip.open(datafile).read().decode("utf-8") )
783 else: zones.read_file( gzip.open(datafile) )
786 zones.read(datafile, encoding="utf-8")
790 message = "%s error: can't find \"%s\" data file\n" % (
791 os.path.basename( sys.argv[0] ),
794 sys.stderr.write(message)
802 if searchtype == "airport":
803 expression = expression.lower()
804 airports = configparser.ConfigParser()
805 dataname = "airports"
806 if dataname in datafiles:
807 datafile = datafiles[dataname][0]
808 if datafile.endswith(".gz"):
811 airports.read_string(
812 gzip.open(datafile).read().decode("utf-8") )
813 else: airports.read_file( gzip.open(datafile) )
816 airports.read(datafile, encoding="utf-8")
818 airports.read(datafile)
820 message = "%s error: can't find \"%s\" data file\n" % (
821 os.path.basename( sys.argv[0] ),
824 sys.stderr.write(message)
826 if airports.has_section(expression) \
827 and airports.has_option(expression, "station"):
828 search = (expression, "IATA/FAA airport code %s" % expression)
829 station = ( airports.get(expression, "station"), 0 )
830 if stations.has_option(station[0], "zone"):
831 zone = eval( stations.get(station[0], "zone") )
833 if not ( info or quiet ) \
834 and stations.has_option( station[0], "description" ):
838 stations.get(station[0], "description")
842 message = "No IATA/FAA airport code \"%s\" in the %s file.\n" % (
844 datafiles["airports"][0]
846 sys.stderr.write(message)
848 elif searchtype == "station":
849 expression = expression.lower()
850 if stations.has_section(expression):
851 station = (expression, 0)
853 search = (expression, "ICAO station code %s" % expression)
854 if stations.has_option(expression, "zone"):
855 zone = eval( stations.get(expression, "zone") )
857 if not ( info or quiet ) \
858 and stations.has_option(expression, "description"):
862 stations.get(expression, "description")
866 message = "No ICAO weather station \"%s\" in the %s file.\n" % (
868 datafiles["stations"][0]
870 sys.stderr.write(message)
872 elif searchtype == "zone":
873 expression = expression.lower()
874 if zones.has_section(expression) \
875 and zones.has_option(expression, "station"):
876 zone = (expression, 0)
877 station = eval( zones.get(expression, "station") )
879 search = (expression, "NWS/NOAA weather zone %s" % expression)
880 if not ( info or quiet ) \
881 and zones.has_option(expression, "description"):
885 zones.get(expression, "description")
889 message = "No usable NWS weather zone \"%s\" in the %s file.\n" % (
891 datafiles["zones"][0]
893 sys.stderr.write(message)
895 elif searchtype == "ZCTA":
896 zctas = configparser.ConfigParser()
898 if dataname in datafiles:
899 datafile = datafiles[dataname][0]
900 if datafile.endswith(".gz"):
904 gzip.open(datafile).read().decode("utf-8") )
905 else: zctas.read_file( gzip.open(datafile) )
908 zctas.read(datafile, encoding="utf-8")
912 message = "%s error: can't find \"%s\" data file\n" % (
913 os.path.basename( sys.argv[0] ),
916 sys.stderr.write(message)
919 if zctas.has_section(expression) \
920 and zctas.has_option(expression, "station"):
921 station = eval( zctas.get(expression, "station") )
922 search = (expression, "Census ZCTA (ZIP code) %s" % expression)
923 if zctas.has_option(expression, "zone"):
924 zone = eval( zctas.get(expression, "zone") )
926 message = "No census ZCTA (ZIP code) \"%s\" in the %s file.\n" % (
928 datafiles["zctas"][0]
930 sys.stderr.write(message)
932 elif searchtype == "coordinates":
933 search = (expression, "Geographic coordinates %s" % expression)
935 for station in stations.sections():
936 if stations.has_option(station, "location"):
937 stationtable[station] = {
938 "location": eval( stations.get(station, "location") )
940 station = closest( gecos(expression), stationtable, "location", 0.1 )
942 message = "No ICAO weather station found near %s.\n" % expression
943 sys.stderr.write(message)
946 for zone in zones.sections():
947 if zones.has_option(zone, "centroid"):
949 "centroid": eval( zones.get(zone, "centroid") )
951 zone = closest( gecos(expression), zonetable, "centroid", 0.1 )
953 message = "No NWS weather zone near %s; forecasts unavailable.\n" \
955 sys.stderr.write(message)
956 elif searchtype in ("FIPS", "name"):
957 places = configparser.ConfigParser()
959 if dataname in datafiles:
960 datafile = datafiles[dataname][0]
961 if datafile.endswith(".gz"):
965 gzip.open(datafile).read().decode("utf-8") )
966 else: places.read_file( gzip.open(datafile) )
969 places.read(datafile, encoding="utf-8")
971 places.read(datafile)
973 message = "%s error: can't find \"%s\" data file\n" % (
974 os.path.basename( sys.argv[0] ),
977 sys.stderr.write(message)
980 place = expression.lower()
981 if places.has_section(place) and places.has_option(place, "station"):
982 station = eval( places.get(place, "station") )
983 search = (expression, "Census Place %s" % expression)
984 if places.has_option(place, "description"):
987 search[1] + ", %s" % places.get(place, "description")
989 if places.has_option(place, "zone"):
990 zone = eval( places.get(place, "zone") )
991 if not ( info or quiet ) \
992 and places.has_option(place, "description"):
996 places.get(place, "description")
1000 for place in places.sections():
1001 if places.has_option(place, "description") \
1002 and places.has_option(place, "station") \
1005 places.get(place, "description"),
1008 possibilities.append(place)
1009 for place in stations.sections():
1010 if stations.has_option(place, "description") \
1013 stations.get(place, "description"),
1016 possibilities.append(place)
1017 for place in zones.sections():
1018 if zones.has_option(place, "description") \
1019 and zones.has_option(place, "station") \
1022 zones.get(place, "description"),
1025 possibilities.append(place)
1026 if len(possibilities) == 1:
1027 place = possibilities[0]
1028 if places.has_section(place):
1029 station = eval( places.get(place, "station") )
1030 description = places.get(place, "description")
1031 if places.has_option(place, "zone"):
1032 zone = eval( places.get(place, "zone" ) )
1033 search = ( expression, "%s: %s" % (place, description) )
1034 elif stations.has_section(place):
1035 station = (place, 0.0)
1036 description = stations.get(place, "description")
1037 if stations.has_option(place, "zone"):
1038 zone = eval( stations.get(place, "zone" ) )
1039 search = ( expression, "ICAO station code %s" % place )
1040 elif zones.has_section(place):
1041 station = eval( zones.get(place, "station") )
1042 description = zones.get(place, "description")
1044 search = ( expression, "NWS/NOAA weather zone %s" % place )
1045 if not ( info or quiet ):
1046 print( "[%s result %s]" % (action, description) )
1047 if not possibilities and not station[0]:
1048 message = "No FIPS code/census area match in the %s file.\n" % (
1049 datafiles["places"][0]
1051 sys.stderr.write(message)
1054 uris["metar"] = stations.get( station[0], "metar" )
1056 for key,value in zones.items( zone[0] ):
1057 if key not in ("centroid", "description", "station"):
1060 count = len(possibilities)
1061 if count <= max_results:
1062 print( "Your search is ambiguous, returning %s matches:" % count )
1063 for place in sorted(possibilities):
1064 if places.has_section(place):
1068 places.get(place, "description")
1071 elif stations.has_section(place):
1075 stations.get(place, "description")
1078 elif zones.has_section(place):
1082 zones.get(place, "description")
1087 "Your search is too ambiguous, returning %s matches." % count
1094 for section in dataset.sections():
1095 if dataset.has_option(section, "station"):
1097 eval( dataset.get(section, "station") )[1]
1099 if dataset.has_option(section, "zone"):
1100 zonelist.append( eval( dataset.get(section, "zone") )[1] )
1103 scount = len(stationlist)
1104 zcount = len(zonelist)
1107 for score in scores:
1109 sranks.append( stationlist[ int( (1-score[0]) * scount ) ] )
1111 zranks.append( zonelist[ int( (1-score[0]) * zcount ) ] )
1112 description = search[1]
1113 uris["description"] = description
1115 "%s\n%s" % ( description, "-" * len(description) )
1120 stations.get( station[0], "description" )
1123 km = radian_to_km*station[1]
1124 mi = radian_to_mi*station[1]
1125 if sranks and not description.startswith("ICAO station code "):
1126 for index in range(0, len(scores)):
1127 if station[1] >= sranks[index]:
1128 score = scores[index][1]
1131 " (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1133 elif searchtype == "coordinates":
1134 print( " (%.3gkm, %.3gmi)" % (km, mi) )
1137 "%s: %s" % ( zone[0], zones.get( zone[0], "description" ) )
1139 km = radian_to_km*zone[1]
1140 mi = radian_to_mi*zone[1]
1141 if zranks and not description.startswith("NWS/NOAA weather zone "):
1142 for index in range(0, len(scores)):
1143 if zone[1] >= zranks[index]:
1144 score = scores[index][1]
1147 " (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1149 elif searchtype == "coordinates" and zone[0]:
1150 print( " (%.3gkm, %.3gmi)" % (km, mi) )
1153 nowstamp = "%s (%s)" % (
1155 datetime.datetime.isoformat(
1156 datetime.datetime.fromtimestamp(now),
1160 search_cache = ["\n"]
1161 search_cache.append( "[%s]\n" % search[0] )
1162 search_cache.append( "cached = %s\n" % nowstamp )
1163 for uriname in sorted(uris.keys()):
1164 search_cache.append( "%s = %s\n" % ( uriname, uris[uriname] ) )
1165 real_cachedir = os.path.expanduser(cachedir)
1166 if not os.path.exists(real_cachedir):
1167 try: os.makedirs(real_cachedir)
1168 except (IOError, OSError): pass
1169 scache_fn = os.path.join(real_cachedir, "searches")
1170 if not os.path.exists(scache_fn):
1172 [ x[1] for x in datafiles.values() ],
1175 thenstamp = "%s (%s)" % (
1177 datetime.datetime.isoformat(
1178 datetime.datetime.fromtimestamp(then),
1182 search_cache.insert(
1184 "# based on data files from: %s\n" % thenstamp
1187 scache_existing = configparser.ConfigParser()
1189 scache_existing.read(scache_fn, encoding="utf-8")
1191 scache_existing.read(scache_fn)
1192 if not scache_existing.has_section(search[0]):
1193 scache_fd = codecs.open(scache_fn, "a", "utf-8")
1194 scache_fd.writelines(search_cache)
1196 except (IOError, OSError): pass
1200 def closest(position, nodes, fieldname, angle=None):
1202 if not angle: angle = 2*math.pi
1205 if fieldname in nodes[name]:
1206 node = nodes[name][fieldname]
1207 if node and abs( position[0]-node[0] ) < angle:
1208 if abs( position[1]-node[1] ) < angle \
1209 or abs( abs( position[1]-node[1] ) - 2*math.pi ) < angle:
1210 if position == node:
1214 candidate = math.acos(
1215 math.sin( position[0] ) * math.sin( node[0] ) \
1216 + math.cos( position[0] ) \
1217 * math.cos( node[0] ) \
1218 * math.cos( position[1] - node[1] )
1220 if candidate < angle:
1223 if match: match = str(match)
1224 return (match, angle)
1226 def gecos(formatted):
1228 coordinates = formatted.split(",")
1229 for coordinate in range(0, 2):
1230 degrees, foo, minutes, bar, seconds, hemisphere = re.match(
1231 r"([\+-]?\d+\.?\d*)(-(\d+))?(-(\d+))?([ensw]?)$",
1232 coordinates[coordinate].strip().lower()
1234 value = float(degrees)
1235 if minutes: value += float(minutes)/60
1236 if seconds: value += float(seconds)/3600
1237 if hemisphere and hemisphere in "sw": value *= -1
1238 coordinates[coordinate] = math.radians(value)
1239 return tuple(coordinates)
1242 import codecs, csv, datetime, hashlib, os, re, sys, time, zipfile
1243 if pyversion("3"): import configparser
1244 else: import ConfigParser as configparser
1245 for filename in os.listdir("."):
1246 if re.match("[0-9]{4}_Gaz_counties_national.zip$", filename):
1247 gcounties_an = filename
1248 gcounties_fn = filename[:-4] + ".txt"
1249 elif re.match("[0-9]{4}_Gaz_cousubs_national.zip$", filename):
1250 gcousubs_an = filename
1251 gcousubs_fn = filename[:-4] + ".txt"
1252 elif re.match("[0-9]{4}_Gaz_place_national.zip$", filename):
1253 gplace_an = filename
1254 gplace_fn = filename[:-4] + ".txt"
1255 elif re.match("[0-9]{4}_Gaz_zcta_national.zip$", filename):
1257 gzcta_fn = filename[:-4] + ".txt"
1258 elif re.match("bp[0-9]{2}[a-z]{2}[0-9]{2}.dbx$", filename):
1259 cpfzcf_fn = filename
1260 nsdcccc_fn = "nsd_cccc.txt"
1261 ourairports_fn = "airports.csv"
1262 overrides_fn = "overrides.conf"
1263 overrideslog_fn = "overrides.log"
1267 airports_fn = "airports"
1268 places_fn = "places"
1269 stations_fn = "stations"
1274 # generated by %s on %s from these public domain sources:
1276 # https://www.census.gov/geographies/reference-files/time-series/geo/gazetteer-files.html
1282 # https://www.weather.gov/gis/ZoneCounty/
1285 # https://tgftp.nws.noaa.gov/data/
1288 # https://ourairports.com/data/
1291 # ...and these manually-generated or hand-compiled adjustments:
1297 os.path.basename( sys.argv[0] ),
1298 datetime.date.isoformat(
1299 datetime.datetime.utcfromtimestamp( int(os.environ.get('SOURCE_DATE_EPOCH', time.time())) )
1301 hashlib.md5( open(gcounties_an, "rb").read() ).hexdigest(),
1302 datetime.date.isoformat(
1303 datetime.datetime.utcfromtimestamp( os.path.getmtime(gcounties_an) )
1306 hashlib.md5( open(gcousubs_an, "rb").read() ).hexdigest(),
1307 datetime.date.isoformat(
1308 datetime.datetime.utcfromtimestamp( os.path.getmtime(gcousubs_an) )
1311 hashlib.md5( open(gplace_an, "rb").read() ).hexdigest(),
1312 datetime.date.isoformat(
1313 datetime.datetime.utcfromtimestamp( os.path.getmtime(gplace_an) )
1316 hashlib.md5( open(gzcta_an, "rb").read() ).hexdigest(),
1317 datetime.date.isoformat(
1318 datetime.datetime.utcfromtimestamp( os.path.getmtime(gzcta_an) )
1321 hashlib.md5( open(cpfzcf_fn, "rb").read() ).hexdigest(),
1322 datetime.date.isoformat(
1323 datetime.datetime.utcfromtimestamp( os.path.getmtime(cpfzcf_fn) )
1326 hashlib.md5( open(nsdcccc_fn, "rb").read() ).hexdigest(),
1327 datetime.date.isoformat(
1328 datetime.datetime.utcfromtimestamp( os.path.getmtime(nsdcccc_fn) )
1331 hashlib.md5( open(ourairports_fn, "rb").read() ).hexdigest(),
1332 datetime.date.isoformat(
1333 datetime.datetime.utcfromtimestamp( os.path.getmtime(ourairports_fn) )
1336 hashlib.md5( open(overrides_fn, "rb").read() ).hexdigest(),
1337 datetime.date.isoformat(
1338 datetime.datetime.utcfromtimestamp( os.path.getmtime(overrides_fn) )
1341 hashlib.md5( open(slist_fn, "rb").read() ).hexdigest(),
1342 datetime.date.isoformat(
1343 datetime.datetime.utcfromtimestamp( os.path.getmtime(slist_fn) )
1346 hashlib.md5( open(zlist_fn, "rb").read() ).hexdigest(),
1347 datetime.date.isoformat(
1348 datetime.datetime.utcfromtimestamp( os.path.getmtime(zlist_fn) )
1357 message = "Reading %s:%s..." % (gcounties_an, gcounties_fn)
1358 sys.stdout.write(message)
1361 gcounties = zipfile.ZipFile(gcounties_an).open(gcounties_fn, "r")
1362 columns = gcounties.readline().decode("utf-8").strip().split("\t")
1363 for line in gcounties:
1364 fields = line.decode("utf-8").strip().split("\t")
1365 f_geoid = fields[ columns.index("GEOID") ].strip()
1366 f_name = fields[ columns.index("NAME") ].strip()
1367 f_usps = fields[ columns.index("USPS") ].strip()
1368 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1369 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1370 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1371 fips = "fips%s" % f_geoid
1372 if fips not in places: places[fips] = {}
1373 places[fips]["centroid"] = gecos(
1374 "%s,%s" % (f_intptlat, f_intptlong)
1376 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1379 print("done (%s lines)." % count)
1380 message = "Reading %s:%s..." % (gcousubs_an, gcousubs_fn)
1381 sys.stdout.write(message)
1384 gcousubs = zipfile.ZipFile(gcousubs_an).open(gcousubs_fn, "r")
1385 columns = gcousubs.readline().decode("utf-8").strip().split("\t")
1386 for line in gcousubs:
1387 fields = line.decode("utf-8").strip().split("\t")
1388 f_geoid = fields[ columns.index("GEOID") ].strip()
1389 f_name = fields[ columns.index("NAME") ].strip()
1390 f_usps = fields[ columns.index("USPS") ].strip()
1391 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1392 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1393 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1394 fips = "fips%s" % f_geoid
1395 if fips not in places: places[fips] = {}
1396 places[fips]["centroid"] = gecos(
1397 "%s,%s" % (f_intptlat, f_intptlong)
1399 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1402 print("done (%s lines)." % count)
1403 message = "Reading %s:%s..." % (gplace_an, gplace_fn)
1404 sys.stdout.write(message)
1407 gplace = zipfile.ZipFile(gplace_an).open(gplace_fn, "r")
1408 columns = gplace.readline().decode("utf-8").strip().split("\t")
1410 fields = line.decode("utf-8").strip().split("\t")
1411 f_geoid = fields[ columns.index("GEOID") ].strip()
1412 f_name = fields[ columns.index("NAME") ].strip()
1413 f_usps = fields[ columns.index("USPS") ].strip()
1414 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1415 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1416 if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1417 fips = "fips%s" % f_geoid
1418 if fips not in places: places[fips] = {}
1419 places[fips]["centroid"] = gecos(
1420 "%s,%s" % (f_intptlat, f_intptlong)
1422 places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1425 print("done (%s lines)." % count)
1426 message = "Reading %s..." % slist_fn
1427 sys.stdout.write(message)
1430 slist = codecs.open(slist_fn, "r", "utf-8")
1432 icao = line.split("#")[0].strip()
1435 "metar": "https://tgftp.nws.noaa.gov/data/observations/"\
1436 + "metar/decoded/%s.TXT" % icao.upper()
1440 print("done (%s lines)." % count)
1441 message = "Reading %s..." % nsdcccc_fn
1442 sys.stdout.write(message)
1445 nsdcccc = codecs.open(nsdcccc_fn, "r", "utf-8")
1446 for line in nsdcccc:
1448 fields = line.split(";")
1449 icao = fields[0].strip().lower()
1450 if icao in stations:
1452 name = " ".join( fields[3].strip().title().split() )
1453 if name: description.append(name)
1454 st = fields[4].strip()
1455 if st: description.append(st)
1456 country = " ".join( fields[5].strip().title().split() )
1457 if country: description.append(country)
1459 stations[icao]["description"] = ", ".join(description)
1460 lat, lon = fields[7:9]
1462 stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1463 elif "location" not in stations[icao]:
1464 lat, lon = fields[5:7]
1466 stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1469 print("done (%s lines)." % count)
1470 message = "Reading %s..." % ourairports_fn
1471 sys.stdout.write(message)
1474 ourairports = open(ourairports_fn, "r")
1475 for row in csv.reader(ourairports):
1476 icao = row[12].lower()
1477 if icao in stations:
1478 iata = row[13].lower()
1479 if len(iata) == 3: airports[iata] = { "station": icao }
1480 if "description" not in stations[icao]:
1483 if name: description.append(name)
1484 municipality = row[10]
1485 if municipality: description.append(municipality)
1490 c,r = region.split("-", 1)
1491 if c == country: region = r
1492 description.append(region)
1494 description.append(country)
1496 stations[icao]["description"] = ", ".join(description)
1497 if "location" not in stations[icao]:
1502 stations[icao]["location"] = gecos(
1503 "%s,%s" % (lat, lon)
1507 print("done (%s lines)." % count)
1508 message = "Reading %s..." % zlist_fn
1509 sys.stdout.write(message)
1512 zlist = codecs.open(zlist_fn, "r", "utf-8")
1514 line = line.split("#")[0].strip()
1519 print("done (%s lines)." % count)
1520 message = "Reading %s..." % cpfzcf_fn
1521 sys.stdout.write(message)
1525 cpfzcf = codecs.open(cpfzcf_fn, "r", "utf-8")
1527 fields = line.strip().split("|")
1528 if len(fields) == 11 \
1529 and fields[0] and fields[1] and fields[9] and fields[10]:
1530 zone = "z".join( fields[:2] ).lower()
1533 description = fields[3].strip()
1534 fips = "fips%s"%fields[6]
1535 countycode = "%sc%s" % (state.lower(), fips[-3:])
1537 zones[zone]["coastal_flood_statement"] = (
1538 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1539 "flood/coastal/%s/%s.txt" % (state.lower(), zone))
1540 zones[zone]["flash_flood_statement"] = (
1541 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1542 "flash_flood/statement/%s/%s.txt"
1543 % (state.lower(), countycode))
1544 zones[zone]["flash_flood_warning"] = (
1545 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1546 "flash_flood/warning/%s/%s.txt"
1547 % (state.lower(), countycode))
1548 zones[zone]["flash_flood_watch"] = (
1549 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1550 "flash_flood/watch/%s/%s.txt" % (state.lower(), zone))
1551 zones[zone]["flood_warning"] = (
1552 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1553 "flood/warning/%s/%s.txt"
1554 % (state.lower(), countycode))
1555 zones[zone]["severe_thunderstorm_warning"] = (
1556 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1557 "thunderstorm/%s/%s.txt" % (state.lower(), countycode))
1558 zones[zone]["severe_weather_statement"] = (
1559 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1560 "severe_weather_stmt/%s/%s.txt"
1561 % (state.lower(), countycode))
1562 zones[zone]["short_term_forecast"] = (
1563 "https://tgftp.nws.noaa.gov/data/forecasts/nowcast/"
1564 "%s/%s.txt" % (state.lower(), zone))
1565 zones[zone]["special_weather_statement"] = (
1566 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1567 "special_weather_stmt/%s/%s.txt"
1568 % (state.lower(), zone))
1569 zones[zone]["state_forecast"] = (
1570 "https://tgftp.nws.noaa.gov/data/forecasts/state/"
1571 "%s/%s.txt" % (state.lower(), zone))
1572 zones[zone]["tornado"] = (
1573 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1574 "tornado/%s/%s.txt" % (state.lower(), countycode))
1575 zones[zone]["urgent_weather_message"] = (
1576 "https://tgftp.nws.noaa.gov/data/watches_warnings/"
1577 "non_precip/%s/%s.txt" % (state.lower(), zone))
1578 zones[zone]["zone_forecast"] = (
1579 "https://tgftp.nws.noaa.gov/data/forecasts/zone/"
1580 "%s/%s.txt" % (state.lower(), zone))
1583 if description.endswith(county):
1584 description += " County"
1586 description += ", %s County" % county
1587 description += ", %s, US" % state
1588 zones[zone]["description"] = description
1589 zones[zone]["centroid"] = gecos( ",".join( fields[9:11] ) )
1590 if fips in places and not zones[zone]["centroid"]:
1591 zones[zone]["centroid"] = places[fips]["centroid"]
1594 print("done (%s lines)." % count)
1595 message = "Reading %s:%s..." % (gzcta_an, gzcta_fn)
1596 sys.stdout.write(message)
1599 gzcta = zipfile.ZipFile(gzcta_an).open(gzcta_fn, "r")
1600 columns = gzcta.readline().decode("utf-8").strip().split("\t")
1602 fields = line.decode("utf-8").strip().split("\t")
1603 f_geoid = fields[ columns.index("GEOID") ].strip()
1604 f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1605 f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1606 if f_geoid and f_intptlat and f_intptlong:
1607 if f_geoid not in zctas: zctas[f_geoid] = {}
1608 zctas[f_geoid]["centroid"] = gecos(
1609 "%s,%s" % (f_intptlat, f_intptlong)
1613 print("done (%s lines)." % count)
1614 message = "Reading %s..." % overrides_fn
1615 sys.stdout.write(message)
1621 overrides = configparser.ConfigParser()
1622 overrides.read_file( codecs.open(overrides_fn, "r", "utf8") )
1624 for section in overrides.sections():
1627 if section.startswith("-"):
1628 section = section[1:]
1630 else: delete = False
1631 if re.match("[A-Za-z]{3}$", section):
1633 if section in airports:
1634 del( airports[section] )
1635 logact = "removed airport %s" % section
1638 logact = "tried to remove nonexistent airport %s" % section
1640 if section in airports:
1641 logact = "changed airport %s" % section
1644 airports[section] = {}
1645 logact = "added airport %s" % section
1647 for key,value in overrides.items(section):
1648 if key in airports[section]: chgopt += 1
1650 if key in ("centroid", "location"):
1651 airports[section][key] = eval(value)
1653 airports[section][key] = value
1654 if addopt and chgopt:
1655 logact += " (+%s/!%s options)" % (addopt, chgopt)
1656 elif addopt: logact += " (+%s options)" % addopt
1657 elif chgopt: logact += " (!%s options)" % chgopt
1658 elif re.match("[A-Za-z0-9]{4}$", section):
1660 if section in stations:
1661 del( stations[section] )
1662 logact = "removed station %s" % section
1665 logact = "tried to remove nonexistent station %s" % section
1667 if section in stations:
1668 logact = "changed station %s" % section
1671 stations[section] = {}
1672 logact = "added station %s" % section
1674 for key,value in overrides.items(section):
1675 if key in stations[section]: chgopt += 1
1677 if key in ("centroid", "location"):
1678 stations[section][key] = eval(value)
1680 stations[section][key] = value
1681 if addopt and chgopt:
1682 logact += " (+%s/!%s options)" % (addopt, chgopt)
1683 elif addopt: logact += " (+%s options)" % addopt
1684 elif chgopt: logact += " (!%s options)" % chgopt
1685 elif re.match("[0-9]{5}$", section):
1687 if section in zctas:
1688 del( zctas[section] )
1689 logact = "removed zcta %s" % section
1692 logact = "tried to remove nonexistent zcta %s" % section
1694 if section in zctas:
1695 logact = "changed zcta %s" % section
1699 logact = "added zcta %s" % section
1701 for key,value in overrides.items(section):
1702 if key in zctas[section]: chgopt += 1
1704 if key in ("centroid", "location"):
1705 zctas[section][key] = eval(value)
1707 zctas[section][key] = value
1708 if addopt and chgopt:
1709 logact += " (+%s/!%s options)" % (addopt, chgopt)
1710 elif addopt: logact += " (+%s options)" % addopt
1711 elif chgopt: logact += " (!%s options)" % chgopt
1712 elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", section):
1714 if section in zones:
1715 del( zones[section] )
1716 logact = "removed zone %s" % section
1719 logact = "tried to remove nonexistent zone %s" % section
1721 if section in zones:
1722 logact = "changed zone %s" % section
1726 logact = "added zone %s" % section
1728 for key,value in overrides.items(section):
1729 if key in zones[section]: chgopt += 1
1731 if key in ("centroid", "location"):
1732 zones[section][key] = eval(value)
1734 zones[section][key] = value
1735 if addopt and chgopt:
1736 logact += " (+%s/!%s options)" % (addopt, chgopt)
1737 elif addopt: logact += " (+%s options)" % addopt
1738 elif chgopt: logact += " (!%s options)" % chgopt
1739 elif re.match("fips[0-9]+$", section):
1741 if section in places:
1742 del( places[section] )
1743 logact = "removed place %s" % section
1746 logact = "tried to remove nonexistent place %s" % section
1748 if section in places:
1749 logact = "changed place %s" % section
1752 places[section] = {}
1753 logact = "added place %s" % section
1755 for key,value in overrides.items(section):
1756 if key in places[section]: chgopt += 1
1758 if key in ("centroid", "location"):
1759 places[section][key] = eval(value)
1761 places[section][key] = value
1762 if addopt and chgopt:
1763 logact += " (+%s/!%s options)" % (addopt, chgopt)
1764 elif addopt: logact += " (+%s options)" % addopt
1765 elif chgopt: logact += " (!%s options)" % chgopt
1767 overrideslog.append("%s\n" % logact)
1769 if os.path.exists(overrideslog_fn):
1770 os.rename(overrideslog_fn, "%s_old"%overrideslog_fn)
1771 overrideslog_fd = codecs.open(overrideslog_fn, "w", "utf8")
1773 overrideslog_fd.write(
1774 '# Copyright (c) %s Jeremy Stanley <fungi@yuggoth.org>. Permission to\n'
1775 '# use, copy, modify, and distribute this software is granted under terms\n'
1776 '# provided in the LICENSE file distributed with this software.\n\n'
1777 % time.gmtime().tm_year)
1778 overrideslog_fd.writelines(overrideslog)
1779 overrideslog_fd.close()
1780 print("done (%s overridden sections: +%s/-%s/!%s)." % (
1786 estimate = 2*len(places) + len(stations) + 2*len(zctas) + len(zones)
1788 "Correlating places, stations, ZCTAs and zones (upper bound is %s):" % \
1792 milestones = list( range(51) )
1794 sys.stdout.write(message)
1797 centroid = places[fips]["centroid"]
1799 station = closest(centroid, stations, "location", 0.1)
1801 places[fips]["station"] = station
1804 level = int(50*count/estimate)
1805 if level in milestones:
1806 for remaining in milestones[:milestones.index(level)+1]:
1809 sys.stdout.write(message)
1812 message = "%s%%" % (remaining*2,)
1813 sys.stdout.write(message)
1815 milestones.remove(remaining)
1817 zone = closest(centroid, zones, "centroid", 0.1)
1819 places[fips]["zone"] = zone
1822 level = int(50*count/estimate)
1823 if level in milestones:
1824 for remaining in milestones[:milestones.index(level)+1]:
1827 sys.stdout.write(message)
1830 message = "%s%%" % (remaining*2,)
1831 sys.stdout.write(message)
1833 milestones.remove(remaining)
1834 for station in stations:
1835 if "location" in stations[station]:
1836 location = stations[station]["location"]
1838 zone = closest(location, zones, "centroid", 0.1)
1840 stations[station]["zone"] = zone
1843 level = int(50*count/estimate)
1844 if level in milestones:
1845 for remaining in milestones[:milestones.index(level)+1]:
1848 sys.stdout.write(message)
1851 message = "%s%%" % (remaining*2,)
1852 sys.stdout.write(message)
1854 milestones.remove(remaining)
1855 for zcta in zctas.keys():
1856 centroid = zctas[zcta]["centroid"]
1858 station = closest(centroid, stations, "location", 0.1)
1860 zctas[zcta]["station"] = station
1863 level = int(50*count/estimate)
1864 if level in milestones:
1865 for remaining in milestones[ : milestones.index(level)+1 ]:
1868 sys.stdout.write(message)
1871 message = "%s%%" % (remaining*2,)
1872 sys.stdout.write(message)
1874 milestones.remove(remaining)
1876 zone = closest(centroid, zones, "centroid", 0.1)
1878 zctas[zcta]["zone"] = zone
1881 level = int(50*count/estimate)
1882 if level in milestones:
1883 for remaining in milestones[:milestones.index(level)+1]:
1886 sys.stdout.write(message)
1889 message = "%s%%" % (remaining*2,)
1890 sys.stdout.write(message)
1892 milestones.remove(remaining)
1893 for zone in zones.keys():
1894 if "centroid" in zones[zone]:
1895 centroid = zones[zone]["centroid"]
1897 station = closest(centroid, stations, "location", 0.1)
1899 zones[zone]["station"] = station
1902 level = int(50*count/estimate)
1903 if level in milestones:
1904 for remaining in milestones[:milestones.index(level)+1]:
1907 sys.stdout.write(message)
1910 message = "%s%%" % (remaining*2,)
1911 sys.stdout.write(message)
1913 milestones.remove(remaining)
1914 for remaining in milestones:
1917 sys.stdout.write(message)
1920 message = "%s%%" % (remaining*2,)
1921 sys.stdout.write(message)
1923 print("\n done (%s correlations)." % count)
1924 message = "Writing %s..." % airports_fn
1925 sys.stdout.write(message)
1928 if os.path.exists(airports_fn):
1929 os.rename(airports_fn, "%s_old"%airports_fn)
1930 airports_fd = codecs.open(airports_fn, "w", "utf8")
1931 airports_fd.write(header)
1932 for airport in sorted( airports.keys() ):
1933 airports_fd.write("\n\n[%s]" % airport)
1934 for key, value in sorted( airports[airport].items() ):
1935 if type(value) is float: value = "%.7f"%value
1936 elif type(value) is tuple:
1938 for element in value:
1939 if type(element) is float: elements.append("%.7f"%element)
1940 else: elements.append( repr(element) )
1941 value = "(%s)"%", ".join(elements)
1942 airports_fd.write( "\n%s = %s" % (key, value) )
1944 airports_fd.write("\n")
1946 print("done (%s sections)." % count)
1947 message = "Writing %s..." % places_fn
1948 sys.stdout.write(message)
1951 if os.path.exists(places_fn):
1952 os.rename(places_fn, "%s_old"%places_fn)
1953 places_fd = codecs.open(places_fn, "w", "utf8")
1954 places_fd.write(header)
1955 for fips in sorted( places.keys() ):
1956 places_fd.write("\n\n[%s]" % fips)
1957 for key, value in sorted( places[fips].items() ):
1958 if type(value) is float: value = "%.7f"%value
1959 elif type(value) is tuple:
1961 for element in value:
1962 if type(element) is float: elements.append("%.7f"%element)
1963 else: elements.append( repr(element) )
1964 value = "(%s)"%", ".join(elements)
1965 places_fd.write( "\n%s = %s" % (key, value) )
1967 places_fd.write("\n")
1969 print("done (%s sections)." % count)
1970 message = "Writing %s..." % stations_fn
1971 sys.stdout.write(message)
1974 if os.path.exists(stations_fn):
1975 os.rename(stations_fn, "%s_old"%stations_fn)
1976 stations_fd = codecs.open(stations_fn, "w", "utf-8")
1977 stations_fd.write(header)
1978 for station in sorted( stations.keys() ):
1979 stations_fd.write("\n\n[%s]" % station)
1980 for key, value in sorted( stations[station].items() ):
1981 if type(value) is float: value = "%.7f"%value
1982 elif type(value) is tuple:
1984 for element in value:
1985 if type(element) is float: elements.append("%.7f"%element)
1986 else: elements.append( repr(element) )
1987 value = "(%s)"%", ".join(elements)
1988 if type(value) is bytes:
1989 value = value.decode("utf-8")
1990 stations_fd.write( "\n%s = %s" % (key, value) )
1992 stations_fd.write("\n")
1994 print("done (%s sections)." % count)
1995 message = "Writing %s..." % zctas_fn
1996 sys.stdout.write(message)
1999 if os.path.exists(zctas_fn):
2000 os.rename(zctas_fn, "%s_old"%zctas_fn)
2001 zctas_fd = codecs.open(zctas_fn, "w", "utf8")
2002 zctas_fd.write(header)
2003 for zcta in sorted( zctas.keys() ):
2004 zctas_fd.write("\n\n[%s]" % zcta)
2005 for key, value in sorted( zctas[zcta].items() ):
2006 if type(value) is float: value = "%.7f"%value
2007 elif type(value) is tuple:
2009 for element in value:
2010 if type(element) is float: elements.append("%.7f"%element)
2011 else: elements.append( repr(element) )
2012 value = "(%s)"%", ".join(elements)
2013 zctas_fd.write( "\n%s = %s" % (key, value) )
2015 zctas_fd.write("\n")
2017 print("done (%s sections)." % count)
2018 message = "Writing %s..." % zones_fn
2019 sys.stdout.write(message)
2022 if os.path.exists(zones_fn):
2023 os.rename(zones_fn, "%s_old"%zones_fn)
2024 zones_fd = codecs.open(zones_fn, "w", "utf8")
2025 zones_fd.write(header)
2026 for zone in sorted( zones.keys() ):
2027 zones_fd.write("\n\n[%s]" % zone)
2028 for key, value in sorted( zones[zone].items() ):
2029 if type(value) is float: value = "%.7f"%value
2030 elif type(value) is tuple:
2032 for element in value:
2033 if type(element) is float: elements.append("%.7f"%element)
2034 else: elements.append( repr(element) )
2035 value = "(%s)"%", ".join(elements)
2036 zones_fd.write( "\n%s = %s" % (key, value) )
2038 zones_fd.write("\n")
2040 print("done (%s sections)." % count)
2041 message = "Starting QA check..."
2042 sys.stdout.write(message)
2044 airports = configparser.ConfigParser()
2046 airports.read(airports_fn, encoding="utf-8")
2048 airports.read(airports_fn)
2049 places = configparser.ConfigParser()
2051 places.read(places_fn, encoding="utf-8")
2053 places.read(places_fn)
2054 stations = configparser.ConfigParser()
2056 stations.read(stations_fn, encoding="utf-8")
2058 stations.read(stations_fn)
2059 zctas = configparser.ConfigParser()
2061 zctas.read(zctas_fn, encoding="utf-8")
2063 zctas.read(zctas_fn)
2064 zones = configparser.ConfigParser()
2066 zones.read(zones_fn, encoding="utf-8")
2068 zones.read(zones_fn)
2070 places_nocentroid = 0
2071 places_nodescription = 0
2072 for place in sorted( places.sections() ):
2073 if not places.has_option(place, "centroid"):
2074 qalog.append("%s: no centroid\n" % place)
2075 places_nocentroid += 1
2076 if not places.has_option(place, "description"):
2077 qalog.append("%s: no description\n" % place)
2078 places_nodescription += 1
2079 stations_nodescription = 0
2080 stations_nolocation = 0
2081 stations_nometar = 0
2082 for station in sorted( stations.sections() ):
2083 if not stations.has_option(station, "description"):
2084 qalog.append("%s: no description\n" % station)
2085 stations_nodescription += 1
2086 if not stations.has_option(station, "location"):
2087 qalog.append("%s: no location\n" % station)
2088 stations_nolocation += 1
2089 if not stations.has_option(station, "metar"):
2090 qalog.append("%s: no metar\n" % station)
2091 stations_nometar += 1
2092 airports_badstation = 0
2093 airports_nostation = 0
2094 for airport in sorted( airports.sections() ):
2095 if not airports.has_option(airport, "station"):
2096 qalog.append("%s: no station\n" % airport)
2097 airports_nostation += 1
2099 station = airports.get(airport, "station")
2100 if station not in stations.sections():
2101 qalog.append( "%s: bad station %s\n" % (airport, station) )
2102 airports_badstation += 1
2103 zctas_nocentroid = 0
2104 for zcta in sorted( zctas.sections() ):
2105 if not zctas.has_option(zcta, "centroid"):
2106 qalog.append("%s: no centroid\n" % zcta)
2107 zctas_nocentroid += 1
2108 zones_nocentroid = 0
2109 zones_nodescription = 0
2110 zones_noforecast = 0
2111 zones_overlapping = 0
2113 for zone in zones.sections():
2114 if zones.has_option(zone, "centroid"):
2116 "centroid": eval( zones.get(zone, "centroid") )
2118 for zone in sorted( zones.sections() ):
2119 if zones.has_option(zone, "centroid"):
2120 zonetable_local = zonetable.copy()
2121 del( zonetable_local[zone] )
2122 centroid = eval( zones.get(zone, "centroid") )
2124 nearest = closest(centroid, zonetable_local, "centroid", 0.1)
2125 if nearest[1]*radian_to_km < 1:
2126 qalog.append( "%s: within one km of %s\n" % (
2130 zones_overlapping += 1
2132 qalog.append("%s: no centroid\n" % zone)
2133 zones_nocentroid += 1
2134 if not zones.has_option(zone, "description"):
2135 qalog.append("%s: no description\n" % zone)
2136 zones_nodescription += 1
2137 if not zones.has_option(zone, "zone_forecast"):
2138 qalog.append("%s: no forecast\n" % zone)
2139 zones_noforecast += 1
2140 if os.path.exists(qalog_fn):
2141 os.rename(qalog_fn, "%s_old"%qalog_fn)
2142 qalog_fd = codecs.open(qalog_fn, "w", "utf8")
2145 '# Copyright (c) %s Jeremy Stanley <fungi@yuggoth.org>. Permission to\n'
2146 '# use, copy, modify, and distribute this software is granted under terms\n'
2147 '# provided in the LICENSE file distributed with this software.\n\n'
2148 % time.gmtime().tm_year)
2149 qalog_fd.writelines(qalog)
2152 print("issues found (see %s for details):"%qalog_fn)
2153 if airports_badstation:
2154 print(" %s airports with invalid station"%airports_badstation)
2155 if airports_nostation:
2156 print(" %s airports with no station"%airports_nostation)
2157 if places_nocentroid:
2158 print(" %s places with no centroid"%places_nocentroid)
2159 if places_nodescription:
2160 print(" %s places with no description"%places_nodescription)
2161 if stations_nodescription:
2162 print(" %s stations with no description"%stations_nodescription)
2163 if stations_nolocation:
2164 print(" %s stations with no location"%stations_nolocation)
2165 if stations_nometar:
2166 print(" %s stations with no METAR"%stations_nometar)
2167 if zctas_nocentroid:
2168 print(" %s ZCTAs with no centroid"%zctas_nocentroid)
2169 if zones_nocentroid:
2170 print(" %s zones with no centroid"%zones_nocentroid)
2171 if zones_nodescription:
2172 print(" %s zones with no description"%zones_nodescription)
2173 if zones_noforecast:
2174 print(" %s zones with no forecast"%zones_noforecast)
2175 if zones_overlapping:
2176 print(" %s zones within one km of another"%zones_overlapping)
2177 else: print("no issues found.")
2178 print("Indexing complete!")