Support more recent data sources
[weather.git] / weather.py
1 """Contains various object definitions needed by the weather utility."""
2
3 weather_copyright = """\
4 # Copyright (c) 2006-2014 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.
7 #"""
8
9 weather_version = "2.0"
10
11 radian_to_km = 6372.795484
12 radian_to_mi = 3959.871528
13
14 def pyversion(ref=None):
15     """Determine the Python version and optionally compare to a reference."""
16     import platform
17     ver = platform.python_version()
18     if ref:
19         return [
20             int(x) for x in ver.split(".")[:2]
21         ] >= [
22             int(x) for x in ref.split(".")[:2]
23         ]
24     else: return ver
25
26 class Selections:
27     """An object to contain selection data."""
28     def __init__(self):
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(
35                 self.config,
36                 self.get("cachedir"),
37                 self.get("setpath")
38             )
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"] )
44                 import sys
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(
52                     "^%s city, %s" % (
53                         self.options.__dict__["city"],
54                         self.options.__dict__["st"]
55                     )
56                 )
57                 del( self.options.__dict__["city"] )
58                 del( self.options.__dict__["st"] )
59                 import sys
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."""
64         if argument:
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")
69             ):
70                 self.config.remove_section(argument)
71                 import sys
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):
75                 guessed = guess(
76                     argument,
77                     path=self.get("setpath"),
78                     info=self.get("info"),
79                     cache_search=(
80                         self.get("cache") and self.get("cache_search")
81                     ),
82                     cachedir=self.get("cachedir"),
83                     quiet=self.get_bool("quiet")
84                 )
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]
92         else:
93             import os, sys
94             message = "%s error: no URI defined for %s\n" % (
95                 os.path.basename( sys.argv[0] ),
96                 option
97             )
98             sys.stderr.write(message)
99             exit(1)
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)
107         else: return 0
108
109 def average(coords):
110     """Average a list of coordinates."""
111     x = 0
112     y = 0
113     for coord in coords:
114         x += coord[0]
115         y += coord[1]
116     count = len(coords)
117     return (x/count, y/count)
118
119 def filter_units(line, units="imperial"):
120     """Filter or convert units in a line of text between US/UK and metric."""
121     import re
122     # filter lines with both pressures in the form of "X inches (Y hPa)" or
123     # "X in. Hg (Y hPa)"
124     dual_p = re.match(
125         "(.* )(\d*(\.\d+)? (inches|in\. Hg)) \((\d*(\.\d+)? hPa)\)(.*)",
126         line
127     )
128     if dual_p:
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)"
133     dual_t = re.match(
134         "(.* )(-?\d*(\.\d+)? F) \((-?\d*(\.\d+)? C)\)(.*)",
135         line
136     )
137     if dual_t:
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
142     # "Y kilometer(s)"
143     if units == "metric":
144         imperial_d = re.match(
145             "(.* )(\d+)( mile\(s\))(.*)",
146             line
147         )
148         if imperial_d:
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\))(.*)",
156         line
157     )
158     if imperial_s:
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" + \
163                 trailer
164     imperial_s = re.match(
165         "(.* )(\d+)( MPH)( \(\d+ KT\))(.*)",
166         line
167     )
168     if imperial_s:
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" + \
173                 trailer
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+)(\.|,)(.*)",
178         line
179     )
180     if imperial_t:
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 \
187                 + trailer
188     # hand off the resulting line
189     return line
190
191 def get_uri(
192     uri,
193     ignore_fail=False,
194     cache_data=False,
195     cacheage=900,
196     cachedir="."
197 ):
198     """Return a string containing the results of a URI GET."""
199     if pyversion("3"):
200         import urllib, urllib.error, urllib.request
201         URLError = urllib.error.URLError
202         urlopen = urllib.request.urlopen
203     else:
204         import urllib2 as urllib
205         URLError = urllib.URLError
206         urlopen = urllib.urlopen
207     import os, time
208     if cache_data:
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(
214             dcachedir,
215             uri.split(":")[1].replace("/","_")
216         )
217     now = time.time()
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()
222         dcache_fd.close()
223     else:
224         try:
225             if pyversion("3"): data = urlopen(uri).read().decode("utf-8")
226             else: data = urlopen(uri).read()
227         except URLError:
228             if ignore_fail: return ""
229             else:
230                 import os, sys, traceback
231                 message = "%s error: failed to retrieve\n   %s\n   %s" % (
232                         os.path.basename( sys.argv[0] ),
233                         uri,
234                         traceback.format_exception_only(
235                             sys.exc_type,
236                             sys.exc_value
237                         )[0]
238                     )
239                 sys.stderr.write(message)
240                 sys.exit(1)
241         if cache_data:
242             try:
243                 import codecs
244                 dcache_fd = codecs.open(dcache_fn, "w", "utf-8")
245                 dcache_fd.write(data)
246                 dcache_fd.close()
247             except (IOError, OSError): pass
248     return data
249
250 def get_metar(
251     uri=None,
252     verbose=False,
253     quiet=False,
254     headers=None,
255     imperial=False,
256     metric=False,
257     cache_data=False,
258     cacheage=900,
259     cachedir="."
260 ):
261     """Return a summarized METAR for the specified station."""
262     if not uri:
263         import os, sys
264         message = "%s error: METAR URI required for conditions\n" % \
265             os.path.basename( sys.argv[0] )
266         sys.stderr.write(message)
267         sys.exit(1)
268     metar = get_uri(
269         uri,
270         cache_data=cache_data,
271         cacheage=cacheage,
272         cachedir=cachedir
273     )
274     if pyversion("3") and type(metar) is bytes: metar = metar.decode("utf-8")
275     if verbose: return metar
276     else:
277         import re
278         lines = metar.split("\n")
279         if not headers:
280             headers = \
281                 "relative_humidity," \
282                 + "precipitation_last_hour," \
283                 + "sky conditions," \
284                 + "temperature," \
285                 + "heat index," \
286                 + "windchill," \
287                 + "weather," \
288                 + "wind"
289         headerlist = headers.lower().replace("_"," ").split(",")
290         output = []
291         if not quiet:
292             title = "Current conditions at %s"
293             place = lines[0].split(", ")
294             if len(place) > 1:
295                 place = "%s, %s" % ( place[0].title(), place[1] )
296             else: place = "<UNKNOWN>"
297             output.append(title%place)
298             output.append("Last updated " + lines[1])
299         header_match = False
300         for header in headerlist:
301             for line in lines:
302                 if line.lower().startswith(header + ":"):
303                     if re.match(r".*:\d+$", line): line = line[:line.rfind(":")]
304                     if imperial: line = filter_units(line, units="imperial")
305                     elif metric: line = filter_units(line, units="metric")
306                     if quiet: output.append(line)
307                     else: output.append("   " + line)
308                     header_match = True
309         if not header_match:
310             output.append(
311                 "(no conditions matched your header list, try with --verbose)"
312             )
313         return "\n".join(output)
314
315 def get_alert(
316     uri=None,
317     verbose=False,
318     quiet=False,
319     cache_data=False,
320     cacheage=900,
321     cachedir="."
322 ):
323     """Return alert notice for the specified URI."""
324     if not uri:
325         import os, sys
326         message = "%s error: Alert URI required for alerts\n" % \
327             os.path.basename( sys.argv[0] )
328         sys.stderr.write(message)
329         sys.exit(1)
330     alert = get_uri(
331         uri,
332         ignore_fail=True,
333         cache_data=cache_data,
334         cacheage=cacheage,
335         cachedir=cachedir
336     ).strip()
337     if pyversion("3") and type(alert) is bytes: alert = alert.decode("utf-8")
338     if alert:
339         if verbose: return alert
340         else:
341             if alert.find("\nNATIONAL WEATHER SERVICE") == -1:
342                 muted = False
343             else:
344                 muted = True
345             lines = alert.split("\n")
346             import time
347             valid_time = time.strftime("%Y%m%d%H%M")
348             output = []
349             for line in lines:
350                 if line.startswith("Expires:") \
351                     and "Expires:" + valid_time > line:
352                     return ""
353                 if muted and line.startswith("NATIONAL WEATHER SERVICE"):
354                     muted = False
355                     line = ""
356                 elif line == "&&":
357                     line = ""
358                 elif line == "$$":
359                     muted = True
360                 if line and not muted:
361                     if quiet: output.append(line)
362                     else: output.append("   " + line)
363             return "\n".join(output)
364
365 def get_options(config):
366     """Parse the options passed on the command line."""
367
368     # for optparse's builtin -h/--help option
369     usage = \
370         "usage: %prog [options] [alias1|search1 [alias2|search2 [...]]]"
371
372     # for optparse's builtin --version option
373     verstring = "%prog " + weather_version
374
375     # create the parser
376     import optparse
377     option_parser = optparse.OptionParser(usage=usage, version=verstring)
378     # separate options object from list of arguments and return both
379
380     # the -a/--alert option
381     if config.has_option("default", "alert"):
382         default_alert = bool(config.get("default", "alert"))
383     else: default_alert = False
384     option_parser.add_option("-a", "--alert",
385         dest="alert",
386         action="store_true",
387         default=default_alert,
388         help="include local alert notices")
389
390     # the --atypes option
391     if config.has_option("default", "atypes"):
392         default_atypes = config.get("default", "atypes")
393     else:
394         default_atypes = \
395             "coastal_flood_statement," \
396             + "flash_flood_statement," \
397             + "flash_flood_warning," \
398             + "flash_flood_watch," \
399             + "flood_statement," \
400             + "flood_warning," \
401             + "marine_weather_statement," \
402             + "river_statement," \
403             + "severe_thunderstorm_warning," \
404             + "severe_weather_statement," \
405             + "short_term_forecast," \
406             + "special_marine_warning," \
407             + "special_weather_statement," \
408             + "tornado_warning," \
409             + "urgent_weather_message"
410     option_parser.add_option("--atypes",
411         dest="atypes",
412         default=default_atypes,
413         help="list of alert notification types to display")
414
415     # the --build-sets option
416     option_parser.add_option("--build-sets",
417         dest="build_sets",
418         action="store_true",
419         default=False,
420         help="(re)build location correlation sets")
421
422     # the --cacheage option
423     if config.has_option("default", "cacheage"):
424         default_cacheage = config.getint("default", "cacheage")
425     else: default_cacheage = 900
426     option_parser.add_option("--cacheage",
427         dest="cacheage",
428         default=default_cacheage,
429         help="duration in seconds to refresh cached data")
430
431     # the --cachedir option
432     if config.has_option("default", "cachedir"):
433         default_cachedir = config.get("default", "cachedir")
434     else: default_cachedir = "~/.weather"
435     option_parser.add_option("--cachedir",
436         dest="cachedir",
437         default=default_cachedir,
438         help="directory for storing cached searches and data")
439
440     # the -f/--forecast option
441     if config.has_option("default", "forecast"):
442         default_forecast = bool(config.get("default", "forecast"))
443     else: default_forecast = False
444     option_parser.add_option("-f", "--forecast",
445         dest="forecast",
446         action="store_true",
447         default=default_forecast,
448         help="include a local forecast")
449
450     # the --headers option
451     if config.has_option("default", "headers"):
452         default_headers = config.get("default", "headers")
453     else:
454         default_headers = \
455             "temperature," \
456             + "relative_humidity," \
457             + "wind," \
458             + "heat_index," \
459             + "windchill," \
460             + "weather," \
461             + "sky_conditions," \
462             + "precipitation_last_hour"
463     option_parser.add_option("--headers",
464         dest="headers",
465         default=default_headers,
466         help="list of conditions headers to display")
467
468     # the --imperial option
469     if config.has_option("default", "imperial"):
470         default_imperial = bool(config.get("default", "imperial"))
471     else: default_imperial = False
472     option_parser.add_option("--imperial",
473         dest="imperial",
474         action="store_true",
475         default=default_imperial,
476         help="filter/convert conditions for US/UK units")
477
478     # the --info option
479     option_parser.add_option("--info",
480         dest="info",
481         action="store_true",
482         default=False,
483         help="output detailed information for your search")
484
485     # the -l/--list option
486     option_parser.add_option("-l", "--list",
487         dest="list",
488         action="store_true",
489         default=False,
490         help="list all configured aliases and cached searches")
491
492     # the --longlist option
493     option_parser.add_option("--longlist",
494         dest="longlist",
495         action="store_true",
496         default=False,
497         help="display details of all configured aliases")
498
499     # the -m/--metric option
500     if config.has_option("default", "metric"):
501         default_metric = bool(config.get("default", "metric"))
502     else: default_metric = False
503     option_parser.add_option("-m", "--metric",
504         dest="metric",
505         action="store_true",
506         default=default_metric,
507         help="filter/convert conditions for metric units")
508
509     # the -n/--no-conditions option
510     if config.has_option("default", "conditions"):
511         default_conditions = bool(config.get("default", "conditions"))
512     else: default_conditions = True
513     option_parser.add_option("-n", "--no-conditions",
514         dest="conditions",
515         action="store_false",
516         default=default_conditions,
517         help="disable output of current conditions")
518
519     # the --no-cache option
520     if config.has_option("default", "cache"):
521         default_cache = bool(config.get("default", "cache"))
522     else: default_cache = True
523     option_parser.add_option("--no-cache",
524         dest="cache",
525         action="store_false",
526         default=True,
527         help="disable all caching (searches and data)")
528
529     # the --no-cache-data option
530     if config.has_option("default", "cache_data"):
531         default_cache_data = bool(config.get("default", "cache_data"))
532     else: default_cache_data = True
533     option_parser.add_option("--no-cache-data",
534         dest="cache_data",
535         action="store_false",
536         default=True,
537         help="disable retrieved data caching")
538
539     # the --no-cache-search option
540     if config.has_option("default", "cache_search"):
541         default_cache_search = bool(config.get("default", "cache_search"))
542     else: default_cache_search = True
543     option_parser.add_option("--no-cache-search",
544         dest="cache_search",
545         action="store_false",
546         default=True,
547         help="disable search result caching")
548
549     # the -q/--quiet option
550     if config.has_option("default", "quiet"):
551         default_quiet = bool(config.get("default", "quiet"))
552     else: default_quiet = False
553     option_parser.add_option("-q", "--quiet",
554         dest="quiet",
555         action="store_true",
556         default=default_quiet,
557         help="skip preambles and don't indent")
558
559     # the --setpath option
560     if config.has_option("default", "setpath"):
561         default_setpath = config.get("default", "setpath")
562     else: default_setpath = ".:~/.weather"
563     option_parser.add_option("--setpath",
564         dest="setpath",
565         default=default_setpath,
566         help="directory search path for correlation sets")
567
568     # the -v/--verbose option
569     if config.has_option("default", "verbose"):
570         default_verbose = bool(config.get("default", "verbose"))
571     else: default_verbose = False
572     option_parser.add_option("-v", "--verbose",
573         dest="verbose",
574         action="store_true",
575         default=default_verbose,
576         help="show full decoded feeds")
577
578     # deprecated options
579     if config.has_option("default", "city"):
580         default_city = config.get("default", "city")
581     else: default_city = ""
582     option_parser.add_option("-c", "--city",
583         dest="city",
584         default=default_city,
585         help=optparse.SUPPRESS_HELP)
586     if config.has_option("default", "id"):
587         default_id = config.get("default", "id")
588     else: default_id = ""
589     option_parser.add_option("-i", "--id",
590         dest="id",
591         default=default_id,
592         help=optparse.SUPPRESS_HELP)
593     if config.has_option("default", "st"):
594         default_st = config.get("default", "st")
595     else: default_st = ""
596     option_parser.add_option("-s", "--st",
597         dest="st",
598         default=default_st,
599         help=optparse.SUPPRESS_HELP)
600
601     options, arguments = option_parser.parse_args()
602     return options, arguments
603
604 def get_config():
605     """Parse the aliases and configuration."""
606     if pyversion("3"): import configparser
607     else: import ConfigParser as configparser
608     config = configparser.ConfigParser()
609     import os
610     rcfiles = [
611         "/etc/weatherrc",
612         "/etc/weather/weatherrc",
613         os.path.expanduser("~/.weather/weatherrc"),
614         os.path.expanduser("~/.weatherrc"),
615         "weatherrc"
616         ]
617     for rcfile in rcfiles:
618         if os.access(rcfile, os.R_OK): config.read(rcfile)
619     for section in config.sections():
620         if section != section.lower():
621             if config.has_section(section.lower()):
622                 config.remove_section(section.lower())
623             config.add_section(section.lower())
624             for option,value in config.items(section):
625                 config.set(section.lower(), option, value)
626     return config
627
628 def integrate_search_cache(config, cachedir, setpath):
629     """Add cached search results into the configuration."""
630     if pyversion("3"): import configparser
631     else: import ConfigParser as configparser
632     import os, time
633     scache_fn = os.path.join( os.path.expanduser(cachedir), "searches" )
634     if not os.access(scache_fn, os.R_OK): return config
635     scache_fd = open(scache_fn)
636     created = float( scache_fd.readline().split(":")[1].strip().split()[0] )
637     scache_fd.close()
638     now = time.time()
639     datafiles = data_index(setpath)
640     if datafiles:
641         data_freshness = sorted(
642             [ x[1] for x in datafiles.values() ],
643             reverse=True
644         )[0]
645     else: data_freshness = now
646     if created < data_freshness <= now:
647         try:
648             os.remove(scache_fn)
649             print( "[clearing outdated %s]" % scache_fn )
650         except (IOError, OSError):
651             pass
652         return config
653     scache = configparser.ConfigParser()
654     scache.read(scache_fn)
655     for section in scache.sections():
656         if not config.has_section(section):
657             config.add_section(section)
658             for option,value in scache.items(section):
659                 config.set(section, option, value)
660     return config
661
662 def list_aliases(config, detail=False):
663     """Return a formatted list of aliases defined in the config."""
664     if detail:
665         output = "\n# configured alias details..."
666         for section in sorted(config.sections()):
667             output += "\n\n[%s]" % section
668             for item in sorted(config.items(section)):
669                 output += "\n%s = %s" % item
670         output += "\n"
671     else:
672         output = "configured aliases and cached searches..."
673         for section in sorted(config.sections()):
674             if config.has_option(section, "description"):
675                 description = config.get(section, "description")
676             else: description = "(no description provided)"
677             output += "\n   %s: %s" % (section, description)
678     return output
679
680 def data_index(path):
681     import os
682     datafiles = {}
683     for filename in ("airports", "places", "stations", "zctas", "zones"):
684         for dirname in path.split(":"):
685             for extension in ("", ".gz", ".txt"):
686                 candidate = os.path.expanduser(
687                     os.path.join( dirname, "".join( (filename, extension) ) )
688                 )
689                 if os.path.exists(candidate):
690                     datafiles[filename] = (
691                         candidate,
692                         os.stat(candidate).st_mtime
693                     )
694                     break
695     return datafiles
696
697 def guess(
698     expression,
699     path=".",
700     max_results=20,
701     info=False,
702     cache_search=False,
703     cacheage=900,
704     cachedir=".",
705     quiet=False
706 ):
707     """Find URIs using airport, gecos, placename, station, ZCTA/ZIP, zone."""
708     import codecs, datetime, time, os, re, sys
709     if pyversion("3"): import configparser
710     else: import ConfigParser as configparser
711     datafiles = data_index(path)
712     if re.match("[A-Za-z]{3}$", expression): searchtype = "airport"
713     elif re.match("[A-Za-z0-9]{4}$", expression): searchtype = "station"
714     elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", expression): searchtype = "zone"
715     elif re.match("[0-9]{5}$", expression): searchtype = "ZCTA"
716     elif re.match(
717         r"[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?, *[\+-]?\d+(\.\d+)?(-\d+){,2}[ENSWensw]?$",
718         expression
719     ):
720         searchtype = "coordinates"
721     elif re.match(r"(FIPS|fips)\d+$", expression): searchtype = "FIPS"
722     else:
723         searchtype = "name"
724         cache_search = False
725     if cache_search: action = "caching"
726     else: action = "using"
727     if info:
728         scores = [
729             (0.005, "bad"),
730             (0.025, "poor"),
731             (0.160, "suspect"),
732             (0.500, "mediocre"),
733             (0.840, "good"),
734             (0.975, "great"),
735             (0.995, "excellent"),
736             (1.000, "ideal"),
737         ]
738     if not quiet: print("Searching via %s..."%searchtype)
739     stations = configparser.ConfigParser()
740     dataname = "stations"
741     if dataname in datafiles:
742         datafile = datafiles[dataname][0]
743         if datafile.endswith(".gz"):
744             import gzip
745             stations.readfp( gzip.open(datafile) )
746         else:
747             stations.read(datafile)
748     else:
749         message = "%s error: can't find \"%s\" data file\n" % (
750             os.path.basename( sys.argv[0] ),
751             dataname
752         )
753         sys.stderr.write(message)
754         exit(1)
755     zones = configparser.ConfigParser()
756     dataname = "zones"
757     if dataname in datafiles:
758         datafile = datafiles[dataname][0]
759         if datafile.endswith(".gz"):
760             import gzip
761             zones.readfp( gzip.open(datafile) )
762         else:
763             zones.read(datafile)
764     else:
765         message = "%s error: can't find \"%s\" data file\n" % (
766             os.path.basename( sys.argv[0] ),
767             dataname
768         )
769         sys.stderr.write(message)
770         exit(1)
771     search = None
772     station = ("", 0)
773     zone = ("", 0)
774     dataset = None
775     possibilities = []
776     uris = {}
777     if searchtype == "airport":
778         expression = expression.lower()
779         airports = configparser.ConfigParser()
780         dataname = "airports"
781         if dataname in datafiles:
782             datafile = datafiles[dataname][0]
783             if datafile.endswith(".gz"):
784                 import gzip
785                 airports.readfp( gzip.open(datafile) )
786             else:
787                 airports.read(datafile)
788         else:
789             message = "%s error: can't find \"%s\" data file\n" % (
790                 os.path.basename( sys.argv[0] ),
791                 dataname
792             )
793             sys.stderr.write(message)
794             exit(1)
795         if airports.has_section(expression) \
796             and airports.has_option(expression, "station"):
797             search = (expression, "IATA/FAA airport code %s" % expression)
798             station = ( airports.get(expression, "station"), 0 )
799             if stations.has_option(station[0], "zone"):
800                 zone = eval( stations.get(station[0], "zone") )
801                 dataset = stations
802             if not ( info or quiet ) \
803                 and stations.has_option( station[0], "description" ):
804                 print(
805                     "[%s result %s]" % (
806                         action,
807                         stations.get(station[0], "description")
808                     )
809                 )
810         else:
811             message = "No IATA/FAA airport code \"%s\" in the %s file.\n" % (
812                 expression,
813                 datafiles["airports"][0]
814             )
815             sys.stderr.write(message)
816             exit(1)
817     elif searchtype == "station":
818         expression = expression.lower()
819         if stations.has_section(expression):
820             station = (expression, 0)
821             if not search:
822                 search = (expression, "ICAO station code %s" % expression)
823             if stations.has_option(expression, "zone"):
824                 zone = eval( stations.get(expression, "zone") )
825                 dataset = stations
826             if not ( info or quiet ) \
827                 and stations.has_option(expression, "description"):
828                 print(
829                     "[%s result %s]" % (
830                         action,
831                         stations.get(expression, "description")
832                     )
833                 )
834         else:
835             message = "No ICAO weather station \"%s\" in the %s file.\n" % (
836                 expression,
837                 datafiles["stations"][0]
838             )
839             sys.stderr.write(message)
840             exit(1)
841     elif searchtype == "zone":
842         expression = expression.lower()
843         if zones.has_section(expression) \
844             and zones.has_option(expression, "station"):
845             zone = (expression, 0)
846             station = eval( zones.get(expression, "station") )
847             dataset = zones
848             search = (expression, "NWS/NOAA weather zone %s" % expression)
849             if not ( info or quiet ) \
850                 and zones.has_option(expression, "description"):
851                 print(
852                     "[%s result %s]" % (
853                         action,
854                         zones.get(expression, "description")
855                     )
856                 )
857         else:
858             message = "No usable NWS weather zone \"%s\" in the %s file.\n" % (
859                 expression,
860                 datafiles["zones"][0]
861             )
862             sys.stderr.write(message)
863             exit(1)
864     elif searchtype == "ZCTA":
865         zctas = configparser.ConfigParser()
866         dataname = "zctas"
867         if dataname in datafiles:
868             datafile = datafiles[dataname][0]
869             if datafile.endswith(".gz"):
870                 import gzip
871                 zctas.readfp( gzip.open(datafile) )
872             else:
873                 zctas.read(datafile)
874         else:
875             message = "%s error: can't find \"%s\" data file\n" % (
876                 os.path.basename( sys.argv[0] ),
877                 dataname
878             )
879             sys.stderr.write(message)
880             exit(1)
881         dataset = zctas
882         if zctas.has_section(expression) \
883             and zctas.has_option(expression, "station"):
884             station = eval( zctas.get(expression, "station") )
885             search = (expression, "Census ZCTA (ZIP code) %s" % expression)
886             if zctas.has_option(expression, "zone"):
887                 zone = eval( zctas.get(expression, "zone") )
888         else:
889             message = "No census ZCTA (ZIP code) \"%s\" in the %s file.\n" % (
890                 expression,
891                 datafiles["zctas"][0]
892             )
893             sys.stderr.write(message)
894             exit(1)
895     elif searchtype == "coordinates":
896         search = (expression, "Geographic coordinates %s" % expression)
897         stationtable = {}
898         for station in stations.sections():
899             if stations.has_option(station, "location"):
900                 stationtable[station] = {
901                     "location": eval( stations.get(station, "location") )
902                 }
903         station = closest( gecos(expression), stationtable, "location", 0.1 )
904         if not station[0]:
905             message = "No ICAO weather station found near %s.\n" % expression
906             sys.stderr.write(message)
907             exit(1)
908         zonetable = {}
909         for zone in zones.sections():
910             if zones.has_option(zone, "centroid"):
911                 zonetable[zone] = {
912                     "centroid": eval( zones.get(zone, "centroid") )
913                 }
914         zone = closest( gecos(expression), zonetable, "centroid", 0.1 )
915         if not zone[0]:
916             message = "No NWS weather zone near %s; forecasts unavailable.\n" \
917                 % expression
918             sys.stderr.write(message)
919     elif searchtype in ("FIPS", "name"):
920         places = configparser.ConfigParser()
921         dataname = "places"
922         if dataname in datafiles:
923             datafile = datafiles[dataname][0]
924             if datafile.endswith(".gz"):
925                 import gzip
926                 places.readfp( gzip.open(datafile) )
927             else:
928                 places.read(datafile)
929         else:
930             message = "%s error: can't find \"%s\" data file\n" % (
931                 os.path.basename( sys.argv[0] ),
932                 dataname
933             )
934             sys.stderr.write(message)
935             exit(1)
936         dataset = places
937         place = expression.lower()
938         if places.has_section(place) and places.has_option(place, "station"):
939             station = eval( places.get(place, "station") )
940             search = (expression, "Census Place %s" % expression)
941             if places.has_option(place, "description"):
942                 search = (
943                     search[0],
944                     search[1] + ", %s" % places.get(place, "description")
945                 )
946             if places.has_option(place, "zone"):
947                 zone = eval( places.get(place, "zone") )
948             if not ( info or quiet ) \
949                 and places.has_option(place, "description"):
950                 print(
951                     "[%s result %s]" % (
952                         action,
953                         places.get(place, "description")
954                     )
955                 )
956         else:
957             for place in places.sections():
958                 if places.has_option(place, "description") \
959                     and places.has_option(place, "station") \
960                     and re.search(
961                         expression,
962                         places.get(place, "description"),
963                         re.I
964                     ):
965                         possibilities.append(place)
966             for place in stations.sections():
967                 if stations.has_option(place, "description") \
968                     and re.search(
969                         expression,
970                         stations.get(place, "description"),
971                         re.I
972                     ):
973                         possibilities.append(place)
974             for place in zones.sections():
975                 if zones.has_option(place, "description") \
976                     and zones.has_option(place, "station") \
977                     and re.search(
978                         expression,
979                         zones.get(place, "description"),
980                         re.I
981                     ):
982                         possibilities.append(place)
983             if len(possibilities) == 1:
984                 place = possibilities[0]
985                 if places.has_section(place):
986                     station = eval( places.get(place, "station") )
987                     description = places.get(place, "description")
988                     if places.has_option(place, "zone"):
989                         zone = eval( places.get(place, "zone" ) )
990                     search = ( expression, "%s: %s" % (place, description) )
991                 elif stations.has_section(place):
992                     station = (place, 0.0)
993                     description = stations.get(place, "description")
994                     if stations.has_option(place, "zone"):
995                         zone = eval( stations.get(place, "zone" ) )
996                     search = ( expression, "ICAO station code %s" % place )
997                 elif zones.has_section(place):
998                     station = eval( zones.get(place, "station") )
999                     description = zones.get(place, "description")
1000                     zone = (place, 0.0)
1001                     search = ( expression, "NWS/NOAA weather zone %s" % place )
1002                 if not ( info or quiet ):
1003                     print( "[%s result %s]" % (action, description) )
1004             if not possibilities and not station[0]:
1005                 message = "No FIPS code/census area match in the %s file.\n" % (
1006                     datafiles["places"][0]
1007                 )
1008                 sys.stderr.write(message)
1009                 exit(1)
1010     if station[0]:
1011         uris["metar"] = stations.get( station[0], "metar" )
1012         if zone[0]:
1013             for key,value in zones.items( zone[0] ):
1014                 if key not in ("centroid", "description", "station"):
1015                     uris[key] = value
1016     elif possibilities:
1017         count = len(possibilities)
1018         if count <= max_results:
1019             print( "Your search is ambiguous, returning %s matches:" % count )
1020             for place in sorted(possibilities):
1021                 if places.has_section(place):
1022                     print(
1023                         "   [%s] %s" % (
1024                             place,
1025                             places.get(place, "description")
1026                         )
1027                     )
1028                 elif stations.has_section(place):
1029                     print(
1030                         "   [%s] %s" % (
1031                             place,
1032                             stations.get(place, "description")
1033                         )
1034                     )
1035                 elif zones.has_section(place):
1036                     print(
1037                         "   [%s] %s" % (
1038                             place,
1039                             zones.get(place, "description")
1040                         )
1041                     )
1042         else:
1043             print(
1044                 "Your search is too ambiguous, returning %s matches." % count
1045             )
1046         exit(0)
1047     if info:
1048         stationlist = []
1049         zonelist = []
1050         if dataset:
1051             for section in dataset.sections():
1052                 if dataset.has_option(section, "station"):
1053                     stationlist.append(
1054                         eval( dataset.get(section, "station") )[1]
1055                     )
1056                 if dataset.has_option(section, "zone"):
1057                     zonelist.append( eval( dataset.get(section, "zone") )[1] )
1058         stationlist.sort()
1059         zonelist.sort()
1060         scount = len(stationlist)
1061         zcount = len(zonelist)
1062         sranks = []
1063         zranks = []
1064         for score in scores:
1065             if stationlist:
1066                 sranks.append( stationlist[ int( (1-score[0]) * scount ) ] )
1067             if zonelist:
1068                 zranks.append( zonelist[ int( (1-score[0]) * zcount ) ] )
1069         description = search[1]
1070         uris["description"] = description
1071         print(
1072             "%s\n%s" % ( description, "-" * len(description) )
1073         )
1074         print(
1075             "%s: %s" % (
1076                 station[0],
1077                 stations.get( station[0], "description" )
1078             )
1079         )
1080         km = radian_to_km*station[1]
1081         mi = radian_to_mi*station[1]
1082         if sranks and not description.startswith("ICAO station code "):
1083             for index in range(0, len(scores)):
1084                 if station[1] >= sranks[index]:
1085                     score = scores[index][1]
1086                     break
1087             print(
1088                 "   (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1089             )
1090         elif searchtype is "coordinates":
1091             print( "   (%.3gkm, %.3gmi)" % (km, mi) )
1092         if zone[0]:
1093             print(
1094                 "%s: %s" % ( zone[0], zones.get( zone[0], "description" ) )
1095             )
1096         km = radian_to_km*zone[1]
1097         mi = radian_to_mi*zone[1]
1098         if zranks and not description.startswith("NWS/NOAA weather zone "):
1099             for index in range(0, len(scores)):
1100                 if zone[1] >= zranks[index]:
1101                     score = scores[index][1]
1102                     break
1103             print(
1104                 "   (proximity %s, %.3gkm, %.3gmi)" % ( score, km, mi )
1105             )
1106         elif searchtype is "coordinates" and zone[0]:
1107             print( "   (%.3gkm, %.3gmi)" % (km, mi) )
1108     if cache_search:
1109         now = time.time()
1110         nowstamp = "%s (%s)" % (
1111             now,
1112             datetime.datetime.isoformat(
1113                 datetime.datetime.fromtimestamp(now),
1114                 " "
1115             )
1116         )
1117         search_cache = ["\n"]
1118         search_cache.append( "[%s]\n" % search[0] ) 
1119         search_cache.append( "description = cached %s\n" % nowstamp )
1120         for uriname in sorted(uris.keys()):
1121             search_cache.append( "%s = %s\n" % ( uriname, uris[uriname] ) )
1122         real_cachedir = os.path.expanduser(cachedir)
1123         if not os.path.exists(real_cachedir):
1124             try: os.makedirs(real_cachedir)
1125             except (IOError, OSError): pass
1126         scache_fn = os.path.join(real_cachedir, "searches")
1127         if not os.path.exists(scache_fn):
1128             then = sorted(
1129                     [ x[1] for x in datafiles.values() ],
1130                     reverse=True
1131                 )[0]
1132             thenstamp = "%s (%s)" % (
1133                 then,
1134                 datetime.datetime.isoformat(
1135                     datetime.datetime.fromtimestamp(then),
1136                     " "
1137                 )
1138             )
1139             search_cache.insert(
1140                 0,
1141                 "# based on data files from: %s\n" % thenstamp
1142             )
1143         try:
1144             scache_existing = configparser.ConfigParser()
1145             scache_existing.read(scache_fn)
1146             if not scache_existing.has_section(search[0]):
1147                 scache_fd = codecs.open(scache_fn, "a", "utf-8")
1148                 scache_fd.writelines(search_cache)
1149                 scache_fd.close()
1150         except (IOError, OSError): pass
1151     if not info:
1152         return(uris)
1153
1154 def closest(position, nodes, fieldname, angle=None):
1155     import math
1156     if not angle: angle = 2*math.pi
1157     match = None
1158     for name in nodes:
1159         if fieldname in nodes[name]:
1160             node = nodes[name][fieldname]
1161             if node and abs( position[0]-node[0] ) < angle:
1162                 if abs( position[1]-node[1] ) < angle \
1163                     or abs( abs( position[1]-node[1] ) - 2*math.pi ) < angle:
1164                     if position == node:
1165                         angle = 0
1166                         match = name
1167                     else:
1168                         candidate = math.acos(
1169                             math.sin( position[0] ) * math.sin( node[0] ) \
1170                                 + math.cos( position[0] ) \
1171                                 * math.cos( node[0] ) \
1172                                 * math.cos( position[1] - node[1] )
1173                             )
1174                         if candidate < angle:
1175                             angle = candidate
1176                             match = name
1177     if match: match = str(match)
1178     return (match, angle)
1179
1180 def gecos(formatted):
1181     import math, re
1182     coordinates = formatted.split(",")
1183     for coordinate in range(0, 2):
1184         degrees, foo, minutes, bar, seconds, hemisphere = re.match(
1185             r"([\+-]?\d+\.?\d*)(-(\d+))?(-(\d+))?([ensw]?)$",
1186             coordinates[coordinate].strip().lower()
1187         ).groups()
1188         value = float(degrees)
1189         if minutes: value += float(minutes)/60
1190         if seconds: value += float(seconds)/3600
1191         if hemisphere and hemisphere in "sw": value *= -1
1192         coordinates[coordinate] = math.radians(value)
1193     return tuple(coordinates)
1194
1195 def correlate():
1196     import codecs, datetime, hashlib, os, re, sys, tarfile, time, zipfile
1197     if pyversion("3"): import configparser
1198     else: import ConfigParser as configparser
1199     gcounties_an = "2014_Gaz_counties_national.zip"
1200     gcounties_fn = "2014_Gaz_counties_national.txt"
1201     gcousubs_an = "2014_Gaz_cousubs_national.zip"
1202     gcousubs_fn = "2014_Gaz_cousubs_national.txt"
1203     gplace_an = "2014_Gaz_place_national.zip"
1204     gplace_fn = "2014_Gaz_place_national.txt"
1205     gzcta_an = "2014_Gaz_zcta_national.zip"
1206     gzcta_fn = "2014_Gaz_zcta_national.txt"
1207     for filename in os.listdir("."):
1208         if re.match("bp[0-9][0-9][a-z][a-z][0-9][0-9].dbx$", filename):
1209             cpfzcf_fn = filename
1210             break
1211     nsdcccc_fn = "nsd_cccc.txt"
1212     zcatalog_an = "zonecatalog.curr.tar"
1213     metartbl_fn = "metar.tbl"
1214     coopstn_fn = "coop-stations.txt"
1215     overrides_fn = "overrides.conf"
1216     overrideslog_fn = "overrides.log"
1217     slist_fn = "slist"
1218     zlist_fn = "zlist"
1219     qalog_fn = "qa.log"
1220     airports_fn = "airports"
1221     places_fn = "places"
1222     stations_fn = "stations"
1223     zctas_fn = "zctas"
1224     zones_fn = "zones"
1225     header = """\
1226 %s
1227 # generated by %s on %s from these public domain sources:
1228 #
1229 # http://www.census.gov/geo/maps-data/data/gazetteer2014.html
1230 # %s %s %s
1231 # %s %s %s
1232 # %s %s %s
1233 # %s %s %s
1234 #
1235 # http://www.weather.gov/geodata/catalog/wsom/html/cntyzone.htm
1236 # %s %s %s
1237 #
1238 # http://weather.noaa.gov/data/nsd_cccc.txt
1239 # %s %s %s
1240 #
1241 # http://weather.noaa.gov/pub/data/zonecatalog.curr.tar
1242 # %s %s %s
1243 #
1244 # http://www.nco.ncep.noaa.gov/pmb/codes/nwprod/dictionaries/metar.tbl
1245 # %s %s %s
1246 #
1247 # http://www.ncdc.noaa.gov/homr/reports
1248 # %s %s %s
1249 #
1250 # ...and these manually-generated or hand-compiled adjustments:
1251 # %s %s %s
1252 # %s %s %s
1253 # %s %s %s\
1254 """ % (
1255         weather_copyright,
1256         os.path.basename( sys.argv[0] ),
1257         datetime.date.isoformat(
1258             datetime.datetime.fromtimestamp( time.time() )
1259         ),
1260         hashlib.md5( open(gcounties_an, "rb").read() ).hexdigest(),
1261         datetime.date.isoformat(
1262             datetime.datetime.fromtimestamp( os.path.getmtime(gcounties_an) )
1263         ),
1264         gcounties_an,
1265         hashlib.md5( open(gcousubs_an, "rb").read() ).hexdigest(),
1266         datetime.date.isoformat(
1267             datetime.datetime.fromtimestamp( os.path.getmtime(gcousubs_an) )
1268         ),
1269         gcousubs_an,
1270         hashlib.md5( open(gplace_an, "rb").read() ).hexdigest(),
1271         datetime.date.isoformat(
1272             datetime.datetime.fromtimestamp( os.path.getmtime(gplace_an) )
1273         ),
1274         gplace_an,
1275         hashlib.md5( open(gzcta_an, "rb").read() ).hexdigest(),
1276         datetime.date.isoformat(
1277             datetime.datetime.fromtimestamp( os.path.getmtime(gzcta_an) )
1278         ),
1279         gzcta_an,
1280         hashlib.md5( open(cpfzcf_fn, "rb").read() ).hexdigest(),
1281         datetime.date.isoformat(
1282             datetime.datetime.fromtimestamp( os.path.getmtime(cpfzcf_fn) )
1283         ),
1284         cpfzcf_fn,
1285         hashlib.md5( open(nsdcccc_fn, "rb").read() ).hexdigest(),
1286         datetime.date.isoformat(
1287             datetime.datetime.fromtimestamp( os.path.getmtime(nsdcccc_fn) )
1288         ),
1289         nsdcccc_fn,
1290         hashlib.md5( open(zcatalog_an, "rb").read() ).hexdigest(),
1291         datetime.date.isoformat(
1292             datetime.datetime.fromtimestamp( os.path.getmtime(zcatalog_an) )
1293         ),
1294         zcatalog_an,
1295         hashlib.md5( open(metartbl_fn, "rb").read() ).hexdigest(),
1296         datetime.date.isoformat(
1297             datetime.datetime.fromtimestamp( os.path.getmtime(metartbl_fn) )
1298         ),
1299         metartbl_fn,
1300         hashlib.md5( open(coopstn_fn, "rb").read() ).hexdigest(),
1301         datetime.date.isoformat(
1302             datetime.datetime.fromtimestamp( os.path.getmtime(coopstn_fn) )
1303         ),
1304         coopstn_fn,
1305         hashlib.md5( open(overrides_fn, "rb").read() ).hexdigest(),
1306         datetime.date.isoformat(
1307             datetime.datetime.fromtimestamp( os.path.getmtime(overrides_fn) )
1308         ),
1309         overrides_fn,
1310         hashlib.md5( open(slist_fn, "rb").read() ).hexdigest(),
1311         datetime.date.isoformat(
1312             datetime.datetime.fromtimestamp( os.path.getmtime(slist_fn) )
1313         ),
1314         slist_fn,
1315         hashlib.md5( open(zlist_fn, "rb").read() ).hexdigest(),
1316         datetime.date.isoformat(
1317             datetime.datetime.fromtimestamp( os.path.getmtime(zlist_fn) )
1318         ),
1319         zlist_fn
1320     )
1321     airports = {}
1322     places = {}
1323     stations = {}
1324     zctas = {}
1325     zones = {}
1326     message = "Reading %s:%s..." % (gcounties_an, gcounties_fn)
1327     sys.stdout.write(message)
1328     sys.stdout.flush()
1329     count = 0
1330     gcounties = zipfile.ZipFile(gcounties_an).open(gcounties_fn, "rU")
1331     columns = gcounties.readline().decode("latin1").strip().split("\t")
1332     for line in gcounties:
1333         fields = line.decode("latin1").strip().split("\t")
1334         f_geoid = fields[ columns.index("GEOID") ].strip()
1335         f_name = fields[ columns.index("NAME") ].strip()
1336         f_usps = fields[ columns.index("USPS") ].strip()
1337         f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1338         f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1339         if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1340             fips = "fips%s" % f_geoid
1341             if fips not in places: places[fips] = {}
1342             places[fips]["centroid"] = gecos(
1343                 "%s,%s" % (f_intptlat, f_intptlong)
1344             )
1345             places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1346             count += 1
1347     gcounties.close()
1348     print("done (%s lines)." % count)
1349     message = "Reading %s:%s..." % (gcousubs_an, gcousubs_fn)
1350     sys.stdout.write(message)
1351     sys.stdout.flush()
1352     count = 0
1353     gcousubs = zipfile.ZipFile(gcousubs_an).open(gcousubs_fn, "rU")
1354     columns = gcousubs.readline().decode("latin1").strip().split("\t")
1355     for line in gcousubs:
1356         fields = line.decode("latin1").strip().split("\t")
1357         f_geoid = fields[ columns.index("GEOID") ].strip()
1358         f_name = fields[ columns.index("NAME") ].strip()
1359         f_usps = fields[ columns.index("USPS") ].strip()
1360         f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1361         f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1362         if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1363             fips = "fips%s" % f_geoid
1364             if fips not in places: places[fips] = {}
1365             places[fips]["centroid"] = gecos(
1366                 "%s,%s" % (f_intptlat, f_intptlong)
1367             )
1368             places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1369             count += 1
1370     gcousubs.close()
1371     print("done (%s lines)." % count)
1372     message = "Reading %s:%s..." % (gplace_an, gplace_fn)
1373     sys.stdout.write(message)
1374     sys.stdout.flush()
1375     count = 0
1376     gplace = zipfile.ZipFile(gplace_an).open(gplace_fn, "rU")
1377     columns = gplace.readline().decode("latin1").strip().split("\t")
1378     for line in gplace:
1379         fields = line.decode("latin1").strip().split("\t")
1380         f_geoid = fields[ columns.index("GEOID") ].strip()
1381         f_name = fields[ columns.index("NAME") ].strip()
1382         f_usps = fields[ columns.index("USPS") ].strip()
1383         f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1384         f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1385         if f_geoid and f_name and f_usps and f_intptlat and f_intptlong:
1386             fips = "fips%s" % f_geoid
1387             if fips not in places: places[fips] = {}
1388             places[fips]["centroid"] = gecos(
1389                 "%s,%s" % (f_intptlat, f_intptlong)
1390             )
1391             places[fips]["description"] = "%s, %s" % (f_name, f_usps)
1392             count += 1
1393     gplace.close()
1394     print("done (%s lines)." % count)
1395     message = "Reading %s..." % slist_fn
1396     sys.stdout.write(message)
1397     sys.stdout.flush()
1398     count = 0
1399     slist = codecs.open(slist_fn, "rU")
1400     for line in slist:
1401         icao = line.split("#")[0].strip()
1402         if icao:
1403             stations[icao] = {
1404                 "metar": "http://weather.noaa.gov/pub/data/observations/"\
1405                     + "metar/decoded/%s.TXT" % icao.upper()
1406             }
1407             count += 1
1408     slist.close()
1409     print("done (%s lines)." % count)
1410     message = "Reading %s..." % metartbl_fn
1411     sys.stdout.write(message)
1412     sys.stdout.flush()
1413     count = 0
1414     metartbl = codecs.open(metartbl_fn, "rU")
1415     for line in metartbl:
1416         icao = line[:4].strip().lower()
1417         if icao in stations:
1418             description = []
1419             name = " ".join(
1420                 line[16:48].replace("_", " ").strip().title().split()
1421             )
1422             if name: description.append(name)
1423             st = line[49:51].strip()
1424             if st: description.append(st)
1425             cn = line[52:54].strip()
1426             if cn: description.append(cn)
1427             if description:
1428                 stations[icao]["description"] = ", ".join(description)
1429             lat = line[55:60].strip()
1430             if lat:
1431                 lat = int(lat)/100.0
1432                 lon = line[61:67].strip()
1433                 if lon:
1434                     lon = int(lon)/100.0
1435                     stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1436         count += 1
1437     metartbl.close()
1438     print("done (%s lines)." % count)
1439     message = "Reading %s..." % nsdcccc_fn
1440     sys.stdout.write(message)
1441     sys.stdout.flush()
1442     count = 0
1443     nsdcccc = codecs.open(nsdcccc_fn, "rU", "latin1")
1444     for line in nsdcccc:
1445         line = str(line)
1446         fields = line.split(";")
1447         icao = fields[0].strip().lower()
1448         if icao in stations:
1449             description = []
1450             name = " ".join( fields[3].strip().title().split() )
1451             if name: description.append(name)
1452             st = fields[4].strip()
1453             if st: description.append(st)
1454             country = " ".join( fields[5].strip().title().split() )
1455             if country: description.append(country)
1456             if description:
1457                 stations[icao]["description"] = ", ".join(description)
1458             lat, lon = fields[7:9]
1459             if lat and lon:
1460                 stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1461             elif "location" not in stations[icao]:
1462                 lat, lon = fields[5:7]
1463                 if lat and lon:
1464                     stations[icao]["location"] = gecos( "%s,%s" % (lat, lon) )
1465         count += 1
1466     nsdcccc.close()
1467     print("done (%s lines)." % count)
1468     message = "Reading %s..." % coopstn_fn
1469     sys.stdout.write(message)
1470     sys.stdout.flush()
1471     count = 0
1472     coopstn = open(coopstn_fn)
1473     for line in coopstn:
1474         icao = line[33:37].strip().lower()
1475         if icao in stations:
1476             iata = line[22:26].strip().lower()
1477             if len(iata) == 3: airports[iata] = { "station": icao }
1478             if "description" not in stations[icao]:
1479                 description = []
1480                 name = " ".join( line[99:129].strip().title().split() )
1481                 if name: description.append(name)
1482                 st = line[59:61].strip()
1483                 if st: description.append(st)
1484                 country = " ".join( line[38:58].strip().title().split() )
1485                 if country: description.append(country)
1486                 if description:
1487                     stations[icao]["description"] = ", ".join(description)
1488             if "location" not in stations[icao]:
1489                 lat = line[130:139].strip()
1490                 if lat:
1491                     lat = lat.replace(" ", "-")
1492                     lon = line[140:150].strip()
1493                     if lon:
1494                         lon = lon.replace(" ", "-")
1495                         stations[icao]["location"] = gecos(
1496                             "%s,%s" % (lat, lon)
1497                         )
1498         count += 1
1499     coopstn.close()
1500     print("done (%s lines)." % count)
1501     message = "Reading %s..." % zlist_fn
1502     sys.stdout.write(message)
1503     sys.stdout.flush()
1504     count = 0
1505     zlist = codecs.open(zlist_fn, "rU")
1506     for line in zlist:
1507         line = line.split("#")[0].strip()
1508         if line:
1509             zones[line] = {}
1510             count += 1
1511     zlist.close()
1512     print("done (%s lines)." % count)
1513     message = "Reading %s:*..." % zcatalog_an
1514     sys.stdout.write(message)
1515     sys.stdout.flush()
1516     count = 0
1517     zcatalog = tarfile.open(zcatalog_an)
1518     for entry in zcatalog.getmembers():
1519         if entry.isfile():
1520             fnmatch = re.match(
1521                 r"([a-z]+z[0-9]+)\.txt$",
1522                 os.path.basename(entry.name)
1523             )
1524             if fnmatch:
1525                 zone = fnmatch.group(1)
1526                 if zone in zones:
1527                     data = zcatalog.extractfile(entry).readlines()
1528                     description = data[0].decode("ascii").strip()
1529                     zones[zone]["description"] = description
1530                     for line in data[1:]:
1531                         line = line.decode("latin1").strip()
1532                         urimatch = re.match("/webdocs/(.+):(.+) for ", line)
1533                         if urimatch:
1534                             uritype = urimatch.group(2).lower().replace(" ","_")
1535                             zones[zone][uritype] \
1536                                 = "http://weather.noaa.gov/%s" \
1537                                 % urimatch.group(1)
1538         count += 1
1539     zcatalog.close()
1540     print("done (%s files)." % count)
1541     message = "Reading %s..." % cpfzcf_fn
1542     sys.stdout.write(message)
1543     sys.stdout.flush()
1544     count = 0
1545     cpfz = {}
1546     cpfzcf = open(cpfzcf_fn)
1547     for line in cpfzcf:
1548         fields = line.strip().split("|")
1549         if len(fields) == 11 \
1550             and fields[0] and fields[1] and fields[9] and fields[10]:
1551             zone = "z".join( fields[:2] ).lower()
1552             if zone in zones:
1553                 zones[zone]["centroid"] = gecos( ",".join( fields[9:11] ) )
1554             elif fields[6]:
1555                 state = fields[0]
1556                 description = fields[3]
1557                 county = fields[5]
1558                 fips = "fips%s"%fields[6]
1559                 possible = [
1560                     "%s, %s" % (county, state),
1561                     "%s County, %s" % (county, state),
1562                 ]
1563                 if description.endswith(" Counties"):
1564                     description = description[:-9]
1565                 for addition in description.split(" and "):
1566                     possible.append( "%s, %s" % (addition, state) )
1567                     possible.append( "%s County, %s" % (addition, state) )
1568                 if fips in places and "centroid" in places[fips]:
1569                     for candidate in zones:
1570                         if "centroid" not in zones[candidate] and \
1571                             "description" in zones[candidate] and \
1572                             zones[candidate]["description"] in possible:
1573                             zones[candidate]["centroid"] = \
1574                                 places[fips]["centroid"]
1575         count += 1
1576     cpfzcf.close()
1577     print("done (%s lines)." % count)
1578     message = "Reading %s:%s..." % (gzcta_an, gzcta_fn)
1579     sys.stdout.write(message)
1580     sys.stdout.flush()
1581     count = 0
1582     gzcta = zipfile.ZipFile(gzcta_an).open(gzcta_fn, "rU")
1583     columns = gzcta.readline().decode("latin1").strip().split("\t")
1584     for line in gzcta:
1585         fields = line.decode("latin1").strip().split("\t")
1586         f_geoid = fields[ columns.index("GEOID") ].strip()
1587         f_intptlat = fields[ columns.index("INTPTLAT") ].strip()
1588         f_intptlong = fields[ columns.index("INTPTLONG") ].strip()
1589         if f_geoid and f_intptlat and f_intptlong:
1590             if f_geoid not in zctas: zctas[f_geoid] = {}
1591             zctas[f_geoid]["centroid"] = gecos(
1592                 "%s,%s" % (f_intptlat, f_intptlong)
1593             )
1594             count += 1
1595     gzcta.close()
1596     print("done (%s lines)." % count)
1597     message = "Reading %s..." % overrides_fn
1598     sys.stdout.write(message)
1599     sys.stdout.flush()
1600     count = 0
1601     added = 0
1602     removed = 0
1603     changed = 0
1604     overrides = configparser.ConfigParser()
1605     overrides.readfp( codecs.open(overrides_fn, "r", "utf8") )
1606     overrideslog = []
1607     for section in overrides.sections():
1608         addopt = 0
1609         chgopt = 0
1610         if section.startswith("-"):
1611             section = section[1:]
1612             delete = True
1613         else: delete = False
1614         if re.match("[A-Za-z]{3}$", section):
1615             if delete:
1616                 if section in airports:
1617                     del( airports[section] )
1618                     logact = "removed airport %s" % section
1619                     removed += 1
1620                 else:
1621                     logact = "tried to remove nonexistent airport %s" % section
1622             else:
1623                 if section in airports:
1624                     logact = "changed airport %s" % section
1625                     changed += 1
1626                 else:
1627                     airports[section] = {}
1628                     logact = "added airport %s" % section
1629                     added += 1
1630                 for key,value in overrides.items(section):
1631                     if key in airports[section]: chgopt += 1
1632                     else: addopt += 1
1633                     if key in ("centroid", "location"):
1634                         airports[section][key] = eval(value)
1635                     else:
1636                         airports[section][key] = value
1637                 if addopt and chgopt:
1638                     logact += " (+%s/!%s options)" % (addopt, chgopt)
1639                 elif addopt: logact += " (+%s options)" % addopt
1640                 elif chgopt: logact += " (!%s options)" % chgopt
1641         elif re.match("[A-Za-z0-9]{4}$", section):
1642             if delete:
1643                 if section in stations:
1644                     del( stations[section] )
1645                     logact = "removed station %s" % section
1646                     removed += 1
1647                 else:
1648                     logact = "tried to remove nonexistent station %s" % section
1649             else:
1650                 if section in stations:
1651                     logact = "changed station %s" % section
1652                     changed += 1
1653                 else:
1654                     stations[section] = {}
1655                     logact = "added station %s" % section
1656                     added += 1
1657                 for key,value in overrides.items(section):
1658                     if key in stations[section]: chgopt += 1
1659                     else: addopt += 1
1660                     if key in ("centroid", "location"):
1661                         stations[section][key] = eval(value)
1662                     else:
1663                         stations[section][key] = value
1664                 if addopt and chgopt:
1665                     logact += " (+%s/!%s options)" % (addopt, chgopt)
1666                 elif addopt: logact += " (+%s options)" % addopt
1667                 elif chgopt: logact += " (!%s options)" % chgopt
1668         elif re.match("[0-9]{5}$", section):
1669             if delete:
1670                 if section in zctas:
1671                     del( zctas[section] )
1672                     logact = "removed zcta %s" % section
1673                     removed += 1
1674                 else:
1675                     logact = "tried to remove nonexistent zcta %s" % section
1676             else:
1677                 if section in zctas:
1678                     logact = "changed zcta %s" % section
1679                     changed += 1
1680                 else:
1681                     zctas[section] = {}
1682                     logact = "added zcta %s" % section
1683                     added += 1
1684                 for key,value in overrides.items(section):
1685                     if key in zctas[section]: chgopt += 1
1686                     else: addopt += 1
1687                     if key in ("centroid", "location"):
1688                         zctas[section][key] = eval(value)
1689                     else:
1690                         zctas[section][key] = value
1691                 if addopt and chgopt:
1692                     logact += " (+%s/!%s options)" % (addopt, chgopt)
1693                 elif addopt: logact += " (+%s options)" % addopt
1694                 elif chgopt: logact += " (!%s options)" % chgopt
1695         elif re.match("[A-Za-z]{2}[Zz][0-9]{3}$", section):
1696             if delete:
1697                 if section in zones:
1698                     del( zones[section] )
1699                     logact = "removed zone %s" % section
1700                     removed += 1
1701                 else:
1702                     logact = "tried to remove nonexistent zone %s" % section
1703             else:
1704                 if section in zones:
1705                     logact = "changed zone %s" % section
1706                     changed += 1
1707                 else:
1708                     zones[section] = {}
1709                     logact = "added zone %s" % section
1710                     added += 1
1711                 for key,value in overrides.items(section):
1712                     if key in zones[section]: chgopt += 1
1713                     else: addopt += 1
1714                     if key in ("centroid", "location"):
1715                         zones[section][key] = eval(value)
1716                     else:
1717                         zones[section][key] = value
1718                 if addopt and chgopt:
1719                     logact += " (+%s/!%s options)" % (addopt, chgopt)
1720                 elif addopt: logact += " (+%s options)" % addopt
1721                 elif chgopt: logact += " (!%s options)" % chgopt
1722         elif re.match("fips[0-9]+$", section):
1723             if delete:
1724                 if section in places:
1725                     del( places[section] )
1726                     logact = "removed place %s" % section
1727                     removed += 1
1728                 else:
1729                     logact = "tried to remove nonexistent place %s" % section
1730             else:
1731                 if section in places:
1732                     logact = "changed place %s" % section
1733                     changed += 1
1734                 else:
1735                     places[section] = {}
1736                     logact = "added place %s" % section
1737                     added += 1
1738                 for key,value in overrides.items(section):
1739                     if key in places[section]: chgopt += 1
1740                     else: addopt += 1
1741                     if key in ("centroid", "location"):
1742                         places[section][key] = eval(value)
1743                     else:
1744                         places[section][key] = value
1745                 if addopt and chgopt:
1746                     logact += " (+%s/!%s options)" % (addopt, chgopt)
1747                 elif addopt: logact += " (+%s options)" % addopt
1748                 elif chgopt: logact += " (!%s options)" % chgopt
1749         count += 1
1750         overrideslog.append("%s\n" % logact)
1751     overrideslog.sort()
1752     if os.path.exists(overrideslog_fn):
1753         os.rename(overrideslog_fn, "%s_old"%overrideslog_fn)
1754     overrideslog_fd = codecs.open(overrideslog_fn, "w", "utf8")
1755     overrideslog_fd.writelines(overrideslog)
1756     overrideslog_fd.close()
1757     print("done (%s overridden sections: +%s/-%s/!%s)." % (
1758         count,
1759         added,
1760         removed,
1761         changed
1762     ) )
1763     estimate = 2*len(places) + len(stations) + 2*len(zctas) + len(zones)
1764     print(
1765         "Correlating places, stations, ZCTAs and zones (upper bound is %s):" % \
1766             estimate
1767     )
1768     count = 0
1769     milestones = list( range(51) )
1770     message = "   "
1771     sys.stdout.write(message)
1772     sys.stdout.flush()
1773     for fips in places:
1774         centroid = places[fips]["centroid"]
1775         if centroid:
1776             station = closest(centroid, stations, "location", 0.1)
1777         if station[0]:
1778             places[fips]["station"] = station
1779             count += 1
1780             if not count%100:
1781                 level = int(50*count/estimate)
1782                 if level in milestones:
1783                     for remaining in milestones[:milestones.index(level)+1]:
1784                         if remaining%5:
1785                             message = "."
1786                             sys.stdout.write(message)
1787                             sys.stdout.flush()
1788                         else:
1789                             message = "%s%%" % (remaining*2,)
1790                             sys.stdout.write(message)
1791                             sys.stdout.flush()
1792                         milestones.remove(remaining)
1793         if centroid:
1794             zone = closest(centroid, zones, "centroid", 0.1)
1795         if zone[0]:
1796             places[fips]["zone"] = zone
1797             count += 1
1798             if not count%100:
1799                 level = int(50*count/estimate)
1800                 if level in milestones:
1801                     for remaining in milestones[:milestones.index(level)+1]:
1802                         if remaining%5:
1803                             message = "."
1804                             sys.stdout.write(message)
1805                             sys.stdout.flush()
1806                         else:
1807                             message = "%s%%" % (remaining*2,)
1808                             sys.stdout.write(message)
1809                             sys.stdout.flush()
1810                         milestones.remove(remaining)
1811     for station in stations:
1812         if "location" in stations[station]:
1813             location = stations[station]["location"]
1814             if location:
1815                 zone = closest(location, zones, "centroid", 0.1)
1816             if zone[0]:
1817                 stations[station]["zone"] = zone
1818                 count += 1
1819                 if not count%100:
1820                     level = int(50*count/estimate)
1821                     if level in milestones:
1822                         for remaining in milestones[:milestones.index(level)+1]:
1823                             if remaining%5:
1824                                 message = "."
1825                                 sys.stdout.write(message)
1826                                 sys.stdout.flush()
1827                             else:
1828                                 message = "%s%%" % (remaining*2,)
1829                                 sys.stdout.write(message)
1830                                 sys.stdout.flush()
1831                             milestones.remove(remaining)
1832     for zcta in zctas.keys():
1833         centroid = zctas[zcta]["centroid"]
1834         if centroid:
1835             station = closest(centroid, stations, "location", 0.1)
1836         if station[0]:
1837             zctas[zcta]["station"] = station
1838             count += 1
1839             if not count%100:
1840                 level = int(50*count/estimate)
1841                 if level in milestones:
1842                     for remaining in milestones[ : milestones.index(level)+1 ]:
1843                         if remaining%5:
1844                             message = "."
1845                             sys.stdout.write(message)
1846                             sys.stdout.flush()
1847                         else:
1848                             message = "%s%%" % (remaining*2,)
1849                             sys.stdout.write(message)
1850                             sys.stdout.flush()
1851                         milestones.remove(remaining)
1852         if centroid:
1853             zone = closest(centroid, zones, "centroid", 0.1)
1854         if zone[0]:
1855             zctas[zcta]["zone"] = zone
1856             count += 1
1857             if not count%100:
1858                 level = int(50*count/estimate)
1859                 if level in milestones:
1860                     for remaining in milestones[:milestones.index(level)+1]:
1861                         if remaining%5:
1862                             message = "."
1863                             sys.stdout.write(message)
1864                             sys.stdout.flush()
1865                         else:
1866                             message = "%s%%" % (remaining*2,)
1867                             sys.stdout.write(message)
1868                             sys.stdout.flush()
1869                         milestones.remove(remaining)
1870     for zone in zones.keys():
1871         if "centroid" in zones[zone]:
1872             centroid = zones[zone]["centroid"]
1873             if centroid:
1874                 station = closest(centroid, stations, "location", 0.1)
1875             if station[0]:
1876                 zones[zone]["station"] = station
1877                 count += 1
1878                 if not count%100:
1879                     level = int(50*count/estimate)
1880                     if level in milestones:
1881                         for remaining in milestones[:milestones.index(level)+1]:
1882                             if remaining%5:
1883                                 message = "."
1884                                 sys.stdout.write(message)
1885                                 sys.stdout.flush()
1886                             else:
1887                                 message = "%s%%" % (remaining*2,)
1888                                 sys.stdout.write(message)
1889                                 sys.stdout.flush()
1890                             milestones.remove(remaining)
1891     for remaining in milestones:
1892         if remaining%5:
1893             message = "."
1894             sys.stdout.write(message)
1895             sys.stdout.flush()
1896         else:
1897             message = "%s%%" % (remaining*2,)
1898             sys.stdout.write(message)
1899             sys.stdout.flush()
1900     print("\n   done (%s correlations)." % count)
1901     message = "Writing %s..." % airports_fn
1902     sys.stdout.write(message)
1903     sys.stdout.flush()
1904     count = 0
1905     if os.path.exists(airports_fn):
1906         os.rename(airports_fn, "%s_old"%airports_fn)
1907     airports_fd = codecs.open(airports_fn, "w", "utf8")
1908     airports_fd.write(header)
1909     for airport in sorted( airports.keys() ):
1910         airports_fd.write("\n\n[%s]" % airport)
1911         for key, value in sorted( airports[airport].items() ):
1912             if type(value) is float: value = "%.7f"%value
1913             elif type(value) is tuple:
1914                 elements = []
1915                 for element in value:
1916                     if type(element) is float: elements.append("%.7f"%element)
1917                     else: elements.append( repr(element) )
1918                 value = "(%s)"%", ".join(elements)
1919             airports_fd.write( "\n%s = %s" % (key, value) )
1920         count += 1
1921     airports_fd.write("\n")
1922     airports_fd.close()
1923     print("done (%s sections)." % count)
1924     message = "Writing %s..." % places_fn
1925     sys.stdout.write(message)
1926     sys.stdout.flush()
1927     count = 0
1928     if os.path.exists(places_fn):
1929         os.rename(places_fn, "%s_old"%places_fn)
1930     places_fd = codecs.open(places_fn, "w", "utf8")
1931     places_fd.write(header)
1932     for fips in sorted( places.keys() ):
1933         places_fd.write("\n\n[%s]" % fips)
1934         for key, value in sorted( places[fips].items() ):
1935             if type(value) is float: value = "%.7f"%value
1936             elif type(value) is tuple:
1937                 elements = []
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             places_fd.write( "\n%s = %s" % (key, value) )
1943         count += 1
1944     places_fd.write("\n")
1945     places_fd.close()
1946     print("done (%s sections)." % count)
1947     message = "Writing %s..." % stations_fn
1948     sys.stdout.write(message)
1949     sys.stdout.flush()
1950     count = 0
1951     if os.path.exists(stations_fn):
1952         os.rename(stations_fn, "%s_old"%stations_fn)
1953     stations_fd = codecs.open(stations_fn, "w", "utf8")
1954     stations_fd.write(header)
1955     for station in sorted( stations.keys() ):
1956         stations_fd.write("\n\n[%s]" % station)
1957         for key, value in sorted( stations[station].items() ):
1958             if type(value) is float: value = "%.7f"%value
1959             elif type(value) is tuple:
1960                 elements = []
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             stations_fd.write( "\n%s = %s" % (key, value) )
1966         count += 1
1967     stations_fd.write("\n")
1968     stations_fd.close()
1969     print("done (%s sections)." % count)
1970     message = "Writing %s..." % zctas_fn
1971     sys.stdout.write(message)
1972     sys.stdout.flush()
1973     count = 0
1974     if os.path.exists(zctas_fn):
1975         os.rename(zctas_fn, "%s_old"%zctas_fn)
1976     zctas_fd = codecs.open(zctas_fn, "w", "utf8")
1977     zctas_fd.write(header)
1978     for zcta in sorted( zctas.keys() ):
1979         zctas_fd.write("\n\n[%s]" % zcta)
1980         for key, value in sorted( zctas[zcta].items() ):
1981             if type(value) is float: value = "%.7f"%value
1982             elif type(value) is tuple:
1983                 elements = []
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             zctas_fd.write( "\n%s = %s" % (key, value) )
1989         count += 1
1990     zctas_fd.write("\n")
1991     zctas_fd.close()
1992     print("done (%s sections)." % count)
1993     message = "Writing %s..." % zones_fn
1994     sys.stdout.write(message)
1995     sys.stdout.flush()
1996     count = 0
1997     if os.path.exists(zones_fn):
1998         os.rename(zones_fn, "%s_old"%zones_fn)
1999     zones_fd = codecs.open(zones_fn, "w", "utf8")
2000     zones_fd.write(header)
2001     for zone in sorted( zones.keys() ):
2002         zones_fd.write("\n\n[%s]" % zone)
2003         for key, value in sorted( zones[zone].items() ):
2004             if type(value) is float: value = "%.7f"%value
2005             elif type(value) is tuple:
2006                 elements = []
2007                 for element in value:
2008                     if type(element) is float: elements.append("%.7f"%element)
2009                     else: elements.append( repr(element) )
2010                 value = "(%s)"%", ".join(elements)
2011             zones_fd.write( "\n%s = %s" % (key, value) )
2012         count += 1
2013     zones_fd.write("\n")
2014     zones_fd.close()
2015     print("done (%s sections)." % count)
2016     message = "Starting QA check..."
2017     sys.stdout.write(message)
2018     sys.stdout.flush()
2019     airports = configparser.ConfigParser()
2020     airports.read(airports_fn)
2021     places = configparser.ConfigParser()
2022     places.read(places_fn)
2023     stations = configparser.ConfigParser()
2024     stations.read(stations_fn)
2025     zctas = configparser.ConfigParser()
2026     zctas.read(zctas_fn)
2027     zones = configparser.ConfigParser()
2028     zones.read(zones_fn)
2029     qalog = []
2030     places_nocentroid = 0
2031     places_nodescription = 0
2032     for place in sorted( places.sections() ):
2033         if not places.has_option(place, "centroid"):
2034             qalog.append("%s: no centroid\n" % place)
2035             places_nocentroid += 1
2036         if not places.has_option(place, "description"):
2037             qalog.append("%s: no description\n" % place)
2038             places_nodescription += 1
2039     stations_nodescription = 0
2040     stations_nolocation = 0
2041     stations_nometar = 0
2042     for station in sorted( stations.sections() ):
2043         if not stations.has_option(station, "description"):
2044             qalog.append("%s: no description\n" % station)
2045             stations_nodescription += 1
2046         if not stations.has_option(station, "location"):
2047             qalog.append("%s: no location\n" % station)
2048             stations_nolocation += 1
2049         if not stations.has_option(station, "metar"):
2050             qalog.append("%s: no metar\n" % station)
2051             stations_nometar += 1
2052     airports_badstation = 0
2053     airports_nostation = 0
2054     for airport in sorted( airports.sections() ):
2055         if not airports.has_option(airport, "station"):
2056             qalog.append("%s: no station\n" % airport)
2057             airports_nostation += 1
2058         else:
2059             station = airports.get(airport, "station")
2060             if station not in stations.sections():
2061                 qalog.append( "%s: bad station %s\n" % (airport, station) )
2062                 airports_badstation += 1
2063     zctas_nocentroid = 0
2064     for zcta in sorted( zctas.sections() ):
2065         if not zctas.has_option(zcta, "centroid"):
2066             qalog.append("%s: no centroid\n" % zcta)
2067             zctas_nocentroid += 1
2068     zones_nocentroid = 0
2069     zones_nodescription = 0
2070     zones_noforecast = 0
2071     zones_overlapping = 0
2072     zonetable = {}
2073     for zone in zones.sections():
2074         if zones.has_option(zone, "centroid"):
2075             zonetable[zone] = {
2076                 "centroid": eval( zones.get(zone, "centroid") )
2077             }
2078     for zone in sorted( zones.sections() ):
2079         if zones.has_option(zone, "centroid"):
2080             zonetable_local = zonetable.copy()
2081             del( zonetable_local[zone] )
2082             centroid = eval( zones.get(zone, "centroid") )
2083             if centroid:
2084                 nearest = closest(centroid, zonetable_local, "centroid", 0.1)
2085             if nearest[1]*radian_to_km < 1:
2086                 qalog.append( "%s: within one km of %s\n" % (
2087                     zone,
2088                     nearest[0]
2089                 ) )
2090                 zones_overlapping += 1
2091         else:
2092             qalog.append("%s: no centroid\n" % zone)
2093             zones_nocentroid += 1
2094         if not zones.has_option(zone, "description"):
2095             qalog.append("%s: no description\n" % zone)
2096             zones_nodescription += 1
2097         if not zones.has_option(zone, "zone_forecast"):
2098             qalog.append("%s: no forecast\n" % zone)
2099             zones_noforecast += 1
2100     if os.path.exists(qalog_fn):
2101         os.rename(qalog_fn, "%s_old"%qalog_fn)
2102     qalog_fd = codecs.open(qalog_fn, "w", "utf8")
2103     qalog_fd.writelines(qalog)
2104     qalog_fd.close()
2105     if qalog:
2106         print("issues found (see %s for details):"%qalog_fn)
2107         if airports_badstation:
2108             print("   %s airports with invalid station"%airports_badstation)
2109         if airports_nostation:
2110             print("   %s airports with no station"%airports_nostation)
2111         if places_nocentroid:
2112             print("   %s places with no centroid"%places_nocentroid)
2113         if places_nodescription:
2114             print("   %s places with no description"%places_nodescription)
2115         if stations_nodescription:
2116             print("   %s stations with no description"%stations_nodescription)
2117         if stations_nolocation:
2118             print("   %s stations with no location"%stations_nolocation)
2119         if stations_nometar:
2120             print("   %s stations with no METAR"%stations_nometar)
2121         if zctas_nocentroid:
2122             print("   %s ZCTAs with no centroid"%zctas_nocentroid)
2123         if zones_nocentroid:
2124             print("   %s zones with no centroid"%zones_nocentroid)
2125         if zones_nodescription:
2126             print("   %s zones with no description"%zones_nodescription)
2127         if zones_noforecast:
2128             print("   %s zones with no forecast"%zones_noforecast)
2129         if zones_overlapping:
2130             print("   %s zones within one km of another"%zones_overlapping)
2131     else: print("no issues found.")
2132     print("Indexing complete!")